コード例 #1
0
ファイル: krsearchmod.cpp プロジェクト: KDE/krusader
void KRSearchMod::scanLocalDir(QUrl urlToScan)
{
    QString dir = vfs::ensureTrailingSlash(urlToScan).path();

    QT_DIR* d = QT_OPENDIR(dir.toLocal8Bit());
    if (!d) return ;

    QT_DIRENT* dirEnt;

    while ((dirEnt = QT_READDIR(d)) != NULL) {
        QString name = QString::fromLocal8Bit(dirEnt->d_name);

        // we don't scan the ".",".." enteries
        if (name == "." || name == "..") continue;

        QT_STATBUF stat_p;
        QT_LSTAT((dir + name).toLocal8Bit(), &stat_p);

        QUrl url = QUrl::fromLocalFile(dir + name);

        QString mime;
        if (query->searchInArchives() || !query->hasMimeType()) {
            QMimeDatabase db;
            QMimeType mt = db.mimeTypeForUrl(url);
            if (mt.isValid())
                mime = mt.name();
        }

        // creating a vfile object for matching with krquery
        vfile * vf = new vfile(name, (KIO::filesize_t)stat_p.st_size, KRpermHandler::mode2QString(stat_p.st_mode),
                               stat_p.st_mtime, S_ISLNK(stat_p.st_mode), false/*FIXME*/, stat_p.st_uid, stat_p.st_gid,
                               mime, "", stat_p.st_mode, -1, url);

        if (query->isRecursive()) {
            if (S_ISLNK(stat_p.st_mode) && query->followLinks())
                unScannedUrls.push(QUrl::fromLocalFile(QDir(dir + name).canonicalPath()));
            else if (S_ISDIR(stat_p.st_mode))
                unScannedUrls.push(url);
        }
        if (query->searchInArchives()) {
            if (KRarcHandler::arcSupported(mime)) {
                QUrl archiveURL = url;
                bool encrypted;
                QString realType = arcHandler.getType(encrypted, url.path(), mime);

                if (!encrypted) {
                    if (realType == "tbz" || realType == "tgz" || realType == "tarz" || realType == "tar" || realType == "tlz")
                        archiveURL.setScheme("tar");
                    else
                        archiveURL.setScheme("krarc");

                    unScannedUrls.push(archiveURL);
                }
            }
        }

        if (query->match(vf)) {
            // if we got here - we got a winner
            results.append(dir + name);
            emit found(name, dir, (KIO::filesize_t) stat_p.st_size, stat_p.st_mtime,
                       KRpermHandler::mode2QString(stat_p.st_mode), stat_p.st_uid, stat_p.st_gid, query->foundText());
        }
        delete vf;

        if (timer.elapsed() >= EVENT_PROCESS_DELAY) {
            qApp->processEvents();
            timer.start();
            if (stopSearch) return;
        }
    }
    // clean up
    QT_CLOSEDIR(d);
}
コード例 #2
0
ファイル: ktar.cpp プロジェクト: euroelessar/cutereader
// Only called when a filename was given
bool KTar::createDevice(QIODevice::OpenMode mode)
{
    if (d->mimetype.isEmpty()) {
        // Find out mimetype manually

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

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

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

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

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

        setDevice(d->tmpFile);
        return true;
    }
}
コード例 #3
0
ファイル: qmesh.cpp プロジェクト: RSATom/Qt
/*!
 * \internal
 */
QGeometry *MeshLoaderFunctor::operator()()
{
    if (m_sourcePath.isEmpty()) {
        qCWarning(Render::Jobs) << Q_FUNC_INFO << "Mesh is empty, nothing to load";
        return nullptr;
    }

    QStringList ext;
    if (!Qt3DCore::QDownloadHelperService::isLocal(m_sourcePath)) {
        if (m_sourceData.isEmpty()) {
            if (m_mesh) {
                // Output a warning in the case a user is calling the functor directly
                // in the frontend
                if (m_nodeManagers == nullptr || m_downloaderService == nullptr) {
                    qWarning() << "Mesh source points to a remote URL. Remotes meshes can only be loaded if the geometry is processed by the Qt3DRender backend";
                    return nullptr;
                }
                Qt3DCore::QDownloadRequestPtr request(new MeshDownloadRequest(m_mesh, m_sourcePath, m_nodeManagers));
                m_downloaderService->submitRequest(request);
            }
            return nullptr;
        }

        QMimeDatabase db;
        QMimeType mtype = db.mimeTypeForData(m_sourceData);
        if (mtype.isValid()) {
            ext = mtype.suffixes();
        }
        QFileInfo finfo(m_sourcePath.path());
        ext << finfo.suffix();
        ext.removeAll(QLatin1String(""));
        if (!ext.contains(QLatin1String("obj")))
            ext << QLatin1String("obj");
    } else {
        QString filePath = Qt3DRender::QUrlHelper::urlToLocalFileOrQrc(m_sourcePath);
        QFileInfo finfo(filePath);
        if (finfo.suffix().isEmpty())
            ext << QLatin1String("obj");
        else
            ext << finfo.suffix();
    }

    QScopedPointer<QGeometryLoaderInterface> loader;
    for (const QString &e: qAsConst(ext)) {
        loader.reset(qLoadPlugin<QGeometryLoaderInterface, QGeometryLoaderFactory>(geometryLoader(), e));
        if (loader)
            break;
    }
    if (!loader) {
        qCWarning(Render::Jobs, "unsupported format encountered (%s)", qPrintable(ext.join(QLatin1String(", "))));
        return nullptr;
    }

    if (m_sourceData.isEmpty()) {
        QString filePath = Qt3DRender::QUrlHelper::urlToLocalFileOrQrc(m_sourcePath);
        QFile file(filePath);
        if (!file.open(QIODevice::ReadOnly)) {
            qCDebug(Render::Jobs) << "Could not open file" << filePath << "for reading";
            return nullptr;
        }

        if (loader->load(&file, m_meshName))
            return loader->geometry();
        qCWarning(Render::Jobs) << Q_FUNC_INFO << "Mesh loading failure for:" << filePath;
    } else {
        QT_PREPEND_NAMESPACE(QBuffer) buffer(&m_sourceData);
        if (!buffer.open(QIODevice::ReadOnly)) {
            return nullptr;
        }

        if (loader->load(&buffer, m_meshName))
            return loader->geometry();

        qCWarning(Render::Jobs) << Q_FUNC_INFO << "Mesh loading failure for:" << m_sourcePath;
    }

    return nullptr;
}
コード例 #4
0
ファイル: main.cpp プロジェクト: BoltsJ/albert
/** ***************************************************************************/
vector<shared_ptr<Files::File>>
Files::FilesPrivate::indexFiles(const IndexSettings &indexSettings) const {

    // Get a new index
    std::vector<shared_ptr<File>> newIndex;
    std::set<QString> indexedDirs;
    QMimeDatabase mimeDatabase;
    std::vector<QRegExp> mimeFilters;
    for (const QString &re : indexSettings.filters)
        mimeFilters.emplace_back(re, Qt::CaseInsensitive, QRegExp::Wildcard);

    // Prepare the iterator properties
    QDir::Filters filters = QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot;
    if (indexSettings.indexHidden)
        filters |= QDir::Hidden;

    // Anonymous function that implemnents the index recursion
    std::function<void(const QFileInfo&, vector<IgnoreEntry>)> indexRecursion =
            [&](const QFileInfo& fileInfo, const vector<IgnoreEntry> &ignoreEntries){

        if (abort) return;

        const QString canonicalPath = fileInfo.canonicalFilePath();
        const QMimeType mimetype = mimeDatabase.mimeTypeForFile(canonicalPath);
        const QString mimeName = mimetype.name();

        // If the file matches the index options, index it
        if ( std::any_of(mimeFilters.begin(), mimeFilters.end(),
                         [&](const QRegExp &re){ return re.exactMatch(mimeName); }) )
            newIndex.push_back(std::make_shared<File>(canonicalPath, mimetype));

        if (fileInfo.isDir()) {

            emit q->statusInfo(QString("Indexing %1.").arg(canonicalPath));

            // Skip if this dir has already been indexed
            if ( indexedDirs.find(canonicalPath) != indexedDirs.end() )
                return;

            // Remember that this dir has been indexed to avoid loops
            indexedDirs.insert(canonicalPath);

            // Read the ignore file, see http://doc.qt.io/qt-5/qregexp.html#wildcard-matching
            vector<IgnoreEntry> localIgnoreEntries = ignoreEntries;
            QFile file(QDir(canonicalPath).filePath(IGNOREFILE));
            if ( file.open(QIODevice::ReadOnly | QIODevice::Text) ) {
                QTextStream in(&file);
                while ( !in.atEnd() ) {
                    QString pattern = QDir::cleanPath(in.readLine());

                    if ( pattern.isEmpty() || pattern.startsWith("#") )
                        continue;

                    // Replace ** and * by their regex analogons
                    pattern.replace(QRegularExpression("(?<!\\*)\\*(?!\\*)"), "[^\\/]*");
                    pattern.replace(QRegularExpression("\\*{2,}"), ".*");

                    // Determine pattern type
                    PatternType patternType = PatternType::Exclude;
                    if ( pattern.startsWith('!') ) {
                        patternType = PatternType::Include;
                        pattern = pattern.mid(1, -1);
                    }

                    // Respect files beginning with excalmation mark
                    if ( pattern.startsWith("\\!") )
                        pattern = pattern.mid(1, -1);

                    if ( pattern.startsWith("/") ) {
                        pattern = QString("^%1$").arg(QDir(fileInfo.filePath()).filePath(pattern.mid(1, -1)));
                        localIgnoreEntries.emplace_back(QRegularExpression(pattern), patternType);
                    } else {
                        pattern = QString("%1$").arg(pattern);
                        localIgnoreEntries.emplace_back(QRegularExpression(pattern), patternType);
                    }
                }
                file.close();
            }

            // Index all children in the dir
            QDirIterator dirIterator(canonicalPath, filters, QDirIterator::NoIteratorFlags);
            while ( dirIterator.hasNext() ) {
                dirIterator.next();
                const QFileInfo & fileInfo = dirIterator.fileInfo();

                // Skip if this file depending on ignore patterns
                PatternType patternType = PatternType::Include;
                for ( const IgnoreEntry &ignoreEntry : localIgnoreEntries )
                    if ( ignoreEntry.regex.match(fileInfo.filePath()).hasMatch() )
                        patternType = ignoreEntry.type;
                if ( patternType == PatternType::Exclude )
                    continue;

                // Skip if this file is a symlink and we should skip symlinks
                if ( fileInfo.isSymLink() && !indexSettings.followSymlinks )
                    continue;

                // Index this file
                indexRecursion(fileInfo, localIgnoreEntries);
            }
        }
    };

    // Start the indexing
    for ( const QString &rootDir : indexSettings.rootDirs ) {
        // Index rootdir, ignore ignorefile by default
        vector<IgnoreEntry> ignores = {IgnoreEntry(
                                       QRegularExpression(QString("%1$").arg(IGNOREFILE)),
                                       PatternType::Exclude)};
        indexRecursion(QFileInfo(rootDir), ignores);
        if ( abort )
            return vector<shared_ptr<Files::File>>();
    }

    // Serialize data
    QFile file(QDir(QStandardPaths::writableLocation(QStandardPaths::CacheLocation)).
                   filePath(QString("%1.txt").arg(q->Core::Extension::id)));
    if ( file.open(QIODevice::WriteOnly|QIODevice::Text) ) {
        qDebug() << qPrintable(QString("Serializing files to '%1'").arg(file.fileName()));
        QTextStream out(&file);
        for (const shared_ptr<File> &item : newIndex)
            out << item->path() << endl << item->mimetype().name() << endl;
    } else
        qWarning() << qPrintable(QString("Could not write to file '%1': %2").arg(file.fileName(), file.errorString()));

    return newIndex;
}
コード例 #5
0
ファイル: imageshacktalker.cpp プロジェクト: KDE/kipi-plugins
QString ImageshackTalker::mimeType(const QString& path)
{
    QMimeDatabase db;
    QMimeType ptr = db.mimeTypeForUrl(QUrl::fromLocalFile(path));
    return ptr.name();
}
コード例 #6
0
QString CDoodFileViewManager::getMimeType(const QString &filepath)
{
    QMimeDatabase mdb;
    return mdb.mimeTypeForFile(filepath).name();
}
コード例 #7
0
ファイル: ContentList.cpp プロジェクト: KDE/peruse
QString ContentList::getMimetype(QString filePath)
{
    QMimeDatabase db;
    QMimeType mime = db.mimeTypeForFile(filePath);
    return mime.name();
}
コード例 #8
0
shared_ptr<ZLMimeType> QtZLFSManager::mimeType(const std::string &path) const
{
    QMimeDatabase database;
    QMimeType type = database.mimeTypeForFile(QString::fromStdString(path));
    return ZLMimeType::get(type.name().toStdString());
}
コード例 #9
0
LocalListingNetworkReply::LocalListingNetworkReply(QObject *parent, const QNetworkRequest &request) : QNetworkReply(parent),
	m_offset(0)
{
	setRequest(request);

	open(QIODevice::ReadOnly | QIODevice::Unbuffered);

	QFile file(QLatin1String(":/files/listing.html"));
	file.open(QIODevice::ReadOnly | QIODevice::Text);

	QTextStream stream(&file);
	stream.setCodec("UTF-8");

	QDir directory(request.url().toLocalFile());
	const QFileInfoList entries = directory.entryInfoList((QDir::AllEntries | QDir::Hidden), (QDir::Name | QDir::DirsFirst));
	const QRegularExpression expression(QLatin1String("^/+"));
	QStringList navigation;

	do
	{
		navigation.prepend(QStringLiteral("<a href=\"file:///%1\">%2</a>%3").arg(directory.canonicalPath().remove(expression)).arg(directory.dirName().isEmpty() ? QString('/') : directory.dirName()).arg(directory.dirName().isEmpty() ? QString() : QString('/')));
	}
	while (directory.cdUp());

	QHash<QString, QString> variables;
	variables[QLatin1String("title")] = QFileInfo(request.url().toLocalFile()).canonicalFilePath();
	variables[QLatin1String("description")] = tr("Directory Contents");
	variables[QLatin1String("dir")] = (QGuiApplication::isLeftToRight() ? QLatin1String("ltr") : QLatin1String("rtl"));
	variables[QLatin1String("navigation")] = navigation.join(QString());
	variables[QLatin1String("header_name")] = tr("Name");
	variables[QLatin1String("header_type")] = tr("Type");
	variables[QLatin1String("header_size")] = tr("Size");
	variables[QLatin1String("header_date")] = tr("Date");
	variables[QLatin1String("body")] = QString();

	const QMimeDatabase database;

	for (int i = 0; i < entries.count(); ++i)
	{
		const QMimeType mimeType = database.mimeTypeForFile(entries.at(i).canonicalFilePath());
		QByteArray byteArray;
		QBuffer buffer(&byteArray);
		QIcon::fromTheme(mimeType.iconName(), Utils::getIcon(entries.at(i).isDir() ? QLatin1String("inode-directory") : QLatin1String("unknown"))).pixmap(16, 16).save(&buffer, "PNG");

		variables[QLatin1String("body")].append(QStringLiteral("<tr>\n<td><a href=\"file:///%1\"><img src=\"data:image/png;base64,%2\" alt=\"\"> %3</a></td>\n<td>%4</td>\n<td>%5</td>\n<td>%6</td>\n</tr>\n").arg(entries.at(i).filePath().remove(expression)).arg(QString(byteArray.toBase64())).arg(entries.at(i).fileName()).arg(mimeType.comment()).arg(entries.at(i).isDir() ? QString() : Utils::formatUnit(entries.at(i).size(), false, 2)).arg(QLocale().toString(entries.at(i).lastModified())));
	}

	QString html = stream.readAll();
	QHash<QString, QString>::iterator iterator;

	for (iterator = variables.begin(); iterator != variables.end(); ++iterator)
	{
		html.replace(QStringLiteral("{%1}").arg(iterator.key()), iterator.value());
	}

	m_content = html.toUtf8();

	setHeader(QNetworkRequest::ContentTypeHeader, QVariant("text/html; charset=UTF-8"));
	setHeader(QNetworkRequest::ContentLengthHeader, QVariant(m_content.size()));

	QTimer::singleShot(0, this, SIGNAL(readyRead()));
	QTimer::singleShot(0, this, SIGNAL(finished()));
}
コード例 #10
0
ファイル: packagejobthread.cpp プロジェクト: KDE/kpackage
bool PackageJobThread::installPackage(const QString &src, const QString &dest, OperationType operation)
{
    QDir root(dest);
    if (!root.exists()) {
        QDir().mkpath(dest);
        if (!root.exists()) {
            d->errorMessage = i18n("Could not create package root directory: %1", dest);
            d->errorCode = Package::JobError::RootCreationError;
            //qWarning() << "Could not create package root directory: " << dest;
            return false;
        }
    }

    QFileInfo fileInfo(src);
    if (!fileInfo.exists()) {
        d->errorMessage = i18n("No such file: %1", src);
        d->errorCode = Package::JobError::PackageFileNotFoundError;
        return false;
    }

    QString path;
    QTemporaryDir tempdir;
    bool archivedPackage = false;

    if (fileInfo.isDir()) {
        // we have a directory, so let's just install what is in there
        path = src;
        // make sure we end in a slash!
        if (!path.endsWith('/')) {
            path.append('/');
        }
    } else {
        KArchive *archive = 0;
        QMimeDatabase db;
        QMimeType mimetype = db.mimeTypeForFile(src);
        if (mimetype.inherits(QStringLiteral("application/zip"))) {
            archive = new KZip(src);
        } else if (mimetype.inherits(QStringLiteral("application/x-compressed-tar")) ||
                   mimetype.inherits(QStringLiteral("application/x-tar")) ||
                   mimetype.inherits(QStringLiteral("application/x-bzip-compressed-tar")) ||
                   mimetype.inherits(QStringLiteral("application/x-xz")) ||
                   mimetype.inherits(QStringLiteral("application/x-lzma"))) {
            archive = new KTar(src);
        } else {
            //qWarning() << "Could not open package file, unsupported archive format:" << src << mimetype.name();
            d->errorMessage = i18n("Could not open package file, unsupported archive format: %1 %2", src, mimetype.name());
            d->errorCode = Package::JobError::UnsupportedArchiveFormatError;
            return false;
        }

        if (!archive->open(QIODevice::ReadOnly)) {
            //qWarning() << "Could not open package file:" << src;
            delete archive;
            d->errorMessage = i18n("Could not open package file: %1", src);
            d->errorCode = Package::JobError::PackageOpenError;
            return false;
        }

        archivedPackage = true;
        path = tempdir.path() + '/';

        d->installPath = path;

        const KArchiveDirectory *source = archive->directory();
        source->copyTo(path);

        QStringList entries = source->entries();
        if (entries.count() == 1) {
            const KArchiveEntry *entry = source->entry(entries[0]);
            if (entry->isDirectory()) {
                path.append(entry->name()).append("/");
            }
        }

        delete archive;
    }

    QDir packageDir(path);
    QFileInfoList entries = packageDir.entryInfoList(*metaDataFiles);
    KPluginMetaData meta;
    if (!entries.isEmpty()) {
        const QString metadataFilePath = entries.first().filePath();
        if (metadataFilePath.endsWith(QLatin1String(".desktop")))
            meta = KPluginMetaData(metadataFilePath);
        else {
            QFile f(metadataFilePath);
            if(!f.open(QIODevice::ReadOnly)){
                qWarning() << "Couldn't open metadata file" << src << path;
                d->errorMessage = i18n("Could not open metadata file: %1", src);
                d->errorCode = Package::JobError::MetadataFileMissingError;
                return false;
            }
            QJsonObject metadataObject = QJsonDocument::fromJson(f.readAll()).object();
            meta = KPluginMetaData(metadataObject, QString(), metadataFilePath);
        }
    }

    if (!meta.isValid()) {
        qDebug() << "No metadata file in package" << src << path;
        d->errorMessage = i18n("No metadata file in package: %1", src);
        d->errorCode = Package::JobError::MetadataFileMissingError;
        return false;
    }


    QString pluginName = meta.pluginId();
    qDebug() << "pluginname: " << meta.pluginId();
    if (pluginName.isEmpty()) {
        //qWarning() << "Package plugin name not specified";
        d->errorMessage = i18n("Package plugin name not specified: %1", src);
        d->errorCode = Package::JobError::PluginNameMissingError;
        return false;
    }

    // Ensure that package names are safe so package uninstall can't inject
    // bad characters into the paths used for removal.
    QRegExp validatePluginName("^[\\w-\\.]+$"); // Only allow letters, numbers, underscore and period.
    if (!validatePluginName.exactMatch(pluginName)) {
        //qDebug() << "Package plugin name " << pluginName << "contains invalid characters";
        d->errorMessage = i18n("Package plugin name %1 contains invalid characters", pluginName);
        d->errorCode = Package::JobError::PluginNameInvalidError;
        return false;
    }

    QString targetName = dest;
    if (targetName[targetName.size() - 1] != '/') {
        targetName.append('/');
    }
    targetName.append(pluginName);

    if (QFile::exists(targetName)) {
        if (operation == Update) {
            KPluginMetaData oldMeta(targetName + QLatin1String("/metadata.desktop"));

            if (oldMeta.serviceTypes() != meta.serviceTypes()) {
                d->errorMessage = i18n("The new package has a different type from the old version already installed.", meta.version(), meta.pluginId(), oldMeta.version());
                d->errorCode = Package::JobError::UpdatePackageTypeMismatchError;
            } else if (isVersionNewer(oldMeta.version(), meta.version())) {
                const bool ok = uninstallPackage(targetName);
                if (!ok) {
                    d->errorMessage = i18n("Impossible to remove the old installation of %1 located at %2. error: %3", pluginName, targetName, d->errorMessage);
                    d->errorCode = Package::JobError::OldVersionRemovalError;
                }
            } else {
                d->errorMessage = i18n("Not installing version %1 of %2. Version %3 already installed.", meta.version(), meta.pluginId(), oldMeta.version());
                d->errorCode = Package::JobError::NewerVersionAlreadyInstalledError;
            }
        } else {
            d->errorMessage = i18n("%1 already exists", targetName);
            d->errorCode = Package::JobError::PackageAlreadyInstalledError;
        }

        if (d->errorCode != KJob::NoError) {
            d->installPath = targetName;
            return false;
        }
    }

    //install dependencies
    const QStringList dependencies = KPluginMetaData::readStringList(meta.rawData(), QStringLiteral("X-KPackage-Dependencies"));
    for(const QString &dep : dependencies) {
        QUrl depUrl(dep);
        if (!installDependency(depUrl)) {
            d->errorMessage = i18n("Could not install dependency: %1", dep);
            d->errorCode = Package::JobError::PackageCopyError;
            return false;
        }
    }

    if (archivedPackage) {
        // it's in a temp dir, so just move it over.
        const bool ok = copyFolder(path, targetName);
        removeFolder(path);
        if (!ok) {
            //qWarning() << "Could not move package to destination:" << targetName;
            d->errorMessage = i18n("Could not move package to destination: %1", targetName);
            d->errorCode = Package::JobError::PackageMoveError;
            return false;
        }
    } else {
        // it's a directory containing the stuff, so copy the contents rather
        // than move them
        const bool ok = copyFolder(path, targetName);
        if (!ok) {
            //qWarning() << "Could not copy package to destination:" << targetName;
            d->errorMessage = i18n("Could not copy package to destination: %1", targetName);
            d->errorCode = Package::JobError::PackageCopyError;
            return false;
        }
    }

    if (archivedPackage) {
        // no need to remove the temp dir (which has been successfully moved if it's an archive)
        tempdir.setAutoRemove(false);
    }


    indexDirectory(dest, QStringLiteral("kpluginindex.json"));


    d->installPath = targetName;

    //qWarning() << "Not updating kbuildsycoca4, since that will go away. Do it yourself for now if needed.";
    return true;
}
コード例 #11
0
ファイル: krvfsmodel.cpp プロジェクト: KDE/krusader
QVariant KrVfsModel::data(const QModelIndex& index, int role) const
{
    if (!index.isValid() || index.row() >= rowCount())
        return QVariant();
    vfile *vf = _vfiles.at(index.row());
    if (vf == 0)
        return QVariant();

    switch (role) {
    case Qt::FontRole:
        return _defaultFont;
    case Qt::EditRole: {
        if (index.column() == 0) {
            return vf->vfile_getName();
        }
        return QVariant();
    }
    case Qt::UserRole: {
        if (index.column() == 0) {
            return nameWithoutExtension(vf, false);
        }
        return QVariant();
    }
    case Qt::ToolTipRole:
    case Qt::DisplayRole: {
        switch (index.column()) {
        case KrViewProperties::Name: {
            return nameWithoutExtension(vf);
        }
        case KrViewProperties::Ext: {
            QString nameOnly = nameWithoutExtension(vf);
            const QString& vfName = vf->vfile_getName();
            return vfName.mid(nameOnly.length() + 1);
        }
        case KrViewProperties::Size: {
            if (vf->vfile_isDir() && vf->vfile_getSize() <= 0) {
                //HACK add <> brackets AFTER translating - otherwise KUIT thinks it's a tag
                static QString label = QString("<") +
                    i18nc("Show the string 'DIR' instead of file size in detailed view (for folders)", "DIR") + ">";
                return label;
            } else
                return (properties()->humanReadableSize) ?
                       KIO::convertSize(vf->vfile_getSize()) + "  " :
                       KRpermHandler::parseSize(vf->vfile_getSize()) + ' ';
        }
        case KrViewProperties::Type: {
            if (vf == _dummyVfile)
                return QVariant();
            QMimeDatabase db;
            QMimeType mt = db.mimeTypeForName(vf->vfile_getMime());
            if (mt.isValid())
                return mt.comment();
            return QVariant();
        }
        case KrViewProperties::Modified: {
            if (vf == _dummyVfile)
                return QVariant();
            time_t time = vf->vfile_getTime_t();
            struct tm* t = localtime((time_t *) & time);

            QDateTime tmp(QDate(t->tm_year + 1900, t->tm_mon + 1, t->tm_mday), QTime(t->tm_hour, t->tm_min));
            return QLocale().toString(tmp, QLocale::ShortFormat);
        }
        case KrViewProperties::Permissions: {
            if (vf == _dummyVfile)
                return QVariant();
            if (properties()->numericPermissions) {
                QString perm;
                return perm.sprintf("%.4o", vf->vfile_getMode() & PERM_BITMASK);
            }
            return vf->vfile_getPerm();
        }
        case KrViewProperties::KrPermissions: {
            if (vf == _dummyVfile)
                return QVariant();
            return KrView::krPermissionString(vf);
        }
        case KrViewProperties::Owner: {
            if (vf == _dummyVfile)
                return QVariant();
            return vf->vfile_getOwner();
        }
        case KrViewProperties::Group: {
            if (vf == _dummyVfile)
                return QVariant();
            return vf->vfile_getGroup();
        }
        default: return QString();
        }
        return QVariant();
    }
    case Qt::DecorationRole: {
        switch (index.column()) {
        case KrViewProperties::Name: {
            if (properties()->displayIcons) {
                if (_justForSizeHint)
                    return QPixmap(_view->fileIconSize(), _view->fileIconSize());
                return _view->getIcon(vf);
            }
            break;
        }
        default:
            break;
        }
        return QVariant();
    }
    case Qt::TextAlignmentRole: {
        switch (index.column()) {
        case KrViewProperties::Size:
            return QVariant(Qt::AlignRight | Qt::AlignVCenter);
        default:
            return QVariant(Qt::AlignLeft | Qt::AlignVCenter);
        }
        return QVariant();
    }
    case Qt::BackgroundRole:
    case Qt::ForegroundRole: {
        KrColorItemType colorItemType;
        colorItemType.m_activePanel = _view->isFocused();
        int actRow = index.row();
        if (_alternatingTable) {
            int itemNum = _view->itemsPerPage();
            if (itemNum == 0)
                itemNum++;
            if ((itemNum & 1) == 0)
                actRow += (actRow / itemNum);
        }
        colorItemType.m_alternateBackgroundColor = (actRow & 1);
        colorItemType.m_currentItem = _view->getCurrentIndex().row() == index.row();
        colorItemType.m_selectedItem = _view->isSelected(index);
        if (vf->vfile_isSymLink()) {
            if (vf->vfile_isBrokenLink())
                colorItemType.m_fileType = KrColorItemType::InvalidSymlink;
            else
                colorItemType.m_fileType = KrColorItemType::Symlink;
        } else if (vf->vfile_isDir())
            colorItemType.m_fileType = KrColorItemType::Directory;
        else if (vf->vfile_isExecutable())
            colorItemType.m_fileType = KrColorItemType::Executable;
        else
            colorItemType.m_fileType = KrColorItemType::File;

        KrColorGroup cols;
        KrColorCache::getColorCache().getColors(cols, colorItemType);

        if (colorItemType.m_selectedItem) {
            if (role == Qt::ForegroundRole)
                return cols.highlightedText();
            else
                return cols.highlight();
        }
        if (role == Qt::ForegroundRole)
            return cols.text();
        else
            return cols.background();
    }
    default:
        return QVariant();
    }
}
コード例 #12
0
void NetworkAccessManager::HandleDownload(QObject *object){
#ifdef WEBENGINEVIEW
    static QSet<QObject*> set;
    if(set.contains(object)) return;
    set << object;
    connect(object, &QObject::destroyed, [object](){ set.remove(object);});

    Application::AskDownloadPolicyIfNeed();

    DownloadItem *item = new DownloadItem(object);
    QWebEngineDownloadItem *orig_item = qobject_cast<QWebEngineDownloadItem*>(object);

    QString dir = Application::GetDownloadDirectory();
    QString filename;
    QString mime;
    QUrl url;
    if(orig_item){
        if(WebEngineView *w = qobject_cast<WebEngineView*>(Application::CurrentWidget())){
            if(TreeBank *tb = w->GetTreeBank()) tb->GoBackOrCloseForDownload(w);
        }
        filename = orig_item->path();
        mime = orig_item->mimeType();
        url = orig_item->url();
    } else {
        if(QuickWebEngineView *w = qobject_cast<QuickWebEngineView*>(Application::CurrentWidget())){
            if(TreeBank *tb = w->GetTreeBank()) tb->GoBackOrCloseForDownload(w);
        }
        filename = object->property("path").toString();
        mime = object->property("mimeType").toString();
        url = object->property("url").toUrl();
    }

    filename = filename.isEmpty() ? dir
        : dir + filename.split(QStringLiteral("/")).last();

    if(filename.isEmpty() ||
       Application::GetDownloadPolicy() == Application::Undefined_ ||
       Application::GetDownloadPolicy() == Application::AskForEachDownload){

        QString filter;

        QMimeDatabase db;
        QMimeType mimeType = db.mimeTypeForName(mime);
        if(!mimeType.isValid() || mimeType.isDefault()) mimeType = db.mimeTypeForFile(filename);
        if(!mimeType.isValid() || mimeType.isDefault()) mimeType = db.mimeTypeForUrl(url);

        if(mimeType.isValid() && !mimeType.isDefault()) filter = mimeType.filterString();

        filename = ModalDialog::GetSaveFileName_(QString(), filename, filter);
    }

    if(filename.isEmpty()){
        QMetaObject::invokeMethod(object, "cancel");
        item->deleteLater();
        return;
    }

    item->SetPath(filename);
    if(orig_item){
        orig_item->setPath(filename);
    } else {
        object->setProperty("path", filename);
    }
    QMetaObject::invokeMethod(object, "accept");
    MainWindow *win = Application::GetCurrentWindow();
    if(win && win->GetTreeBank()->GetNotifier())
        win->GetTreeBank()->GetNotifier()->RegisterDownload(item);

    QStringList path = filename.split(QStringLiteral("/"));
    path.removeLast();
    Application::SetDownloadDirectory(path.join(QStringLiteral("/")) + QStringLiteral("/"));
#else
    Q_UNUSED(object);
#endif
}
コード例 #13
0
ファイル: twittermicroblog.cpp プロジェクト: KDE/choqok
void TwitterMicroBlog::createPostWithAttachment(Choqok::Account *theAccount, Choqok::Post *post,
        const QString &mediumToAttach)
{
    if (mediumToAttach.isEmpty()) {
        TwitterApiMicroBlog::createPost(theAccount, post);
    } else {
        const QUrl picUrl = QUrl::fromUserInput(mediumToAttach);
        KIO::StoredTransferJob *picJob = KIO::storedGet(picUrl, KIO::Reload, KIO::HideProgressInfo);
        picJob->exec();
        if (picJob->error()) {
            qCCritical(CHOQOK) << "Job error:" << picJob->errorString();
            KMessageBox::detailedError(Choqok::UI::Global::mainWindow(),
                                       i18n("Uploading medium failed: cannot read the medium file."),
                                       picJob->errorString());
            return;
        }
        const QByteArray picData = picJob->data();
        if (picData.count() == 0) {
            qCCritical(CHOQOK) << "Cannot read the media file, please check if it exists.";
            KMessageBox::error(Choqok::UI::Global::mainWindow(),
                               i18n("Uploading medium failed: cannot read the medium file."));
            return;
        }

        TwitterAccount *account = qobject_cast<TwitterAccount *>(theAccount);
        QUrl url = account->uploadUrl();
        url.setPath(url.path() + QStringLiteral("/statuses/update_with_media.%1").arg(format));
        const QMimeDatabase db;
        QByteArray fileContentType = db.mimeTypeForUrl(picUrl).name().toUtf8();

        QMap<QString, QByteArray> formdata;
        formdata[QLatin1String("status")] = post->content.toUtf8();
        if (!post->replyToPostId.isEmpty()) {
            formdata[QLatin1String("in_reply_to_status_id")] = post->replyToPostId.toLatin1();
        }
        formdata[QLatin1String("source")] = QCoreApplication::applicationName().toLatin1();

        QMap<QString, QByteArray> mediafile;
        mediafile[QLatin1String("name")] = "media[]";
        mediafile[QLatin1String("filename")] = picUrl.fileName().toUtf8();
        mediafile[QLatin1String("mediumType")] = fileContentType;
        mediafile[QLatin1String("medium")] = picData;
        QList< QMap<QString, QByteArray> > listMediafiles;
        listMediafiles.append(mediafile);

        QByteArray data = Choqok::MediaManager::createMultipartFormData(formdata, listMediafiles);

        KIO::StoredTransferJob *job = KIO::storedHttpPost(data, url, KIO::HideProgressInfo) ;
        if (!job) {
            qCCritical(CHOQOK) << "Cannot create a http POST request!";
            return;
        }
        job->addMetaData(QStringLiteral("content-type"),
                         QStringLiteral("Content-Type: multipart/form-data; boundary=AaB03x"));
        job->addMetaData(QStringLiteral("customHTTPHeader"),
                         QStringLiteral("Authorization: ") +
                         QLatin1String(authorizationHeader(account, url, QOAuth::POST)));
        mCreatePostMap[ job ] = post;
        mJobsAccount[job] = theAccount;
        connect(job, SIGNAL(result(KJob*)),
                SLOT(slotCreatePost(KJob*)));
        job->start();
    }
}