コード例 #1
0
void tst_QTemporaryDir::autoRemove()
{
    // Test auto remove
    QString dirName;
    {
        QTemporaryDir dir("tempXXXXXX");
        dir.setAutoRemove(true);
        QVERIFY(dir.isValid());
        dirName = dir.path();
    }
#ifdef Q_OS_WIN
    // Windows seems unreliable here: sometimes it says the directory still exists,
    // immediately after we deleted it.
    QTRY_VERIFY(!QDir(dirName).exists());
#else
    QVERIFY(!QDir(dirName).exists());
#endif

    // Test if disabling auto remove works.
    {
        QTemporaryDir dir("tempXXXXXX");
        dir.setAutoRemove(false);
        QVERIFY(dir.isValid());
        dirName = dir.path();
    }
    QVERIFY(QDir(dirName).exists());
    QVERIFY(QDir().rmdir(dirName));
    QVERIFY(!QDir(dirName).exists());

    // Do not explicitly call setAutoRemove (tests if it really is the default as documented)
    {
        QTemporaryDir dir("tempXXXXXX");
        QVERIFY(dir.isValid());
        dirName = dir.path();
    }
#ifdef Q_OS_WIN
    QTRY_VERIFY(!QDir(dirName).exists());
#else
    QVERIFY(!QDir(dirName).exists());
#endif

    // Test autoremove with files and subdirs in the temp dir
    {
        QTemporaryDir tempDir("tempXXXXXX");
        QVERIFY(tempDir.isValid());
        dirName = tempDir.path();
        QDir dir(dirName);
        QVERIFY(dir.mkdir(QString::fromLatin1("dir1")));
        QVERIFY(dir.mkdir(QString::fromLatin1("dir2")));
        QVERIFY(dir.mkdir(QString::fromLatin1("dir2/nested")));
        QFile file(dirName + "/dir1/file");
        QVERIFY(file.open(QIODevice::WriteOnly));
        QCOMPARE(file.write("Hello"), 5LL);
    }
#ifdef Q_OS_WIN
    QTRY_VERIFY(!QDir(dirName).exists());
#else
    QVERIFY(!QDir(dirName).exists());
#endif
}
コード例 #2
0
PartsEditorView * PartsEditorViewsWidget::createViewImageWidget(
    SketchModel* sketchModel, WaitPushUndoStack *undoStack,
    ViewLayer::ViewIdentifier viewId, QString iconFileName, QString startText,
    ConnectorsInfoWidget* info, ViewLayer::ViewLayerID viewLayerId, ItemBase * fromItem)
{

    PartsEditorView * viw = new PartsEditorView(viewId,tempDir(),showingTerminalPoints(),PartsEditorMainWindow::emptyViewItem(iconFileName,startText),this, 150, false, fromItem);
    viw->setSketchModel(sketchModel);
    viw->setUndoStack(undoStack);
    viw->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    viw->addViewLayer(new ViewLayer(viewLayerId, true, 2.5));

    m_views[viewId] = viw;

    connect(
        info, SIGNAL(connectorSelected(const QString&)),
        viw, SLOT(informConnectorSelection(const QString&))
    );
    connect(
        viw, SIGNAL(connectorsFoundSignal(ViewLayer::ViewIdentifier, const QList< QPointer<Connector> > &)),
        info, SLOT(syncNewConnectors(ViewLayer::ViewIdentifier, const QList< QPointer<Connector> > &))
    );
    connect(
        info, SIGNAL(existingConnectorSignal(ViewLayer::ViewIdentifier, const QString &, Connector*, Connector*)),
        viw, SLOT(checkConnectorLayers(ViewLayer::ViewIdentifier, const QString &, Connector*, Connector*))
    );

    connect(
        info, SIGNAL(setMismatching(ViewLayer::ViewIdentifier, const QString &, bool)),
        viw, SLOT(setMismatching(ViewLayer::ViewIdentifier, const QString &, bool))
    );

    return viw;
}
コード例 #3
0
void ServiceContextMongoDTest::setUp() {
    Client::initThread(getThreadName());

    auto const serviceContext = getServiceContext();

    auto logicalClock = stdx::make_unique<LogicalClock>(serviceContext);
    LogicalClock::set(serviceContext, std::move(logicalClock));

    if (!serviceContext->getGlobalStorageEngine()) {
        // When using the "ephemeralForTest" storage engine, it is fine for the temporary directory
        // to go away after the global storage engine is initialized.
        unittest::TempDir tempDir("service_context_d_test_fixture");
        storageGlobalParams.dbpath = tempDir.path();
        storageGlobalParams.engine = "ephemeralForTest";
        storageGlobalParams.engineSetByUser = true;

        checked_cast<ServiceContextMongoD*>(serviceContext)->createLockFile();
        serviceContext->initializeGlobalStorageEngine();
        serviceContext->setOpObserver(stdx::make_unique<OpObserverNoop>());
    }

    // Set up UUID Catalog observer. This is necessary because the Collection destructor contains an
    // invariant to ensure the UUID corresponding to that Collection object is no longer associated
    // with that Collection object in the UUIDCatalog. UUIDs may be registered in the UUIDCatalog
    // directly in certain code paths, but they can only be removed from the UUIDCatalog via a
    // UUIDCatalogObserver. It is therefore necessary to install the observer to ensure the
    // invariant in the Collection destructor is not triggered.
    auto observerRegistry = stdx::make_unique<OpObserverRegistry>();
    observerRegistry->addObserver(stdx::make_unique<UUIDCatalogObserver>());
    serviceContext->setOpObserver(std::unique_ptr<OpObserver>(observerRegistry.release()));
}
コード例 #4
0
ファイル: parttest.cpp プロジェクト: Saljack/osp-okular
void PartTest::testFowardPDF()
{
    QFETCH(QString, dir);

    QVariantList dummyArgs;
    Okular::Part part(NULL, NULL, dummyArgs, KGlobal::mainComponent());

    KTempDir tempDir(dir);
    QFile f(KDESRCDIR "data/synctextest.tex");
    const QString texDestination = tempDir.name() + "synctextest.tex";
    QVERIFY(f.copy(texDestination));

    QProcess process;
    process.setWorkingDirectory(tempDir.name());
    process.start("pdflatex", QStringList() << "-synctex=1" << "-interaction=nonstopmode" << texDestination);
    process.waitForFinished();

    const QString pdfResult = tempDir.name() + "synctextest.pdf";
    
    QVERIFY(QFile::exists(pdfResult));
    
    part.openDocument(pdfResult);
    part.m_document->setViewportPage(0);
    QCOMPARE(part.m_document->currentPage(), 0u);
    part.closeUrl();
    
    KUrl u(pdfResult);
    u.setHTMLRef("src:100" + texDestination);
    part.openUrl(u);
    QCOMPARE(part.m_document->currentPage(), 1u);
}
コード例 #5
0
ファイル: bpfile_UNIX.cpp プロジェクト: Go-LiDth/platform
bfs::path
getTempDirectory()
{
    bfs::path tempDir("/tmp/YahooBrowserPlus");
    boost::filesystem::create_directories(tempDir);
    return tempDir;
}
コード例 #6
0
ファイル: PluginProcessor.cpp プロジェクト: OpenDAWN/mcfx
void Mcfx_convolverAudioProcessor::setStateInformation (const void* data, int sizeInBytes)
{
    // You should use this method to restore your parameters from this memory block,
    // whose contents will have been created by the getStateInformation() call.
    
    ScopedPointer<XmlElement> xmlState (getXmlFromBinary (data, sizeInBytes));
    
    if (xmlState != nullptr)
    {
        String newPresetDir;
        
        // make sure that it's actually our type of XML object..
        if (xmlState->hasTagName ("MYPLUGINSETTINGS"))
        {
            // ok, now pull out our parameters..
            activePreset  = xmlState->getStringAttribute("activePreset", "");
            
            newPresetDir = xmlState->getStringAttribute("presetDir", presetDir.getFullPathName());
            
            _ConvBufferSize = xmlState->getIntAttribute("ConvBufferSize", _ConvBufferSize);
        }
        
        if (activePreset.isNotEmpty()) {
            LoadPresetByName(activePreset);
        }
        
        File tempDir(newPresetDir);
        if (tempDir.exists()) {
            presetDir = tempDir;
            SearchPresets(presetDir);
        }
    }
}
コード例 #7
0
terrama2::core::DataSetSeries terrama2::core::DataAccessorDcpToa5::getSeries(const std::string& uri,
        const terrama2::core::Filter& filter,
        terrama2::core::DataSetPtr dataSet) const

{
    std::string mask = getMask(dataSet);
    std::string folder = getFolder(dataSet);

    QTemporaryDir tempBaseDir;
    if(!tempBaseDir.isValid())
    {
        QString errMsg = QObject::tr("Can't create temporary folder.");
        TERRAMA2_LOG_ERROR() << errMsg;
        throw DataAccessException() << ErrorDescription(errMsg);
    }

    QDir tempDir(tempBaseDir.path());
    tempDir.mkdir(QString::fromStdString(folder));
    tempDir.cd(QString::fromStdString(folder));

    QUrl url((uri+"/"+folder+"/"+mask).c_str());
    QFileInfo originalInfo(url.path());

    QFile file(url.path());
    QFile tempFile(tempDir.path()+"/"+originalInfo.fileName());
    if(!file.open(QIODevice::ReadOnly))
    {
        QString errMsg = QObject::tr("Can't open file: dataset %1.").arg(dataSet->id);
        TERRAMA2_LOG_ERROR() << errMsg;
        throw DataAccessException() << ErrorDescription(errMsg);
    }

    if(!tempFile.open(QIODevice::ReadWrite))
    {
        QString errMsg = QObject::tr("Can't open temporary file: dataset %1.").arg(dataSet->id);
        TERRAMA2_LOG_ERROR() << errMsg;
        throw DataAccessException() << ErrorDescription(errMsg);
    }

    file.readLine();//ignore first line
    tempFile.write(file.readLine()); //headers line

    //ignore third and fourth lines
    file.readLine();
    file.readLine();

    //read all file
    tempFile.write(file.readAll()); //headers line

    //update file path
    std::string tempUri = "file://"+tempBaseDir.path().toStdString();

    file.close();
    tempFile.close();

    auto dataSeries = terrama2::core::DataAccessorFile::getSeries(tempUri, filter, dataSet);

    return dataSeries;
}
コード例 #8
0
ファイル: DataArrayTest.cpp プロジェクト: thewtex/DREAM3D
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void RemoveTestFiles()
{
#if REMOVE_TEST_FILES
  QFile::remove(UnitTest::DataArrayTest::TestFile);
  QDir tempDir(UnitTest::DataArrayTest::TestDir);
  tempDir.removeRecursively();
#endif
}
コード例 #9
0
/*!
 \brief 先清理temp_project中的文件,然后将保存的文件保存在temp_project目录中,然后再将目标目录清理干净,最后将temp_project目录中的文件copy到目标目录中

 \fn CMainWindow::on_actionSave_triggered
*/
void CMainWindow::on_actionSave_triggered()
{
    emit signal_ClearDebug();
    emit signal_ShowMessageDebug(0,QString("开始保存... %1").arg(QDateTime::currentDateTime().toString("yyyy/MM/dd hh:mm:ss.zzz")));
    ///< 清理掉temp_project目录中的文件
    QDir tempDir("temp_project");
    if (tempDir.exists())
    {
        qDebug()<<__func__<<__LINE__<<"有";
        DeletePathFile(QDir::currentPath()+"/temp_project");
    }else
    {
        qDebug()<<__func__<<__LINE__<<"无";
        tempDir.mkdir(QDir::currentPath()+"/temp_project");
    }
//    qDebug()<<__func__<<__LINE__<<__FILE__<<m_pTreeWidget->topLevelItemCount();

    ///< 生成配置文件,生成在temp目录中
    for (int nTreeItemCount = 0; nTreeItemCount < m_pTreeWidget->topLevelItemCount(); ++nTreeItemCount)
    {
        if (m_pTreeWidget->topLevelItem(nTreeItemCount)->type() == CGI_SCADA_DLL_I::TreeItemType_Undefined)
        {
            continue;
        }else
        {
            ((CGI_SCADA_DLL_I*)m_pTreeWidget->topLevelItem(nTreeItemCount))->SaveAction();
        }
    }

    DeletePathFile(m_strProjectPath);///< 清理掉目标目录中的文件

    /// 将temp_project目录中的文件复制到目标目录
    if (!tempDir.exists())
        return ;
    tempDir.setFilter(QDir::Dirs|QDir::Files);
    tempDir.setSorting(QDir::DirsFirst);
    QFileInfoList list = tempDir.entryInfoList();
    int i=0;
    do{
        QFileInfo fileInfo = list.at(i);
        if((fileInfo.fileName()==".")|(fileInfo.fileName()==".."))
        {
            i++;
            continue;
        }
        bool bisDir=fileInfo.isDir();
        if(bisDir)
        {
            qDebug()<<(QString("%1 %2 %3").arg(fileInfo.size(), 10).arg(fileInfo.fileName(),10).arg(fileInfo.path()))<<fileInfo.absoluteFilePath();
        }else{
            qDebug()<<(QString("%1 %2 %3").arg(fileInfo.size(), 10).arg(fileInfo.fileName(),10).arg(fileInfo.path()))<<fileInfo.absoluteFilePath()<<fileInfo.baseName();
            QFile::copy(fileInfo.absoluteFilePath(),QString("%1/%2").arg(m_strProjectPath).arg(fileInfo.fileName()));
        }
        i++;
    }while(i<list.size());
    emit signal_ShowMessageDebug(0,QString("保存完毕"));
}
コード例 #10
0
static WCHAR *GetTempUninstallerPath()
{
    ScopedMem<WCHAR> tempDir(GetValidTempDir());
    if (!tempDir)
        return NULL;
    // Using fixed (unlikely) name instead of GetTempFileName()
    // so that we don't litter temp dir with copies of ourselves
    return path::Join(tempDir, L"sum~inst.exe");
}
コード例 #11
0
ファイル: placesmodeltest.cpp プロジェクト: kursusHC/homerun
void PlacesModelTest::testProxyDirModelSortOrder()
{
    KTempDir tempDir("placesmodeltest");
    QDir dir(tempDir.name());
    QStringList dirNames = QStringList() << "aaa" << "Abc" << "Hello";
    QStringList fileNames = QStringList() << "foo" << "Goo" << "hoo" << "img1" << "img2" << "img10";

    Q_FOREACH(const QString &name, fileNames) {
        touch(dir.absoluteFilePath(name));
    }
コード例 #12
0
void FirewallCodeViewer::showDiff()
{
    QString fileName = this->files.at(ui->fileSelector->currentIndex());
    QString autoCompiledFileName;

    QDir tempDir(m_project->getTemporaryDirPath());

    if (tempDir.exists())
        autoCompiledFileName = QString(tempDir.absolutePath()).append("/").append(fileName.split("/").last());

    showDiff(autoCompiledFileName, fileName);
}
コード例 #13
0
void tst_QTemporaryDir::fileTemplate()
{
    QFETCH(QString, constructorTemplate);
    QFETCH(QString, prefix);

    QTemporaryDir tempDir(constructorTemplate);

    QVERIFY(tempDir.isValid());

    QString dirName = QDir(tempDir.path()).dirName();
    if (prefix.length())
        QCOMPARE(dirName.left(prefix.length()), prefix);
}
コード例 #14
0
ファイル: tempdir.cpp プロジェクト: flying-sheep/ktikz
bool TempDir::cleanUp()
{
	const QString dirName = name();
	if (dirName.isEmpty()) // we must return in this case, otherwise in the QDir constructor below, the program's working directory is used and we really don't want to remove the files in that
		return false;

	QDir tempDir(dirName);
	if (!tempDir.exists())
		return false;

	bool success = true;
	const QStringList fileList = tempDir.entryList(QDir::NoDotAndDotDot | QDir::AllEntries);
	Q_FOREACH (const QString &fileName, fileList)
		success = success && tempDir.remove(fileName);
	return success;
}
コード例 #15
0
void OptionsDialog::setTempDirPath()
{
    // Set default temp dir
    QString tempDirPath = QDir::tempPath();

    TextFileHandler::PathsConfig config;

    TextFileHandler::readPathsConfigFile( config );

    if ( ! config.tempDirPath.isEmpty() )
    {
        tempDirPath = config.tempDirPath;
    }

    // Set up validator
    m_directoryValidator = new DirectoryValidator();
    m_ui->lineEdit_TempDir->setValidator( m_directoryValidator );

    QObject::connect( m_directoryValidator, SIGNAL( isValid(bool) ),
                      this, SLOT( displayDirValidityText(bool) ) );

    m_ui->lineEdit_TempDir->setText( tempDirPath );

    // Create a sub-dir with a unique name; there may be multiple instances of Shuriken running
    QDir tempDir( tempDirPath );

    QString userName = QProcessEnvironment::systemEnvironment().value( "USER", "user" );

    QString pid;
    pid.setNum( QCoreApplication::applicationPid() );

    QString subDirName( "shuriken-" );
    subDirName.append( userName );
    subDirName.append( "-" );
    subDirName.append( pid );

    bool isSuccessful = tempDir.mkdir( subDirName );

    if ( isSuccessful )
    {
        m_tempDirPath = tempDir.absoluteFilePath( subDirName );
    }
}
コード例 #16
0
ファイル: k3bmixeddoc.cpp プロジェクト: KDE/k3b
bool K3b::MixedDoc::saveDocumentData( QDomElement* docElem )
{
    QDomDocument doc = docElem->ownerDocument();
    saveGeneralDocumentData( docElem );

    QDomElement audioElem = doc.createElement( "audio" );
    m_audioDoc->saveDocumentData( &audioElem );
    docElem->appendChild( audioElem );

    QDomElement dataElem = doc.createElement( "data" );
    m_dataDoc->saveDocumentData( &dataElem );
    docElem->appendChild( dataElem );

    QDomElement mixedElem = doc.createElement( "mixed" );
    docElem->appendChild( mixedElem );

    QDomElement bufferFilesElem = doc.createElement( "remove_buffer_files" );
    bufferFilesElem.appendChild( doc.createTextNode( removeImages() ? "yes" : "no" ) );
    mixedElem.appendChild( bufferFilesElem );

    QDomElement imagePathElem = doc.createElement( "image_path" );
    imagePathElem.appendChild( doc.createTextNode( tempDir() ) );
    mixedElem.appendChild( imagePathElem );

    QDomElement mixedTypeElem = doc.createElement( "mixed_type" );
    switch( mixedType() ) {
    case DATA_FIRST_TRACK:
        mixedTypeElem.appendChild( doc.createTextNode( "first_track" ) );
        break;
    case DATA_LAST_TRACK:
        mixedTypeElem.appendChild( doc.createTextNode( "last_track" ) );
        break;
    case DATA_SECOND_SESSION:
        mixedTypeElem.appendChild( doc.createTextNode( "second_session" ) );
        break;
    }
    mixedElem.appendChild( mixedTypeElem );

    setModified( false );

    return true;
}
コード例 #17
0
ファイル: tempdir.cpp プロジェクト: flying-sheep/ktikz
TempDir::~TempDir()
{
	// removing all temporary files
	qDebug("removing temporary files");

	if (!cleanUp())
	{
		qCritical("Error: removing temporary files failed");
		return;
	}

	// remove temp dir if empty
	QDir tempDir(m_name);
	if (tempDir.exists())
	{
		const QString dirName = tempDir.dirName();
		if (!tempDir.cdUp() || !tempDir.rmdir(dirName))
			qCritical("Error: removing temporary directory failed");
	}
}
コード例 #18
0
void OptionsDialog::reject()
{
    tearDownMidiInputTestSynth();

    m_ui->comboBox_AudioBackend->setCurrentIndex( m_originalBackendIndex );
    on_comboBox_AudioBackend_activated( m_originalBackendIndex );

    m_deviceManager.setAudioDeviceSetup( m_originalConfig, true );

    updateAudioDeviceComboBox();
    updateOutputChannelComboBox();
    updateSampleRateComboBox();
    updateBufferSizeComboBox();

    QDir tempDir( m_tempDirPath );
    tempDir.cdUp();
    m_ui->lineEdit_TempDir->setText( tempDir.absolutePath() );

    QDialog::reject();
}
コード例 #19
0
ScriptsTabController::ScriptsTabController()
  : MainTabController(new ScriptsTabView(nullptr)), scriptsTabView(dynamic_cast<ScriptsTabView *>(mainContentWidget()))
{
  auto app = OSAppBase::instance();
  boost::optional<path> tempDir = app->tempDir();
  OS_ASSERT(tempDir);

  // save the current osm to a temp location
  app->measureManager().saveTempModel(*tempDir);

  // update measures
  app->currentDocument()->disable();
  app->measureManager().updateMeasuresLists();
  app->currentDocument()->enable();

  m_workflowController = QSharedPointer<openstudio::measuretab::WorkflowController>(new openstudio::measuretab::WorkflowController(OSAppBase::instance()));
  m_workflowSectionItemDelegate = QSharedPointer<openstudio::measuretab::WorkflowSectionItemDelegate>(new openstudio::measuretab::WorkflowSectionItemDelegate());

  scriptsTabView->workflowView->setListController(m_workflowController);
  scriptsTabView->workflowView->setDelegate(m_workflowSectionItemDelegate);
}
コード例 #20
0
/*--- Prepare download, then issue the FTP commands ---*/
void Downloader::DownloadFile(QString dir, QString file)
{
    qDebug() << "Downloader::DownloadFile " + dir + file;

    // Data
    QUrl fileUrl(*baseUrl);
    QNetworkRequest r;
    QDir tempDir(".");

    // Setup
    downloadedSize = 0;
    lastDownloadedSize = 0;
    currentFtpDir = dir;
    currentFtpFile = file;
    currentFile = new QFile(currentFtpDir + currentFtpFile);
    fileUrl.setPath(FTP_UPDATE_ROOT + currentFtpDir + currentFtpFile);
    r.setUrl(fileUrl);

    // Local file preparation
    if (currentFtpDir.length() > 0)
    {
        tempDir.mkpath(currentFtpDir);
    }
    if (currentFtpFile.length() > 0 && currentFile->exists())
    {
        currentFile->remove();
    }
    currentFile->open(QIODevice::WriteOnly);

    // Download command
    bDownloading = true;
    reply = ftp->get(r);
    reply->setReadBufferSize(FTP_PART_SIZE);
    connect(reply, SIGNAL(readyRead()), this, SLOT(FilePart()));
    connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(FileError(QNetworkReply::NetworkError)));

    // Timers
    timeoutTimer->setSingleShot(true);
    timeoutTimer->start(FTP_TIMEOUT);
}
コード例 #21
0
ファイル: tempdir.cpp プロジェクト: flying-sheep/ktikz
TempDir::TempDir(const QString &directoryPrefix, int mode)
{
	Q_UNUSED(mode);

	// use QTemporaryFile to obtain a unique name
	const QString dirPrefix = (directoryPrefix.isEmpty() ? QDir::tempPath() + QLatin1String("/qtikz") : directoryPrefix);
	QTemporaryFile *tempFile = new QTemporaryFile(dirPrefix + QLatin1String("XXXXXX"));
	if (tempFile->open())
	{
		const QFileInfo tempFileInfo = QFileInfo(*tempFile);
		m_name = tempFileInfo.absolutePath() + QLatin1Char('/') + tempFileInfo.completeBaseName();
	}
	else
		qCritical("Error: could not create temporary directory");
	delete tempFile; // this also deletes the file on disk, so the creation of a directory with the same name below can be done successfully

	// we have a unique name, let's create the directory
	QDir tempDir(m_name);
	const QString dirName = tempDir.dirName();
	if (!tempDir.cdUp() || !tempDir.mkdir(dirName)) // by construction, QDir::temp() is the parent of tempDir
		m_name.clear();
}
コード例 #22
0
ファイル: WorkerThread.cpp プロジェクト: MrFlibb/WHDRun
void WorkerThread::runRezip() {
	emit(beginRunRezip());
	emit(stageEvent("Finding and saving modified game data"));
	
	emit(infoEvent("Identifying modified files (including previously modified files)"));
	QMap<QString, uint32_t> newChecksums;
	collectFiles(m_tempPath, &newChecksums);
	QStringList modified; // TODO: also determine removed files?
	QMapIterator<QString, uint32_t> i(newChecksums);
	while (i.hasNext()) {
		i.next();
		if(!m_checksums.contains(i.key()) || m_checksums[i.key()] != i.value()) { modified << i.key(); }
	}
	
	if(modified.empty()) {
		emit(infoEvent("No modified files found"));
		return;
	}
	
	emit(infoEvent("Rezipping modified files"));

	QString gameFileBase = QFileInfo(m_gameFileName).baseName();
	QString diffFileName = m_dataPath + "/" + gameFileBase + __WHDRun__DiffSuffix;
	CZipArchive zip;
	try {
		zip.Open(diffFileName.toUtf8(), CZipArchive::zipCreate);

		// TODO: review that path finding stuff some time.
		QDir tempDir(m_tempPath); tempDir.makeAbsolute();
		foreach(QString externalPath, modified) {
			QDir externalDir(externalPath); externalDir.makeAbsolute();
			QString internalPath = tempDir.relativeFilePath(externalDir.absolutePath());
			zip.AddNewFile((LPCTSTR)externalPath.toUtf8(),
				(LPCTSTR)internalPath.toUtf8(), CZipCompressor::levelBest);
		}

		zip.Close();
	} catch(CZipException ex) {
コード例 #23
0
ファイル: unixcommand.cpp プロジェクト: aarnt/octoxbps
/*
 * Does some garbage collection, removing uneeded files
 */
void UnixCommand::removeTemporaryFiles()
{
  QDir tempDir(QDir::tempPath());
  QStringList nameFilters;
  nameFilters << "qtsingleapp*" << "gpg*" << ".qt_temp_*";
  QFileInfoList list = tempDir.entryInfoList(nameFilters, QDir::Dirs | QDir::Files | QDir::System | QDir::Hidden);

  foreach(QFileInfo file, list){
    QFile fileAux(file.filePath());

    if (!file.isDir()){
      fileAux.remove();
    }
    else{
      QDir dir(file.filePath());
      QFileInfoList listd = dir.entryInfoList(QDir::Files | QDir::System);

      foreach(QFileInfo filed, listd){
        QFile fileAuxd(filed.filePath());
        fileAuxd.remove();
      }

      dir.rmdir(file.filePath());
    }
コード例 #24
0
MatrixFile::MatrixFile(QString fileBase, Mode mode,
                       size_t cellSize, size_t width, size_t height) :
    m_fd(-1),
    m_mode(mode),
    m_flags(0),
    m_fmode(0),
    m_cellSize(cellSize),
    m_width(width),
    m_height(height),
    m_headerSize(2 * sizeof(size_t)),
    m_setColumns(0),
    m_autoClose(false),
    m_readyToReadColumn(-1)
{
    Profiler profiler("MatrixFile::MatrixFile", true);

#ifdef DEBUG_MATRIX_FILE
    std::cerr << "MatrixFile::MatrixFile(" << fileBase.toStdString() << ", " << int(mode) << ", " << cellSize << ", " << width << ", " << height << ")" << std::endl;
#endif

    m_createMutex.lock();

    QDir tempDir(TempDirectory::getInstance()->getPath());
    QString fileName(tempDir.filePath(QString("%1.mfc").arg(fileBase)));
    bool newFile = !QFileInfo(fileName).exists();

    if (newFile && m_mode == ReadOnly) {
        std::cerr << "ERROR: MatrixFile::MatrixFile: Read-only mode "
                  << "specified, but cache file does not exist" << std::endl;
        throw FileNotFound(fileName);
    }

    if (!newFile && m_mode == WriteOnly) {
        std::cerr << "ERROR: MatrixFile::MatrixFile: Write-only mode "
                  << "specified, but file already exists" << std::endl;
        throw FileOperationFailed(fileName, "create");
    }

    m_flags = 0;
    m_fmode = S_IRUSR | S_IWUSR;

    if (m_mode == WriteOnly) {
        m_flags = O_WRONLY | O_CREAT;
    } else {
        m_flags = O_RDONLY;
    }

#ifdef _WIN32
    m_flags |= O_BINARY;
#endif

#ifdef DEBUG_MATRIX_FILE
    std::cerr << "MatrixFile(" << this << ")::MatrixFile: opening " << fileName.toStdString() << "..." << std::endl;
#endif

    if ((m_fd = ::open(fileName.toLocal8Bit(), m_flags, m_fmode)) < 0) {
        ::perror("Open failed");
        std::cerr << "ERROR: MatrixFile::MatrixFile: "
                  << "Failed to open cache file \""
                  << fileName.toStdString() << "\"";
        if (m_mode == WriteOnly) std::cerr << " for writing";
        std::cerr << std::endl;
        throw FailedToOpenFile(fileName);
    }

    m_createMutex.unlock();

#ifdef DEBUG_MATRIX_FILE
    std::cerr << "MatrixFile(" << this << ")::MatrixFile: fd is " << m_fd << std::endl;
#endif

    if (newFile) {
        initialise(); // write header and "unwritten" column tags
    } else {
        size_t header[2];
        if (::read(m_fd, header, 2 * sizeof(size_t)) < 0) {
            ::perror("MatrixFile::MatrixFile: read failed");
            std::cerr << "ERROR: MatrixFile::MatrixFile: "
                      << "Failed to read header (fd " << m_fd << ", file \""
                      << fileName.toStdString() << "\")" << std::endl;
            throw FileReadFailed(fileName);
        }
        if (header[0] != m_width || header[1] != m_height) {
            std::cerr << "ERROR: MatrixFile::MatrixFile: "
                      << "Dimensions in file header (" << header[0] << "x"
                      << header[1] << ") differ from expected dimensions "
                      << m_width << "x" << m_height << std::endl;
            throw FailedToOpenFile(fileName);
        }
    }

    m_fileName = fileName;
    ++m_refcount[fileName];

#ifdef DEBUG_MATRIX_FILE
    std::cerr << "MatrixFile[" << m_fd << "]::MatrixFile: File " << fileName.toStdString() << ", ref " << m_refcount[fileName] << std::endl;

    std::cerr << "MatrixFile[" << m_fd << "]::MatrixFile: Done, size is " << "(" << m_width << ", " << m_height << ")" << std::endl;
#endif

    ++totalCount;
    ++openCount;
}
コード例 #25
0
ファイル: ModelPackager.cpp プロジェクト: Nex-Pro/hifi
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;
}
コード例 #26
0
ファイル: pspecific_mac.cpp プロジェクト: jubalh/tdesktop
void PsUpdateDownloader::unpackUpdate() {
    QByteArray packed;
	if (!outputFile.open(QIODevice::ReadOnly)) {
		LOG(("Update Error: cant read updates file!"));
		return fatalFail();
	}
#ifdef Q_OS_WIN // use Lzma SDK for win
	const int32 hSigLen = 128, hShaLen = 20, hPropsLen = LZMA_PROPS_SIZE, hOriginalSizeLen = sizeof(int32), hSize = hSigLen + hShaLen + hPropsLen + hOriginalSizeLen; // header
#else
	const int32 hSigLen = 128, hShaLen = 20, hPropsLen = 0, hOriginalSizeLen = sizeof(int32), hSize = hSigLen + hShaLen + hOriginalSizeLen; // header
#endif
	QByteArray compressed = outputFile.readAll();
	int32 compressedLen = compressed.size() - hSize;
	if (compressedLen <= 0) {
		LOG(("Update Error: bad compressed size: %1").arg(compressed.size()));
		return fatalFail();
	}
	outputFile.close();

	QString tempDirPath = cWorkingDir() + qsl("tupdates/temp"), readyDirPath = cWorkingDir() + qsl("tupdates/ready");
	deleteDir(tempDirPath);
	deleteDir(readyDirPath);

	QDir tempDir(tempDirPath), readyDir(readyDirPath);
	if (tempDir.exists() || readyDir.exists()) {
		LOG(("Update Error: cant clear tupdates/temp or tupdates/ready dir!"));
		return fatalFail();
	}

	uchar sha1Buffer[20];
	bool goodSha1 = !memcmp(compressed.constData() + hSigLen, hashSha1(compressed.constData() + hSigLen + hShaLen, compressedLen + hPropsLen + hOriginalSizeLen, sha1Buffer), hShaLen);
	if (!goodSha1) {
		LOG(("Update Error: bad SHA1 hash of update file!"));
		return fatalFail();
	}

	RSA *pbKey = PEM_read_bio_RSAPublicKey(BIO_new_mem_buf(const_cast<char*>(UpdatesPublicKey), -1), 0, 0, 0);
	if (!pbKey) {
		LOG(("Update Error: cant read public rsa key!"));
		return fatalFail();
	}
    if (RSA_verify(NID_sha1, (const uchar*)(compressed.constData() + hSigLen), hShaLen, (const uchar*)(compressed.constData()), hSigLen, pbKey) != 1) { // verify signature
		RSA_free(pbKey);
		LOG(("Update Error: bad RSA signature of update file!"));
		return fatalFail();
    }
	RSA_free(pbKey);

	QByteArray uncompressed;

	int32 uncompressedLen;
	memcpy(&uncompressedLen, compressed.constData() + hSigLen + hShaLen + hPropsLen, hOriginalSizeLen);
	uncompressed.resize(uncompressedLen);

	size_t resultLen = uncompressed.size();
#ifdef Q_OS_WIN // use Lzma SDK for win
	SizeT srcLen = compressedLen;
	int uncompressRes = LzmaUncompress((uchar*)uncompressed.data(), &resultLen, (const uchar*)(compressed.constData() + hSize), &srcLen, (const uchar*)(compressed.constData() + hSigLen + hShaLen), LZMA_PROPS_SIZE);
	if (uncompressRes != SZ_OK) {
		LOG(("Update Error: could not uncompress lzma, code: %1").arg(uncompressRes));
		return fatalFail();
	}
#else
	lzma_stream stream = LZMA_STREAM_INIT;

	lzma_ret ret = lzma_stream_decoder(&stream, UINT64_MAX, LZMA_CONCATENATED);
	if (ret != LZMA_OK) {
		const char *msg;
		switch (ret) {
			case LZMA_MEM_ERROR: msg = "Memory allocation failed"; break;
			case LZMA_OPTIONS_ERROR: msg = "Specified preset is not supported"; break;
			case LZMA_UNSUPPORTED_CHECK: msg = "Specified integrity check is not supported"; break;
			default: msg = "Unknown error, possibly a bug"; break;
		}
		LOG(("Error initializing the decoder: %1 (error code %2)").arg(msg).arg(ret));
		return fatalFail();
	}

	stream.avail_in = compressedLen;
	stream.next_in = (uint8_t*)(compressed.constData() + hSize);
	stream.avail_out = resultLen;
	stream.next_out = (uint8_t*)uncompressed.data();

	lzma_ret res = lzma_code(&stream, LZMA_FINISH);
	if (stream.avail_in) {
		LOG(("Error in decompression, %1 bytes left in _in of %2 whole.").arg(stream.avail_in).arg(compressedLen));
		return fatalFail();
	} else if (stream.avail_out) {
		LOG(("Error in decompression, %1 bytes free left in _out of %2 whole.").arg(stream.avail_out).arg(resultLen));
		return fatalFail();
	}
	lzma_end(&stream);
	if (res != LZMA_OK && res != LZMA_STREAM_END) {
		const char *msg;
		switch (res) {
			case LZMA_MEM_ERROR: msg = "Memory allocation failed"; break;
			case LZMA_FORMAT_ERROR: msg = "The input data is not in the .xz format"; break;
			case LZMA_OPTIONS_ERROR: msg = "Unsupported compression options"; break;
			case LZMA_DATA_ERROR: msg = "Compressed file is corrupt"; break;
			case LZMA_BUF_ERROR: msg = "Compressed data is truncated or otherwise corrupt"; break;
			default: msg = "Unknown error, possibly a bug"; break;
		}
		LOG(("Error in decompression: %1 (error code %2)").arg(msg).arg(res));
		return fatalFail();
	}
#endif

	tempDir.mkdir(tempDir.absolutePath());

	quint32 version;
	{
		QBuffer buffer(&uncompressed);
		buffer.open(QIODevice::ReadOnly);
		QDataStream stream(&buffer);
		stream.setVersion(QDataStream::Qt_5_1);

		stream >> version;
		if (stream.status() != QDataStream::Ok) {
			LOG(("Update Error: cant read version from downloaded stream, status: %1").arg(stream.status()));
			return fatalFail();
		}
		if (version <= AppVersion) {
			LOG(("Update Error: downloaded version %1 is not greater, than mine %2").arg(version).arg(AppVersion));
			return fatalFail();
		}

		quint32 filesCount;
		stream >> filesCount;
		if (stream.status() != QDataStream::Ok) {
			LOG(("Update Error: cant read files count from downloaded stream, status: %1").arg(stream.status()));
			return fatalFail();
		}
		if (!filesCount) {
			LOG(("Update Error: update is empty!"));
			return fatalFail();
		}
		for (uint32 i = 0; i < filesCount; ++i) {
			QString relativeName;
			quint32 fileSize;
			QByteArray fileInnerData;
			bool executable = false;

			stream >> relativeName >> fileSize >> fileInnerData;
#if defined Q_OS_MAC || defined Q_OS_LINUX
			stream >> executable;
#endif
			if (stream.status() != QDataStream::Ok) {
				LOG(("Update Error: cant read file from downloaded stream, status: %1").arg(stream.status()));
				return fatalFail();
			}
			if (fileSize != quint32(fileInnerData.size())) {
				LOG(("Update Error: bad file size %1 not matching data size %2").arg(fileSize).arg(fileInnerData.size()));
				return fatalFail();
			}

			QFile f(tempDirPath + '/' + relativeName);
			if (!QDir().mkpath(QFileInfo(f).absolutePath())) {
				LOG(("Update Error: cant mkpath for file '%1'").arg(tempDirPath + '/' + relativeName));
				return fatalFail();
			}
			if (!f.open(QIODevice::WriteOnly)) {
				LOG(("Update Error: cant open file '%1' for writing").arg(tempDirPath + '/' + relativeName));
				return fatalFail();
			}
			if (f.write(fileInnerData) != fileSize) {
				f.close();
				LOG(("Update Error: cant write file '%1'").arg(tempDirPath + '/' + relativeName));
				return fatalFail();
			}
			f.close();
			if (executable) {
				QFileDevice::Permissions p = f.permissions();
				p |= QFileDevice::ExeOwner | QFileDevice::ExeUser | QFileDevice::ExeGroup | QFileDevice::ExeOther;
				f.setPermissions(p);
			}
		}

		// create tdata/version file
		tempDir.mkdir(QDir(tempDirPath + qsl("/tdata")).absolutePath());
		std::wstring versionString = ((version % 1000) ? QString("%1.%2.%3").arg(int(version / 1000000)).arg(int((version % 1000000) / 1000)).arg(int(version % 1000)) : QString("%1.%2").arg(int(version / 1000000)).arg(int((version % 1000000) / 1000))).toStdWString();

		VerInt versionNum = VerInt(version), versionLen = VerInt(versionString.size() * sizeof(VerChar));
		VerChar versionStr[32];
		memcpy(versionStr, versionString.c_str(), versionLen);

		QFile fVersion(tempDirPath + qsl("/tdata/version"));
		if (!fVersion.open(QIODevice::WriteOnly)) {
			LOG(("Update Error: cant write version file '%1'").arg(tempDirPath + qsl("/version")));
			return fatalFail();
		}
		fVersion.write((const char*)&versionNum, sizeof(VerInt));
		fVersion.write((const char*)&versionLen, sizeof(VerInt));
		fVersion.write((const char*)&versionStr[0], versionLen);
		fVersion.close();
	}

	if (!tempDir.rename(tempDir.absolutePath(), readyDir.absolutePath())) {
		LOG(("Update Error: cant rename temp dir '%1' to ready dir '%2'").arg(tempDir.absolutePath()).arg(readyDir.absolutePath()));
		return fatalFail();
	}
	deleteDir(tempDirPath);
	outputFile.remove();

    emit App::app()->updateReady();
}
コード例 #27
0
bool LongStream::freeSpace( const QString &path, int min)
{
    unsigned long long boundary = minFree;
    if (min >= 0)
        boundary = min;

    QString partitionPath = tempDir() + "/.";
    if (!path.isEmpty())
        partitionPath = path;
    
#if defined(Q_OS_SYMBIAN)
    bool result(false);
   
    RFs fsSession;
    TInt rv;
    if ((rv = fsSession.Connect()) != KErrNone) {
        qDebug() << "Unable to connect to FS:" << rv;
    } else {
        TParse parse;
        TPtrC name(path.utf16(), path.length());

        if ((rv = fsSession.Parse(name, parse)) != KErrNone) {
            qDebug() << "Unable to parse:" << path << rv;
        } else {
            TInt drive;
            if ((rv = fsSession.CharToDrive(parse.Drive()[0], drive)) != KErrNone) {
                qDebug() << "Unable to convert:" << QString::fromUtf16(parse.Drive().Ptr(), parse.Drive().Length()) << rv;
            } else {
                TVolumeInfo info;
                if ((rv = fsSession.Volume(info, drive)) != KErrNone) {
                    qDebug() << "Unable to volume:" << drive << rv;
                } else {
                    result = (info.iFree > boundary);
                }
            }
        }
        
        fsSession.Close();
    }
    
    return result;
#elif !defined(Q_OS_WIN)
    struct statfs stats;

    statfs(partitionPath.toLocal8Bit(), &stats);
    unsigned long long bavail = ((unsigned long long)stats.f_bavail);
    unsigned long long bsize = ((unsigned long long)stats.f_bsize);

    return ((bavail * bsize) > boundary);
#else
    // MS recommend the use of GetDiskFreeSpaceEx, but this is not available on early versions
    // of windows 95.  GetDiskFreeSpace is unable to report free space larger than 2GB, but we're 
    // only concerned with much smaller amounts of free space, so this is not a hindrance.
    DWORD bytesPerSector(0);
    DWORD sectorsPerCluster(0);
    DWORD freeClusters(0);
    DWORD totalClusters(0);

    if (::GetDiskFreeSpace(partitionPath.utf16(), &bytesPerSector, &sectorsPerCluster, &freeClusters, &totalClusters) == FALSE) {
        qWarning() << "Unable to get free disk space:" << partitionPath;
    }

    return ((bytesPerSector * sectorsPerCluster * freeClusters) > boundary);
#endif
}
コード例 #28
0
ファイル: autoupdater.cpp プロジェクト: 2asoft/tdesktop
void UpdateChecker::unpackUpdate() {
	QByteArray packed;
	if (!outputFile.open(QIODevice::ReadOnly)) {
		LOG(("Update Error: cant read updates file!"));
		return fatalFail();
	}

#ifdef Q_OS_WIN // use Lzma SDK for win
	const int32 hSigLen = 128, hShaLen = 20, hPropsLen = LZMA_PROPS_SIZE, hOriginalSizeLen = sizeof(int32), hSize = hSigLen + hShaLen + hPropsLen + hOriginalSizeLen; // header
#else // Q_OS_WIN
	const int32 hSigLen = 128, hShaLen = 20, hPropsLen = 0, hOriginalSizeLen = sizeof(int32), hSize = hSigLen + hShaLen + hOriginalSizeLen; // header
#endif // Q_OS_WIN

	QByteArray compressed = outputFile.readAll();
	int32 compressedLen = compressed.size() - hSize;
	if (compressedLen <= 0) {
		LOG(("Update Error: bad compressed size: %1").arg(compressed.size()));
		return fatalFail();
	}
	outputFile.close();

	QString tempDirPath = cWorkingDir() + qsl("tupdates/temp"), readyFilePath = cWorkingDir() + qsl("tupdates/temp/ready");
	psDeleteDir(tempDirPath);

	QDir tempDir(tempDirPath);
	if (tempDir.exists() || QFile(readyFilePath).exists()) {
		LOG(("Update Error: cant clear tupdates/temp dir!"));
		return fatalFail();
	}

	uchar sha1Buffer[20];
	bool goodSha1 = !memcmp(compressed.constData() + hSigLen, hashSha1(compressed.constData() + hSigLen + hShaLen, compressedLen + hPropsLen + hOriginalSizeLen, sha1Buffer), hShaLen);
	if (!goodSha1) {
		LOG(("Update Error: bad SHA1 hash of update file!"));
		return fatalFail();
	}

	RSA *pbKey = PEM_read_bio_RSAPublicKey(BIO_new_mem_buf(const_cast<char*>(AppAlphaVersion ? UpdatesPublicAlphaKey : UpdatesPublicKey), -1), 0, 0, 0);
	if (!pbKey) {
		LOG(("Update Error: cant read public rsa key!"));
		return fatalFail();
	}
	if (RSA_verify(NID_sha1, (const uchar*)(compressed.constData() + hSigLen), hShaLen, (const uchar*)(compressed.constData()), hSigLen, pbKey) != 1) { // verify signature
		RSA_free(pbKey);
		if (cAlphaVersion() || cBetaVersion()) { // try other public key, if we are in alpha or beta version
			pbKey = PEM_read_bio_RSAPublicKey(BIO_new_mem_buf(const_cast<char*>(AppAlphaVersion ? UpdatesPublicKey : UpdatesPublicAlphaKey), -1), 0, 0, 0);
			if (!pbKey) {
				LOG(("Update Error: cant read public rsa key!"));
				return fatalFail();
			}
			if (RSA_verify(NID_sha1, (const uchar*)(compressed.constData() + hSigLen), hShaLen, (const uchar*)(compressed.constData()), hSigLen, pbKey) != 1) { // verify signature
				RSA_free(pbKey);
				LOG(("Update Error: bad RSA signature of update file!"));
				return fatalFail();
			}
		} else {
			LOG(("Update Error: bad RSA signature of update file!"));
			return fatalFail();
		}
	}
	RSA_free(pbKey);

	QByteArray uncompressed;

	int32 uncompressedLen;
	memcpy(&uncompressedLen, compressed.constData() + hSigLen + hShaLen + hPropsLen, hOriginalSizeLen);
	uncompressed.resize(uncompressedLen);

	size_t resultLen = uncompressed.size();
#ifdef Q_OS_WIN // use Lzma SDK for win
	SizeT srcLen = compressedLen;
	int uncompressRes = LzmaUncompress((uchar*)uncompressed.data(), &resultLen, (const uchar*)(compressed.constData() + hSize), &srcLen, (const uchar*)(compressed.constData() + hSigLen + hShaLen), LZMA_PROPS_SIZE);
	if (uncompressRes != SZ_OK) {
		LOG(("Update Error: could not uncompress lzma, code: %1").arg(uncompressRes));
		return fatalFail();
	}
#else // Q_OS_WIN
	lzma_stream stream = LZMA_STREAM_INIT;

	lzma_ret ret = lzma_stream_decoder(&stream, UINT64_MAX, LZMA_CONCATENATED);
	if (ret != LZMA_OK) {
		const char *msg;
		switch (ret) {
		case LZMA_MEM_ERROR: msg = "Memory allocation failed"; break;
		case LZMA_OPTIONS_ERROR: msg = "Specified preset is not supported"; break;
		case LZMA_UNSUPPORTED_CHECK: msg = "Specified integrity check is not supported"; break;
		default: msg = "Unknown error, possibly a bug"; break;
		}
		LOG(("Error initializing the decoder: %1 (error code %2)").arg(msg).arg(ret));
		return fatalFail();
	}

	stream.avail_in = compressedLen;
	stream.next_in = (uint8_t*)(compressed.constData() + hSize);
	stream.avail_out = resultLen;
	stream.next_out = (uint8_t*)uncompressed.data();

	lzma_ret res = lzma_code(&stream, LZMA_FINISH);
	if (stream.avail_in) {
		LOG(("Error in decompression, %1 bytes left in _in of %2 whole.").arg(stream.avail_in).arg(compressedLen));
		return fatalFail();
	} else if (stream.avail_out) {
		LOG(("Error in decompression, %1 bytes free left in _out of %2 whole.").arg(stream.avail_out).arg(resultLen));
		return fatalFail();
	}
	lzma_end(&stream);
	if (res != LZMA_OK && res != LZMA_STREAM_END) {
		const char *msg;
		switch (res) {
		case LZMA_MEM_ERROR: msg = "Memory allocation failed"; break;
		case LZMA_FORMAT_ERROR: msg = "The input data is not in the .xz format"; break;
		case LZMA_OPTIONS_ERROR: msg = "Unsupported compression options"; break;
		case LZMA_DATA_ERROR: msg = "Compressed file is corrupt"; break;
		case LZMA_BUF_ERROR: msg = "Compressed data is truncated or otherwise corrupt"; break;
		default: msg = "Unknown error, possibly a bug"; break;
		}
		LOG(("Error in decompression: %1 (error code %2)").arg(msg).arg(res));
		return fatalFail();
	}
#endif // Q_OS_WIN

	tempDir.mkdir(tempDir.absolutePath());

	quint32 version;
	{
		QBuffer buffer(&uncompressed);
		buffer.open(QIODevice::ReadOnly);
		QDataStream stream(&buffer);
		stream.setVersion(QDataStream::Qt_5_1);

		stream >> version;
		if (stream.status() != QDataStream::Ok) {
			LOG(("Update Error: cant read version from downloaded stream, status: %1").arg(stream.status()));
			return fatalFail();
		}

		quint64 betaVersion = 0;
		if (version == 0x7FFFFFFF) { // beta version
			stream >> betaVersion;
			if (stream.status() != QDataStream::Ok) {
				LOG(("Update Error: cant read beta version from downloaded stream, status: %1").arg(stream.status()));
				return fatalFail();
			}
			if (!cBetaVersion() || betaVersion <= cBetaVersion()) {
				LOG(("Update Error: downloaded beta version %1 is not greater, than mine %2").arg(betaVersion).arg(cBetaVersion()));
				return fatalFail();
			}
		} else if (int32(version) <= AppVersion) {
コード例 #29
0
ファイル: qthreeinonedialog.cpp プロジェクト: luxiaodong/Qt
void QThreeInOneDialog::clickOK()
{
    if(ui->lineEdit->text().isEmpty() == true)
    {
        QMessageBox::information(this,"3In1Dialog", "iGB1_ is empty");
        return ;
    }

    QString path = m_dirPath;
    path = path.remove(path.size() - 1, 1);
    QString oldFolderString = path.split("/").last();
    QString newFolderString = QString("iGB2_%1").arg(ui->lineEdit->text());
    int index1 = path.lastIndexOf("/");
    QString newDirPath = QString("%1/%2/").arg(path.left(index1), newFolderString);

    QDir tempDir(newDirPath);

    if(tempDir.exists() == true)
    {
        QMessageBox::warning(this,"3In1Dialog", "The dir has been exist");
        return ;
    }

    QString nodeCoverPng = QString("");
    QString nodeInfoPng = QString("");
    QString nodeInfoPlist = QString("");
    QString nodeMp3 = QString("");
    QString unKnowMp3 = QString("");
    QString easyPlist = QString("");
    QString normalPlist = QString("");
    QString hardPlist = QString("");

    QDir dir(m_dirPath);
    QFileInfoList fileInfoList = dir.entryInfoList(QDir::Files);

    foreach(QFileInfo fileInfo, fileInfoList)
    {
        QString fileSuffix = fileInfo.suffix().toLower();
        QString fileName = fileInfo.fileName();

        if(fileSuffix == QString("mp3"))
        {
            if(fileName == QString("%1.mp3").arg(oldFolderString))
            {
                nodeMp3 = fileName;
            }
            else
            {
                unKnowMp3 = fileName;
            }
        }
        else if(fileSuffix == QString("png"))
        {
            if(fileName == QString("%1_Cover.png").arg(oldFolderString))
            {
                nodeCoverPng = fileName;
            }
            else if(fileName == QString("%1_Info.png").arg(oldFolderString))
            {
                nodeInfoPng = fileName;
            }
        }
        else if(fileSuffix == QString("plist"))
        {
            if(fileName == QString("%1_Info.plist").arg(oldFolderString))
            {
                nodeInfoPlist = fileName;
            }
            else if(fileName == QString("%1_E.plist").arg(oldFolderString))
            {
                easyPlist = fileName;
            }
            else if(fileName == QString("%1_N.plist").arg(oldFolderString))
            {
                normalPlist = fileName;
            }
            else if(fileName == QString("%1_H.plist").arg(oldFolderString))
            {
                hardPlist = fileName;
            }
        }
    }
コード例 #30
0
void ScanFileOrFolder::listFolder(QFileInfo source,QFileInfo destination)
{
    ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,QStringLiteral("source: %1 (%2), destination: %3 (%4)").arg(source.absoluteFilePath()).arg(source.isSymLink()).arg(destination.absoluteFilePath()).arg(destination.isSymLink()));
    if(stopIt)
        return;
    destination=resolvDestination(destination);
    if(stopIt)
        return;
    if(fileErrorAction==FileError_Skip)
        return;
    //if is same
    if(source.absoluteFilePath()==destination.absoluteFilePath())
    {
        emit folderAlreadyExists(source,destination,true);
        waitOneAction.acquire();
        QString destinationSuffixPath;
        switch(folderExistsAction)
        {
            case FolderExists_Merge:
            break;
            case FolderExists_Skip:
                return;
            break;
            case FolderExists_Rename:
                ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"destination before rename: "+destination.absoluteFilePath());
                if(newName.isEmpty())
                {
                    ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"pattern: "+folder_isolation.pattern());
                    //resolv the new name
                    destinationSuffixPath=destination.baseName();
                    int num=1;
                    do
                    {
                        if(num==1)
                        {
                            if(firstRenamingRule.isEmpty())
                                destinationSuffixPath=tr("%1 - copy").arg(destination.baseName());
                            else
                            {
                                destinationSuffixPath=firstRenamingRule;
                                destinationSuffixPath.replace(QStringLiteral("%name%"),destination.baseName());
                            }
                        }
                        else
                        {
                            if(otherRenamingRule.isEmpty())
                                destinationSuffixPath=tr("%1 - copy (%2)").arg(destination.baseName()).arg(num);
                            else
                            {
                                destinationSuffixPath=otherRenamingRule;
                                destinationSuffixPath.replace(QStringLiteral("%name%"),destination.baseName());
                                destinationSuffixPath.replace(QStringLiteral("%number%"),QString::number(num));
                            }
                        }
                        num++;
                        if(destination.completeSuffix().isEmpty())
                            destination.setFile(destination.absolutePath()+text_slash+destinationSuffixPath);
                        else
                            destination.setFile(destination.absolutePath()+text_slash+destinationSuffixPath+text_dot+destination.completeSuffix());
                    }
                    while(destination.exists());
                }
                else
                {
                    ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"use new name: "+newName);
                    destinationSuffixPath = newName;
                }
                destination.setFile(destination.absolutePath()+text_slash+destinationSuffixPath);
                ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"destination after rename: "+destination.absoluteFilePath());
            break;
            default:
                return;
            break;
        }
    }
    //check if destination exists
    if(checkDestinationExists)
    {
        if(destination.exists())
        {
            emit folderAlreadyExists(source,destination,false);
            waitOneAction.acquire();
            QString destinationSuffixPath;
            switch(folderExistsAction)
            {
                case FolderExists_Merge:
                break;
                case FolderExists_Skip:
                    return;
                break;
                case FolderExists_Rename:
                    ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"destination before rename: "+destination.absoluteFilePath());
                    if(newName.isEmpty())
                    {
                        //resolv the new name
                        QFileInfo destinationInfo;
                        int num=1;
                        do
                        {
                            if(num==1)
                            {
                                if(firstRenamingRule.isEmpty())
                                    destinationSuffixPath=tr("%1 - copy").arg(destination.baseName());
                                else
                                {
                                    destinationSuffixPath=firstRenamingRule;
                                    destinationSuffixPath.replace(QStringLiteral("%name%"),destination.baseName());
                                }
                            }
                            else
                            {
                                if(otherRenamingRule.isEmpty())
                                    destinationSuffixPath=tr("%1 - copy (%2)").arg(destination.baseName()).arg(num);
                                else
                                {
                                    destinationSuffixPath=otherRenamingRule;
                                    destinationSuffixPath.replace(QStringLiteral("%name%"),destination.baseName());
                                    destinationSuffixPath.replace(QStringLiteral("%number%"),QString::number(num));
                                }
                            }
                            destinationInfo.setFile(destinationInfo.absolutePath()+text_slash+destinationSuffixPath);
                            num++;
                        }
                        while(destinationInfo.exists());
                    }
                    else
                    {
                        ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"use new name: "+newName);
                        destinationSuffixPath = newName;
                    }
                    if(destination.completeSuffix().isEmpty())
                        destination.setFile(destination.absolutePath()+text_slash+destinationSuffixPath);
                    else
                        destination.setFile(destination.absolutePath()+text_slash+destinationSuffixPath+QStringLiteral(".")+destination.completeSuffix());
                    ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"destination after rename: "+destination.absoluteFilePath());
                break;
                default:
                    return;
                break;
            }
        }
    }
    //do source check
    //check of source is readable
    do
    {
        fileErrorAction=FileError_NotSet;
        if(!source.isReadable() || !source.isExecutable() || !source.exists() || !source.isDir())
        {
            if(!source.isDir())
                emit errorOnFolder(source,tr("This is not a folder"));
            else if(!source.exists())
                emit errorOnFolder(source,tr("The folder does exists"));
            else
                emit errorOnFolder(source,tr("The folder is not readable"));
            waitOneAction.acquire();
            ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"actionNum: "+QString::number(fileErrorAction));
        }
    } while(fileErrorAction==FileError_Retry);
    do
    {
        QDir tempDir(source.absoluteFilePath());
        fileErrorAction=FileError_NotSet;
        if(!tempDir.isReadable() || !tempDir.exists())
        {
            emit errorOnFolder(source,tr("Problem with name encoding"));
            waitOneAction.acquire();
            ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"actionNum: "+QString::number(fileErrorAction));
        }
    } while(fileErrorAction==FileError_Retry);
    if(stopIt)
        return;
    /// \todo check here if the folder is not readable or not exists
    QFileInfoList entryList;
    if(copyListOrder)
        entryList=QDir(source.absoluteFilePath()).entryInfoList(QDir::AllEntries|QDir::NoDotAndDotDot|QDir::Hidden|QDir::System,QDir::DirsFirst|QDir::Name|QDir::IgnoreCase);//possible wait time here
    else
        entryList=QDir(source.absoluteFilePath()).entryInfoList(QDir::AllEntries|QDir::NoDotAndDotDot|QDir::Hidden|QDir::System);//possible wait time here
    if(stopIt)
        return;
    int sizeEntryList=entryList.size();
    emit newFolderListing(source.absoluteFilePath());
    if(mode!=Ultracopier::Move)
        emit addToMkPath(source,destination,sizeEntryList);
    for (int index=0;index<sizeEntryList;++index)
    {
        QFileInfo fileInfo=entryList.at(index);
        if(stopIt)
            return;
        if(haveFilters)
        {
            if(reloadTheNewFilters)
            {
                QMutexLocker lock(&filtersMutex);
                QCoreApplication::processEvents(QEventLoop::AllEvents);
                reloadTheNewFilters=false;
                this->include=this->include_send;
                this->exclude=this->exclude_send;
            }
            QString fileName=fileInfo.fileName();
            if(fileInfo.isDir() && !fileInfo.isSymLink())
            {
                bool excluded=false,included=(include.size()==0);
                int filters_index=0;
                while(filters_index<exclude.size())
                {
                    if(exclude.at(filters_index).apply_on==ApplyOn_folder || exclude.at(filters_index).apply_on==ApplyOn_fileAndFolder)
                    {
                        if(fileName.contains(exclude.at(filters_index).regex))
                        {
                            excluded=true;
                            break;
                        }
                    }
                    filters_index++;
                }
                if(excluded)
                {}
                else
                {
                    filters_index=0;
                    while(filters_index<include.size())
                    {
                        if(include.at(filters_index).apply_on==ApplyOn_folder || include.at(filters_index).apply_on==ApplyOn_fileAndFolder)
                        {
                            if(fileName.contains(include.at(filters_index).regex))
                            {
                                included=true;
                                break;
                            }
                        }
                        filters_index++;
                    }
                    if(!included)
                    {}
                    else
                        listFolder(fileInfo,destination.absoluteFilePath()+text_slash+fileInfo.fileName());
                }
            }
            else
            {
                bool excluded=false,included=(include.size()==0);
                int filters_index=0;
                while(filters_index<exclude.size())
                {
                    if(exclude.at(filters_index).apply_on==ApplyOn_file || exclude.at(filters_index).apply_on==ApplyOn_fileAndFolder)
                    {
                        if(fileName.contains(exclude.at(filters_index).regex))
                        {
                            excluded=true;
                            break;
                        }
                    }
                    filters_index++;
                }
                if(excluded)
                {}
                else
                {
                    filters_index=0;
                    while(filters_index<include.size())
                    {
                        if(include.at(filters_index).apply_on==ApplyOn_file || include.at(filters_index).apply_on==ApplyOn_fileAndFolder)
                        {
                            if(fileName.contains(include.at(filters_index).regex))
                            {
                                included=true;
                                break;
                            }
                        }
                        filters_index++;
                    }
                    if(!included)
                    {}
                    else
                        #ifndef ULTRACOPIER_PLUGIN_RSYNC
                        emit fileTransfer(fileInfo,destination.absoluteFilePath()+text_slash+fileInfo.fileName(),mode);
                        #else
                        {
                            bool sendToTransfer=false;
                            if(!rsync)
                                sendToTransfer=true;
                            else if(!QFile::exists(destination.absoluteFilePath()+"/"+fileInfo.fileName()))
                                sendToTransfer=true;
                            else if(fileInfo.lastModified()!=QFileInfo(destination.absoluteFilePath()+"/"+fileInfo.fileName()).lastModified())
                                sendToTransfer=true;
                            if(sendToTransfer)
                                emit fileTransfer(fileInfo.absoluteFilePath(),destination.absoluteFilePath()+"/"+fileInfo.fileName(),mode);
                        }
                        #endif
                }
            }
        }
        else
        {
            if(fileInfo.isDir() && !fileInfo.isSymLink())//possible wait time here
                //listFolder(source,destination,suffixPath+fileInfo.fileName()+QDir::separator());
                listFolder(fileInfo,destination.absoluteFilePath()+text_slash+fileInfo.fileName());//put unix separator because it's transformed into that's under windows too
            else
                #ifndef ULTRACOPIER_PLUGIN_RSYNC
                emit fileTransfer(fileInfo,destination.absoluteFilePath()+text_slash+fileInfo.fileName(),mode);
                #else
                {
                    bool sendToTransfer=false;
                    if(!rsync)
                        sendToTransfer=true;
                    else if(!QFile::exists(destination.absoluteFilePath()+"/"+fileInfo.fileName()))
                        sendToTransfer=true;
                    else if(fileInfo.lastModified()!=QFileInfo(destination.absoluteFilePath()+"/"+fileInfo.fileName()).lastModified())
                        sendToTransfer=true;
                    if(sendToTransfer)
                        emit fileTransfer(fileInfo.absoluteFilePath(),destination.absoluteFilePath()+"/"+fileInfo.fileName(),mode);
                }
                #endif
        }
    }
    #ifdef ULTRACOPIER_PLUGIN_RSYNC
    if(rsync)
    {
        //check the reverse path here
        QFileInfoList entryListDestination;
        if(copyListOrder)
            entryListDestination=QDir(destination.absoluteFilePath()).entryInfoList(QDir::AllEntries|QDir::NoDotAndDotDot|QDir::Hidden|QDir::System,QDir::DirsFirst|QDir::Name|QDir::IgnoreCase);//possible wait time here
        else
            entryListDestination=QDir(destination.absoluteFilePath()).entryInfoList(QDir::AllEntries|QDir::NoDotAndDotDot|QDir::Hidden|QDir::System);//possible wait time here
        int sizeEntryListDestination=entryListDestination.size();
        int index=0;
        for (int indexDestination=0;indexDestination<sizeEntryListDestination;++indexDestination)
        {
            index=0;
            while(index<sizeEntryList)
            {
                if(entryListDestination.at(indexDestination).fileName()==entryList.at(index).fileName())
                    break;
                index++;
            }
            if(index==sizeEntryList)
            {
                //then not found, need be remove
                emit addToRmForRsync(entryListDestination.at(indexDestination));
            }
         }
         return;
    }
    #endif
    if(mode==Ultracopier::Move)
    {
        ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"source: "+source.absoluteFilePath()+", sizeEntryList: "+QString::number(sizeEntryList));
        emit addToMovePath(source,destination,sizeEntryList);
    }
}