コード例 #1
0
ファイル: tools.cpp プロジェクト: daniel-artchounin/pr-c
void load(const QString &file) {
    QFile oldFile(file);
    if (!oldFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        throw ToolsException("Erreur ouverture fichier");
    }
    QXmlStreamReader xml(&oldFile);

    while(!xml.atEnd() && !xml.hasError()) {
        QXmlStreamReader::TokenType token = xml.readNext();
        if(token == QXmlStreamReader::StartDocument) continue;
        if(token == QXmlStreamReader::StartElement) {
            if(xml.name() == "root") continue;
            if(xml.name() == "ProjetManager") {
                ProjetManager::getInstance().loadFrom(xml);
            }
            if(xml.name() == "ProgrammationManager") {
                ProgrammationManager::getInstance().loadFrom(xml);
            }
        }
    }
    if(xml.hasError()) {
        throw ToolsException("Erreur lecteur fichier taches, parser xml. " + toString(xml.errorString()));
    }
    xml.clear();
}
コード例 #2
0
ファイル: convert_sqlite3.cpp プロジェクト: eliovir/krecipes
bool ConvertSQLite3::copyFile( const QString &oldFilePath, const QString &newFilePath )
{
	//load both files
	QFile oldFile(oldFilePath);
	QFile newFile(newFilePath);
	bool openOld = oldFile.open( QIODevice::ReadOnly );
	bool openNew = newFile.open( QIODevice::WriteOnly );

	//if either file fails to open bail
	if(!openOld || !openNew) { return false; }

	//copy contents
	uint BUFFER_SIZE = 16000;
	char* buffer = new char[BUFFER_SIZE];
	while(!oldFile.atEnd())
	{
		Q_ULONG len = oldFile.read( buffer, BUFFER_SIZE );
		newFile.write( buffer, len );
	}

	//deallocate buffer
	delete[] buffer;
	buffer = NULL;
	return true;
}
コード例 #3
0
QApplicationSettings::QApplicationSettings()
{
	QString dataDir = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
	QString oldStylePath = StaticHelpers::CombinePathes(QApplication::applicationDirPath(), "CuteTorrent.ini");
	QString newStylePath = StaticHelpers::CombinePathes(dataDir, "settings.ini");
	QFile oldFile(oldStylePath);

	if (oldFile.exists())
	{
		if (!oldFile.rename(newStylePath))
		{
			CustomMessageBox::warning(NULL, "Move file failed", QString("Failed to move %1 to %2!").arg(oldStylePath, newStylePath));
		}
	}

	settings = new QSettings(newStylePath, QSettings::IniFormat);
	//Prev version compability
	settings->beginGroup("KeyMap");

	if (settings->contains("ACTION_OTHER_DISCRIBTION"))
	{
		QVariant oldVal = settings->value("ACTION_OTHER_DISCRIBTION");
		settings->remove("ACTION_OTHER_DISCRIBTION");
		settings->setValue("ACTION_OTHER_COPY_DISCRIBTION", oldVal);
	}

	settings->endGroup();
	locker = new QMutex();
	m_pCryptor = new SimpleCrypt(0x1D5AE35A4BDD232LL);
	ReedSettings();
}
コード例 #4
0
ファイル: collect4output.cpp プロジェクト: aoloe/scribus
bool CollectForOutput::collectProfiles()
{
    int c = 0;
    ProfilesL::Iterator itend = docProfiles.end();
    for (ProfilesL::Iterator it = docProfiles.begin(); it != itend; ++it)
    {
        QString profileName(it.key());
        QString oldFile(it.value());
        QString outFile(m_outputDirectory + "profiles/" + QFileInfo(oldFile).fileName());
        bool success = copyFileAtomic(oldFile, outFile);
        if (!success)
            qDebug()<<"CollectForOutput::collectFile copyFileAtomic failed for"<<oldFile<<"to"<<outFile;
#ifndef Q_OS_WIN32
        else
        {
            QFile of(outFile);
            if (of.exists())
            {
                bool permsSet=of.setPermissions(QFile::permissions(oldFile));
                if (!permsSet)
                    qDebug()<<"Unable to set permissions successfully while collecting for output on"<<outFile;
            }
            else
                qDebug()<<"Unable to set permissions successfully while collecting for output on"<<outFile<<"as the file does not exist";
        }
#endif
        if (uiCollect)
            emit profilesCollected(c++);
    }
    return true;
}
コード例 #5
0
ファイル: addons.cpp プロジェクト: alanvar/Al-Anavr
void Addons::on_pushButtonUpdate_clicked()
{
    QString urlStr="http://al-anvar.com/addons/addonse-0.4.8.xml";
    QUrl url(urlStr);
    QFileInfo fileInfo(url.path());
    QString fileName = fileInfo.fileName();
    fileName=db->pathUser+"/"+fileName+"-update";
    QFile updateFile(fileName);
    if(updateFile.exists())
         updateFile.remove();
     progressTotal->setVisible(false);
    downlod->downloadFile(urlStr,fileName);
    if(downlod->downloded)
    {
        QFile oldFile(db->pathUser+"/addonse-0.4.8.xml");
        if(oldFile.exists())
             oldFile.remove(db->pathUser+"/addonse-0.4.8.xml");
        if(updateFile.rename(db->pathUser+"/addonse-0.4.8.xml")){
            QMessageBox::information(this,db->trlang("Update Add-ons list"),db->trlang("Add-ons list was updated Successfully"), QMessageBox::Ok);
            treeChargeAddons(treeWidget);
        }else
            QMessageBox::warning(this,db->trlang("Update Add-ons list"),db->trlang("Add-ons list was not updated Successfully"), QMessageBox::Ok);


    }else
         QMessageBox::warning(this,db->trlang("Update Add-ons list"),db->trlang("Add-ons list was not updated Successfully"), QMessageBox::Ok);

}
コード例 #6
0
ファイル: Utilities.cpp プロジェクト: TMA-AQ/AQ
//------------------------------------------------------------------------------
int FileRename(const char* pszSrcPath, const char* pszDstPath)
{
  boost::system::error_code ec;
  boost::filesystem::path oldFile(pszSrcPath);
  boost::filesystem::path newFile(pszDstPath);
  boost::filesystem::rename(oldFile, newFile, ec);
  if (ec)
  {
    aq::Logger::getInstance().log(AQ_ERROR, "Cannot rename file %s to %s\n", pszSrcPath, pszDstPath);
    return -1;
  }
  aq::Logger::getInstance().log(AQ_DEBUG, "rename file %s to %s\n", pszSrcPath, pszDstPath);
  return 0;
}
コード例 #7
0
ファイル: homescreen.cpp プロジェクト: muromec/qtopia-ezx
//TODO: reduce duplicated code
void HomescreenSettings::editSecondaryPhoto()
{
    QImageSourceSelectorDialog *dlg = new QImageSourceSelectorDialog( this );
    dlg->setMaximumImageSize( QApplication::desktop()->availableGeometry(1).size()  );
    dlg->setContent( secondaryHsImage );
    dlg->setModal( true );
    dlg->setWindowTitle( tr("Homescreen Photo") );
    if( QtopiaApplication::execDialog( dlg ) == QDialog::Accepted ) { 
        if (!dlg->content().isValid()) {
            secondaryHsImage = QContent();
            secondaryImage->setIcon(QIcon());
            secondaryImage->setText(tr("No image"));
            secondaryImageMode->setVisible(false);
            return;
        }
        
        secondaryHsImage = dlg->content();
        secondaryImage->setIcon(QIcon(secondaryHsImage.fileName()));
        secondaryImage->setText(QString());
        secondaryImageMode->setVisible(true);

        //BUG: shouldn't change files here (in case use cancels dialog)
        //     should only change document filename
        qLog(Resource) << "Selected Document:" << secondaryHsImage.fileName();
        // remove old image
        QFile::remove( HOMESCREEN_IMAGE_PATH2 );
        // check if the file is from a removable storage
        const QFileSystem *fs = QStorageMetaInfo::instance()->fileSystemOf(hsImage.fileName());
    
        if (fs && fs->isRemovable()) {
            qLog(Resource) << secondaryHsImage.fileName() << "is from a removable storage," << secondaryHsImage.media();    
            // check if the file has Distribute right
            QDrmContent imgContent( QDrmRights::Distribute, QDrmContent::NoLicenseOptions );
            if ( imgContent.requestLicense( secondaryHsImage ) ) {
                qLog(Resource) << "File has Distribute right";
                // save a copy
                QFile oldFile( secondaryHsImage.fileName() );
                if ( oldFile.copy( HOMESCREEN_IMAGE_PATH2 ) ) {
                    secondaryHsImage = QContent( HOMESCREEN_IMAGE_PATH2 );
                    qLog(Resource) << "Successfully copied" << secondaryHsImage.fileName() << "to" << HOMESCREEN_IMAGE_PATH2;
                } else {
                    qLog(Resource) << "Failed to copy" << secondaryHsImage.fileName() << ". Need to use as is.";
                }
            } else {
                qLog(Resource) << "File does not have Distribute right";
            }
        }
    }
    delete dlg;
}
コード例 #8
0
void CompareCFLADiffCuts()
{
  TFile newFile("~/Analysis/lambda/AliAnalysisLambda/Results/2016-01/15-NoOppChargeCut/All/CFs.root");
  TDirectory *newDir = newFile.GetDirectory("Merged");
  vector<TH1D*> newCFs;
  newCFs.push_back((TH1D*)newDir->Get("CFLamALam010"));
  newCFs.push_back((TH1D*)newDir->Get("CFLamALam1030"));
  newCFs.push_back((TH1D*)newDir->Get("CFLamALam3050"));

  TFile oldFile("~/Analysis/lambda/AliAnalysisLambda/Results/2016-01/08-NewAvgSepCuts/All/CFs.root");
  TDirectory *oldDir = oldFile.GetDirectory("Merged");
  vector<TH1D*> oldCFs;
  oldCFs.push_back((TH1D*)oldDir->Get("CFLamALam010"));
  oldCFs.push_back((TH1D*)oldDir->Get("CFLamALam1030"));
  oldCFs.push_back((TH1D*)oldDir->Get("CFLamALam3050"));

  TFile *compareFile = new TFile("Compare.root","update");
  TDirectory *dir = compareFile->GetDirectory("Delta");
  if(!dir) dir = compareFile->mkdir("Delta");
  for(UInt_t i = 0; i < newCFs.size(); i++) {
    // TH1D *ratio = (TH1D*)newCFs[i]->Clone();
    // TString name = ratio->GetName();
    // ratio->SetName(name + "Ratio");
    // ratio->SetTitle(name + "Ratio");
    // ratio->Divide(oldCFs[i]);

    // TH1D *barlowRatio = ComputeRogerBarlowRatio(newCFs[i], oldCFs[i]);
    // barlowRatio->SetName(name + "BarlowRatio");
    // barlowRatio->SetTitle(name + "BarlowRatio");

    TString name = newCFs[i]->GetName();
    TH1D *barlowDifference = ComputeRogerBarlowDifference(newCFs[i], oldCFs[i]);
    barlowDifference->SetName(name + "BarlowDifference");
    barlowDifference->SetTitle(name + "BarlowDifference");
    
    dir->cd();
    // ratio->Write();
    // barlowRatio->Write();
    barlowDifference->Write(barlowDifference->GetName(), TObject::kOverwrite);
    Chi2TestWithZero(barlowDifference);
    FitWithConstant(barlowDifference, compareFile);
    // LookAtMean(barlowDifference);
    RebinHist(barlowDifference, compareFile);
    ManuallyRebin(barlowDifference, compareFile);
  }
    
  compareFile->Close();
}
コード例 #9
0
bool PathManager::CopyFile(const QString &SrcFile, const QString &DestFile, bool isCover)
{
	if (!QFile::exists(SrcFile)){
		return true;
	}

	if (QFile::exists(DestFile)){
		if (isCover){
			if (!QFile::remove(DestFile)){
				return false;
			}
		}
		else{
			return false;
		}
	}
	QFile oldFile(SrcFile);
	return oldFile.copy(DestFile);
}
コード例 #10
0
static bool preparePath(QDir &episode, QString &relDirPath, QString &inPath, QString &backupTo, bool doBackup)
{
    relDirPath = episode.relativeFilePath( inPath );
    int idx = relDirPath.lastIndexOf('/');
    if(idx >= 0)
        relDirPath.remove(idx, relDirPath.size()-idx);
    else
        relDirPath.clear();

    bool ret = relDirPath.startsWith("pge_maintainer_backup-", Qt::CaseInsensitive);

    if(!ret && doBackup)
    {
        qDebug() << "Make backup";
        QFileInfo oldFile(inPath);
        episode.mkpath(backupTo + "/" + relDirPath);
        QFile::copy(inPath, backupTo+"/" + relDirPath + "/" + oldFile.fileName() );
    }
    return ret;
}
コード例 #11
0
ファイル: androidmanager.cpp プロジェクト: choenig/qt-creator
static bool mergeGradleProperties(const QString &path, GradleProperties properties)
{
    QFile::remove(path + QLatin1Char('~'));
    QFile::rename(path, path + QLatin1Char('~'));
    QFile file(path);
    if (!file.open(QIODevice::Truncate | QIODevice::WriteOnly | QIODevice::Text))
        return false;

    QFile oldFile(path + QLatin1Char('~'));
    if (oldFile.open(QIODevice::ReadOnly)) {
        while (!oldFile.atEnd()) {
            QByteArray line(oldFile.readLine());
            QList<QByteArray> prop(line.split('='));
            if (prop.size() > 1) {
                GradleProperties::iterator it = properties.find(prop.at(0).trimmed());
                if (it != properties.end()) {
                    file.write(it.key() + '=' + it.value() + '\n');
                    properties.erase(it);
                    continue;
                }
            }
            file.write(line);
        }
        oldFile.close();
    } else {
        file.write("## This file is automatically generated by QtCreator.\n"
                   "#\n"
                   "# This file must *NOT* be checked into Version Control Systems,\n"
                   "# as it contains information specific to your local configuration.\n\n");

    }

    for (GradleProperties::const_iterator it = properties.constBegin(); it != properties.constEnd();
         ++it)
        file.write(it.key() + '=' + it.value() + '\n');

    file.close();
    return true;
}
コード例 #12
0
void AskFile::handleDC(){
    qDebug() << "-->DC";
    if( m_writeFile->isOpen() ){
        m_writeFile->flush();
        m_writeFile->close();
    }

    //recebeu o ficheiro todo
    qDebug() << "desligou-se" << m_sumReceived << m_info["seek"].toInt() << " != " << m_info["fSize"].toInt();
    if( (m_sumReceived + m_info["seek"].toInt()) != m_info["fSize"].toInt())
        emit errorTransfer(m_info["code"], m_info["fSize"].toInt(), m_sumReceived );
    else{
        QString absoluteFPath;
        absoluteFPath.append(m_downloadPath).append("/").append(m_info["code"]).append("_").append(m_info["fName"]);

        QFile oldFile(absoluteFPath);
        if (oldFile.exists())
            oldFile.remove();

        m_writeFile->rename(absoluteFPath);
        //m_writeFile->rename(m_info["code"]+"-"+m_info["fName"]);
        emit finished(m_info["code"], m_downloadPath);
    }
}
コード例 #13
0
void hotkey_parser::writeBindingsToFile( const key_binding& springbindings )
{
	const wxString newTmpFilename = this->m_filename + wxT(".tmp");
	wxTextFile newFile( newTmpFilename );

	//open new file for writing
	if ( ( !newFile.Exists() && !newFile.Create() ) || ( newFile.Exists() && !newFile.Open() ) )
	{
		throw HotkeyException( _("Error opening file for writing: ") + newTmpFilename );
	}

	//now read the old uikeys.txt line after line and copy all comments to the new file
	wxTextFile oldFile( this->m_filename );
	if ( !oldFile.Open() )
	{
		throw HotkeyException( _("Error opening file for writing: ") + newTmpFilename );
	}

	for( size_t i = 0; i < oldFile.GetLineCount(); ++i )
	{
		wxString line = oldFile.GetLine( i );
		line.Trim();
		if ( line.StartsWith(wxT("//")) )
		{
			newFile.AddLine( line );
		}
	}
	oldFile.Close();

	//add keysyms
	key_sym_map keySymRev;
	for( key_sym_map::const_iterator iter = springbindings.getKeySyms().begin(); iter != springbindings.getKeySyms().end(); ++iter )
	{
		newFile.AddLine( wxT("keysym\t\t") + iter->first + wxT("\t\t") + iter->second );
		keySymRev[ KeynameConverter::convertHexValueToKey( iter->second ) ] = iter->first;
	}

	//add keysyms
	key_sym_map keySymSetRev;
	for( key_sym_set_map::const_iterator iter = springbindings.getKeySymsSet().begin(); iter != springbindings.getKeySymsSet().end(); ++iter )
	{
		newFile.AddLine( wxT("keyset\t\t") + iter->first + wxT("\t\t") + springbindings.resolveKeySymKey(iter->second ) );
		keySymSetRev[ iter->second ] = iter->first;
	}

	//add fakemeta
	if ( SpringDefaultProfile::getBindings().getMetaKey() != springbindings.getMetaKey() )
	{
		newFile.AddLine( wxT("fakemeta\t\t") + springbindings.getMetaKey() );		
	}

	//check all default bindings if they still exist in current profile
	//do unbind if not
	const key_commands_sorted unbinds = (SpringDefaultProfile::getBindings() - springbindings).getBinds();
	for( key_commands_sorted::const_iterator iter = unbinds.begin(); iter != unbinds.end(); ++iter )
	{
		newFile.AddLine( wxT("unbind\t\t") + springbindings.resolveKeySymKeyAndSet( iter->first ) + wxT("\t\t") + iter->second );
	}

	//add binds, should be ordered
	const key_commands_sorted dobinds = (springbindings - SpringDefaultProfile::getBindings()).getBinds();
	for( key_commands_sorted::const_iterator iter = dobinds.begin(); iter != dobinds.end(); ++iter )
	{
		newFile.AddLine( wxT("bind\t\t") + springbindings.resolveKeySymKeyAndSet( iter->first ) + wxT("\t\t") + iter->second );
	}

	newFile.Write();

	const wxString prevFilenameBak = this->m_filename + wxT(".bak");

	//backup our current uikeys.txt
	{
		if ( wxRenameFile( this->m_filename, prevFilenameBak ) == false )
		{
			throw HotkeyException( _("Error renaming uikeys.txt to uikeys.txt.bak") );
		}
	}

	//rename our new tmp file to uikeys.txt. restore backup if failed
	{
		if ( wxRenameFile( newTmpFilename, this->m_filename ) == false )
		{
			wxString msg = _("Error renaming uikeys.txt.tmp to uikeys.txt.");
			
			//restore backup
			if ( wxRenameFile( prevFilenameBak, this->m_filename ) == false )
			{
				msg += _(" Restoring backup failed also. Good luck!");
			}
			throw HotkeyException( msg );
		}
	}
}
コード例 #14
0
ファイル: qupd_updater.cpp プロジェクト: idtek/qUpdater
bool QUPDUpdater::isUpdateRequested()
{
    qDebug() << "isUpdateRequested";

    if (QSettings().contains(QUPD_UPDATED_VERSION_KEY)) {

        QFileInfo updatedFile (QSettings().value(QUPD_UPDATED_VERSION_KEY).toString());
        QFileInfo applicationFile ( qApp->applicationFilePath() );

#if defined Q_OS_MAC
        QDir dir = applicationFile.dir();
        dir.cdUp(); dir.cdUp();
        applicationFile = QFileInfo( dir.absolutePath() );

#elif defined Q_OS_WIN
        qt_ntfs_permission_lookup++; // Allow permissions verification os NTFS file system

#endif

        if (!updatedFile.exists()) {
            ; // TODO Error
        } else if (!applicationFile.isWritable()) {
            qDebug() << "Unwritable file, update aborted";
        } else {

#if defined Q_OS_WIN
            ;

#elif defined Q_OS_MAC
            QProcess process;
            process.setProgram("hdiutil");
            process.setArguments(QStringList() << "verify" << updatedFile.absoluteFilePath());
            process.start();
            process.waitForFinished();
            if (process.exitStatus() == QProcess::NormalExit) {
                QString mountPoint = applicationFile.absolutePath() + "/" + applicationFile.baseName();

                // Mount the downloaded dmg
                process.setProgram("hdiutil");
                process.setArguments(QStringList() << "attach" << "-mountpoint" << mountPoint << updatedFile.absoluteFilePath());
                process.start();
                process.waitForFinished(180000);
                qDebug() << process.exitStatus();
                qDebug() << process.readAllStandardError();

                // Replace the Application
                QString newFile(mountPoint + "/" +
                              qApp->applicationName() +".app");
                QString oldFile(applicationFile.absoluteFilePath());

                process.setProgram("rm");
                process.setArguments(QStringList() << "-rf" << oldFile);
                process.start();
                process.waitForFinished();
                process.exitStatus();

                process.setProgram("cp");
                process.setArguments(QStringList() << "-r" << newFile << oldFile);
                process.start();
                process.waitForFinished();

                // Unmount it
                process.setProgram("hdiutil");
                process.setArguments(QStringList() << "detach" << applicationFile.absolutePath() + "/" + applicationFile.baseName());
                process.start();
                process.waitForFinished();
                process.exitCode();
                process.exitStatus();
            }
#endif

        }

#if defined Q_OS_WIN
        qt_ntfs_permission_lookup--;
#endif

        QSettings().remove(QUPD_UPDATED_VERSION_KEY);
    }

    return false;
}
コード例 #15
0
bool EpisodeConverterWorker::runJob()
{
    m_jobRunning = true;
    m_isFine = false;

    QString BackupDirectory = QString("pge_maintainer_backup-%1-%2-%3_%4-%5-%6")
            .arg(QDate().currentDate().year())
            .arg(QDate().currentDate().month())
            .arg(QDate().currentDate().day())
            .arg(QTime().currentTime().hour())
            .arg(QTime().currentTime().minute())
            .arg(QTime().currentTime().second());
    m_currentValue = 0;

    try
    {
        for(int i=0; i<m_episodeBox.d.size(); i++)
        {
            EpisodeBox_level& lvl = m_episodeBox.d[i];
            QString relDirPath;
            QString oldPath = lvl.fPath;
            if(preparePath(m_episode, relDirPath, lvl.fPath, BackupDirectory, m_doBackup))
                continue;
            switch(m_targetFormat)
            {
            case 0://PGE-X
                qDebug() << "Make LVLX";
                lvl.ftype = EpisodeBox_level::F_LVLX;
                renameExtension(lvl.fPath, ".lvlx");
                if(!FileFormats::SaveLevelFile(lvl.d, lvl.fPath, FileFormats::LVL_PGEX))
                    throw(FileFormats::errorString);
                break;
            case 1://SMBX 1...64
                qDebug() << "Make LVL SMBX" << lvl.ftypeVer;
                lvl.ftype = EpisodeBox_level::F_LVL;
                lvl.ftypeVer = m_targetFormatVer;
                renameExtension(lvl.fPath, ".lvl");
                if(!FileFormats::SaveLevelFile(lvl.d, lvl.fPath, FileFormats::LVL_SMBX64, m_targetFormatVer))
                    throw(FileFormats::errorString);
                break;
            case 2://SMBX-38A
                qDebug() << "Make LVL SMBX-38a";
                lvl.ftype = EpisodeBox_level::F_LVL38A;
                renameExtension(lvl.fPath, ".lvl");
                if(!FileFormats::SaveLevelFile(lvl.d, lvl.fPath, FileFormats::LVL_SMBX38A))
                    throw(FileFormats::errorString);
                break;
            }

            if(oldPath != lvl.fPath)
            {
                m_episodeBox.renameLevel(oldPath, lvl.fPath);
                QFile::remove(oldPath);
            }
            qDebug() << "Successfully!";
            m_currentValue++;
        }

        for(int i=0; i<m_episodeBox.dw.size(); i++)
        {
            EpisodeBox_world& wld = m_episodeBox.dw[i];
            qDebug() << "Open world map" << wld.fPath;
            QString relDirPath;
            if(preparePath(m_episode, relDirPath, wld.fPath, BackupDirectory, m_doBackup))
                continue;

            qDebug() << "Will be processed";

            if(m_doBackup)
            {
                qDebug() << "Make backup";
                QFileInfo oldFile(wld.fPath);
                m_episode.mkpath(BackupDirectory + "/" + relDirPath);
                QFile::copy(wld.fPath, BackupDirectory+"/" + relDirPath + "/" + oldFile.fileName() );
            }
            QString oldPath = wld.fPath;

            switch(m_targetFormat)
            {
            case 0://PGE-X
                qDebug() << "Make WLDX";
                wld.ftype = EpisodeBox_world::F_WLDX;
                renameExtension(wld.fPath, ".wldx");
                if(!FileFormats::SaveWorldFile(wld.d, wld.fPath, FileFormats::WLD_PGEX))
                    throw(FileFormats::errorString);
                break;
            case 1://SMBX 1...64
                qDebug() << "Make WLD SMBX "<<wld.ftypeVer;
                wld.ftype = EpisodeBox_world::F_WLD;
                wld.ftypeVer = m_targetFormatVer;
                renameExtension(wld.fPath, ".wld");
                if(!FileFormats::SaveWorldFile(wld.d, wld.fPath, FileFormats::WLD_SMBX64, m_targetFormatVer))
                    throw(FileFormats::errorString);
                break;
            case 2://SMBX-38A
                qDebug() << "Make WLD SMBX-38a";
                wld.ftype = EpisodeBox_world::F_WLD38A;
                renameExtension(wld.fPath, ".wld");
                if(!FileFormats::SaveWorldFile(wld.d, wld.fPath, FileFormats::WLD_SMBX38A))
                    throw(FileFormats::errorString);
                break;
            }

            if(oldPath != wld.fPath)
            {
                qDebug() << "Delete old file";
                //m_episodeBox.renameLevel(oldPath, wld.fPath);
                QFile::remove(oldPath);
            }
            qDebug() << "Successfully!";
            m_currentValue++;
        }

        m_isFine=true;
    }
    catch(QString err)
    {
        m_errorString = "Error ocouped while conversion process: " + err;
        emit workFinished(false);
        m_isFine = false;
    }
    m_jobRunning = false;

    qDebug() << "Work done, exiting";
    emit workFinished(true);
    return m_isFine;
}
コード例 #16
0
ファイル: C23Cooker.cpp プロジェクト: slajar/BeatDetection
//---------------------------------------------------------------------------
STATIC void C23Cooker::CookObjFilesInFolder( const std::string& rawDataDirectory, const std::string& cookedDataDestinationDirectory, bool isCookAllEnabled )
{
	std::vector< Vertex3D > vertexes;
	std::vector< unsigned int > indexes;
	std::vector< std::string > filePaths;
	std::string objFileName;
	std::string c23FileName;
	std::string destination( cookedDataDestinationDirectory );
	OBJFileHandler objFileHandler;
	C23FileHandler c23FileHandler;
	
	// find all the .obj files in this directory
// 	if ( rawDataDirectory.back() == '/' )
// 	{
// 		FileSystem::EnumerateFilesInDirectory( rawDataDirectory + "*.obj", filePaths );
// 	}
// 	else
// 	{
// 		FileSystem::EnumerateFilesInDirectory( rawDataDirectory + "/*.obj", filePaths );
// 	}
	FileSystem::EnumerateFilesInDirectory( rawDataDirectory, filePaths );


	// if we found no files, return
	if ( filePaths.empty() )
	{
		std::cerr << "No files found!" << std::endl;
		return;
	}

	// add a trailing '/' to destination if don't already have
	if ( destination.back() != '/' )
	{
		destination += '/';
	}

	std::wstring dataFolder( destination.begin(), destination.end() );
	CreateDirectoryW( dataFolder.c_str(), nullptr );

	for ( unsigned int index = 0; index < ( unsigned int ) filePaths.size(); ++ index )
	{
		std::string& currentFilePath = filePaths[ index ];
		destination = cookedDataDestinationDirectory + currentFilePath.substr( rawDataDirectory.find_first_of( '*' ) );

		if ( currentFilePath.substr( 0, currentFilePath.find_last_of( '/' ) + 1 ) == currentFilePath )
		{
			std::cout << "Creating directory " + destination + "... ";
			std::wstring newDir( destination.begin(), destination.end() );
			CreateDirectoryW( newDir.c_str(), nullptr );
			std::cout << "Done!" << std::endl;
		}
		else if ( currentFilePath.substr( currentFilePath.find_last_of( '.' ) ) == ".obj" )
		{
			if ( FileSystem::IsFileDateOlder( currentFilePath, destination.substr( 0, destination.find_last_of( '.' ) ) + ".c23" ) && !isCookAllEnabled ) continue;

			destination = destination.substr( 0, destination.find_last_of( '/' ) + 1 );
			objFileName = currentFilePath.substr( currentFilePath.find_last_of( '/' ) + 1 );

			c23FileName = objFileName.substr( 0, objFileName.find_last_of( '.' ) ) + ".c23";

			std::cout << "Cooking " << objFileName << "... ";

			objFileHandler.ReadFromObjAndStoreVertexesAndIndexes( currentFilePath.c_str(), vertexes, indexes );

			if ( vertexes.empty() )
			{
				std::cerr << "Error - file failed to load!" << std:: endl;
				continue;
			}

			c23FileHandler.WriteToFile( ( destination + c23FileName ).c_str(), vertexes, indexes );

			std::cout << "Success!" << std::endl;

			vertexes.clear();
			indexes.clear();
		}
		else
		{
			if ( FileSystem::IsFileDateOlder( currentFilePath, destination ) && !isCookAllEnabled ) continue;

			std::cout << "Copying " << currentFilePath << " to " << destination << "... ";
			std::wstring oldFile( currentFilePath.begin(), currentFilePath.end() );
			std::wstring newFile( destination.begin(), destination.end() );
			CopyFileW( oldFile.c_str(), newFile.c_str(), false );
			std::cout << "Done!" << std::endl;
		}
	}

// 	std::cout << "Cooking " << filePaths.size() << " items..." << std::endl;
	// cook each file to the destination directory
}