Exemplo n.º 1
0
static void rm_dash_rf_execute(wxArrayString &fList, 
                               int count, int files_p, int dirs_p,
                               const wxChar *prompt){

   AudacityProject *p = GetActiveProject();

   if (prompt && p)
      p->ProgressShow(_("Progress"), prompt);
  
   for (int i = 0; i < count; i++) {
      const wxChar *file = fList[i].c_str();
      if(files_p){
         wxRemoveFile(file);
      }
      if(dirs_p){
         wxRmdir(file);
      }

      if (prompt && p)
         p->ProgressUpdate(int ((i * 1000.0) / count));
   }
   
   if (prompt && p)
      p->ProgressHide();
}
Exemplo n.º 2
0
//all messageboxes need to be modal, updater closes immeadiately when receiving the UpdateFinished event
void UpdaterClass::OnDownloadEvent( wxCommandEvent& event )
{
    int code = event.GetInt();
    if ( code != 0)
        customMessageBox(SL_MAIN_ICON, _("There was an error downloading for the latest version.\nPlease try again later.\nIf the problem persists, please use Help->Report Bug to report this bug."), _("Error"));
    else {
        if (!PostMinGW44( m_newexe ) ) {
            customMessageBox(SL_MAIN_ICON, _("Automatic update failed\n\nyou will be redirected to a web page with instructions and the download link will be opened in your browser."), _("Updater error.") );
			OpenWebBrowser( _T("http://projects.springlobby.info/wiki/springlobby/Install#Windows-Binary") );
            OpenWebBrowser( GetDownloadUrl( m_latest_version ) );
        }
        if ( !UpdateExe( m_newexe , false ) ) {
			customMessageBox(SL_MAIN_ICON,
							 wxFormat( _("There was an error while trying to replace the current executable version.\n Please manually copy springlobby.exe from: %s\n to: %s\n") )
											   % m_newexe
											   % m_currentexe,
							 _("Error") );
        }
        else {
            bool locale_ok = UpdateLocale( m_newexe, false );
            if ( locale_ok ) {
				customMessageBox(SL_MAIN_ICON, IdentityString( _("Update complete. \nPlease restart %s now.") ), _("Success"));
            }
            else {
				customMessageBox(SL_MAIN_ICON,
								 IdentityString( _("Binary updated successfully. \nSome translation files could not be updated.\nPlease report this in #springlobby. \nPlease restart %s now.") ),
								 _("Partial success") );
            }
            wxRmdir( m_newexe );
        }
    }
    GetGlobalEventSender( GlobalEvents::UpdateFinished ).SendEvent( 0 );
}
Exemplo n.º 3
0
wxDebugReport::~wxDebugReport()
{
    if ( !m_dir.empty() )
    {
        // remove all files in this directory
        wxDir dir(m_dir);
        wxString file;
        for ( bool cont = dir.GetFirst(&file); cont; cont = dir.GetNext(&file) )
        {
            if ( wxRemove(wxFileName(m_dir, file).GetFullPath()) != 0 )
            {
                wxLogSysError(_("Failed to remove debug report file \"%s\""),
                              file.c_str());
                m_dir.clear();
                break;
            }
        }
    }

    if ( !m_dir.empty() )
    {
        // Temp fix: what should this be? eVC++ doesn't like wxRmDir
#ifdef __WXWINCE__
        if ( wxRmdir(m_dir.fn_str()) != 0 )
#else
        if ( wxRmDir(m_dir.fn_str()) != 0 )
#endif
        {
            wxLogSysError(_("Failed to clean up debug report directory \"%s\""),
                          m_dir.c_str());
        }
    }
}
bool deleteDirectory(wxString& path, wxString& item)
{
   {
      wxDir dir;
      wxString filePath = path + "\\" + item;
      
      wxString file;
      dir.Open(filePath);
      if (!dir.IsOpened()) return false;
      bool cont = false;
      if (dir.HasFiles() || dir.HasSubDirs())
         cont = dir.GetFirst(&file);
      while (cont)
      {
         wxString strFile = filePath + "\\" + file;
         
         if (dir.Exists(strFile))
            deleteDirectory(filePath, file);

         SetFileAttributes(strFile.c_str(), FILE_ATTRIBUTE_NORMAL); // Make it not read only, so we can delete it
         wxRemoveFile(strFile);

         cont = dir.GetNext(&file);
      }
   }
   return wxRmdir(path + "\\" + item);
}
Exemplo n.º 5
0
bool RecursiveDelete(const wxString &path)
{
    if (wxFileExists(path))
    {
        if (!wxRemoveFile(path))
            return false;
    }
    else if (wxDirExists(path))
    {
        wxDir dir(path);
        wxString subpath;

        if (dir.GetFirst(&subpath))
        {
            do
            {
                if (!RecursiveDelete(Path::Combine(path, subpath)))
                    return false;
            } while (dir.GetNext(&subpath));
        }

        if (!wxRmdir(path))
            return false;
    }
    return true;
}
Exemplo n.º 6
0
 bool RemoveDir(const wxString& src)
 {
     wxFileName fname(Manager::Get()->GetMacrosManager()->ReplaceMacros(src));
     NormalizePath(fname, wxEmptyString);
     if (!SecurityAllows(_T("RemoveDir"), fname.GetFullPath()))
         return false;
     return wxRmdir(fname.GetFullPath());
 }
Exemplo n.º 7
0
inline void CrashHandlerSaveEditorFiles(wxString& buf)
{
    wxString path;
    //get the "My Files" folder
    HRESULT result = SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, 0, wxStringBuffer(path, MAX_PATH));
    if (FAILED(result))
    {   //get at least the profiles folder
        path = ConfigManager::GetHomeFolder();
    }
    path << _T("\\cb-crash-recover");
    if (!wxDirExists(path)) wxMkdir(path);

    //make a sub-directory of the current date & time
    wxDateTime now = wxDateTime::Now();
    path << now.Format(_T("\\%Y%m%d-%H%M%S"));

    EditorManager* em = Manager::Get()->GetEditorManager();
    if (em)
    {
        bool AnyFileSaved = false;
        if (wxMkdir(path) && wxDirExists(path))
        {
            for (int i = 0; i < em->GetEditorsCount(); ++i)
            {
                cbEditor* ed = em->GetBuiltinEditor(em->GetEditor(i));
                if (ed)
                {
                    wxFileName fn(ed->GetFilename());
                    wxString fnpath = path + _T("/") + fn.GetFullName();
                    wxString newfnpath = fnpath;
                    // add number if filename already exists e.g. main.cpp.001, main.cpp.002, ...
                    int j = 1;
                    while (wxFileExists(newfnpath))
                        newfnpath = fnpath + wxString::Format(wxT(".%03d"),j);

                    if (cbSaveToFile(newfnpath,
                                    ed->GetControl()->GetText(),
                                    ed->GetEncoding(),
                                    ed->GetUseBom() ) )
                    {
                        AnyFileSaved = true;
                    }
                }
            }

            if (AnyFileSaved)
            {
                buf << _("The currently opened files have been saved to the directory\n");
                buf << path;
                buf << _("\nHopefully, this will prevent you from losing recent modifications.\n\n");
            }
            else
                wxRmdir(path);
        }
    }
}
Exemplo n.º 8
0
int cellFsRmdir(u32 path_addr)
{
	const wxString& ps3_path = Memory.ReadString(path_addr);
	wxString path;
	Emu.GetVFS().GetDevice(ps3_path, path);
	sys_fs.Log("cellFsRmdir(path: %s)", path.mb_str());
	if(!wxDirExists(path)) return CELL_ENOENT;
	if(!wxRmdir(path)) return CELL_EBUSY; // (TODO: Under certain conditions it is not able to delete the folder)
	return CELL_OK;
}
Exemplo n.º 9
0
//helper
bool RemoveTempDir(const wxString& dirPath)
{
        //borra en cascada
        if(!wxRmdir(dirPath)) {
                //vaciar
                wxDir dir;
                if (dir.Open(dirPath)) {
                        wxString fileName;
                        bool cont = dir.GetFirst(&fileName);
                        while (cont) {
                                fileName=dir.GetName()+ wxFileName::GetPathSeparator(wxPATH_NATIVE) +fileName;
                                if(wxDir::Exists(fileName)) {
                                        if (RemoveTempDir(fileName)) {
                                                cont = dir.GetFirst(&fileName);
                                        } else {
                                                cont = dir.GetNext(&fileName);
                                        }
                                } else {
                                        int result;
#ifdef _WIN32
                                        result = _chmod(TOPATH(fileName).c_str(), _S_IWRITE);
#else
                                        result = chmod(TOPATH(fileName).c_str(), 0644);
#endif
                                        if (result != 0) {
                                                LOG_ERROR("Core", "Unable to change permission of '" << TOPATH(fileName) << "':" << strerror(errno));
                                        }

                                        if (wxRemoveFile(fileName)) {
                                                cont = dir.GetFirst(&fileName);
                                        } else {
                                                cont = dir.GetNext(&fileName);
                                        }
                                }
                        }
                }
        }
        if(wxDir::Exists(dirPath)) {
                return wxRmdir(dirPath);
        }
        return true;
}
Exemplo n.º 10
0
bool DirectoriesPrefs::Apply()
{

    mTempDir = mTempDirText->GetValue();

    if(!wxDirExists(mTempDir)) {
        int ans = wxMessageBox(
                      wxString::Format(_("Directory %s does not exist. Create it?"),
                                       (const char *) mTempDir),
                      _("New Temporary Directory"),
                      wxYES_NO|wxCENTRE|wxICON_EXCLAMATION);

        if(ans == wxYES) {
            if(!wxMkdir(mTempDir, 0600)) {
                /* wxWindows throws up a decent looking dialog */
                return false;
            }
        }
        else {
            return false;
        }
    }
    else {
        /* If the directory already exists, make sure it is writable */
        wxLogNull logNo;
        wxString tempDir = mTempDir + wxFILE_SEP_PATH + "canicreate";
        if(!wxMkdir(tempDir)) {
            wxMessageBox(
                wxString::Format(_("Directory %s is not writable"),
                                 (const char *) mTempDir),
                _("Error"), wxOK|wxICON_ERROR);
            return false;
        }
        wxRmdir(tempDir);
    }

    gPrefs->Write("/Directories/TempDir", mTempDir);

    if (mTempDir != mOldTempDir)
        wxMessageBox(
            _("Changes to temporary directory will not take effect "
              "until Audacity is restarted"),
            "Temp Directory Update", wxOK|wxCENTRE|wxICON_INFORMATION);

    return true;
}
Exemplo n.º 11
0
// -------------------------------------------------------------------------------- //
bool guRemoveDir( const wxString &path )
{
    wxString CurPath = path;
    if( !CurPath.EndsWith( wxT( "/" ) ) )
        CurPath += wxT( "/" );

    wxDir         Dir;
    wxString      FileName;

    Dir.Open( CurPath );

    if( Dir.IsOpened() )
    {
        if( Dir.GetFirst( &FileName, wxEmptyString, wxDIR_FILES | wxDIR_DIRS ) )
        {
            do {
                if( FileName == wxT( "." ) )
                    continue;

                if( FileName == wxT( ".." ) )
                    continue;

                if( Dir.Exists( CurPath + FileName ) )
                {
                    if( !guRemoveDir( CurPath + FileName ) )
                    {
                        guLogMessage( wxT( "Could not remove dir '%s'" ), wxString( CurPath + FileName ).c_str() );
                        return false;
                    }
                }
                else
                {
                    if( !wxRemoveFile( CurPath + FileName ) )
                    {
                        guLogMessage( wxT( "Could not remove file '%s'" ), wxString( CurPath + FileName ).c_str() );
                        return false;
                    }
                }
            } while( Dir.GetNext( &FileName ) );
        }

        return wxRmdir( CurPath );
    }
    return false;
}
bool TREEPROJECT_ITEM::Delete( bool check )
{
    wxString    msg = wxString::Format( _(
                    "Do you really want to delete \"%s\"" ),
                    GetChars( GetFileName() )
                    );

    wxMessageDialog dialog( m_parent, msg,
                            _( "Delete File" ), wxYES_NO | wxICON_QUESTION );

    if( !check || wxID_YES == dialog.ShowModal() )
    {
        bool success;

        if( !wxDirExists( GetFileName() ) )
            success = wxRemoveFile( GetFileName() );
        else
        {
            wxArrayString filelist;

            wxDir::GetAllFiles( GetFileName(), &filelist );

            for( unsigned int i = 0; i < filelist.Count(); i++ )
                wxRemoveFile( filelist[i] );

            success = wxRmdir( GetFileName() );
        }

        if( success )
            m_parent->Delete( GetId() );

        return success;
    }

    return false;
}
Exemplo n.º 13
0
bool CLocalFileSystem::RecursiveDelete(std::list<wxString> dirsToVisit, wxWindow* parent)
{
	// Under Windows use SHFileOperation to delete files and directories.
	// Under other systems, we have to recurse into subdirectories manually
	// to delete all contents.

#ifdef __WXMSW__
	// SHFileOperation accepts a list of null-terminated strings. Go through all
	// paths to get the required buffer length

	size_t len = 1; // String list terminated by empty string

	for (auto const& dir : dirsToVisit) {
		len += dir.size() + 1;
	}

	// Allocate memory
	wxChar* pBuffer = new wxChar[len];
	wxChar* p = pBuffer;

	for (auto& dir : dirsToVisit) {
		if (dir.Last() == wxFileName::GetPathSeparator())
			dir.RemoveLast();
		if (GetFileType(dir) == unknown)
			continue;

		_tcscpy(p, dir);
		p += dir.size() + 1;
	}
	if (p != pBuffer) {
		*p = 0;

		// Now we can delete the files in the buffer
		SHFILEOPSTRUCT op;
		memset(&op, 0, sizeof(op));
		op.hwnd = parent ? (HWND)parent->GetHandle() : 0;
		op.wFunc = FO_DELETE;
		op.pFrom = pBuffer;

		if (parent) {
			// Move to trash if shift is not pressed, else delete
			op.fFlags = wxGetKeyState(WXK_SHIFT) ? 0 : FOF_ALLOWUNDO;
		}
		else
			op.fFlags = FOF_NOCONFIRMATION;

		SHFileOperation(&op);
	}
	delete [] pBuffer;

	return true;
#else
	if (parent) {
		if (wxMessageBoxEx(_("Really delete all selected files and/or directories from your computer?"), _("Confirmation needed"), wxICON_QUESTION | wxYES_NO, parent) != wxYES)
			return true;
	}

	for (auto& dir : dirsToVisit) {
		if (dir.Last() == '/' && dir != _T("/"))
			dir.RemoveLast();
	}

	bool encodingError = false;

	// Remember the directories to delete after recursing into them
	std::list<wxString> dirsToDelete;

	CLocalFileSystem fs;

	// Process all dirctories that have to be visited
	while (!dirsToVisit.empty()) {
		auto const iter = dirsToVisit.begin();
		wxString const& path = *iter;

		if (GetFileType(path) != dir) {
			wxRemoveFile(path);
			dirsToVisit.erase(iter);
			continue;
		}

		dirsToDelete.splice(dirsToDelete.begin(), dirsToVisit, iter);

		if (!fs.BeginFindFiles(path, false)) {
			continue;
		}

		// Depending on underlying platform, wxDir does not handle
		// changes to the directory contents very well.
		// See http://trac.filezilla-project.org/ticket/3482
		// To work around this, delete files after enumerating everything in current directory
		std::list<wxString> filesToDelete;

		wxString file;
		while (fs.GetNextFile(file)) {
			if (file.empty()) {
				encodingError = true;
				continue;
			}

			const wxString& fullName = path + _T("/") + file;

			if (CLocalFileSystem::GetFileType(fullName) == CLocalFileSystem::dir)
				dirsToVisit.push_back(fullName);
			else
				filesToDelete.push_back(fullName);
		}
		fs.EndFindFiles();

		// Delete all files and links in current directory enumerated before
		for (auto const& file : filesToDelete) {
			wxRemoveFile(file);
		}
	}

	// Delete the now empty directories
	for (auto const& dir : dirsToDelete) {
		wxRmdir(dir);
	}

	return !encodingError;
#endif
}
Exemplo n.º 14
0
bool GPCB_PLUGIN::FootprintLibDelete( const wxString& aLibraryPath, const PROPERTIES* aProperties )
{
    wxFileName fn;
    fn.SetPath( aLibraryPath );

    // Return if there is no library path to delete.
    if( !fn.DirExists() )
        return false;

    if( !fn.IsDirWritable() )
    {
        THROW_IO_ERROR( wxString::Format( _( "user does not have permission to delete directory '%s'" ),
                                          aLibraryPath.GetData() ) );
    }

    wxDir dir( aLibraryPath );

    if( dir.HasSubDirs() )
    {
        THROW_IO_ERROR( wxString::Format( _( "library directory '%s' has unexpected sub-directories" ),
                                          aLibraryPath.GetData() ) );
    }

    // All the footprint files must be deleted before the directory can be deleted.
    if( dir.HasFiles() )
    {
        unsigned      i;
        wxFileName    tmp;
        wxArrayString files;

        wxDir::GetAllFiles( aLibraryPath, &files );

        for( i = 0;  i < files.GetCount();  i++ )
        {
            tmp = files[i];

            if( tmp.GetExt() != KiCadFootprintFileExtension )
            {
                THROW_IO_ERROR( wxString::Format( _( "unexpected file '%s' was found in library path '%s'" ),
                                                  files[i].GetData(), aLibraryPath.GetData() ) );
            }
        }

        for( i = 0;  i < files.GetCount();  i++ )
        {
            wxRemoveFile( files[i] );
        }
    }

    wxLogTrace( traceFootprintLibrary, wxT( "Removing footprint library '%s'" ),
                aLibraryPath.GetData() );

    // Some of the more elaborate wxRemoveFile() crap puts up its own wxLog dialog
    // we don't want that.  we want bare metal portability with no UI here.
    if( !wxRmdir( aLibraryPath ) )
    {
        THROW_IO_ERROR( wxString::Format( _( "footprint library '%s' cannot be deleted" ),
                                          aLibraryPath.GetData() ) );
    }

    // For some reason removing a directory in Windows is not immediately updated.  This delay
    // prevents an error when attempting to immediately recreate the same directory when over
    // writing an existing library.
#ifdef __WINDOWS__
    wxMilliSleep( 250L );
#endif

    if( m_cache && m_cache->GetPath() == aLibraryPath )
    {
        delete m_cache;
        m_cache = NULL;
    }

    return true;
}
Exemplo n.º 15
0
void CLocalTreeView::OnMenuDelete(wxCommandEvent& event)
{
	if (!m_contextMenuItem.IsOk())
		return;

	wxString path = GetDirFromItem(m_contextMenuItem);

	if (!m_pState->LocalDirHasParent(path) || !m_pState->LocalDirIsWriteable(path))
		return;

#ifdef __WXMSW__
	if (path.Len() == 3 && path.Mid(1) == _T(":\\"))
		return;
#endif

	// Under Windows use SHFileOperation to delete files and directories.
	// Under other systems, we have to recurse into subdirectories manually
	// to delete all contents.

#ifdef __WXMSW__
	// SHFileOperation accepts a list of null-terminated strings. Go through all
	// items to get the required buffer length

	if (path.Last() == wxFileName::GetPathSeparator())
		path.RemoveLast();

	int len = path.Len() + 2;

	// Allocate memory
	wxChar* pBuffer = new wxChar[len];
	_tcscpy(pBuffer, path);
	pBuffer[len - 1] = 0;

	// Now we can delete the files in the buffer
	SHFILEOPSTRUCT op;
	memset(&op, 0, sizeof(op));
	op.hwnd = (HWND)GetHandle();
	op.wFunc = FO_DELETE;
	op.pFrom = pBuffer;

	// Move to trash if shift is not pressed, else delete
	op.fFlags = wxGetKeyState(WXK_SHIFT) ? 0 : FOF_ALLOWUNDO;

	SHFileOperation(&op);

	delete [] pBuffer;
#else
	if (wxMessageBox(_("Really delete all selected files and/or directories?"), _("Confirmation needed"), wxICON_QUESTION | wxYES_NO, this) != wxYES)
		return;

	// Remember the directories to delete and the directories to visit
	std::list<wxString> dirsToDelete;
	std::list<wxString> dirsToVisit;

	if (path.Last() != wxFileName::GetPathSeparator())
		path += wxFileName::GetPathSeparator();

	dirsToVisit.push_back(path);
	dirsToDelete.push_front(path);

	// Process any subdirs which still have to be visited
	while (!dirsToVisit.empty())
	{
		wxString filename = dirsToVisit.front();
		dirsToVisit.pop_front();
		wxDir dir;
		if (!dir.Open(filename))
			continue;

		wxString file;
		for (bool found = dir.GetFirst(&file); found; found = dir.GetNext(&file))
		{
			if (file == _T(""))
			{
				wxGetApp().DisplayEncodingWarning();
				continue;
			}
			if (wxFileName::DirExists(filename + file))
			{
				wxString subDir = filename + file + wxFileName::GetPathSeparator();
				dirsToVisit.push_back(subDir);
				dirsToDelete.push_front(subDir);
			}
			else
				wxRemoveFile(filename + file);
		}
	}

	// Delete the now empty directories
	for (std::list<wxString>::const_iterator iter = dirsToDelete.begin(); iter != dirsToDelete.end(); iter++)
		wxRmdir(*iter);

#endif

	wxTreeItemId item = GetSelection();
	while (item && item != m_contextMenuItem)
		item = GetItemParent(item);

	if (!item)
	{
		if (GetItemParent(m_contextMenuItem) == GetSelection())
			m_pState->RefreshLocal();
		else
			Refresh();
		return;
	}

	if (path.Last() == wxFileName::GetPathSeparator())
		path.RemoveLast();
	int pos = path.Find(wxFileName::GetPathSeparator(), true);
	if (pos < 1)
		path = _T("/");
	else
		path = path.Left(pos);

	m_pState->SetLocalDir(path);
	Refresh();
}
Exemplo n.º 16
0
void ConfigManager::MigrateFolders()
{
#ifdef __linux__
    // if the old config-folder (~/.codeblocks) does not exist, we have nothing to do.
    if (!wxDirExists(wxStandardPaths::Get().GetUserDataDir()))
        return;

    // ConfigManager::config_folder might be the portable-path but we want to migrate the standard-conform folder,
    // but only if it not aöready exists
    wxString newConfigFolder = wxString::FromUTF8(g_build_filename (g_get_user_config_dir(), "codeblocks", NULL));
    // if the new config folder already exist, we step out immediately
    if (wxDirExists(newConfigFolder))
        return;

    wxString oldConfigFolder = wxStandardPaths::Get().GetUserDataDir();
    wxString oldDataFolder = oldConfigFolder + wxFILE_SEP_PATH + _T("share") + wxFILE_SEP_PATH + _T("codeblocks");
    wxString newDataFolder = wxString::FromUTF8(g_build_filename (g_get_user_data_dir(), NULL)) + wxFILE_SEP_PATH + _T("codeblocks");
    wxString msg;
    msg = F(_("The places where the configuration files and user-data files are stored\n"
              "have been changed to be more standard-conform.\n"
              "\n"
              "Now moving \"%s\"\n"
              "to \"%s\"\n"
              "and \"%s\"\n"
              "to \"%s\".\n"),
            oldDataFolder.wx_str(),
            newDataFolder.wx_str(),
            oldConfigFolder.wx_str(),
            newConfigFolder.wx_str());
    cbMessageBox(msg, _("Try to migrate config-folder ..."), wxICON_INFORMATION);

    bool success = true;
    if (wxDirExists(oldDataFolder))
    {
        // make sure the target-folder exists
        CreateDirRecursively(newDataFolder);
        success = wxRenameFile(oldDataFolder, newDataFolder);
        wxRmdir(oldConfigFolder + wxFILE_SEP_PATH + _T("share"));
    }
    if (success)
    {
        // make sure the target-folder exists
        CreateDirRecursively(newConfigFolder);
        success = wxRenameFile(oldConfigFolder, newConfigFolder);
    }
    if (!success)
    {
        msg = F(_("Error moving \"%s\"\n"
                  "to \"%s\"\n"
                  "or \"%s\"\n"
                  "to \"%s\".\n\n"
                  "Please check the folders manually (access rights?) !\n"
                  "A new configuration will be created from scratch!"),
                oldDataFolder.wx_str(),
                newDataFolder.wx_str(),
                oldConfigFolder.wx_str(),
                newConfigFolder.wx_str());
        cbMessageBox(msg, _("Error migrating config-folder ..."), wxICON_ERROR);
    }
#endif // __linux__
}
Exemplo n.º 17
0
void CLocalListView::OnMenuDelete(wxCommandEvent& event)
{
	// Under Windows use SHFileOperation to delete files and directories.
	// Under other systems, we have to recurse into subdirectories manually
	// to delete all contents.

#ifdef __WXMSW__
	// SHFileOperation accepts a list of null-terminated strings. Go through all
	// items to get the required buffer length

	wxString dir = m_dir;
	if (dir.Right(1) != _T("\\") && dir.Right(1) != _T("/"))
		dir += _T("\\");
	int dirLen = dir.Length();

	int len = 1; // String list terminated by empty string

	long item = -1;
	while (true)
	{
		item = GetNextItem(item, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
		if (item == -1)
			break;

		if (!item && m_hasParent)
			continue;

		t_fileData *data = GetData(item);
		if (!data)
			continue;

		len += dirLen + data->name.Length() + 1;
	}

	// Allocate memory
	wxChar* pBuffer = new wxChar[len];
	wxChar* p = pBuffer;

	// Loop through all selected items again and fill buffer
	item = -1;
	while (true)
	{
		item = GetNextItem(item, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
		if (item == -1)
			break;

		if (!item && m_hasParent)
			continue;

		t_fileData *data = GetData(item);
		if (!data)
			continue;

		_tcscpy(p, dir);
		p += dirLen;
		_tcscpy(p, data->name);
		p += data->name.Length() + 1;
	}
	*p = 0;

	// Now we can delete the files in the buffer
	SHFILEOPSTRUCT op;
	memset(&op, 0, sizeof(op));
	op.hwnd = (HWND)GetHandle();
	op.wFunc = FO_DELETE;
	op.pFrom = pBuffer;

	// Move to trash if shift is not pressed, else delete
	op.fFlags = wxGetKeyState(WXK_SHIFT) ? 0 : FOF_ALLOWUNDO;

	SHFileOperation(&op);
	delete [] pBuffer;
#else
	if (wxMessageBox(_("Really delete all selected files and/or directories?"), _("Confirmation needed"), wxICON_QUESTION | wxYES_NO, this) != wxYES)
		return;

	// Remember the directories to delete and the directories to visit
	std::list<wxString> dirsToDelete;
	std::list<wxString> dirsToVisit;

	wxString dir = m_dir;
	if (dir.Right(1) != _T("\\") && dir.Right(1) != _T("/"))
		dir += _T("/");

	// First process selected items
	long item = -1;
	while (true)
	{
		item = GetNextItem(item, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
		if (item == -1)
			break;

		if (!item && m_hasParent)
			continue;

		t_fileData *data = GetData(item);
		if (!data)
			continue;

		if (data->dir)
		{
			wxString subDir = dir + data->name + _T("/");
			dirsToVisit.push_back(subDir);
			dirsToDelete.push_front(subDir);
		}
		else
			wxRemoveFile(dir + data->name);
	}

	// Process any subdirs which still have to be visited
	while (!dirsToVisit.empty())
	{
		wxString filename = dirsToVisit.front();
		dirsToVisit.pop_front();
		wxDir dir;
		if (!dir.Open(filename))
			continue;

		wxString file;
		for (bool found = dir.GetFirst(&file); found; found = dir.GetNext(&file))
		{
			if (file == _T(""))
			{
				wxGetApp().DisplayEncodingWarning();
				continue;
			}
			if (wxFileName::DirExists(filename + file))
			{
				wxString subDir = filename + file + _T("/");
				dirsToVisit.push_back(subDir);
				dirsToDelete.push_front(subDir);
			}
			else
				wxRemoveFile(filename + file);
		}
	}

	// Delete the now empty directories
	for (std::list<wxString>::const_iterator iter = dirsToDelete.begin(); iter != dirsToDelete.end(); iter++)
		wxRmdir(*iter);

#endif
	m_pState->SetLocalDir(m_dir);
}
Exemplo n.º 18
0
bool CLocalFileSystem::RecursiveDelete(std::list<wxString> dirsToVisit, wxWindow* parent)
{
	// Under Windows use SHFileOperation to delete files and directories.
	// Under other systems, we have to recurse into subdirectories manually
	// to delete all contents.

#ifdef __WXMSW__
	// SHFileOperation accepts a list of null-terminated strings. Go through all
	// paths to get the required buffer length

	;
	int len = 1; // String list terminated by empty string

	for (std::list<wxString>::const_iterator const_iter = dirsToVisit.begin(); const_iter != dirsToVisit.end(); const_iter++)
		len += const_iter->Length() + 1;

	// Allocate memory
	wxChar* pBuffer = new wxChar[len];
	wxChar* p = pBuffer;

	for (std::list<wxString>::iterator iter = dirsToVisit.begin(); iter != dirsToVisit.end(); iter++)
	{
		wxString& path = *iter;
		if (path.Last() == wxFileName::GetPathSeparator())
			path.RemoveLast();
		if (GetFileType(path) == unknown)
			continue;

		_tcscpy(p, path);
		p += path.Length() + 1;
	}
	if (p != pBuffer)
	{
		*p = 0;

		// Now we can delete the files in the buffer
		SHFILEOPSTRUCT op;
		memset(&op, 0, sizeof(op));
		op.hwnd = parent ? (HWND)parent->GetHandle() : 0;
		op.wFunc = FO_DELETE;
		op.pFrom = pBuffer;

		if (parent)
		{
			// Move to trash if shift is not pressed, else delete
			op.fFlags = wxGetKeyState(WXK_SHIFT) ? 0 : FOF_ALLOWUNDO;
		}
		else
			op.fFlags = FOF_NOCONFIRMATION;

		SHFileOperation(&op);
	}
	delete [] pBuffer;

	return true;
#else
	if (parent)
	{
		if (wxMessageBox(_("Really delete all selected files and/or directories?"), _("Confirmation needed"), wxICON_QUESTION | wxYES_NO, parent) != wxYES)
			return true;
	}

	for (std::list<wxString>::iterator iter = dirsToVisit.begin(); iter != dirsToVisit.end(); iter++)
	{
		wxString& path = *iter;
		if (path.Last() == wxFileName::GetPathSeparator() && path != wxFileName::GetPathSeparator())
			path.RemoveLast();
	}

	bool encodingError = false;

	// Remember the directories to delete after recursing into them
	std::list<wxString> dirsToDelete;

	// Process all dirctories that have to be visited
	while (!dirsToVisit.empty())
	{
		const wxString path = dirsToVisit.front();
		dirsToVisit.pop_front();
		dirsToDelete.push_front(path);

		if (GetFileType(path) != dir)
		{
			wxRemoveFile(path);
			continue;
		}

		wxDir dir;
		if (!dir.Open(path))
			continue;

		// Depending on underlying platform, wxDir does not handle
		// changes to the directory contents very well.
		// See bug [ 1946574 ]
		// To work around this, delete files after enumerating everything in current directory
		std::list<wxString> filesToDelete;

		wxString file;
		for (bool found = dir.GetFirst(&file); found; found = dir.GetNext(&file))
		{
			if (file == _T(""))
			{
				encodingError = true;
				continue;
			}

			const wxString& fullName = path + wxFileName::GetPathSeparator() + file;

			if (CLocalFileSystem::GetFileType(fullName) == CLocalFileSystem::dir)
				dirsToVisit.push_back(fullName);
			else
				filesToDelete.push_back(fullName);
		}

		// Delete all files and links in current directory enumerated before
		for (std::list<wxString>::const_iterator iter = filesToDelete.begin(); iter != filesToDelete.end(); iter++)
			wxRemoveFile(*iter);
	}

	// Delete the now empty directories
	for (std::list<wxString>::const_iterator iter = dirsToDelete.begin(); iter != dirsToDelete.end(); iter++)
		wxRmdir(*iter);

	return !encodingError;
#endif
}
Exemplo n.º 19
0
void MyDialog::OnButton_GA(wxCommandEvent& event )
{
	wxString aid=assemblyid->GetValue();
	if (aid.IsEmpty()) 
	{
		wxLogMessage("Sorry, you have to specify an AssemblyID !");
	} else {
	wxFileDialog* file_dialog=new wxFileDialog(this,"Save AssemblyPackage as...","","","*.zip",wxSAVE,wxDefaultPosition);
	int t=file_dialog->ShowModal();
	
	wxString file;
	wxString path;
	wxString filename;
	if (t==wxID_OK) {
		
		file=file_dialog->GetPath();
		path=file_dialog->GetDirectory();
		filename=file_dialog->GetFilename();
		
		wxString current_directory=wxGetCwd();
		std::vector <AComponentTreeCtrl::fileinfo> filelist=a_TreeCtrl->getFiles();

		std::vector <AComponentTreeCtrl::fileinfo> ::iterator iter;
		for(iter = filelist.begin(); 
		iter != filelist.end(); 
			iter++)
			{
				AComponentTreeCtrl::fileinfo finfo=(*iter);
				
				if (!(wxDirExists("tempqxml"))) 
				{
					wxMkdir("tempqxml");
				}
				//wxSetWorkingDirectory(current_directory.Append("tempqxml"));

				wxString temp="tempqxml/";
				
				wxCopyFile(finfo.link,temp.Append(finfo.filename), TRUE);

				
			}

			if (!(wxDirExists("tempqxml/meta-inf")))
			{
					wxMkdir("tempqxml/meta-inf");
			}
			
			// copy the instantiation properties fillearchives
			p_TreeCtrl->copy_filearchive("tempqxml/meta-inf");

			wxString cadfile="tempqxml/meta-inf/";
			cadfile.Append(filename);
			cadfile.Replace(".zip",".cad",TRUE);

			wxFile* outputfile = new wxFile(cadfile,wxFile::write);
			outputfile->Write(getOutputText().c_str(),wxConvLibc);
			outputfile->Close();

			wxString newDirectory=current_directory;
			newDirectory.Append("\\");
			newDirectory.Append("tempqxml");
			wxSetWorkingDirectory(newDirectory);
						
			//bool value;
			wxProcess *process = new wxProcess(this);
					
			wxString cmd = "zip -u  ";
			cmd.append(filename);
			cmd.append(" ");
			cmd.append("*.*");
	
			std::cout << cmd.c_str() << std::endl;
	
			wxExecute(cmd, wxEXEC_SYNC, NULL);
			cadfile.Replace("tempqxml/","",TRUE);
			wxString cmd2 = "zip -u ";
			cmd2.append(filename);
			cmd2.append(" ");
			cmd2.append("meta-inf/*.*");
			
			wxExecute(cmd2, wxEXEC_SYNC, NULL);
			delete process;
			
			wxCopyFile(filename,file, TRUE);
			
			wxRemoveFile(filename);

			for(iter = filelist.begin(); 
			iter != filelist.end(); 
			iter++)
			{
				AComponentTreeCtrl::fileinfo finfo=(*iter);
				
				wxRemoveFile(finfo.filename);
								
			}

			p_TreeCtrl->remove_files();
			wxRemoveFile(cadfile);
			wxRmdir("meta-inf");

			
			
	}

	file_dialog->~wxFileDialog();
	}
}
Exemplo n.º 20
0
int wtfRenamerAction::PerformAction()
{
	wxASSERT_MSG(m_data.path != NULL, wxT("No arguments"));
	wxArrayString dirs;
	wxFileName fn;
	int rv;
	size_t i, cnt;
	switch (m_type)
	{
		case wtfRenamerActionCreateDir:
			wxLogDebug(wxT("create dir '%s'"), m_data.path->c_str());
			fn.AssignDir( *(m_data.path) );
			if (!fn.Normalize(wxPATH_NORM_ENV_VARS | wxPATH_NORM_DOTS | wxPATH_NORM_ABSOLUTE | wxPATH_NORM_LONG | wxPATH_NORM_TILDE))
			{
				return W_RENAMER_ERROR_NOT_PERMITTED;
			}
			if (fn.GetDirCount() == 0)
			{
				return W_RENAMER_ERROR_SYS_ERROR;
			}
			if (fn.DirExists())
			{
				return W_RENAMER_ERROR_FILE_EXISTS;
			}
			dirs = fn.GetDirs();
			cnt = dirs.GetCount();
			for (i = 0; i < cnt; i++)
			{
				fn.RemoveLastDir();
			}
			i = 0;
			while ((i < cnt - 1) && fn.IsDirReadable())
			{
				fn.AppendDir( dirs.Item(i) );
				i++;
			}
			if (!fn.IsDirReadable())
			{
				if (!fn.DirExists())
				{
					return (wxFileExists( fn.GetFullPath() )) ? W_RENAMER_ERROR_NOT_DIR : W_RENAMER_ERROR_DIR_NOT_EXISTS;
				}
				return W_RENAMER_ERROR_NOT_PERMITTED;
			}
			if (!fn.IsDirWritable())
			{
				return W_RENAMER_ERROR_NOT_PERMITTED;
			}
			fn.AppendDir( dirs.Item(cnt - 1) );
			if (!wxMkdir( fn.GetFullPath() ))
			{
				return W_RENAMER_ERROR_SYS_ERROR;
			}
			return 0;
			break;
		case wtfRenamerActionRemoveDir:
			wxLogDebug(wxT("remove dir '%s'"), m_data.path->c_str());
			rv = wtfRenamer::doGetFileName( *(m_data.path) + wxFileName::GetPathSeparator(), &fn );
			if (rv != 0)
			{
				return rv;
			}
			if (fn.GetDirCount() == 0)
			{
				return W_RENAMER_ERROR_SYS_ERROR;
			}
			fn.RemoveLastDir();
			if (!fn.IsDirWritable())
			{
				return W_RENAMER_ERROR_NOT_PERMITTED;
			}
			if (!wxRmdir( *(m_data.path) ))
			{
				return W_RENAMER_ERROR_SYS_ERROR;
			}
			return 0;
			break;
		case wtfRenamerActionCopyFile:
			wxASSERT_MSG(m_data.newpath != NULL, wxT("Too less arguments"));
			wxLogDebug(wxT("copy file '%s' -> '%s'"), m_data.path->c_str(), m_data.newpath->c_str());
			return W_RENAMER_ERROR_NOT_SUPPORTED;
			break;
		case wtfRenamerActionRenameFile:
			wxASSERT_MSG(m_data.newpath != NULL, wxT("Too less arguments"));
			return wtfRenamer::doRename(*(m_data.path), *(m_data.newpath));
			break;
		case wtfRenamerActionCreateHardLink:
			wxASSERT_MSG(m_data.newpath != NULL, wxT("Too less arguments"));
			return wtfRenamer::doCreateHardlink(*(m_data.path), *(m_data.newpath));
			break;
		case wtfRenamerActionCreateSymlink:
			wxASSERT_MSG(m_data.newpath != NULL, wxT("Too less arguments"));
			return wtfRenamer::doCreateSymlink(*(m_data.path), *(m_data.newpath));
			break;
		case wtfRenamerActionUnlinkFile:
			wxLogDebug(wxT("remove file '%s'"), m_data.path->c_str());
			rv = wtfRenamer::doGetFileName( *(m_data.path), &fn );
			if (rv != 0)
			{
				return rv;
			}
			if (!fn.IsDirWritable())
			{
				return W_RENAMER_ERROR_NOT_PERMITTED;
			}
			if (!wxRemoveFile( fn.GetFullPath() ))
			{
				return W_RENAMER_ERROR_SYS_ERROR;
			}
			return 0;
			break;
		default:
			wxLogDebug(wxT("unknown action: %d"), m_type);
			return W_RENAMER_ERROR_NOT_SUPPORTED;
			break;
	}
	return W_RENAMER_ERROR_NOT_SUPPORTED;
}
Exemplo n.º 21
0
bool vfsLocalDir::Remove(const std::string& path)
{
	return wxRmdir(fmt::FromUTF8(path));
}
Exemplo n.º 22
0
/* DirArchive::save
 * Saves any changes to the directory to the file system
 *******************************************************************/
bool DirArchive::save(string filename)
{
	// Get flat entry list
	vector<ArchiveEntry*> entries;
	getEntryTreeAsList(entries);

	// Get entry path list
	vector<string> entry_paths;
	for (unsigned a = 0; a < entries.size(); a++)
	{
		entry_paths.push_back(this->filename + entries[a]->getPath(true));
		if (separator != "/") entry_paths.back().Replace("/", separator);
	}

	// Get current directory structure
	long time = theApp->runTimer();
	vector<string> files, dirs;
	DirArchiveTraverser traverser(files, dirs);
	wxDir dir(this->filename);
	dir.Traverse(traverser, "", wxDIR_FILES|wxDIR_DIRS);
	//wxDir::GetAllFiles(this->filename, &files, wxEmptyString, wxDIR_FILES|wxDIR_DIRS);
	LOG_MESSAGE(2, "GetAllFiles took %lums", theApp->runTimer() - time);

	// Check for any files to remove
	time = theApp->runTimer();
	for (unsigned a = 0; a < removed_files.size(); a++)
	{
		if (wxFileExists(removed_files[a]))
		{
			LOG_MESSAGE(2, "Removing file %s", removed_files[a]);
			wxRemoveFile(removed_files[a]);
		}
	}

	// Check for any directories to remove
	for (int a = dirs.size() - 1; a >= 0; a--)
	{
		// Check if dir path matches an existing dir
		bool found = false;
		for (unsigned e = 0; e < entry_paths.size(); e++)
		{
			if (dirs[a] == entry_paths[e])
			{
				found = true;
				break;
			}
		}

		// Dir on disk isn't part of the archive in memory
		// (Note that this will fail if there are any untracked files in the
		// directory)
		if (!found && wxRmdir(dirs[a]))
			LOG_MESSAGE(2, "Removing directory %s", dirs[a]);
	}
	LOG_MESSAGE(2, "Remove check took %lums", theApp->runTimer() - time);

	// Go through entries
	vector<string> files_written;
	for (unsigned a = 0; a < entries.size(); a++)
	{
		// Check for folder
		string path = entry_paths[a];
		if (entries[a]->getType() == EntryType::folderType())
		{
			// Create if needed
			if (!wxDirExists(path))
				wxMkdir(path);

			// Set unmodified
			entries[a]->exProp("filePath") = path;
			entries[a]->setState(0);

			continue;
		}

		// Check if entry needs to be (re)written
		if (entries[a]->getState() == 0 && path == entries[a]->exProp("filePath").getStringValue())
			continue;

		// Write entry to file
		if (!entries[a]->exportFile(path))
		{
			LOG_MESSAGE(1, "Unable to save entry %s: %s", entries[a]->getName(), Global::error);
		}
		else
			files_written.push_back(path);

		// Set unmodified
		entries[a]->setState(0);
		entries[a]->exProp("filePath") = path;
		file_modification_times[entries[a]] = wxFileModificationTime(path);
	}

	removed_files.clear();
	setModified(false);

	return true;
}