Exemplo n.º 1
0
void cItem::safeoldsave()
{
	std::string oldFileName( SrvParms->savePath + SrvParms->itemWorldfile + SrvParms->worldfileExtension );
	std::string newFileName( SrvParms->savePath + SrvParms->itemWorldfile + SrvParms->worldfileExtension + "$" );
	remove( newFileName.c_str() );
	rename( oldFileName.c_str(), newFileName.c_str() );
}
Exemplo n.º 2
0
//AC.template.verifiedRecord
void  MainWidget::init_word()
{
    QAxWidget word("Word.Application");
    word.setProperty("Visible", false);//隐式的打开一个word应用程序

    QAxObject * documents = word.querySubObject("Documents"); //获取所有工作文档
    documents->dynamicCall("Add (void)");//创建一个word文档
    QAxObject * document = word.querySubObject("ActiveDocument"); //获取当前激活的文档
    QAxObject *selection = word.querySubObject("Selection"); //写入文件内容

    QDateTime time = QDateTime::currentDateTime();//获取系统现在的时间
    QString    str = time.toString("yyyy-MM-dd hh:mm:ss ddd"); //设置显示格式
    selection->dynamicCall("TypeText(const QString&)","hello"+str);

    //设置保存
    QVariant newFileName("e:/test.doc"); //存放位置和名称
    QVariant fileFormat(1); //文件格式
    QVariant LockComments(false);
    QVariant Password("");     //设置打开密码
    QVariant recent(true);
    QVariant writePassword("");
    QVariant ReadOnlyRecommended(false);

    document->querySubObject("SaveAs(const QVariant&, const QVariant&,const QVariant&, const QVariant&, const QVariant&, const QVariant&,const QVariant&)",    newFileName, fileFormat, LockComments, Password, recent, writePassword, ReadOnlyRecommended);
    document->dynamicCall("Close (boolean)", true);   //关闭文档
    word.dynamicCall("Quit (void)");//退出
}
Exemplo n.º 3
0
// Backend for OnMRUFile and OnMRUProject
bool AudacityApp::MRUOpen(wxString fileName) {
   // Most of the checks below are copied from AudacityProject::ShowFileDialog
   // - some rationalisation might be possible.
   
   AudacityProject *proj = GetActiveProject();
   
   if(!fileName.IsEmpty()) {
      
      // verify that the file exists 
      if(wxFile::Exists(fileName)) {
         wxFileName newFileName(fileName);
         
         gPrefs->Write(wxT("/DefaultOpenPath"), wxPathOnly(fileName));
         
         // Make sure it isn't already open
         size_t numProjects = gAudacityProjects.Count();
         for (size_t i = 0; i < numProjects; i++) {
            if (newFileName.SameAs(gAudacityProjects[i]->GetFileName())) {
               wxMessageBox(wxString::Format(_("%s is already open in another window."),
                  newFileName.GetName().c_str()),
                  _("Error opening project"),
                  wxOK | wxCENTRE);
               continue;
            }
         }
         
         // DMM: If the project is dirty, that means it's been touched at
         // all, and it's not safe to open a new project directly in its
         // place.  Only if the project is brand-new clean and the user
         // hasn't done any action at all is it safe for Open to take place
         // inside the current project.
         //
         // If you try to Open a new project inside the current window when
         // there are no tracks, but there's an Undo history, etc, then
         // bad things can happen, including data files moving to the new
         // project directory, etc.
         if (!proj || proj->GetDirty() || !proj->GetIsEmpty()) {
            proj = CreateNewAudacityProject(gParentWindow);
         }
         // This project is clean; it's never been touched.  Therefore
         // all relevant member variables are in their initial state,
         // and it's okay to open a new project inside this window.
         proj->OpenFile(fileName);

         // Add file to "recent files" list.
         proj->GetRecentFiles()->AddFileToHistory(fileName);
         gPrefs->SetPath(wxT("/RecentFiles"));
         proj->GetRecentFiles()->Save(*gPrefs);
         gPrefs->SetPath(wxT(".."));
      }
      else {
         // File doesn't exist - remove file from history
         wxMessageBox(wxString::Format(_("%s does not exist and could not be opened.\n\nIt has been removed from the history list."), 
                      fileName.c_str()));
         return(false);
      }
   }
   return(true);
}
Exemplo n.º 4
0
	bool CDatabase::BackupDB(std::string sFileName)
	{
		std::string newFileName(sFileName);
		newFileName += ".bak";
		if(::CopyFile(CString(sFileName.c_str()),CString(newFileName.c_str()),FALSE))
		{
			DeleteDict(LastBackupKey);
			InsertDict(LastBackupKey,(int)time(NULL));
			return true;
		}

		return false;
	}
Exemplo n.º 5
0
bool DirManager::CopyToNewProjectDirectory(BlockFile *f)
{
   wxFileName newFileName(projFull, f->mFileName.GetFullName());
   if ( !(newFileName == f->mFileName) ) {
      bool ok = wxCopyFile(f->mFileName.GetFullPath(), newFileName.GetFullPath());
      if (ok) {
         f->mFileName = newFileName;
      }
      else
         return false;
   }

   return true;
}
Exemplo n.º 6
0
wxString BatchCommands::BuildCleanFileName(wxString fileName, wxString extension)
{
   wxFileName newFileName(fileName);
   wxString justName = newFileName.GetName();
   wxString pathName = newFileName.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR);

   if (justName == wxT("")) {
      wxDateTime now = wxDateTime::Now();
      int year = now.GetYear();
      wxDateTime::Month month = now.GetMonth();
      wxString monthName = now.GetMonthName(month);
      int dom = now.GetDay();
      int hour = now.GetHour();
      int minute = now.GetMinute();
      int second = now.GetSecond();
      justName = wxString::Format(wxT("%d-%s-%02d-%02d-%02d-%02d"),
           year, monthName.c_str(), dom, hour, minute, second);

//      SetName(cleanedFileName);
//      bool isStereo;
//      double endTime = project->mTracks->GetEndTime();
//      double startTime = 0.0;
      //OnSelectAll();
      pathName = gPrefs->Read(wxT("/DefaultOpenPath"), ::wxGetCwd());
      ::wxMessageBox(wxString::Format(wxT("Export recording to %s\n/cleaned/%s%s"),
                                      pathName.c_str(), justName.c_str(), extension.c_str()),
                     wxT("Export recording"),
                  wxOK | wxCENTRE);
      pathName += wxT("/");
   }
   wxString cleanedName = pathName;
   cleanedName += wxT("cleaned");
   bool flag  = ::wxFileName::FileExists(cleanedName);
   if (flag == true) {
      ::wxMessageBox(wxT("Cannot create directory 'cleaned'. \nFile already exists that is not a directory"));
      return wxT("");
   }
   ::wxFileName::Mkdir(cleanedName, 0777, wxPATH_MKDIR_FULL); // make sure it exists

   cleanedName += wxT("/");
   cleanedName += justName;
   cleanedName += extension;
   wxGetApp().AddFileToHistory(cleanedName);

   return cleanedName;
}
QString LibSingleFileInterface::overwriteFileName(QString& filename)
{
    QString newFileName(filename);

    while (QFile::exists(newFileName)) {
        Kerfuffle::OverwriteQuery query(newFileName);

        query.setMultiMode(false);
        emit userQuery(&query);
        query.waitForResponse();

        if ((query.responseCancelled()) || (query.responseSkip())) {
            return QString();
        } else if (query.responseOverwrite()) {
            break;
        } else if (query.responseRename()) {
            newFileName = query.newFilename();
        }
    }

    return newFileName;
}
Exemplo n.º 8
0
bool DirManager::MoveToNewProjectDirectory(BlockFile *f)
{
    wxFileName newFileName(projFull, f->mFileName.GetFullName());

    if ( !(newFileName == f->mFileName) ) {
        bool ok = wxRenameFile(FILENAME(f->mFileName.GetFullPath()),
                               FILENAME(newFileName.GetFullPath()));

        if (ok)
            f->mFileName = newFileName;
        else {
            ok = wxCopyFile(FILENAME(f->mFileName.GetFullPath()),
                            FILENAME(newFileName.GetFullPath()));
            if (ok) {
                wxRemoveFile(FILENAME(f->mFileName.GetFullPath()));
                f->mFileName = newFileName;
            }
            else
                return false;
        }
    }

    return true;
}
Exemplo n.º 9
0
// ==== PRIVATE SLOTS ====
void FOWorker::slotStartOperations(){
  if(DEBUG){ qDebug() << "Start File operations" << isRM << isCP << isMV << ofiles << nfiles << overwrite; }
  //Now setup the UI
  /*ui->progressBar->setRange(0,ofiles.length());
  ui->progressBar->setValue(0);
  ui->progressBar->setVisible(true);
  QApplication::processEvents();*/
  /*if(!isRM && overwrite==-1){
    //Check if the new files already exist, and prompt for action
    QStringList existing;
    for(int i=0; i<nfiles.length(); i++){
      if(QFile::exists(nfiles[i])){ existing << nfiles[i].section("/",-1); }
    }
    if(!existing.isEmpty()){
      //Prompt for whether to overwrite, not overwrite, or cancel
      QMessageBox::StandardButton ans = QMessageBox::question(this, tr("Overwrite Files?"), tr("Do you want to overwrite the existing files?")+"\n"+tr("Note: It will just add a number to the filename otherwise.")+"\n\n"+existing.join(", "), QMessageBox::YesToAll | QMessageBox::NoToAll | QMessageBox::Cancel, QMessageBox::NoToAll);
      if(ans==QMessageBox::NoToAll){ overwrite = 0; } //don't overwrite
      else if(ans==QMessageBox::YesToAll){ overwrite = 1; } //overwrite
      else{ emit finished(QStringList()); return; } //cancel operations
    }
  }*/
	
  //Get the complete number of items to be operated on (better tracking)
  QStringList olist, nlist; //old/new list to actually be used (not inputs - modified/added as necessary)
  for(int i=0; i<ofiles.length() && !stopped; i++){
    if(isRM){ //only old files
      olist << subfiles(ofiles[i], false); //dirs need to be last for removals
    }else if(isCP || isRESTORE){
      if(QFile::exists(nfiles[i])){
	if(overwrite!=1){
	  qDebug() << " - Get New Filename:" << nfiles[i];
	  nfiles[i] = newFileName(nfiles[i]); //prompt for new file name up front before anything starts
	  qDebug() << " -- " << nfiles[i];
	}
      }
      if(nfiles[i] == ofiles[i] && overwrite==1){
	//Trying to copy a file/dir to itself - skip it
	continue;
      }
      QStringList subs = subfiles(ofiles[i], true); //dirs need to be first for additions
      for(int s=0; s<subs.length(); s++){
        olist << subs[s];
	QString newsub = subs[s].section(ofiles[i],0,100, QString::SectionSkipEmpty); 
	    newsub.prepend(nfiles[i]);
	nlist << newsub;
      }
    }else{ //Move/rename
      if( nfiles[i].startsWith(ofiles[i]+"/") ){
	//This is trying to move a directory into itself  (not possible)
	// Example: move "~/mydir" -> "~/mydir/mydir2"
	QStringList err; err << tr("Invalid Move") << QString(tr("It is not possible to move a directory into itself. Please make a copy of the directory instead.\n\nOld Location: %1\nNew Location: %2")).arg(ofiles[i], nfiles[i]);
	emit finished(err); return;
      }else{
	//Check for existance of the new name
	if(QFile::exists(nfiles[i])){
	  if(overwrite!=1){
	    nfiles[i] = newFileName(nfiles[i]); //prompt for new file name up front before anything starts
	  }
        }
	//no changes necessary
        olist << ofiles[i];
        nlist << nfiles[i];
      }
    }
  }
  //Now start iterating over the operations
  QStringList errlist;
  for(int i=0; i<olist.length() && !stopped; i++){
    if(isRM){
      /*ui->label->setText( QString(tr("Removing: %1")).arg(olist[i].section("/",-1)) );
      QApplication::processEvents();*/
      emit startingItem(i+1,olist.length(), olist[i], "");
      errlist << removeItem(olist[i]);
    }else if(isCP || isRESTORE){
      /*ui->label->setText( QString(tr("Copying: %1 to %2")).arg(olist[i].section("/",-1), nlist[i].section("/",-1)) );
      QApplication::processEvents();*/
      emit startingItem(i+1,olist.length(), olist[i],nlist[i]);
      if(QFile::exists(nlist[i])){
	if(overwrite==1){
	  errlist << removeItem(nlist[i], true); //recursively remove the file/dir since we are supposed to overwrite it
	}
      }
      //If a parent directory fails to copy, skip all the children as well (they will also fail)
      //QApplication::processEvents();
      if( !errlist.contains(olist[i].section("/",0,-1)) ){ 
        errlist << copyItem(olist[i], nlist[i]);
      }
    }else if(isMV){
      /*ui->label->setText( QString(tr("Moving: %1 to %2")).arg(ofiles[i].section("/",-1), nfiles[i].section("/",-1)) );
      QApplication::processEvents();*/
      emit startingItem(i+1,olist.length(), olist[i], nlist[i]);
      //Clean up any overwritten files/dirs
      if(QFile::exists(nlist[i])){
	if(overwrite==1){
	  errlist << removeItem(nlist[i], true); //recursively remove the file/dir since we are supposed to overwrite it
	}
      }
      //Perform the move if no error yet (including skipping all children)
      if( !errlist.contains(olist[i].section("/",0,-1)) ){ 
        if( !QFile::rename(ofiles[i], nfiles[i]) ){
          errlist << ofiles[i];
        }
      }	
    }
    //ui->progressBar->setValue(i+1);
    //QApplication::processEvents();
  }
  //All finished, emit the signal
  errlist.removeAll(""); //make sure to clear any empty items
  emit finished(errlist);
  qDebug() << "Done with File Operations";
}
Exemplo n.º 10
0
void XManager::loadXFile(IDirect3DDevice9* dev, const std::string& filename, ID3DXMesh** meshOut, std::vector<Material>* mtrls, std::vector<IDirect3DTexture9*>* texs) {
	// Step 1: Load the .x file from file into a system memory mesh.

	ID3DXMesh* meshSys      = 0;
	ID3DXBuffer* adjBuffer  = 0;
	ID3DXBuffer* mtrlBuffer = 0;
	DWORD numMtrls          = 0;

	HR(D3DXLoadMeshFromX(filename.c_str(), D3DXMESH_SYSTEMMEM, dev,
		&adjBuffer,	&mtrlBuffer, 0, &numMtrls, &meshSys));


	// Step 2: Find out if the mesh already has normal info?

	D3DVERTEXELEMENT9 elems[MAX_FVF_DECL_SIZE];
	HR(meshSys->GetDeclaration(elems));
	
	bool hasNormals = false;
	D3DVERTEXELEMENT9 term = D3DDECL_END();
	for(int i = 0; i < MAX_FVF_DECL_SIZE; ++i)
	{
		// Did we reach D3DDECL_END() {0xFF,0,D3DDECLTYPE_UNUSED, 0,0,0}?
		if(elems[i].Stream == 0xff )
			break;

		if( elems[i].Type == D3DDECLTYPE_FLOAT3 &&
			elems[i].Usage == D3DDECLUSAGE_NORMAL &&
			elems[i].UsageIndex == 0 )
		{
			hasNormals = true;
			break;
		}
	}


	// Step 3: Change vertex format to CustomVertex3NormalUV

	D3DVERTEXELEMENT9 elements[64];
	UINT numElements = 0;
	CustomVertex3NormalUV::decl->GetDeclaration(elements, &numElements);

	ID3DXMesh* temp = 0;
	HR(meshSys->CloneMesh(D3DXMESH_SYSTEMMEM, 
		elements, dev, &temp));
	SAFERELEASECOM(meshSys);
	meshSys = temp;


	// Step 4: If the mesh did not have normals, generate them.

	if( hasNormals == false)
		HR(D3DXComputeNormals(meshSys, 0));


	// Step 5: Optimize the mesh.

	HR(meshSys->Optimize(D3DXMESH_MANAGED | 
		D3DXMESHOPT_COMPACT | D3DXMESHOPT_ATTRSORT | D3DXMESHOPT_VERTEXCACHE, 
		(DWORD*)adjBuffer->GetBufferPointer(), 0, 0, 0, meshOut));
	SAFERELEASECOM(meshSys); // Done w/ system mesh.
	SAFERELEASECOM(adjBuffer); // Done with buffer.

	// Step 6: Extract the materials and load the textures.

	if( mtrlBuffer != 0 && numMtrls != 0 )
	{
		D3DXMATERIAL* d3dxmtrls = (D3DXMATERIAL*)mtrlBuffer->GetBufferPointer();

		for(DWORD i = 0; i < numMtrls; ++i)
		{
			// Save the ith material.  Note that the MatD3D property does not have an ambient
			// value set when its loaded, so just set it to the diffuse value.
			Material m;
			m.ambient   = d3dxmtrls[i].MatD3D.Diffuse;
			m.diffuse   = d3dxmtrls[i].MatD3D.Diffuse;
			m.spec      = d3dxmtrls[i].MatD3D.Specular;
			m.specPower = d3dxmtrls[i].MatD3D.Power;
			mtrls->push_back( m );

			// Check if the ith material has an associative texture
			if( d3dxmtrls[i].pTextureFilename != 0 )
			{
				IDirect3DTexture9* tex = 0;
				std::string s(d3dxmtrls[i].pTextureFilename);
				const char folder[] = "./texture/";
				unsigned int pos = s.find_last_of('\/');
				std::string newFileName(folder);

				// std::string::npos gets returned if no / was found
				if(pos != std::string::npos) {
					//std::string sub = s.substr(pos,s.size());

					if(strcmp(s.substr(pos+1,s.size()).c_str(),"Watcher.tga") == 0) {
						newFileName.append("Watcher_Black.tga");
					}
					else {
						newFileName.append(s.substr(pos+1,s.size()));
					}
				}
				else {
					
					newFileName.append(s);
					
				}
				// Save the loaded texture
				HR(D3DXCreateTextureFromFile(dev, newFileName.c_str(), &tex));
				texs->push_back( tex );
			}
			else
			{
Exemplo n.º 11
0
bool ArticleWriter::MoveCompletedFiles(NzbInfo* nzbInfo, const char* oldDestDir)
{
	if (nzbInfo->GetCompletedFiles()->empty())
	{
		return true;
	}

	// Ensure the DstDir is created
	CString errmsg;
	if (!FileSystem::ForceDirectories(nzbInfo->GetDestDir(), errmsg))
	{
		nzbInfo->PrintMessage(Message::mkError, "Could not create directory %s: %s", nzbInfo->GetDestDir(), *errmsg);
		return false;
	}

	// move already downloaded files to new destination
	for (CompletedFile& completedFile : nzbInfo->GetCompletedFiles())
	{
		BString<1024> oldFileName("%s%c%s", oldDestDir, PATH_SEPARATOR, completedFile.GetFilename());
		BString<1024> newFileName("%s%c%s", nzbInfo->GetDestDir(), PATH_SEPARATOR, completedFile.GetFilename());

		// check if file was not moved already
		if (strcmp(oldFileName, newFileName))
		{
			// prevent overwriting of existing files
			newFileName = FileSystem::MakeUniqueFilename(nzbInfo->GetDestDir(), completedFile.GetFilename());

			detail("Moving file %s to %s", *oldFileName, *newFileName);
			if (!FileSystem::MoveFile(oldFileName, newFileName))
			{
				nzbInfo->PrintMessage(Message::mkError, "Could not move file %s to %s: %s",
					*oldFileName, *newFileName, *FileSystem::GetLastErrorMessage());
			}
		}
	}

	// delete old directory (if empty)
	if (FileSystem::DirEmpty(oldDestDir))
	{
		// check if there are pending writes into directory
		bool pendingWrites = false;
		for (FileInfo* fileInfo : nzbInfo->GetFileList())
		{
			if (!pendingWrites)
			{
				break;
			}

			if (fileInfo->GetActiveDownloads() > 0)
			{
				Guard guard = fileInfo->GuardOutputFile();
				pendingWrites = fileInfo->GetOutputInitialized() && !Util::EmptyStr(fileInfo->GetOutputFilename());
			}
			else
			{
				pendingWrites = fileInfo->GetOutputInitialized() && !Util::EmptyStr(fileInfo->GetOutputFilename());
			}
		}

		if (!pendingWrites)
		{
			FileSystem::RemoveDirectory(oldDestDir);
		}
	}

	return true;
}