bool TFileAttachmentWidget::SaveAttachmentItem(const AAttachmentItem* item,
  const QFileInfo& targetPath, bool checkForOverwrite)
  {
  const QString title(tr("Save attachment..."));
  if(checkForOverwrite && targetPath.exists())
    {
    auto result = QMessageBox::question(this, title, tr("File: ") +
      targetPath.absoluteFilePath() + tr(" already exists.\nDo you want to overwrite it ?"));

    if(result == QMessageBox::Button::No)
      return false;
    }

  QFile targetFile(targetPath.absoluteFilePath());
  TSaveStatus saveStatus = item->Save(targetFile);

  switch(saveStatus)
    {
    case TSaveStatus::READ_SOURCE_ERROR:
      QMessageBox::warning(this, title, tr("Cannot read file: ") + item->GetDisplayedFileName());
      return false;

    case TSaveStatus::WRITE_TARGET_ERROR:
      QMessageBox::warning(this, title, tr("Cannot write to file: ") + targetPath.absoluteFilePath());
      return false;

    case TSaveStatus::SUCCESS:
      return true;

    default:
      assert(false && "Unknown save status");
    }

  return false;
  }
bool medPluginGenerator::generateCMakeLists()
{
    QFile targetFile(d->target.absoluteFilePath("CMakeLists.txt"));
    
    if(!targetFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
        qWarning() << "medPluginGenerator: unable to open CMakeLists.txt for writing";
        return false;
    }
    
    QFile templateFile(QString(":template/%1/cmake").arg(d->pluginFamily));
    
    if(!templateFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "medPluginGenerator: unable to open template file " << templateFile.fileName() << " for reading";
        return false;
    }
    
    QTextStream stream(&targetFile);
    
    stream << QString(templateFile.readAll()).arg(d->plugin);
    
    targetFile.close();
    
    templateFile.close();
    
    return true;
}
bool medPluginGenerator::generateExportHeaderFile()
{
    QFile targetFile(d->target.absoluteFilePath(QString(d->plugin).append("PluginExport.h")));
    
    if(!targetFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
        qWarning() << "medPluginGenerator: unable to open" << QString(d->plugin).append("PluginExport.h") << "for writing";
        return false;
    }
    
    QFile templateFile(":template/export.h");
    
    if(!templateFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "medPluginGenerator: unable to open template file " << templateFile.fileName() << " for reading";
        return false;
    }
    
    QTextStream stream(&targetFile);
    
    stream << QString(templateFile.readAll()).arg(d->plugin).arg(d->plugin.toUpper());
    
    targetFile.close();
    
    templateFile.close();
    
    return true;
}
Example #4
0
bool Dialogs::ConvertMemoryCardDialog::ConvertToFile( const wxFileName& sourcePath, const wxFileName& targetPath, const u32 sizeInMB ) {
	// Conversion method: Open FolderMcd as usual, then read the raw data from it and write it to a file stream

	wxFFile targetFile( targetPath.GetFullPath(), L"wb" );
	if ( !targetFile.IsOpened() ) {
		return false;
	}

	FolderMemoryCard sourceFolderMemoryCard;
	AppConfig::McdOptions config;
	config.Enabled = true;
	config.Type = MemoryCardType::MemoryCard_Folder;
	sourceFolderMemoryCard.Open( sourcePath.GetFullPath(), config, ( sizeInMB * 1024 * 1024 ) / FolderMemoryCard::ClusterSize, false, L"" );

	u8 buffer[FolderMemoryCard::PageSizeRaw];
	u32 adr = 0;
	while ( adr < sourceFolderMemoryCard.GetSizeInClusters() * FolderMemoryCard::ClusterSizeRaw ) {
		sourceFolderMemoryCard.Read( buffer, adr, FolderMemoryCard::PageSizeRaw );
		targetFile.Write( buffer, FolderMemoryCard::PageSizeRaw );
		adr += FolderMemoryCard::PageSizeRaw;
	}

	targetFile.Close();
	sourceFolderMemoryCard.Close( false );

	return true;
}
bool medPluginGenerator::generateTypeWorkspaceSourceFile()
{
    QFile targetFile(d->target.absoluteFilePath(QString(d->plugin).append("Workspace.cpp")));

    if(!targetFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
        qWarning() << "medPluginGenerator: unable to open" << QString(d->plugin).append("Workspace.cpp") << "for writing";
        return false;
    }

    QFile templateFile(QString(":template/%1/typeWorkspace.cpp").arg(d->pluginFamily));

    if(!templateFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "medPluginGenerator: unable to open template file " << templateFile.fileName() << " for reading";
        return false;
    }

    QTextStream stream(&targetFile);

    stream << QString(templateFile.readAll())
    .arg(d->plugin);

    targetFile.close();

    templateFile.close();

    return true;
}
Example #6
0
void Importer::importEffectFile(const QFileInfo& effectFile, const QString& targetFileName, const QString& customData)
{
	QFileInfo target(m_targetResourcePath, targetFileName);
	if (!target.absoluteDir().exists())
		m_targetResourcePath.mkpath(target.absolutePath());		
	const CopyJob job(effectFile, target);
	if (!job.exec() && !m_filesToOverwrite.contains(job) && !m_alreadyCopied.contains(job))
	{
		if (!customData.isEmpty())
		{
			if (QMessageBox::question(0, QObject::tr("Overwrite file?"), QObject::tr("Do you want to overwrite the existing effect\n%1").arg(effectFile.absoluteFilePath()), QMessageBox::Yes | QMessageBox::Default, QMessageBox::No, QMessageBox::Cancel | QMessageBox::Escape) != QMessageBox::Yes)
				return;
			QFile targetFile(target.absoluteFilePath());
			if (!targetFile.open(QIODevice::WriteOnly | QIODevice::Truncate))
				m_errorLog.push_back(QObject::tr("Error opening %1 for writing!").arg(target.absoluteFilePath()));
			else
				targetFile.write(customData.toLocal8Bit());
			targetFile.close();
		}
		else
			m_filesToOverwrite.append(job);		
	}
	else
		m_alreadyCopied.append(job);
}
bool medPluginGenerator::generateRPISourceFile()
{
    QString baseName = QString(d->plugin).replace(0, 1, d->plugin.left(1).toUpper());
    QFile targetFile(d->target.absoluteFilePath(QString("rpi" + baseName).append(".hxx")));
    
    if(!targetFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
        qWarning() << "medPluginGenerator: unable to open" << QString("rpi" + baseName).append(".hxx") << "for writing";
        return false;
    }
    
    QFile templateFile(QString(":template/%1/rpiBase.hxx").arg(d->pluginFamily));
    
    if(!templateFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "medPluginGenerator: unable to open template file " << templateFile.fileName() << " for reading";
        return false;
    }
    
    QTextStream stream(&targetFile);
    
    stream << QString(templateFile.readAll())
    .arg(QString(d->plugin).replace(0, 1, d->plugin.left(1).toUpper()));
    
    targetFile.close();
    
    templateFile.close();
    
    return true;
}
Example #8
0
void saveEmbeddedFile( Okular::EmbeddedFile *ef, QWidget *parent )
{
    const QString caption = i18n( "Where do you want to save %1?", ef->name() );
    const QString path = QFileDialog::getSaveFileName( parent, caption, ef->name() );
    if ( path.isEmpty() )
        return;
    QFile targetFile( path );
    writeEmbeddedFile( ef, parent, targetFile );
}
Example #9
0
void MultiMC::InstallUpdate()
{
	int tryNum = 0;
	wxProgressDialog *progDlg = new wxProgressDialog(_("Installing updates..."),
		_("Waiting for old version to exit..."));

Retry:
	tryNum++;
	progDlg->Pulse(wxString::Format(
		_("Waiting for old version to exit... Try #%i."), tryNum));

	// Let the other process exit.
	PulseYieldSleep(1, progDlg);

	wxFileName targetFile(updateTarget);
	
	if (!wxCopyFile(thisFileName, targetFile.GetFullPath()))
	{
		if (tryNum < installUpdateTries)
			goto Retry;
		else
		{
			wxLogError(_("Failed to install updates. Tried %i times. \n\
This is probably because the file that is supposed to be updated is in use. \n\
Please check to make sure there are no other running MultiMC processes \n\
and that MultiMC's updater has sufficient permissions to replace the file \n\
%s and then try again."), tryNum, targetFile.GetFullPath().c_str());
			progDlg->Destroy();
			return;
		}
	}

	progDlg->Pulse(_("Update installed successfully. Starting MultiMC..."));
	progDlg->Fit();
	progDlg->CenterOnScreen();
	wxYieldIfNeeded();
	
	targetFile.MakeAbsolute();

	if (!updateQuiet)
	{
		wxProcess proc;
		wxExecute("\"" + targetFile.GetFullPath() + "\"", wxEXEC_ASYNC, &proc);
		proc.Detach();
	}
	progDlg->Destroy();
}

void MultiMC::YieldSleep(int secs)
{
	int waitLoops = secs * 10;
	for (int i = 0; i < waitLoops; i++)
	{
		wxMilliSleep(100);
		Yield(true);
	}
}
Example #10
0
int BingoApp::generateCard(QTextStream& sourceSvgCard, size_t cardNumber)
{
	const QString& targetFilename = generateTargetCardFilename(cardNumber);
	QFile targetFile(targetFilename);
	if ( ! targetFile.open(QIODevice::Text | QIODevice::WriteOnly) )
		{ cerr << "bingo: could not create " << targetFilename << endl; return 22; }

	QTextStream targetStream(&targetFile);
	Card card(cardNumber, symbols);
	return card.fillSvg(sourceSvgCard, targetStream);
}
Example #11
0
bool ChooseTargetDialog::scanTargetDirectory()
{
	QDir targetDir(QDir::currentPath() + "/targets");
	QStringList targetDirs;
	QStringList targetList;

	// Clean up any leftovers from the last time this was run
	m_targetFileList.clear();
	ui_listWidget->clear();

	// Choke if we can't find the target directory
	if(!targetDir.exists()) {
		qWarning("ChooseTargetDialog::scanTargetDirectory: Could not find targets directory");
		ui_listWidget->clear();
		return false;
	}
	
	// Get a list of the possible target directories and check through them
	targetDirs = targetDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
	QStringListIterator i(targetDirs);

	while(i.hasNext()) {
		QString dirName = i.next();
		targetDir.cd(dirName);
		
		// The target file naming scheme is <dirname>.target
		QFileInfo targetFile(targetDir, dirName + ".target");

		// If we can't find a target file, skip this directory
		if(!targetFile.exists()) {
			qWarning("ChooseTargetDialog::scanTargetDirectory: Invalid target directory %s", qPrintable(targetDir.absolutePath()));
			targetDir.cdUp();
			continue;
		}

		// Add the target file to the list
		m_targetFileList.push_back(targetFile.absoluteFilePath());
		
		QSettings target(m_targetFileList.last(), QSettings::IniFormat);
		targetList << target.value("display_name").toString();
		targetDir.cdUp();
	}

	// Didn't find any targets, quit
	if(targetList.count() == 0) {
		qWarning("ChooseTargetDialog::scanTargetDirectory: No targets to display!\n");
		return false;
	}

	// Add the targets we found, and focus on the top one
	ui_listWidget->addItems(targetList);
	ui_listWidget->setCurrentItem(ui_listWidget->item(0));
	return true;
}
bool SolarSystemEditor::copySolarSystemConfigurationFileTo(QString filePath)
{
	if (QFile::exists(customSolarSystemFilePath))
	{
		QFileInfo targetFile(filePath);
		return QFile::copy(customSolarSystemFilePath, targetFile.absoluteFilePath());
	}
	else
	{
		return false;
	}
}
Example #13
0
bool shouldTargetFileBeUpdated(const std::string & sourceFileName, const std::string & targetFileName)
{
	Poco::File targetFile(targetFileName);

	if(! targetFile.exists()) {
		return true;
	}

	Poco::File sourceFile(sourceFileName);
	
	return sourceFile.getLastModified() >= targetFile.getLastModified();
}
void CSVPointListExporter::exportFromDataBase()
{
    if(!QFile::exists(sourseDataBaseFile_))
    {
        qWarning() << sourseDataBaseFile_ << "not exists";
        return;
    }

    SqlPointListReader reader(sourseDataBaseFile_, sourseTableName_);

    if(!reader.open())
    {
        qWarning() << sourseDataBaseFile_ << "not open";
        return;
    }

    QFile targetFile(targetFileName_);
    if(!targetFile.open(QFile::WriteOnly | QIODevice::Text))
    {
        qWarning() << targetFileName_ << "can't open for writing";
    }

    QTextStream targetFileStream(&targetFile);
    const IDList idList = reader.readAllItems();

    for(int i = 0; i < idList.count(); i++)
    {
        const ID& id = idList.at(i);
        const PointList pointList = reader.read(id);
        for(int j = 0; j < pointList.count(); j++)
        {
            const Point& point = pointList.at(j);
            targetFileStream << pointList.id() << ";" << point;

            const bool isLast = ((i + 1) == idList.count())
                    && ((j + 1) == pointList.count());

            if(!isLast)
            {
                targetFileStream << '\n';
            }
        }
    }

    targetFile.flush();
    targetFile.close();
}
Example #15
0
bool dtkPluginGenerator::generateReadmeFile(void)
{
    QFile targetFile(d->target.absoluteFilePath("README.txt"));

    if(!targetFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
	qWarning() << "dtkPluginGenerator: unable to open CMakeLists.txt for writing";
	return false;
    }

    QTextStream stream(&targetFile);

    stream << d->description;

    targetFile.close();

    return true;
}
Example #16
0
void ModList::Save(QString filePath)
{
    QJsonArray array;
    for (int idx = 0; idx < mods.size(); ++idx)
    {
        array.append(mods.at(idx).save());
    }
    QJsonObject object;
    object.insert("mods", array);
    QJsonDocument doc;
    doc.setObject(object);
    QByteArray filedata = doc.toJson(QJsonDocument::Indented);

    QFile targetFile(filePath);
    targetFile.open(QIODevice::Truncate|QIODevice::WriteOnly);
    targetFile.write(filedata);
}
/**
@SYMTestCaseID PIM-CONVERTERTEST-0001
*/	
void doMainL()
	{
	test.Start(KTest1);

	RFs fs;
	User::LeaveIfError(fs.Connect());
	CleanupClosePushL(fs);
	TBufC<11> targetFile(_L("target file"));

//========================================================
//path
	TBuf<17> path(_L(":\\testHtml\\*.*"));
//single file
	TBuf<25> sourceFile;
	_LIT(KFileName, "test1.txt");
//========================================================
	if(getPathL(path, fs))
		{
		//CONVERT PATH
		TBuf<17> pathName(path);
		pathName.SetLength(pathName.Length()-3);

		convertPathL(path, pathName, fs, targetFile);

		//CONVERT SINGLE FILE

		sourceFile.Copy(pathName);
		sourceFile.Append(KFileName);

		synchronousL(sourceFile, targetFile);
//		asynchronousL(sourceFile, targetFile);

		//OOM TESTS
//		oomSynchronousL(sourceFile, targetFile);
//		oomAsynchronousL(sourceFile, targetFile);
		}
//========================================================

	CleanupStack::PopAndDestroy(); // fs
	
	REComSession::FinalClose(); //needed, otherwise you will get a memory leak
	
	test.End();
	test.Close();
	}
Example #18
0
void GeneneralConf::exportFileConfiguration() {
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"),
                               "flameshot.conf");

    // Cancel button
    if (fileName.isNull()) {
        return;
    }

    QFile targetFile(fileName);
    if (targetFile.exists()) {
        targetFile.remove();
    }
    bool ok = QFile::copy(ConfigHandler().configFilePath(), fileName);
    if (!ok) {
        QMessageBox::about(this, tr("Error"), tr("Unable to write file."));
    }
}
Example #19
0
void PropagateRemoteMove::start()
{
    if (_propagator->_abortRequested.fetchAndAddRelaxed(0))
        return;

    qDebug() << Q_FUNC_INFO << _item->_file << _item->_renameTarget;

    QString targetFile(_propagator->getFilePath(_item->_renameTarget));

    if (_item->_file == _item->_renameTarget) {
        // The parent has been renamed already so there is nothing more to do.
        finalize();
        return;
    }
    if (_item->_file == QLatin1String("Shared") ) {
        // Before owncloud 7, there was no permissions system. At the time all the shared files were
        // in a directory called "Shared" and were not supposed to be moved, otherwise bad things happened

        QString versionString = _propagator->account()->serverVersion();
        if (versionString.contains('.') && versionString.split('.')[0].toInt() < 7) {
            QString originalFile(_propagator->getFilePath(QLatin1String("Shared")));
            emit _propagator->touchedFile(originalFile);
            emit _propagator->touchedFile(targetFile);
            QString renameError;
            if( FileSystem::rename(targetFile, originalFile, &renameError) ) {
                done(SyncFileItem::NormalError, tr("This folder must not be renamed. It is renamed back to its original name."));
            } else {
                done(SyncFileItem::NormalError, tr("This folder must not be renamed. Please name it back to Shared."));
            }
            return;
        }
    }

    QString destination = QDir::cleanPath(_propagator->account()->url().path() + QLatin1Char('/')
            + _propagator->account()->davPath() + _propagator->_remoteFolder + _item->_renameTarget);
    _job = new MoveJob(_propagator->account(),
                        _propagator->_remoteFolder + _item->_file,
                        destination, this);
    connect(_job, SIGNAL(finishedSignal()), this, SLOT(slotMoveJobFinished()));
    _propagator->_activeJobList.append(this);
    _job->start();

}
Example #20
0
bool AddTool::_addOneFile(QString templateName, QString targetName,
                          const QList<QPair<QRegExp, QString> > &mapping)
{
    qDebug() << "Adding file:" << targetName << "from" << templateName;

    { //block to make sure file processing is done when we get out of it
        QFile templateFile(templateName);
        QFile targetFile(targetName);

        if(!targetFile.open(QIODevice::WriteOnly | QIODevice::Text))
        {
            toolError(QString("Could not open file: ") + targetName + " for write.");
            return false;
        }

        if(!templateFile.open(QIODevice::ReadOnly | QIODevice::Text))
        {
            toolError(QString("Could not open file: ") + templateName + " for read.");
            return false;
        }

        QTextStream fromStream(&templateFile);
        QTextStream toStream(&targetFile);

        transformStream(fromStream, toStream, mapping);
    }

    //Now add it to mercurial
    QProcess process;
    process.setWorkingDirectory(QFileInfo(targetName).absolutePath());
    process.start(QString("hg add ") + QFileInfo(targetName).fileName());
    if(!process.waitForFinished(3000)) //3 seconds delay
    {
        toolError(QString("Couldn't hg add the file: ") + targetName);
        return false;
    }

    FormatTool::formatFile(targetName);

    return true;
}
Example #21
0
void KNFileNameLineEdit::setFilePath(const QString &filePath)
{
    //Generate the file info.
    QFileInfo targetFile(filePath);
    //Check the existance of the file path.
    if(!targetFile.exists())
    {
        //Ignore the value which doesn't exist.
        return;
    }
    //Save the file path.
    m_fileName=targetFile.fileName();
    //Save the suffix.
    m_suffix=targetFile.suffix();
    //Get the directory of the file path.
    m_directory=targetFile.absoluteDir();
    //Set the file name to be the line edit text.
    setText(m_fileName);
    //Select all the parts except the suffix.
    setSelection(0, m_fileName.length()-targetFile.suffix().length()-1);
}
Example #22
0
void QwmMonitorWindow::on_btnConfigurationSetBanner_clicked()
{
    QString selectedPath = QFileDialog::getOpenFileName(this, tr("Open Banner Image"),
                                                        QDir::homePath(), tr("PNG-Image (*.png)"));
    if (selectedPath.isEmpty()) { return; }
    QFile targetFile(selectedPath);

    if (!targetFile.open(QIODevice::ReadOnly)) {
        QMessageBox::warning(this, tr("Unable to load banner image"),
            tr("Could not open the image file: %1").arg(targetFile.errorString()));
        return;
    }
    QByteArray imageData = targetFile.readAll();

    // Scale and display the banner
    QImage bannerImage =  QImage::fromData(imageData).scaled(QSize(200, 35), Qt::KeepAspectRatio);
    fConfigurationBanner->setPixmap(QPixmap::fromImage(bannerImage));

    // Emit a signal for the controller
    emit selectedNewBanner(bannerImage);
}
Example #23
0
void DownloadOperation::processFile()
{
  m_fileOffset = 0;

  File targetFile(m_pathToTargetFile.getString());

  if (targetFile.exists()) {
    FileInfo *sourceFileInfo = m_toCopy->getFileInfo();
    FileInfo targetFileInfo(&targetFile);

    //
    // Copy listener must decide what to do with this situation
    //

    int action = m_copyListener->targetFileExists(sourceFileInfo,
                                                  &targetFileInfo,
                                                  m_pathToTargetFile.getString());
    switch (action) {
    case CopyFileEventListener::TFE_OVERWRITE:
      break;
    case CopyFileEventListener::TFE_SKIP:
      m_totalBytesCopied += sourceFileInfo->getSize();
      gotoNext();
      return ;
    case CopyFileEventListener::TFE_APPEND:
      m_fileOffset = targetFileInfo.getSize();
      break;
    case CopyFileEventListener::TFE_CANCEL:
      if (!isTerminating()) {
        terminate();
      } // if not terminating
      return ;
    default:
      _ASSERT(FALSE);
    } // switch
  } // if target file exists

  // Send request that we want to download file
  m_sender->sendDownloadRequest(m_pathToSourceFile.getString(), m_fileOffset);
}
Example #24
0
bool mainWindow::offlineUpdate()
{
    QString updateFileName = QFileDialog::getOpenFileName(this,
                                   tr("Select Update File"), ".",
                                   tr("yadsa update file (*.yadsa)"));
    if(updateFileName.isEmpty())
    return true;
    std::ifstream updateFile(qPrintable(updateFileName),std::ios::in | std::ios::binary);
    std::ofstream targetFile(dbFilePath,std::ios::in | std::ios::binary | std::ios::app);
    if(!updateFile || !targetFile)
    {
        updateError();
        return false;
    }
    updateFile.seekg(0,std::ios::end);
    if(updateFile.tellg()==0)
    {
        updateError();
        return false;
    }
    updateFile.seekg(0);
    //to add check for confirming valid update file
    disc a;
    while(updateFile.read((char *) &a, sizeof(a)))
               {
                    soft b;
                    targetFile.write((char *) &a, sizeof(a));
                    for(int i=0;i<a.count;i++)
                    {
                         updateFile.read((char *) &b, sizeof(b));
                         targetFile.write((char *) &b, sizeof(b));
                    }
               }

    updateFile.close();
    targetFile.close();
    QMessageBox::information(this,tr("Success"),tr("Update successful<br />Reloading Archive..."));
    loadArchive();
    return true;
}
bool medPluginGenerator::generateTypeSourceFile()
{
    QFile targetFile(d->target.absoluteFilePath(QString(d->plugin).append(".cpp")));
    
    if(!targetFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
        qWarning() << "medPluginGenerator: unable to open" << QString(d->plugin).append(".cpp") << "for writing";
        return false;
    }
    
    QFile templateFile(QString(":template/%1/type.cpp").arg(d->pluginFamily));
    
    if(!templateFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "medPluginGenerator: unable to open template file " << templateFile.fileName() << " for reading";
        return false;
    }
    
    QTextStream stream(&targetFile);
    
    if (d->pluginFamily == "registration")
    {    
        stream << QString(templateFile.readAll())
        .arg(d->plugin)
        .arg(d->type)
        .arg(QString(d->plugin).replace(0, 1, d->plugin.left(1).toUpper()))
        .arg(QString(d->name).replace(0, 1, d->name.left(1).toUpper()));
    }
    else
    {
        stream << QString(templateFile.readAll())
        .arg(d->plugin)
        .arg(d->type)
        .arg(QString(d->plugin).replace(0, 1, d->plugin.left(1).toUpper()));
    }
    
    targetFile.close();
    
    templateFile.close();
    
    return true;
}
Example #26
0
bool ReplayProvider::Import(const wxString& filename, bool move)
{
	wxFileName fn(filename);
	if (fn.GetExt().IsSameAs("zip", false))
	{
		// TODO: handle zip files
		wxFileInputStream fstr(filename);
		wxZipInputStream zip(fstr);
		while (wxZipEntry* zipEntry = zip.GetNextEntry())
		{
			wxFileName entryFN(zipEntry->GetName());
			if (entryFN.GetExt().IsSameAs("replay", false))
			{
				wxFileName targetFN(m_localPath, entryFN.GetFullName());
				wxFileOutputStream targetFile(targetFN.GetFullPath());
				zip.Read(targetFile);
				targetFile.Close();
				targetFN.SetTimes(NULL, &zipEntry->GetDateTime(), &zipEntry->GetDateTime());

				Replay::Ptr ri(new Replay(targetFN.GetFullPath()));
				replay.push_back(ri);
			}
		}
	}
	else if (fn.GetExt().IsSameAs("replay", false))
	{
		wxFileName targetFN(m_localPath, fn.GetFullName());
		bool copyRes = wxCopyFile(filename, targetFN.GetFullPath(), false);
		if (copyRes)
		{
			Replay::Ptr ri(new Replay(targetFN.GetFullPath()));
			replay.push_back(ri);
		}

		return copyRes;
	}

	return false;
}
Example #27
0
	string copyFile(const string& sourcePath, File& sourceFile, const string& targetPath,
			const std::function< void (const vector< string >&) >& callback)
	{
		// preparing target
		string openError;
		File targetFile(targetPath, "a", openError);
		if (!openError.empty())
		{
			return format2("unable to open the file '%s' for appending: %s", targetPath, openError);
		}
		auto totalBytes = targetFile.tell();
		callback(vector< string > { "downloading",
				lexical_cast< string >(totalBytes), lexical_cast< string >(0)});

		{ // determing the size
			struct stat st;
			if (::stat(sourcePath.c_str(), &st) == -1)
			{
				fatal2e(__("%s() failed: '%s'"), "stat", sourcePath);
			}
			callback(vector< string > { "expected-size",
					lexical_cast< string >(st.st_size) });
		}

		{ // writing
			char buffer[4096];
			size_t size = sizeof(buffer);
			while (sourceFile.getBlock(buffer, size), size)
			{
				targetFile.put(buffer, size);
				totalBytes += size;
				callback(vector< string > { "downloading",
						lexical_cast< string >(totalBytes), lexical_cast< string >(size)});
			}
		}

		return string();
	}
Example #28
0
bool KNUtil::saveTextToFile(const QString &filePath, const QString &content)
{
    //Generate the target file.
    QFile targetFile(filePath);
    //Ensure the path is valid.
    //Open as write only mode.
    if(ensurePathValid(QFileInfo(targetFile).absolutePath()).isEmpty() ||
            !targetFile.open(QIODevice::WriteOnly))
    {
        //If there's no path to this file, how can we write the file?
        return false;
    }
    //Generate the text stream.
    QTextStream textStream(&targetFile);
    //Set the UTF-8 codec.
    textStream.setCodec(QTextCodec::codecForName("UTF-8"));
    //Save the content to the file.
    textStream << content << flush;
    //Close the file.
    targetFile.close();
    //Mission complete.
    return true;
}
Example #29
0
bool dtkPluginGenerator::generateCopyingFile(void)
{
    QFile targetFile(d->target.absoluteFilePath("COPYING.txt"));

    if(!targetFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
	qWarning() << "dtkPluginGenerator: unable to open COPYING.txt for writing";
	return false;
    }

    QFile templateFile(QString(":template/license/").append(d->license));
    if(!templateFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "dtkPluginGenerator: unable to open template file " << templateFile.fileName() << " for reading";
        return false;
    }

    QTextStream stream(&targetFile);

    stream << QString(templateFile.readAll());

    targetFile.close();

    return true;
}
Example #30
0
	kjm::_tstring calcMD5(LPCTSTR fname) {
		m_hasError = false;
		m_progress = 0;
		kjm::_tstring result;

		kjm::cfile targetFile(fname, _T("rb"));
		if (targetFile.is_open()) {
			//MD5 md5(targetFile.get_handle());
			MD5 md5;
			{
				int fsize = _filelength(fileno(targetFile.get_handle()));

				unsigned char buffer[1024];
				int len;
				int totalRead = 0;
				while (len = fread(buffer, 1, 1024, targetFile.get_handle())) {
					md5.update(buffer, len);
					totalRead += len;

					m_progress = (int)(((double)totalRead / (double)fsize) * 100.0);
				}
			}
			md5.finalize();

			char* pchHexDigest = md5.hex_digest();
			if (pchHexDigest) {
				result = kjm::util::toUnicode(pchHexDigest);
				delete[] pchHexDigest;
			}
		} else {
			m_errDescription = kjm::util::sprintf_str(_T("ファイルがオープンできません(error: %d)"), errno);
			m_hasError = true;
		}

		return result;
	}