Exemple #1
0
bool Import_Argo::loadFromXMIFile(const KZip &zipFile, const QString &fileName)
{
    const KArchiveFile *file = static_cast<const KArchiveFile*>(zipFile.directory()->entry(fileName));
    if (!file)
        return false;

#if QT_VERSION >= 0x050000
    QTemporaryDir tmpDir;
#else
    KTempDir tmpDir;
#endif
    tmpDir.setAutoRemove(true);

#if QT_VERSION >= 0x050000
    file->copyTo(tmpDir.path());
    QFile xmiFile(tmpDir.path() + QLatin1Char('/') + file->name());
#else
    file->copyTo(tmpDir.name());
    QFile xmiFile(tmpDir.name() + file->name());
#endif
    if(!xmiFile.open(QIODevice::ReadOnly)) {
        return false;
    }
    return UMLApp::app()->document()->loadFromXMI(xmiFile, 0);
}
Exemple #2
0
/*
    This tests whether the temporary dir really gets placed in QDir::tempPath
*/
void tst_QTemporaryDir::fileName()
{
    // Get QDir::tempPath and make an absolute path.
    QString tempPath = QDir::tempPath();
    QString absoluteTempPath = QDir(tempPath).absolutePath();
    QTemporaryDir dir;
    dir.setAutoRemove(true);
    QString fileName = dir.path();
    QVERIFY2(fileName.contains("/tst_qtemporarydir-"), qPrintable(fileName));
    QVERIFY(QDir(fileName).exists());
    // Get path to the temp dir, without the file name.
    QString absoluteFilePath = QFileInfo(fileName).absolutePath();
#if defined(Q_OS_WIN)
    absoluteFilePath = absoluteFilePath.toLower();
    absoluteTempPath = absoluteTempPath.toLower();
#endif
    QCOMPARE(absoluteFilePath, absoluteTempPath);
}
static PyObject *meth_QTemporaryDir_setAutoRemove(PyObject *sipSelf, PyObject *sipArgs)
{
    PyObject *sipParseErr = NULL;

    {
        bool a0;
        QTemporaryDir *sipCpp;

        if (sipParseArgs(&sipParseErr, sipArgs, "Bb", &sipSelf, sipType_QTemporaryDir, &sipCpp, &a0))
        {
            sipCpp->setAutoRemove(a0);

            Py_INCREF(Py_None);
            return Py_None;
        }
    }

    /* Raise an exception if the arguments couldn't be parsed. */
    sipNoMethod(sipParseErr, sipName_QTemporaryDir, sipName_setAutoRemove, doc_QTemporaryDir_setAutoRemove);

    return NULL;
}
Exemple #4
0
bool ModelPackager::zipModel() {
    QTemporaryDir dir;
    dir.setAutoRemove(true);
    QDir tempDir(dir.path());
    
    QByteArray nameField = _mapping.value(NAME_FIELD).toByteArray();
    tempDir.mkpath(nameField + "/textures");
    tempDir.mkpath(nameField + "/scripts");
    QDir fbxDir(tempDir.path() + "/" + nameField);
    QDir texDir(fbxDir.path() + "/textures");
    QDir scriptDir(fbxDir.path() + "/scripts");

    // Copy textures
    listTextures();
    if (!_textures.empty()) {
        QByteArray texdirField = _mapping.value(TEXDIR_FIELD).toByteArray();
        _texDir = _modelFile.path() + "/" + texdirField;
        copyTextures(_texDir, texDir);
    }

    // Copy scripts
    QByteArray scriptField = _mapping.value(SCRIPT_FIELD).toByteArray();
    _mapping.remove(SCRIPT_FIELD);
    if (scriptField.size() > 1) {
        tempDir.mkpath(nameField + "/scripts");
        _scriptDir = _modelFile.path() + "/" + scriptField;
        QDir wdir = QDir(_scriptDir);
        _mapping.remove(SCRIPT_FIELD);
        wdir.setSorting(QDir::Name | QDir::Reversed);
        auto list = wdir.entryList(QDir::NoDotAndDotDot | QDir::AllEntries);
        for (auto script : list) {
            auto sc = tempDir.relativeFilePath(scriptDir.path()) + "/" + QUrl(script).fileName();
            _mapping.insertMulti(SCRIPT_FIELD, sc);
        }
        copyDirectoryContent(wdir, scriptDir);
    } 
    
    // Copy LODs
    QVariantHash lodField = _mapping.value(LOD_FIELD).toHash();
    if (!lodField.empty()) {
        for (auto it = lodField.constBegin(); it != lodField.constEnd(); ++it) {
            QString oldPath = _modelFile.path() + "/" + it.key();
            QFile lod(oldPath);
            QString newPath = fbxDir.path() + "/" + QFileInfo(lod).fileName();
            if (lod.exists()) {
                lod.copy(newPath);
            }
        }
    }
    
    // Copy FBX
    QFile fbx(_fbxInfo.filePath());
    QByteArray filenameField = _mapping.value(FILENAME_FIELD).toByteArray();
    QString newPath = fbxDir.path() + "/" + QFileInfo(filenameField).fileName();
    fbx.copy(newPath);
    
    // Correct FST
    _mapping[FILENAME_FIELD] = tempDir.relativeFilePath(newPath);
    _mapping[TEXDIR_FIELD] = tempDir.relativeFilePath(texDir.path());

    for (auto multi : _mapping.values(SCRIPT_FIELD)) {
        multi.fromValue(tempDir.relativeFilePath(scriptDir.path()) + multi.toString());
    }
    // Copy FST
    QFile fst(tempDir.path() + "/" + nameField + ".fst");
    if (fst.open(QIODevice::WriteOnly)) {
        fst.write(FSTReader::writeMapping(_mapping));
        fst.close();
    } else {
        qCDebug(interfaceapp) << "Couldn't write FST file" << fst.fileName();
        return false;
    }
    
    
    QString saveDirPath = QFileDialog::getExistingDirectory(nullptr, "Save Model",
                                                        "", QFileDialog::ShowDirsOnly);
    if (saveDirPath.isEmpty()) {
        qCDebug(interfaceapp) << "Invalid directory" << saveDirPath;
        return false;
    }
    
    QDir saveDir(saveDirPath);
    copyDirectoryContent(tempDir, saveDir);
    return true;
}
Exemple #5
0
void DocumentTest::testImageLocalDirectory() {
  Tellico::Config::setImageLocation(Tellico::Config::ImagesInLocalDir);
  // the default collection will use a temporary directory as a local image dir
  QVERIFY(!Tellico::ImageFactory::localDir().isEmpty());

  QString tempDirName;

  QTemporaryDir tempDir;
  QVERIFY(tempDir.isValid());
  tempDir.setAutoRemove(true);
  tempDirName = tempDir.path();
  QString fileName = tempDirName + "/with-image.tc";
  QString imageDirName = tempDirName + "/with-image_files/";

  // copy a collection file that includes an image into the temporary directory
  QVERIFY(QFile::copy(QFINDTESTDATA("data/with-image.tc"), fileName));

  Tellico::Data::Document* doc = Tellico::Data::Document::self();
  QVERIFY(doc->openDocument(QUrl::fromLocalFile(fileName)));
  QCOMPARE(Tellico::ImageFactory::localDir(), imageDirName);

  Tellico::Data::CollPtr coll = doc->collection();
  QVERIFY(coll);
  QCOMPARE(coll->type(), Tellico::Data::Collection::Book);
  QCOMPARE(coll->title(), QLatin1String("My Books"));
  QCOMPARE(coll->entries().size(), 1);

  Tellico::Data::EntryPtr e = coll->entries().at(0);
  QVERIFY(e);
  QCOMPARE(e->field(QLatin1String("cover")), QLatin1String("17b54b2a742c6d342a75f122d615a793.jpeg"));

  // save the document, so the images get copied out of the .tc file into the local image directory
  QVERIFY(doc->saveDocument(QUrl::fromLocalFile(fileName)));
  // verify that backup file gets created
  QVERIFY(QFile::exists(fileName + '~'));

  // check that the local image directory is created with the image file inside
  QDir imageDir(imageDirName);
  QVERIFY(imageDir.exists());
  QVERIFY(imageDir.exists(e->field(QLatin1String("cover"))));

  // clear the internal image cache
  Tellico::ImageFactory::clean(true);

  // verify that the images are copied from the old directory when saving to a new file
  QString fileName2 = tempDirName + "/with-image2.tc";
  QString imageDirName2 = tempDirName + "/with-image2_files/";
  QVERIFY(doc->saveDocument(QUrl::fromLocalFile(fileName2)));
  QVERIFY(QFile::exists(fileName2));
  QDir imageDir2(imageDirName2);
  QVERIFY(imageDir2.exists());
  QVERIFY(imageDir2.exists(e->field(QLatin1String("cover"))));

  /*************************************************************************/
  /* now also verify image directory when file name has multiple periods */
  /* see https://bugs.kde.org/show_bug.cgi?id=348088 */
  /* also have to check backwards compatibility with prior behavior */
  /*************************************************************************/

  QString fileName3 = tempDirName + "/with-image.1.tc";
  QString imageDirName3 = tempDirName + "/with-image.1_files/";

  // copy the collection file, which no longer contains the images inside
  QVERIFY(QFile::copy(fileName, fileName3));
  QVERIFY(doc->openDocument(QUrl::fromLocalFile(fileName3)));
  QCOMPARE(Tellico::ImageFactory::localDir(), imageDirName3);
  QDir imageDir3(imageDirName3);

  // verify that the images can be loaded from the image directory that does NOT have multiple periods
  // since that was the behavior prior to the bug being fixed
  coll = doc->collection();
  e = coll->entries().at(0);
  // image should not be in the next image dir yet since we haven't saved
  QVERIFY(!imageDir3.exists(e->field(QLatin1String("cover"))));
  QVERIFY(!Tellico::ImageFactory::imageById(e->field("cover")).isNull());

  // now remove the first image from the first image directory, save the document, and verify that
  // the proper image exists and is written
  QVERIFY(imageDir.remove(e->field("cover")));
  QVERIFY(!imageDir.exists(e->field(QLatin1String("cover"))));
  QVERIFY(doc->saveDocument(QUrl::fromLocalFile(fileName3)));
  // now the file should exist in the proper location
  QVERIFY(imageDir3.exists(e->field(QLatin1String("cover"))));
  // clear the cache
  Tellico::ImageFactory::clean(true);
  QVERIFY(!Tellico::ImageFactory::imageById(e->field("cover")).isNull());

  // sanity check, the directory should not exists after QTemporaryDir destruction
  tempDir.remove();
  QVERIFY(!QDir(tempDirName).exists());
}
Exemple #6
0
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;
}
Exemple #7
0
bool ModelPackager::zipModel() {
    QTemporaryDir dir;
    dir.setAutoRemove(true);
    QDir tempDir(dir.path());
    
    QByteArray nameField = _mapping.value(NAME_FIELD).toByteArray();
    tempDir.mkpath(nameField + "/textures");
    QDir fbxDir(tempDir.path() + "/" + nameField);
    QDir texDir(fbxDir.path() + "/textures");
    
    // Copy textures
    listTextures();
    if (!_textures.empty()) {
        QByteArray texdirField = _mapping.value(TEXDIR_FIELD).toByteArray();
        _texDir = _modelFile.path() + "/" + texdirField;
        copyTextures(_texDir, texDir);
    }
    
    // Copy LODs
    QVariantHash lodField = _mapping.value(LOD_FIELD).toHash();
    if (!lodField.empty()) {
        for (auto it = lodField.constBegin(); it != lodField.constEnd(); ++it) {
            QString oldPath = _modelFile.path() + "/" + it.key();
            QFile lod(oldPath);
            QString newPath = fbxDir.path() + "/" + QFileInfo(lod).fileName();
            if (lod.exists()) {
                lod.copy(newPath);
            }
        }
    }
    
    // Copy FBX
    QFile fbx(_fbxInfo.filePath());
    QByteArray filenameField = _mapping.value(FILENAME_FIELD).toByteArray();
    QString newPath = fbxDir.path() + "/" + QFileInfo(filenameField).fileName();
    fbx.copy(newPath);
    
    // Correct FST
    _mapping[FILENAME_FIELD] = tempDir.relativeFilePath(newPath);
    _mapping[TEXDIR_FIELD] = tempDir.relativeFilePath(texDir.path());
    
    // Copy FST
    QFile fst(tempDir.path() + "/" + nameField + ".fst");
    if (fst.open(QIODevice::WriteOnly)) {
        fst.write(FSTReader::writeMapping(_mapping));
        fst.close();
    } else {
        qCDebug(interfaceapp) << "Couldn't write FST file" << fst.fileName();
        return false;
    }
    
    
    QString saveDirPath = QFileDialog::getExistingDirectory(nullptr, "Save Model",
                                                        "", QFileDialog::ShowDirsOnly);
    if (saveDirPath.isEmpty()) {
        qCDebug(interfaceapp) << "Invalid directory" << saveDirPath;
        return false;
    }
    
    QDir saveDir(saveDirPath);
    copyDirectoryContent(tempDir, saveDir);
    return true;
}