Пример #1
0
void MainWindow::loadMedia(){
  // mime database to detect file type
  QMimeDatabase db;

  // the mime type (to test if it is an audio file
  QMimeType type;

  // file list to be inserted into playlist
  QStringList filelist;

  // audio file to be opened
  QFileDialog d;
  filelist = d.getOpenFileNames(this,tr("Open File"),
                                "/home",
                                tr("Audio (*.wav *.mp3 *.ogg *.flac)"));

  // retrieve mime type
  for(QList<QString>::const_iterator it=filelist.begin(); it!= filelist.end(); it++){
    type = db.mimeTypeForFile(*it);
    // test if the file is an audio file
    // if yes, send it to the playlist
    if(type.name().startsWith("audio")){
      playlist->addMedia(QUrl::fromLocalFile(*it));
    }
  }
}
Пример #2
0
QuickLaunchAction::QuickLaunchAction(const QString & fileName, QWidget * parent)
    : QAction(parent),
      m_valid(true)
{
    m_type = ActionFile;
    setText(fileName);
    setData(fileName);
    
    m_settingsMap["file"] = fileName;

    QFileInfo fi(fileName);
    if (fi.isDir())
    {
        QFileIconProvider ip;
        setIcon(ip.icon(fi));
    }
    else
    {
        QMimeDatabase db;
        XdgMimeType mi(db.mimeTypeForFile(fi));
        setIcon(mi.icon());
    }
    
    connect(this, SIGNAL(triggered()), this, SLOT(execAction()));
}
Пример #3
0
QNetworkReply* Parse::uploadFile(QUrl url, QString name)
{
    QString filePath = url.toLocalFile();
    if (!isReady() || !QFile::exists(filePath)) return NULL;

    if (name.isEmpty()) name = url.fileName();
    setEndPoint( "files/"+name);

    QMimeDatabase db;
    QMimeType mime = db.mimeTypeForFile(filePath);

    QFile file(filePath);
    if (mime.inherits("text/plain")){
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
            return NULL;
    }
    else{
        if (!file.open(QIODevice::ReadOnly ))
            return NULL;
    }

    initHeaders();
    setHeader(QNetworkRequest::ContentTypeHeader, mime.name().toUtf8());

    m_conn = connect(this, &BaaS::replyFinished, [=]( QJsonDocument json){
        disconnect(m_conn);
        if ( getHttpCode() == 201 ){
            currentObject = json.object();
            emit fileUploaded( currentObject);
        }

    } );

    return request( BaaS::POST, file.readAll() );
}
void FolderListModel::readDirectory()
{
    this->beginResetModel();

    QFileInfoList fileinfolist = this->_directory.entryInfoList(QDir::AllDirs | QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks, QDir::DirsFirst);

    if(!this->_mimefilter.isEmpty())
    {
        QMimeDatabase mimedb;
        QStringList mimefilter = this->_mimefilter.split("/");
        this->_files.clear();

        foreach(const QFileInfo& fi, fileinfolist)
        {
            if(fi.isDir())
            {
                this->_files.append(fi);
                continue;
            }

            QMimeType mime = mimedb.mimeTypeForFile(fi.filePath());
            QStringList mimestring = mime.name().split("/");

            if(mimefilter[0] != mimestring[0])
                continue;

            if((mimefilter.length() > 1) && mimefilter[1] != mimestring[1])
                continue;

            this->_files.append(fi);
        }
    }
Пример #5
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*)));
    }
Пример #6
0
void FilesystemContentLister::startSearch()
{
    QMimeDatabase mimeDb;
    bool useThis(false);

    qDebug() << "Searching in" << d->locations;
    Q_FOREACH(const QString& folder, d->locations)
    {
        QDirIterator it(folder, QDirIterator::Subdirectories);
        while (it.hasNext())
        {
            QString filePath = it.next();
            QFileInfo info(filePath);

            if(info.isDir())
            {
                qApp->processEvents();
                continue;
            }
            useThis = false;
            QString mimetype = mimeDb.mimeTypeForFile(filePath, QMimeDatabase::MatchExtension).name();
//             qDebug() << useThis << mimetype << filePath;
            Q_FOREACH(const QString& type, d->mimetypes)
            {
                if(type == mimetype) {
                    useThis = true;
                    break;
                }
            }

            if(useThis)
            {
                QVariantHash metadata;
                metadata["created"] = info.created();

                KFileMetaData::UserMetaData data(filePath);
                if (data.hasAttribute("peruse.currentPage")) {
                    int currentPage = data.attribute("peruse.currentPage").toInt();
                    metadata["currentPage"] = QVariant::fromValue<int>(currentPage);
                }
                if (data.hasAttribute("peruse.totalPages")) {
                    int totalPages = data.attribute("peruse.totalPages").toInt();
                    metadata["totalPages"] = QVariant::fromValue<int>(totalPages);
                }

                emit fileFound(filePath, metadata);
            }
            qApp->processEvents();
        }
    }
    // This ensures that, should we decide to search more stuff later, we can do so granularly
    d->locations.clear();

    // Not entirely happy about this, but it makes things not break...
    // Previously, the welcome page in Peruse would end up unpopulated because a signal
    // was unreceived from the main window upon search completion (and consequently
    // application readiness)
    QTimer::singleShot(0, this, SIGNAL(searchCompleted()));
}
Пример #7
0
QByteArray FileAttachmentItem::mimeType() const
{
    if (!m_cachedMime.isEmpty())
        return m_cachedMime;

    QMimeDatabase mimeDb;
    m_cachedMime = mimeDb.mimeTypeForFile(fileName).name().toUtf8();
    return m_cachedMime;
}
Пример #8
0
/** ***************************************************************************/
void Files::Extension::handleQuery(Core::Query * query) {


    if ( query->searchTerm().startsWith('/') || query->searchTerm().startsWith("~") ) {

        QFileInfo queryFileInfo(query->searchTerm());

        // Substitute tilde
        if ( query->searchTerm()[0] == '~' )
            queryFileInfo.setFile(QDir::homePath()+query->searchTerm().right(query->searchTerm().size()-1));

        // Get all matching files
        QFileInfo pathInfo(queryFileInfo.path());
        if ( pathInfo.exists() && pathInfo.isDir() ) {
            QMimeDatabase mimeDatabase;
            QDir dir(pathInfo.filePath());
            for (const QFileInfo& fileinfo : dir.entryInfoList(QDir::AllEntries|QDir::Hidden|QDir::NoDotAndDotDot,
                                                               QDir::DirsFirst|QDir::Name|QDir::IgnoreCase) ) {
                if ( fileinfo.fileName().startsWith(queryFileInfo.fileName()) ) {
                    QMimeType mimetype = mimeDatabase.mimeTypeForFile(fileinfo.filePath());
                    query->addMatch(std::make_shared<File>(fileinfo.filePath(), mimetype),
                                    static_cast<short>(SHRT_MAX * static_cast<float>(queryFileInfo.fileName().size()) / fileinfo.fileName().size()));
                }
            }
        }
    }
    else
    {
        if ( QString("albert scan files").startsWith(query->searchTerm()) ) {
            shared_ptr<StandardItem> standardItem = std::make_shared<StandardItem>("org.albert.extension.files.action.index");
            standardItem->setText("albert scan files");
            standardItem->setSubtext("Update the file index");
            standardItem->setIconPath(":app_icon");

            shared_ptr<StandardAction> standardAction = std::make_shared<StandardAction>();
            standardAction->setText("Update the file index");
            standardAction->setAction([this](){ this->updateIndex(); });

            standardItem->setActions({standardAction});

            query->addMatch(standardItem);
        }

        // Search for matches
        const vector<shared_ptr<Core::Indexable>> &indexables = d->offlineIndex.search(query->searchTerm().toLower());

        // Add results to query
        vector<pair<shared_ptr<Core::Item>,short>> results;
        for (const shared_ptr<Core::Indexable> &item : indexables)
            // TODO `Search` has to determine the relevance. Set to 0 for now
            results.emplace_back(std::static_pointer_cast<File>(item), -1);

        query->addMatches(results.begin(), results.end());
    }
}
// create table of file lists qualified for search
QHash<SearchWorker::WorkSet, QStringList> SearchWorker::createFileTable(QDir dir, QDir::Filter hidden, QHash<SearchWorker::WorkSet, bool> enabler)
{
    QHash<SearchWorker::WorkSet, QStringList> wtab;
    QStringList filetypefilters;

    if (!enabler[SearchWorker::EnableMimeType]) {
        if (enabler[SearchWorker::EnableTxt]) {
            filetypefilters.clear();
            filetypefilters << "*.txt";
            wtab[SearchWorker::EnableTxt] = dir.entryList(filetypefilters, QDir::Files | hidden);
        }
        if (enabler[SearchWorker::EnableHtml]) {
            filetypefilters.clear();
            filetypefilters << "*.html" << "*.htm";
            wtab[SearchWorker::EnableHtml] = dir.entryList(filetypefilters, QDir::Files | hidden);
        }
        if (enabler[SearchWorker::EnableSrc]) {
            filetypefilters.clear();
            filetypefilters << "*.cpp" << "*.c" << "*.h" << "*.py" << "*.sh" << "*.qml" << "*.js";
            wtab[SearchWorker::EnableSrc] = dir.entryList(filetypefilters, QDir::Files | hidden);
        }
        if (enabler[SearchWorker::EnableApps]) {
            filetypefilters.clear();
            filetypefilters << "*.desktop";
            wtab[SearchWorker::EnableApps] = dir.entryList(filetypefilters, QDir::Files | hidden);
        }
        if (enabler[SearchWorker::EnableSqlite]) {
            filetypefilters.clear();
            filetypefilters << "*.sqlite" << "*.sqlite3" << "*.db";
            wtab[SearchWorker::EnableSqlite] = dir.entryList(filetypefilters, QDir::Files | hidden);
        }
    }

    if (enabler[SearchWorker::EnableMimeType]) {
        filetypefilters.clear();
        QStringList names = dir.entryList(filetypefilters, QDir::Files | hidden);
        QMimeDatabase db;
        for (int i = 0 ; i < names.count() ; ++i) {
            QString fullpath = dir.absoluteFilePath(names.at(i));
            QMimeType mime = db.mimeTypeForFile(fullpath);
            if ( mime.inherits("application/x-sqlite3") ) {
                if (enabler[SearchWorker::EnableSqlite]) wtab[SearchWorker::EnableSqlite].append(names.at(i)); }
            else if ( mime.inherits("application/x-desktop") ) {
                if (enabler[SearchWorker::EnableApps]) wtab[SearchWorker::EnableApps].append(names.at(i)); }
            else if ( mime.inherits("text/html") ) {
                if (enabler[SearchWorker::EnableHtml]) wtab[SearchWorker::EnableHtml].append(names.at(i)); }
            else if ( mime.inherits("text/x-csrc") || mime.inherits("application/x-shellscript")
                   || mime.inherits("text/x-python") || mime.inherits("text/x-qml") ) {
                if (enabler[SearchWorker::EnableSrc]) wtab[SearchWorker::EnableSrc].append(names.at(i)); }
            else if ( mime.inherits("text/plain") ) {
                if (enabler[SearchWorker::EnableTxt]) wtab[SearchWorker::EnableTxt].append(names.at(i)); }
        }
    }
    return wtab;
}
Пример #10
0
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);
}
Пример #11
0
void InfoPanel::showMetaDataFor(const QModelIndex &index)
{
    showMetaData();

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

    QMimeDatabase db;
    QMimeType mimeType;

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

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

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

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

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

    if (entry->property("isPasswordProtected").toBool()) {
        m_passwordLabel->show();
        m_passwordValueLabel->show();
    } else {
        m_passwordLabel->hide();
        m_passwordValueLabel->hide();
    }
}
Пример #12
0
void FileInfo::Private::resolvePath()
{
    path = QUrl(source);
    if(path.isEmpty())
        path = QUrl::fromLocalFile(source);

    if(path.isRelative())
        path = QUrl::fromLocalFile(QDir::current().absoluteFilePath(source));

    fileInfo = QFileInfo(path.toLocalFile());
    QMimeDatabase db;
    mimeType = db.mimeTypeForFile(fileInfo);
}
Пример #13
0
QStringList EpisodeFinder::getEpisodes(const QString &seasonPath, int season, int episode) const
{
    QDir seasonDir(seasonPath);
    QMimeDatabase db;
    QStringList files;
    foreach (const QFileInfo &fileInfo, seasonDir.entryInfoList()) {
        if (!fileInfo.isFile())
            continue;
        QMimeType mimeType = db.mimeTypeForFile(fileInfo);

        // must have got a video mime type
        if (!mimeType.name().startsWith("video/"))
            continue;

        if (season == -1) {
            files << fileInfo.absoluteFilePath();
            continue;
        }

        QString fileName = fileInfo.fileName();
        int fileSeason, fileEpisode;

        // SXXEXX expression?
        QRegularExpression re("\\bS([0-9]+)E([0-9]+)", QRegularExpression::CaseInsensitiveOption);

        QRegularExpressionMatch match = re.match(fileName);
        if (match.hasMatch()) {
            fileSeason = match.captured(1).toInt();
            fileEpisode = match.captured(2).toInt();
            if (fileSeason == season && fileEpisode == episode)
                files << fileInfo.absoluteFilePath();
            continue;
        }

        // SxE expression?
        re.setPattern("\\b([0-9]+)x([0-9]+)");

        match = re.match(fileName);
        if (match.hasMatch()) {
            fileSeason = match.captured(1).toInt();
            fileEpisode = match.captured(2).toInt();
            if (fileSeason == season && fileEpisode == episode)
                files << fileInfo.absoluteFilePath();
            continue;
        }

    }
    return files;
}
Пример #14
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

}
Пример #15
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;
}
Пример #16
0
 ///
 /// \brief Load
 /// \param filename
 /// \return
 ///
 static SharedResourceList Load ( FileDescriptor filename ) {
     QMimeDatabase db;
     QUuid uuidFile = UUIDManager::createUUID( filename.fullFilename );
     if ( mLibraries.find ( uuidFile ) != mLibraries.end () )
         return mLibraries [ uuidFile ];
     SharedResourceList lib;
     SharedResourceLoaderPtr loader;
     QMimeType mimeType = db.mimeTypeForFile(filename.fullFilename);
     if ( mResourceLoaders.find ( mimeType.name () ) != mResourceLoaders.end () )
         loader = mResourceLoaders [ mimeType.name () ];
     if ( ! loader.isNull() )
         lib = loader->load(filename);
     mLibraries[uuidFile] = lib;
     foreach ( SharedResourcePtr res, lib ) {
         res->InitializeUUID("Assets:"+filename.fullFilename+":"+res->getName());
         mResources [ res->getUUID () ] = res;
         mResourceDescriptors [ res->mTypeID ]->mManager->mLoadedResources [ res->getUUID() ] = res;
     }
Пример #17
0
//! [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;
}
void FileViewModel::OpenArchive(const QString& archiveName)
{
    m_Archiver->OpenArchive(archiveName.toStdString());
    std::vector<Header>& fileCollection = m_Archiver->GetFileCollection();
    QMimeDatabase db;

    for (auto file : fileCollection)
    {
        time_t modificationTime = file.GetFileModificationTime();
        QString fileName = QString::fromStdString(file.GetFileName());

        addItem(fileName,
                QString::number(file.GetFileSize()),
                db.mimeTypeForFile(fileName).name(),
                ctime(&modificationTime));
    }


}
void URLRequestQrcJobQt::startGetHead()
{
    // Get qrc file path.
    QString qrcFilePath = ':' + toQt(request_->url()).path(QUrl::RemovePath | QUrl::RemoveQuery);
    m_file.setFileName(qrcFilePath);
    QFileInfo qrcFileInfo(m_file);
    // Get qrc file mime type.
    QMimeDatabase mimeDatabase;
    QMimeType mimeType = mimeDatabase.mimeTypeForFile(qrcFileInfo);
    m_mimeType = mimeType.name().toStdString();
    // Open file
    if (m_file.open(QIODevice::ReadOnly)) {
        m_remainingBytes = m_file.size();
        // Notify that the headers are complete
        NotifyHeadersComplete();
    } else {
        NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED, ERR_INVALID_URL));
    }
}
Пример #20
0
ProjectTreeItem::ProjectTreeItem(ProjectTreeItem* parent, const FilePath& filepath) :
    mFilePath(filepath), mParent(parent), mDepth(parent ? parent->getDepth() + 1 : 0)
{
    QMimeDatabase db;
    mMimeType = db.mimeTypeForFile(mFilePath.toStr());

    if (mFilePath.isExistingDir())
    {
        // it's a directory
        QDir dir(mFilePath.toStr());

        QStringList projectFiles = dir.entryList(QStringList("*.lpp"), QDir::Files);
        if (projectFiles.count() == 1)
        {
            // it's a project folder
            mType = ProjectFolder;
        }
        else
        {
            // it's a normal folder
            mType = Folder;
        }

        // scan folder and add child items
        if (mDepth < 15) // limit the maximum depth in the project directory to avoid endless recursion
        {
            QFileInfoList items = dir.entryInfoList(QDir::Files | QDir::Dirs |
                                                    QDir::NoDotAndDotDot,
                                                    QDir::DirsFirst | QDir::Name);
            foreach (QFileInfo item, items)
                mChilds.append(new ProjectTreeItem(this, FilePath(item.absoluteFilePath())));
        }
    }
    else if (mFilePath.isExistingFile())
    {
        // it's a file
        if (mFilePath.getSuffix() == "lpp")
            mType = ProjectFile;
        else
            mType = File;
    }    
}
Пример #21
0
void InfoPanel::setIndex(const QModelIndex& index)
{
    if (!index.isValid()) {
        updateWithDefaults();
    } else {
        const Archive::Entry *entry = m_model->entryForIndex(index);
        if (!entry) {
            return;
        }

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

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

            }
        }

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

        showMetaDataFor(index);
    }
}
Пример #22
0
int main(int argc, char** argv)
{
    QCoreApplication app(argc, argv);

    QTemporaryDir tempDir;
    qDebug() << tempDir.path();

    Database db(tempDir.path());
    db.open(Baloo::Database::CreateDatabase);

    Transaction tr(db, Transaction::ReadWrite);

    QMimeDatabase mimeDb;
    {
        QTime timer;
        timer.start();

        QDirIterator it(QDir::homePath(), QDirIterator::Subdirectories);
        uint num = 0;
        while (it.hasNext()) {
            const QString& path = it.next();
            const QString& mimetype = mimeDb.mimeTypeForFile(path, QMimeDatabase::MatchExtension).name();

            BasicIndexingJob job(path, mimetype);
            job.index();

            tr.addDocument(job.document());
            num++;

            if ((num % 10000) == 0) {
                qDebug() << num;
            }
        }
        tr.commit();

        qDebug() << "Done" << timer.elapsed() << "msecs";
        app.exec();
    }

    return 0;
}
Пример #23
0
void NoteEditorUtils::insertImage(QTextDocument *doc, QTextCursor &cursor, QTextEdit *par)
{
    QString imageFileName = QFileDialog::getOpenFileName(par, i18n("Select image file"), QLatin1String("."), QLatin1String("Images (*.png *.bmp *.jpg *.jpeg *.jpe)"));
    if (!imageFileName.isEmpty()) {
        QFileInfo qfio = QFileInfo(imageFileName);
        QImage imgRes(imageFileName);
        if (!imgRes.isNull()) {
            QMimeDatabase mimedb;
            QByteArray imageData;
            QBuffer buffer(&imageData);
            QMimeType filemime = mimedb.mimeTypeForFile(qfio);
            QString filetype = filemime.name();
            QByteArray formatChars = filemime.preferredSuffix().toUpper().toLatin1();

            buffer.open(QIODevice::WriteOnly);
            imgRes.save(&buffer, formatChars.data());
            QString Base64Image = QString::fromLatin1(imageData.toBase64().data());//is null
            par->insertHtml(QLatin1String("<img src=\"data:") + filetype + QLatin1String(";base64,") + Base64Image + QLatin1String("\" />"));

        }
    }
}
Пример #24
0
////////////
/// \brief QQPalmiFilePoster::postFileUpload3TerOrg
/// \param file
///
QNetworkReply * QQPalmiFilePoster::postFileUpload3TerOrg(QFile *file)
{
	QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);

	QHttpPart filePart;
#if(QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
	QMimeDatabase mimeDatabase;
	QMimeType mimeType = mimeDatabase.mimeTypeForFile(file->fileName(), QMimeDatabase::MatchDefault);
	filePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant(mimeType.name()));
#else
	filePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/octet-stream"));
#endif
	filePart.setHeader(QNetworkRequest::ContentDispositionHeader,
					   QString("form-data; name=\"file\"; filename=\"%1\"").arg(file->fileName()));
	filePart.setBodyDevice(file);
	file->setParent(multiPart); // we cannot delete the file now, so delete it with the multiPart

	multiPart->append(filePart);

	QHttpPart timePart;
	timePart.setHeader(QNetworkRequest::ContentDispositionHeader,
					   QString("form-data; name=\"time\""));
	timePart.setBody(QString::fromLatin1("week").toLatin1());
	multiPart->append(timePart);

	QUrl url(QString("http://%1/script.php").arg(FILE_SHARING_SERVICE_JIRAFEAU_3TER_ORG));
	QNetworkRequest request(url);
	//request.setRawHeader("User-Agent", "Mozilla/5.0 (quteqoin)"); // Le service n'accepte pas l'ua par défaut ...
	//request.setRawHeader("Accept", "application/json, text/javascript, */*; q=0.01");
	//request.setRawHeader("Accept-Language", "en-US,en;q=0.5");
	//request.setRawHeader("Accept-Encoding", "gzip, deflate"); // Qt 4 ne supporte pas gunzip nativement ....
	//request.setRawHeader("X-Requested-With", "XMLHttpRequest");
	request.setRawHeader("Referer", QString("http://%1/").arg(FILE_SHARING_SERVICE_JIRAFEAU_3TER_ORG).toLatin1());

	QNetworkReply *reply = httpPost(request, multiPart);
	multiPart->setParent(reply); // delete the multiPart with the reply

	return reply;
}
Пример #25
0
void NewFileIndexer::run()
{
    QMimeDatabase mimeDb;

    Transaction tr(m_db, Transaction::ReadWrite);

    for (const QString& filePath : qAsConst(m_files)) {
        Q_ASSERT(!filePath.endsWith(QLatin1Char('/')));

        QString fileName = filePath.mid(filePath.lastIndexOf(QLatin1Char('/')) + 1);
        if (!m_config->shouldFileBeIndexed(fileName)) {
            continue;
        }

        QString mimetype = mimeDb.mimeTypeForFile(filePath, QMimeDatabase::MatchExtension).name();
        if (!m_config->shouldMimeTypeBeIndexed(mimetype)) {
            continue;
        }

        BasicIndexingJob::IndexingLevel level =
            m_config->onlyBasicIndexing() ? BasicIndexingJob::NoLevel : BasicIndexingJob::MarkForContentIndexing;
        BasicIndexingJob job(filePath, mimetype, level);
        if (!job.index()) {
            continue;
        }

        // The same file can be sent twice though it shouldn't be.
        // Lets just silently ignore it instead of crashing
        if (tr.hasDocument(job.document().id())) {
            continue;
        }
        tr.addDocument(job.document());
    }

    tr.commit();
    Q_EMIT done();
}
Пример #26
0
bool KoOdtFrameReportPicture::saveData(KoStore* store, KoXmlWriter* manifestWriter) const
{
    QString name = "Pictures/" + pictureName();
    if (!store->open(name)) {
        return false;
    }
    KoStoreDevice device(store);
    QImage image(m_primitive->size().toSize(), QImage::Format_ARGB32);
    image.fill(0);
    QPainter painter;
    painter.begin(&image);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.drawPicture(0, 0, *(picture()->picture()));
    painter.end();
    //kreportDebug()<<image.format();
    bool ok = image.save(&device, "PNG");
    if (ok) {
        QMimeDatabase db;
        const QString mimetype(db.mimeTypeForFile(name, QMimeDatabase::MatchExtension).name());
        manifestWriter->addManifestEntry(name,  mimetype);
    }
    ok = store->close() && ok;
    return ok;
}
Пример #27
0
bool GDTalker::addPhoto(const QString& imgPath, const GSPhoto& info,
                        const QString& id, bool rescale, int maxDim, int imageQuality)
{
    if (m_reply)
    {
        m_reply->abort();
        m_reply = 0;
    }

    emit signalBusy(true);
    MPForm_GDrive form;
    form.addPair(QUrl::fromLocalFile(imgPath).fileName(),info.description,imgPath,id);
    QString path = imgPath;

    QMimeDatabase mimeDB;

    if (!mimeDB.mimeTypeForFile(path).name().startsWith(QLatin1String("video/")))
    {
        QImage image;

        if (m_iface)
        {
            image = m_iface->preview(QUrl::fromLocalFile(imgPath));
        }

        if (image.isNull())
        {
            image.load(imgPath);
        }

        if (image.isNull())
        {
            return false;
        }

        path                  = makeTemporaryDir("gs").filePath(QFileInfo(imgPath)
                                                      .baseName().trimmed() + QLatin1String(".jpg"));
        int imgQualityToApply = 100;

        if (rescale)
        {
            if (image.width() > maxDim || image.height() > maxDim)
                image = image.scaled(maxDim,maxDim,Qt::KeepAspectRatio,Qt::SmoothTransformation);

            imgQualityToApply = imageQuality;
        }

        image.save(path,"JPEG",imgQualityToApply);

        if (m_iface)
        {
            QPointer<MetadataProcessor> meta = m_iface->createMetadataProcessor();

            if (meta && meta->load(QUrl::fromLocalFile(imgPath)))
            {
                meta->setImageDimensions(image.size());
                meta->setImageProgramId(QString::fromLatin1("Kipi-plugins"), kipipluginsVersion());
                meta->save(QUrl::fromLocalFile(path), true);
            }
        }
    }

    if (!form.addFile(path))
    {
        emit signalBusy(false);
        return false;
    }

    form.finish();

    QUrl url(QString::fromLatin1("https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart"));

    QNetworkRequest netRequest(url);
    netRequest.setHeader(QNetworkRequest::ContentTypeHeader, form.contentType());
    netRequest.setRawHeader("Authorization", m_bearer_access_token.toLatin1());
    netRequest.setRawHeader("Host", "www.googleapis.com");

    m_reply = m_netMngr->post(netRequest, form.formData());

    qCDebug(KIPIPLUGINS_LOG) << "In add photo";
    m_state = GD_ADDPHOTO;
    m_buffer.resize(0);
    emit signalBusy(true);
    return true;
}
Пример #28
0
ActionReply SddmAuthHelper::installtheme(const QVariantMap &args)
{
    const QString filePath = args["filePath"].toString();
    if (filePath.isEmpty()) {
        return ActionReply::HelperErrorReply();
    }

    const QString themesBaseDir = QStandardPaths::locate(QStandardPaths::GenericDataLocation, "sddm/themes", QStandardPaths::LocateDirectory);
    QDir dir(themesBaseDir);
    if (!dir.exists()) {
        return ActionReply::HelperErrorReply();
    }

    qDebug() << "Installing " << filePath << " into " << themesBaseDir;

    if (!QFile::exists(filePath)) {
        return ActionReply::HelperErrorReply();
    }

    QMimeDatabase db;
    QMimeType mimeType = db.mimeTypeForFile(filePath);
    qWarning() << "Postinstallation: uncompress the file";

    QScopedPointer<KArchive> archive;

    //there must be a better way to do this? If not, make a static bool KZip::supportsMimeType(const QMimeType &type); ?
    //or even a factory class in KArchive

    if (mimeType.inherits(QStringLiteral("application/zip"))) {
        archive.reset(new KZip(filePath));
    } else if (mimeType.inherits(QStringLiteral("application/tar"))
                || mimeType.inherits(QStringLiteral("application/x-gzip"))
                || mimeType.inherits(QStringLiteral("application/x-bzip"))
                || mimeType.inherits(QStringLiteral("application/x-lzma"))
                || mimeType.inherits(QStringLiteral("application/x-xz"))
                || mimeType.inherits(QStringLiteral("application/x-bzip-compressed-tar"))
                || mimeType.inherits(QStringLiteral("application/x-compressed-tar"))) {
        archive.reset(new KTar(filePath));
    } else {
        auto e = ActionReply::HelperErrorReply();
        e.setErrorDescription(i18n("Invalid theme package"));
        return e;    }

    if (!archive->open(QIODevice::ReadOnly)) {
        auto e = ActionReply::HelperErrorReply();
        e.setErrorDescription("Could not open file");
        return e;
    }

    auto directory = archive->directory();

    QStringList installedPaths;

    //some basic validation
    //the top level should only have folders, and those folders should contain a valid metadata.desktop file
    //if we get anything else, abort everything before copying
    for(const QString &name: directory->entries()) {
        auto entry = directory->entry(name);
        if (!entry->isDirectory()) {
            auto e = ActionReply::HelperErrorReply();
            e.setErrorDescription(i18n("Invalid theme package"));
            return e;
        }
        auto subDirectory = static_cast<const KArchiveDirectory*>(entry);
        auto metadataFile = subDirectory->file("metadata.desktop");
        if(!metadataFile || !metadataFile->data().contains("[SddmGreeterTheme]")) {
            auto e = ActionReply::HelperErrorReply();
            e.setErrorDescription(i18n("Invalid theme package"));
            return e;
        }
        installedPaths.append(themesBaseDir + '/' + name);
    }

    if (!directory->copyTo(themesBaseDir)) {
        auto e = ActionReply::HelperErrorReply();
        e.setErrorDescription(i18n("Could not decompress archive"));
        return e;
    }

    auto rc = ActionReply::SuccessReply();
    rc.addData(QStringLiteral("installedPaths"), installedPaths);
    return rc;
}
Пример #29
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();
}
Пример #30
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();
}