/* EntryOperations::compileACS * Attempts to compile [entry] as an ACS script. If the entry is * named SCRIPTS, the compiled data is imported to the BEHAVIOR * entry previous to it, otherwise it is imported to a same-name * compiled library entry in the acs namespace *******************************************************************/ bool EntryOperations::compileACS(ArchiveEntry* entry, bool hexen, ArchiveEntry* target, wxFrame* parent) { // Check entry was given if (!entry) return false; // Check entry has a parent (this is useless otherwise) if (!target && !entry->getParent()) return false; // Check entry is text if (!EntryDataFormat::getFormat("text")->isThisFormat(entry->getMCData())) { wxMessageBox("Error: Entry does not appear to be text", "Error", wxOK|wxCENTRE|wxICON_ERROR); return false; } // Check if the ACC path is set up string accpath = path_acc; if (accpath.IsEmpty() || !wxFileExists(accpath)) { wxMessageBox("Error: ACC path not defined, please configure in SLADE preferences", "Error", wxOK|wxCENTRE|wxICON_ERROR); PreferencesDialog::openPreferences(parent, "ACS"); return false; } // Setup some path strings string srcfile = appPath(entry->getName(true) + ".acs", DIR_TEMP); string ofile = appPath(entry->getName(true) + ".o", DIR_TEMP); wxArrayString include_paths = wxSplit(path_acc_libs, ';'); // Setup command options string opt; if (hexen) opt += " -h"; if (!include_paths.IsEmpty()) { for (unsigned a = 0; a < include_paths.size(); a++) opt += S_FMT(" -i \"%s\"", include_paths[a]); } // Find/export any resource libraries Archive::search_options_t sopt; sopt.match_type = EntryType::getType("acs"); sopt.search_subdirs = true; vector<ArchiveEntry*> entries = theArchiveManager->findAllResourceEntries(sopt); wxArrayString lib_paths; for (unsigned a = 0; a < entries.size(); a++) { // Ignore SCRIPTS if (S_CMPNOCASE(entries[a]->getName(true), "SCRIPTS")) continue; // Ignore entries from other archives if (entry->getParent()->getFilename(true) != entries[a]->getParent()->getFilename(true)) continue; string path = appPath(entries[a]->getName(true) + ".acs", DIR_TEMP); entries[a]->exportFile(path); lib_paths.Add(path); LOG_MESSAGE(2, "Exporting ACS library %s", entries[a]->getName()); } // Export script to file entry->exportFile(srcfile); // Execute acc string command = path_acc + " " + opt + " \"" + srcfile + "\" \"" + ofile + "\""; wxArrayString output; wxArrayString errout; theApp->SetTopWindow(parent); wxExecute(command, output, errout, wxEXEC_SYNC); theApp->SetTopWindow(theMainWindow); // Log output theConsole->logMessage("ACS compiler output:"); string output_log; if (!output.IsEmpty()) { const char *title1 = "=== Log: ===\n"; theConsole->logMessage(title1); output_log += title1; for (unsigned a = 0; a < output.size(); a++) { theConsole->logMessage(output[a]); output_log += output[a]; } } if (!errout.IsEmpty()) { const char *title2 = "\n=== Error log: ===\n"; theConsole->logMessage(title2); output_log += title2; for (unsigned a = 0; a < errout.size(); a++) { theConsole->logMessage(errout[a]); output_log += errout[a]; } } // Delete source file wxRemoveFile(srcfile); // Delete library files for (unsigned a = 0; a < lib_paths.size(); a++) wxRemoveFile(lib_paths[a]); // Check it compiled successfully if (wxFileExists(ofile)) { // If no target entry was given, find one if (!target) { // Check if the script is a map script (BEHAVIOR) if (S_CMPNOCASE(entry->getName(), "SCRIPTS")) { // Get entry before SCRIPTS ArchiveEntry* prev = entry->prevEntry(); // Create a new entry there if it isn't BEHAVIOR if (!prev || !(S_CMPNOCASE(prev->getName(), "BEHAVIOR"))) prev = entry->getParent()->addNewEntry("BEHAVIOR", entry->getParent()->entryIndex(entry)); // Import compiled script prev->importFile(ofile); } else { // Otherwise, treat it as a library // See if the compiled library already exists as an entry Archive::search_options_t opt; opt.match_namespace = "acs"; opt.match_name = entry->getName(true); ArchiveEntry* lib = entry->getParent()->findLast(opt); // If it doesn't exist, create it if (!lib) lib = entry->getParent()->addEntry(new ArchiveEntry(entry->getName(true) + ".o"), "acs"); // Import compiled script lib->importFile(ofile); } } else target->importFile(ofile); // Delete compiled script file wxRemoveFile(ofile); } else { string errors; if (wxFileExists(appPath("acs.err", DIR_TEMP))) { // Read acs.err to string wxFile file(appPath("acs.err", DIR_TEMP)); char* buf = new char[file.Length()]; file.Read(buf, file.Length()); errors = wxString::From8BitData(buf, file.Length()); delete[] buf; } else errors = output_log; ExtMessageDialog dlg(NULL, "Error Compiling"); dlg.setMessage("The following errors were encountered while compiling, please fix them and recompile:"); dlg.setExt(errors); dlg.ShowModal(); return false; } return true; }
void SCH_EDIT_FRAME::OnCloseWindow( wxCloseEvent& aEvent ) { LIB_EDIT_FRAME * libeditFrame = LIB_EDIT_FRAME::GetActiveLibraryEditor();; if( libeditFrame && !libeditFrame->Close() ) // Can close component editor? return; LIB_VIEW_FRAME* viewlibFrame = LIB_VIEW_FRAME::GetActiveLibraryViewer( this ); if( viewlibFrame && !viewlibFrame->Close() ) // Can close component viewer? return; SCH_SHEET_LIST SheetList; if( SheetList.IsModified() ) { wxString msg; msg.Printf( _("Save the changes in\n<%s>\nbefore closing?"), GetChars( g_RootSheet->GetScreen()->GetFileName() ) ); int ii = DisplayExitDialog( this, msg ); switch( ii ) { case wxID_CANCEL: aEvent.Veto(); return; case wxID_NO: break; case wxID_YES: wxCommandEvent tmp( ID_SAVE_PROJECT ); OnSaveProject( tmp ); break; } } // Close the find dialog and perserve it's setting if it is displayed. if( m_dlgFindReplace ) { m_findDialogPosition = m_dlgFindReplace->GetPosition(); m_findDialogSize = m_dlgFindReplace->GetSize(); m_findStringHistoryList = m_dlgFindReplace->GetFindEntries(); m_replaceStringHistoryList = m_dlgFindReplace->GetReplaceEntries(); m_dlgFindReplace->Destroy(); m_dlgFindReplace = NULL; } SCH_SCREENS screens; wxFileName fn; for( SCH_SCREEN* screen = screens.GetFirst(); screen != NULL; screen = screens.GetNext() ) { fn = screen->GetFileName(); // Auto save file name is the normal file name prepended with $. fn.SetName( wxT( "$" ) + fn.GetName() ); if( fn.FileExists() && fn.IsFileWritable() ) wxRemoveFile( fn.GetFullPath() ); } SheetList.ClearModifyStatus(); if( !g_RootSheet->GetScreen()->GetFileName().IsEmpty() && (g_RootSheet->GetScreen()->GetDrawItems() != NULL) ) UpdateFileHistory( g_RootSheet->GetScreen()->GetFileName() ); g_RootSheet->GetScreen()->Clear(); // all sub sheets are deleted, only the main sheet is usable m_CurrentSheet->Clear(); Destroy(); }
/*! \brief Manage the generation of the doxygen configuration and log files. * * \param prj cbProject* The project. * \return int 0 on success, -1 on failure. * \todo Revisit the path management code and add support for allowing the docs to be created in a different location * to the doxyfile via the OUTPUT_PATH setting e.g. using something like ../docs. */ int DoxyBlocks::GenerateDocuments(cbProject *prj) { wxString sMsg; // First, I need to change into the project directory. All following actions // will work with relative pathes. This way, stored pathes in doxygen // configuration files won't cause problems after moving to other places. // The current path is to be restored after my actions... wxString sOldPath = wxGetCwd(); wxFileName fnProject; fnProject.Assign(prj->GetFilename(), ::wxPATH_NATIVE); wxString sPrjPath = fnProject.GetPath(wxPATH_GET_VOLUME); wxSetWorkingDirectory(sPrjPath); // project name, name and path of base config file and logfile wxString sPrjName = fnProject.GetName(); wxString sOutputDir = m_pConfig->GetOutputDirectory(); wxString sDoxygenDir = wxT("doxygen"); wxString sCfgBaseFile = wxT("doxyfile"); wxString sLogFile = wxT("doxygen.log"); if(!sOutputDir.IsEmpty()){ sDoxygenDir = sOutputDir; } wxFileName fnOutput(sDoxygenDir, wxT("")); wxFileName fnDoxyfile(sDoxygenDir + wxFileName::GetPathSeparator() + sCfgBaseFile); wxFileName fnDoxygenLog(sDoxygenDir + wxFileName::GetPathSeparator() + sLogFile); fnOutput.Normalize(); fnDoxyfile.Normalize(); fnDoxygenLog.Normalize(); if (!fnOutput.Mkdir(0777, wxPATH_MKDIR_FULL)){ wxString sMsg = _("Failed. ") + fnOutput.GetFullPath() + _(" was not created."); AppendToLog(sMsg, LOG_WARNING); wxSetWorkingDirectory(sOldPath); return -1; } // I'm in the project directory, now create the doxygen configuration files WriteConfigFiles(prj, sPrjName, sPrjPath, sDoxygenDir, fnDoxyfile, fnDoxygenLog); if(!wxFile::Exists(fnDoxyfile.GetFullPath())){ wxString sMsg = _("Failed. ") + fnDoxyfile.GetFullPath() + _(" was not created."); AppendToLog(sMsg, LOG_WARNING); wxSetWorkingDirectory(sOldPath); return -1; } // Drop into the doxygen dir. wxSetWorkingDirectory(sPrjPath + wxFileName::GetPathSeparator() + sDoxygenDir); // now tango, launch doxygen... wxArrayString sOutput; wxArrayString sErrors; long ret; // Default command. wxString cmd = wxT("doxygen"); // If a path is configured, use that instead. wxString sDoxygenPath = Manager::Get()->GetMacrosManager()->ReplaceMacros(m_pConfig->GetPathDoxygen()); if(!sDoxygenPath.IsEmpty()){ cmd = sDoxygenPath; } ret = wxExecute(cmd + wxT(" ") + fnDoxyfile.GetFullPath(), sOutput, sErrors); if(ret != -1){ // Write doxygen logfile to the log or remove it if it's empty if(wxFile::Exists(fnDoxygenLog.GetFullPath())){ wxString sText; wxFFile fileLog(fnDoxygenLog.GetFullPath()); if(fileLog.IsOpened()){ fileLog.ReadAll(&sText); fileLog.Close(); } else{ AppendToLog(_("Failed to open ") + sLogFile, LOG_WARNING); } if(!sText.IsEmpty()){ AppendToLog(_("\nContents of doxygen's log file:")); AppendToLog(sText, LOG_WARNING); } else{ wxRemoveFile(sLogFile); } } // Run docs if HTML was created. if(m_pConfig->GetGenerateHTML()){ // Open the newly created HTML docs, if prefs allow. if(m_pConfig->GetRunHTML()){ RunHTML(); } if(m_pConfig->GetGenerateHTMLHelp()){ // Open the newly created CHM if prefs allow. if(m_pConfig->GetRunCHM()){ RunCompiledHelp(fnDoxyfile.GetPathWithSep() , sPrjName); } } } // tell the user where to find the docs sMsg = wxT("Success.\nYour documents are in: "); AppendToLog(sMsg + fnDoxyfile.GetPathWithSep()); } else{ // please google, install doxygen, set your path and... AppendToLog(wxString::Format(_("Execution of '%s' failed."), cmd.c_str()), LOG_ERROR); AppendToLog(_("Please ensure that the doxygen 'bin' directory is in your path or provide the specific path in DoxyBlocks' preferences.\n")); } // restore to before saved path and bye... wxSetWorkingDirectory(sOldPath); return ret; }
~TempFile() { if (!m_name.IsEmpty()) wxRemoveFile(m_name); }
void ecAdminDialog::OnAdd(wxCommandEvent& event) { wxString defaultDir; // TODO wxString defaultFile; wxString wildcard = wxT("eCos Package Files (*.epk)|*.epk"); wxFileDialog dlg(this, _("Open eCos Package Files"), defaultDir, defaultFile, wildcard, wxOPEN|wxMULTIPLE); if (wxID_OK == dlg.ShowModal ()) { bool bRepositoryChanged = FALSE; //POSITION posPathName = dlg.GetStartPosition (); wxArrayString filenames; dlg.GetPaths(filenames); size_t i; for (i = (size_t) 0; i < filenames.GetCount(); i++) { wxString strPathName(filenames[i]); if (!wxFileExists(strPathName)) { wxString msg; msg.Printf(_("Cannot open %s"), (const wxChar*) strPathName); wxMessageBox(msg, wxGetApp().GetSettings().GetAppName(), wxICON_EXCLAMATION|wxOK); } else { // get an eCos package distribution file // extract the licence file wxString strCommand; strCommand.Printf(wxT("add %s --extract_license"), (const wxChar*) strPathName); strCommand.Replace(wxT("\\"), wxT("/")); // backslashes -> forward slashes for Tcl_EvalFile EvalTclFile (3, strCommand, _("Adding package")); wxString strLicenseFile = m_strRepository + wxString(wxFILE_SEP_PATH) + wxT("pkgadd.txt"); #ifdef __WXMSW__ strLicenseFile.Replace (wxT("/"), wxT("\\")); // forward slashes -> backslashes for Win32 #endif // read the license file wxFile fileLicenseFile; if (fileLicenseFile.Exists (strLicenseFile) && fileLicenseFile.Open (strLicenseFile, wxFile::read)) { //TRACE (_T("License file found at %s\n"), strLicenseFile); const off_t dwLicenseLength = fileLicenseFile.Length (); char* pszBuffer = new char [dwLicenseLength + 1]; // allocate a buffer fileLicenseFile.Read ((void*) pszBuffer, dwLicenseLength); fileLicenseFile.Close (); wxRemoveFile (strLicenseFile); // delete the license file when read pszBuffer [dwLicenseLength] = 0; // terminate the string in the buffer wxString strLicenseText (pszBuffer); // copy into a wxString to convert to Unicode delete [] pszBuffer; #ifdef __WXMSW__ if (-1 == strLicenseText.Find (wxT("\r\n"))) // if the file has LF line endings... strLicenseText.Replace (_T("\n"), _T("\r\n")); // ... replace with CRLF line endings #else strLicenseText.Replace (_T("\r"), wxEmptyString); // remove CR characters #endif // display the license text ecLicenseDialog dlgLicense (strLicenseText, this, ecID_LICENSE_DIALOG, strPathName + _(" - Add Packages")); if (wxID_OK != dlgLicense.ShowModal ()) // if license not accepted by user continue; // try the next file } // add the contents of the package distribution file strCommand.Printf (wxT("add %s --accept_license"), (const wxChar*) strPathName); strCommand.Replace (wxT("\\"), wxT("/")); // backslashes -> forward slashes for Tcl_EvalFile if (! EvalTclFile (3, strCommand, _("Adding package"))) // if not successful { // try the next file } else { bRepositoryChanged = TRUE; } } } // refresh the package tree only if necessary if (bRepositoryChanged && ! PopulatePackageTree (m_strRepository)) { } } }
//--------------------------------------------------------- bool SG_File_Delete(const SG_Char *FileName) { return( FileName && *FileName && wxRemoveFile(FileName) ); }
// static void DirManager::CleanTempDir(bool startup) { wxString fname; wxStringList fnameList; int count = 0; if (dontDeleteTempFiles) return; // XXX: is this too destructive, to delete everything? fname = wxFindFirstFile((const char *) (temp + wxFILE_SEP_PATH + "b*")); while (fname != "") { count++; fnameList.Add(fname); fname = wxFindNextFile(); } if (count == 0) return; if (startup) { wxString prompt = _("Audacity found temporary files that were not deleted or saved\n" "the last time you used Audacity.\n\n" "Audacity can't recover them automatically, but if you choose not\n" "to delete them, you can recover them manually.\n\n" "Delete temporary files?"); int action = wxMessageBox(prompt, "Warning", wxYES_NO | wxICON_EXCLAMATION, NULL); if (action != wxYES) { dontDeleteTempFiles = true; return; } } wxChar **array = fnameList.ListToArray(); wxProgressDialog *progress = NULL; //wxYield(); wxStartTimer(); for (int i = 0; i < count; i++) { wxString fileName = array[i]; wxRemoveFile(FILENAME(fileName)); if (!progress && wxGetElapsedTime(false) > 500) progress = new wxProgressDialog(_("Progress"), _("Cleaning up temporary files..."), 1000, NULL, wxPD_REMAINING_TIME | wxPD_AUTO_HIDE); if (progress) progress->Update(int ((i * 1000.0) / count)); } if (progress) delete progress; delete [] array; }
void InternetRetrievalDialog::OnRetrieve( wxCommandEvent& event ) { int count = 0; for(int i=0; i < m_lUrls->GetItemCount(); i++) { FaxUrl *faxurl = reinterpret_cast<FaxUrl*> (wxUIntToPtr(m_lUrls->GetItemData(i))); if(event.GetEventObject() == m_bRetrieveScheduled) { if(!faxurl->Scheduled) continue; } else if(m_lUrls->GetNextItem(i - 1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED) != i) continue; count++; wxString path = weatherfax_pi::StandardPath(); wxString filename = faxurl->Url; filename.Replace(_T("/"), _T("!")); filename.Replace(_T(":"), _T("!")); filename = path + wxFileName::GetPathSeparator() + filename; wxFileName fn(filename); if(fn.FileExists() && (wxDateTime::Now() - fn.GetModificationTime()).GetMinutes() < 180) { wxMessageDialog mdlg(this, _("Fax already retrieved less than 180 minutes ago.\n\ Use existing file?"), _("Weather Fax"), wxYES | wxNO | wxCANCEL); switch(mdlg.ShowModal()) { case wxID_YES: goto loadimage; case wxID_NO: break; default: return; } } { #if 0 wxProgressDialog progressdialog(_("WeatherFax InternetRetrieval"), _("Reading Headers: ") + faxurl->Contents, 1000, this, wxPD_CAN_ABORT | wxPD_ELAPSED_TIME | wxPD_REMAINING_TIME); progressdialog.Update(0); DownloadThread *dl = new DownloadThread(faxurl->Url, filename); dl->Run(); while(dl->IsRunning()) { bool ok; if(dl->size) ok = progressdialog.Update(1000*dl->position / dl->size, _("Reading") + wxString(_T(": ")) + faxurl->Contents); else ok = progressdialog.Update(0); if(!ok) { dl->please_quit = true; return; } wxThread::Sleep(250); } dl->please_quit = true; switch(dl->exitcode) { case 1: case 2: { wxMessageDialog mdlg(this, _("Timed out waiting for headers for: ") + faxurl->Contents + _T("\n") + faxurl->Url + _T("\n") + _("Verify there is a working internet connection.") + _T("\n") + _("Possibly the server is down temporarily.") + _T("\n") + _("If the url is incorrect please edit the xml and/or post a bug report."), _("Weather Fax"), wxOK | wxICON_ERROR); mdlg.ShowModal(); } return; case 3: { wxMessageDialog mdlg(this, _("Failed to read file size aborting."), _("Weather Fax"), wxOK | wxICON_INFORMATION); mdlg.ShowModal(); } return; } #else wxFileOutputStream output(filename); wxCurlDownloadDialog ddlg(faxurl->Url, &output, _("WeatherFax InternetRetrieval"), _("Reading Headers: ") + faxurl->Contents, wxNullBitmap, this, wxCTDS_CAN_PAUSE|wxCTDS_CAN_ABORT|wxCTDS_SHOW_ALL|wxCTDS_AUTO_CLOSE); switch(ddlg.RunModal()) { case wxCDRF_SUCCESS: break; case wxCDRF_FAILED: { wxMessageDialog mdlg(this, _("Failed to Download: ") + faxurl->Contents + _T("\n") + faxurl->Url + _T("\n") + _("Verify there is a working internet connection.") + _T("\n") + _("If the url is incorrect please edit the xml and/or post a bug report."), _("Weather Fax"), wxOK | wxICON_ERROR); mdlg.ShowModal(); wxRemoveFile( filename ); } case wxCDRF_USER_ABORTED: return; } #endif } loadimage: m_weatherfax_pi.m_pWeatherFax->OpenImage (filename, faxurl->Server + _T(" - ") + faxurl->Region, faxurl->area_name, faxurl->Contents); }
void CrashReport::GenerateReport(EXCEPTION_POINTERS* p) #endif { wxLogMessage( _T( "Report generated in " ) ); CwdGuard cwgGuard( wxFileName::GetTempDir() ); NetDebugReport* report = new NetDebugReport( "http://debug.springlobby.info/upload" ) ; // NetDebugReport* report = new NetDebugReport( "http://localhost/upload" ) ; // add all standard files: currently this means just a minidump and an // XML file with system info and stack trace report->AddAll( ); wxString dir = report->GetDirectory(); wxString SystemInfos; SystemInfos += _T( "SpringLobby version " ) + GetSpringLobbyVersion() + _T( "\n" ) ; SystemInfos += _T( "Built from " ) + wxString( wxVERSION_STRING ) + _T(" on ") + wxPlatformInfo::Get().GetOperatingSystemIdName() + _T( "\n" ) ; report->AddText( _T( "SystemInfos.txt" ), SystemInfos, _( "System informations" ) ); #if wxUSE_STD_IOSTREAM report->AddText( _T( "AppLog.txt" ), TowxString( crashlog.str() ), _( "Application verbose log" ) ); #endif wxString script_file = SlPaths::GetDataDir() + wxFileName::GetPathSeparator() + _T("script.txt"); if ( wxFile::Exists( script_file ) ) report->AddFile( script_file, _( "Last generated spring launching script" ) ); #if wxUSE_STACKWALKER && !__WXMSW__ StackTrace stacktrace; stacktrace.Walk( 3, 20 ); report->AddText( _T( "stacktrace.txt" ), _T("Call stack:\n") + stacktrace.GetStackTrace(), _( "StackTrace" ) ); #else wxString report_fn = ( wxGetCwd() + wxFileName::GetPathSeparator() + _T("stacktrace.txt") ); if ( wxFile::Exists( report_fn ) ) wxRemoveFile( report_fn ); wxCharBuffer report_fn_char = report_fn.mb_str(); DrMingwGenerateStacktrace( p, (const char*)report_fn_char ); report->AddFile( report_fn, _( "StackTrace" ) ); #endif wxString SlBuildFlags; #ifdef DISABLE_SOUND SlBuildFlags += _T("sound=0"); #else SlBuildFlags += _T("sound=1"); #endif report->AddText( _T("buildflags.txt"), SlBuildFlags, _T("BuildFlags") ); report->AddText( _T("nick.txt"), sett().GetServerAccountNick( sett().GetDefaultServer() ), _T("Nick") ); wxDebugReportPreviewStd* bkl = new wxDebugReportPreviewStd(); // calling Show() is not mandatory, but is more polite if ( bkl->Show( *report ) ) { if ( report->Process() ) { wxLogMessage( _T( "Report successfully uploaded." ) ); } else { wxLogMessage( _T( "Report generated in \"%s\", but failed to upload" ), report->GetCompressedFileName().c_str() ); report->Reset(); wxLogMessage( _T("report reset") ); } } //else: user cancelled the report delete report; wxLogMessage( _T("deleted report") ); }
void LabelDialog::OnExport(wxCommandEvent & WXUNUSED(event)) { int cnt = mData.size(); // Silly user (could just disable the button, but that's a hassle ;-)) if (cnt == 0) { wxMessageBox(_("No labels to export.")); return; } // Extract the actual name. wxString fName = mTrackNames[mTrackNames.GetCount() - 1].AfterFirst(wxT('-')).Mid(1); fName = FileSelector(_("Export Labels As:"), wxEmptyString, fName.c_str(), wxT("txt"), wxT("*.txt"), wxFD_SAVE | wxFD_OVERWRITE_PROMPT | wxRESIZE_BORDER, this); if (fName == wxT("")) return; // Move existing files out of the way. Otherwise wxTextFile will // append to (rather than replace) the current file. if (wxFileExists(fName)) { #ifdef __WXGTK__ wxString safetyFileName = fName + wxT("~"); #else wxString safetyFileName = fName + wxT(".bak"); #endif if (wxFileExists(safetyFileName)) wxRemoveFile(safetyFileName); wxRename(fName, safetyFileName); } wxTextFile f(fName); #ifdef __WXMAC__ wxFile{}.Create(fName); #else f.Create(); #endif f.Open(); if (!f.IsOpened()) { wxMessageBox(_("Couldn't write to file: ") + fName); return; } // Transfer our collection to a temporary label track auto lt = mFactory.NewLabelTrack(); int i; for (i = 0; i < cnt; i++) { RowData &rd = mData[i]; lt->AddLabel(rd.selectedRegion, rd.title); } // Export them and clean lt->Export(f); #ifdef __WXMAC__ f.Write(wxTextFileType_Mac); #else f.Write(); #endif f.Close(); }
wxThread::ExitCode ModderTask::TaskStart() { // Get the mod list ModList *modList = m_inst->GetModList(); wxFileName mcBin = m_inst->GetBinDir(); wxFileName mcJar = m_inst->GetMCJar(); wxFileName mcBackup = m_inst->GetMCBackup(); // Nothing to do if there are no jar mods to install, no backup and just the mc jar if(mcJar.FileExists() && !mcBackup.FileExists() && modList->empty()) { m_inst->SetNeedsRebuild(false); return (ExitCode)1; } SetStatus(_("Installing mods - backing up minecraft.jar...")); if (!mcBackup.FileExists() && !wxCopyFile(mcJar.GetFullPath(), mcBackup.GetFullPath())) { OnFail(_("Failed to back up minecraft.jar")); return (ExitCode)0; } if (mcJar.FileExists() && !wxRemoveFile(mcJar.GetFullPath())) { OnFail(_("Failed to delete old minecraft.jar")); return (ExitCode)0; } // TODO: good spot for user cancel check? or not... TaskStep(); // STEP 1 SetStatus(_("Installing mods - Opening minecraft.jar")); wxFFileOutputStream jarStream(mcJar.GetFullPath()); wxZipOutputStream zipOut(jarStream); // Files already added to the jar. // These files will be skipped. std::set<wxString> addedFiles; // Modify the jar TaskStep(); // STEP 2 SetStatus(_("Installing mods - Adding mod files...")); for (ModList::const_reverse_iterator iter = modList->rbegin(); iter != modList->rend(); iter++) { wxFileName modFileName = iter->GetFileName(); SetStatus(_("Installing mods - Adding ") + modFileName.GetFullName()); if (iter->IsZipMod()) { wxFFileInputStream modStream(modFileName.GetFullPath()); wxZipInputStream zipStream(modStream); std::auto_ptr<wxZipEntry> entry; while (entry.reset(zipStream.GetNextEntry()), entry.get() != NULL) { if (entry->IsDir()) continue; wxString name = entry->GetName(); if (addedFiles.count(name) == 0) { if (!zipOut.CopyEntry(entry.release(), zipStream)) break; addedFiles.insert(name); } } } else { wxFileName destFileName = modFileName; destFileName.MakeRelativeTo(m_inst->GetInstModsDir().GetFullPath()); wxString destFile = destFileName.GetFullPath(); if (addedFiles.count(destFile) == 0) { wxFFileInputStream input(modFileName.GetFullPath()); zipOut.PutNextEntry(destFile); zipOut.Write(input); addedFiles.insert(destFile); } } } { wxFFileInputStream inStream(mcBackup.GetFullPath()); wxZipInputStream zipIn(inStream); std::auto_ptr<wxZipEntry> entry; while (entry.reset(zipIn.GetNextEntry()), entry.get() != NULL) { wxString name = entry->GetName(); if (!name.Matches("META-INF*") && addedFiles.count(name) == 0) { if (!zipOut.CopyEntry(entry.release(), zipIn)) break; addedFiles.insert(name); } } } // Recompress the jar TaskStep(); // STEP 3 SetStatus(_("Installing mods - Recompressing jar...")); m_inst->SetNeedsRebuild(false); m_inst->UpdateVersion(true); return (ExitCode)1; }
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(); }
void SpringLobbyApp::CacheAndSettingsSetup() { SetSettingsStandAlone( false ); const wxString userConfigDir = GetConfigfileDir(); if ( sett().IsFirstRun() && !wxDirExists( userConfigDir ) ) { wxMkdir( userConfigDir ); } if ( (sett().GetCacheVersion() < CACHE_VERSION) && !sett().IsFirstRun() ) { sett().SetMapCachingThreadProgress( 0 ); // reset map cache thread sett().SetModCachingThreadProgress( 0 ); // reset mod cache thread if ( wxDirExists( sett().GetCachePath() ) ) { wxLogWarning( _T("erasing old cache ver %d (app cache ver %d)"), sett().GetCacheVersion(), CACHE_VERSION ); wxString file = wxFindFirstFile( sett().GetCachePath() + wxFILE_SEP_PATH + _T("*") ); while ( !file.empty() ) { wxRemoveFile( file ); file = wxFindNextFile(); } } } if ( !sett().IsFirstRun() ) { int settversion = sett().GetSettingsVersion(); if ( settversion < 3 ) { sett().ConvertOldSpringDirsOptions(); } if ( settversion < 4 ) { if ( sett().GetTorrentPort() == DEFSETT_SPRING_PORT ) sett().SetTorrentPort( DEFSETT_SPRING_PORT + 1 ); } if ( settversion < 5 ) { wxArrayString list = sett().GetServers(); int count = list.GetCount(); wxArrayString wordlist = sett().GetHighlightedWords(); for ( int i= 0; i < count; i++ ) { wxString nick = sett().GetServerAccountNick( list[i] ); if ( wordlist.Index( nick ) == -1 ) { wordlist.Add( nick ); } } sett().SetHighlightedWords( wordlist ); } if ( settversion < 6 ) { sett().ConvertOldServerSettings(); } if ( settversion < 7 ) { sett().AddChannelJoin( _T("springlobby"), _T("") ); } if ( settversion < 8 ) { sett().DeleteServer( _T("Backup server") ); sett().SetServer( _T("Backup server 1"), _T("springbackup1.servegame.com"), 8200 ); sett().SetServer( _T("Backup server 2"), _T("springbackup2.servegame.org"), 8200 ); sett().SetServer( _T("Test server"), _T("taspringmaster.servegame.com"), 8300 ); } if ( settversion < 10 ) { sett().ConvertOldColorSettings(); } if ( settversion < 11 ) { if( IsUACenabled() ) { usync().ReloadUnitSyncLib(); if ( usync().IsLoaded() ) usync().SetSpringDataPath(_T("")); // UAC is on, fix the spring data path } } if ( settversion < 12 ) { sett().ConvertOldChannelSettings(); } if ( settversion < 13 ) { sett().ConvertOldHiglightSettings(); } if ( settversion < 15 ) { sett().TranslateSavedColumWidths(); } if ( settversion < 21 ) { sett().RemoveLayouts(); } if ( settversion < 18 ) { //new downloader was introduced sett().ClearTorrentListToResume(); } if( settversion < 19 ) { //the dummy column hack was removed on win sett().NukeColumnWidths(); } if ( settversion < 22 ) { if ( m_translationhelper ) { // add locale's language code to autojoin if ( m_translationhelper->GetLocale() ) { wxString localecode = m_translationhelper->GetLocale()->GetCanonicalName(); if ( localecode.Find(_T("_")) != -1 ) localecode = localecode.BeforeFirst(_T('_')); if ( localecode == _T("en") ) // we'll skip en for now, maybe in the future we'll reactivate it sett().AddChannelJoin( localecode, _T("") ); } } } } if ( sett().ShouldAddDefaultServerSettings() || ( sett().GetSettingsVersion() < 14 && sett().GetServers().Count() < 2 ) ) sett().SetDefaultServerSettings(); if ( sett().ShouldAddDefaultChannelSettings() ) { sett().AddChannelJoin( _T("main"), _T("") ); sett().AddChannelJoin( _T("newbies"), _T("") ); if ( m_translationhelper ) { if ( m_translationhelper->GetLocale() ) { wxString localecode = m_translationhelper->GetLocale()->GetCanonicalName(); if ( localecode.Find(_T("_")) != -1 ) localecode = localecode.BeforeFirst(_T('_')); sett().AddChannelJoin( localecode, _T("") ); // add locale's language code to autojoin } } } if ( sett().ShouldAddDefaultGroupSettings() ) { sett().AddGroup( _("Default") ); sett().AddGroup( _("Ignore PM") ); useractions().ChangeAction( _("Ignore PM"), UserActions::ActIgnorePM ); sett().AddGroup( _("Ignore chat") ); useractions().ChangeAction( _("Ignore chat"), UserActions::ActIgnoreChat ); sett().AddGroup( _("Battle Autokick") ); useractions().ChangeAction( _("Battle Autokick"), UserActions::ActAutokick ); sett().AddGroup( _("Friends") ); useractions().ChangeAction( _("Friends"), UserActions::ActNotifBattle ); useractions().ChangeAction( _("Friends"), UserActions::ActHighlight ); useractions().ChangeAction( _("Friends"), UserActions::ActNotifLogin ); useractions().SetGroupColor( _("Friends"), wxColour( 0, 0, 255 ) ); } }
/* EntryOperations::optimizePNG * Attempts to optimize [entry] using external PNG optimizers. *******************************************************************/ bool EntryOperations::optimizePNG(ArchiveEntry* entry) { // Check entry was given if (!entry) return false; // Check entry has a parent (this is useless otherwise) if (!entry->getParent()) return false; // Check entry is PNG if (!EntryDataFormat::getFormat("img_png")->isThisFormat(entry->getMCData())) { wxMessageBox("Error: Entry does not appear to be PNG", "Error", wxOK|wxCENTRE|wxICON_ERROR); return false; } // Check if the PNG tools path are set up, at least one of them should be string pngpathc = path_pngcrush; string pngpatho = path_pngout; string pngpathd = path_deflopt; if ((pngpathc.IsEmpty() || !wxFileExists(pngpathc)) && (pngpatho.IsEmpty() || !wxFileExists(pngpatho)) && (pngpathd.IsEmpty() || !wxFileExists(pngpathd))) { wxLogMessage("PNG tool paths not defined or invalid, no optimization done."); return false; } // Save special chunks point2_t offsets; bool alphchunk = getalPhChunk(entry); bool grabchunk = readgrAbChunk(entry, offsets); string errormessages = ""; wxArrayString output; wxArrayString errors; size_t oldsize = entry->getSize(); size_t crushsize = 0, outsize = 0, deflsize = 0; bool crushed = false, outed = false; // Run PNGCrush if (!pngpathc.IsEmpty() && wxFileExists(pngpathc)) { wxFileName fn(pngpathc); fn.SetExt("opt"); string pngfile = fn.GetFullPath(); fn.SetExt("png"); string optfile = fn.GetFullPath(); entry->exportFile(pngfile); string command = path_pngcrush + " -brute \"" + pngfile + "\" \"" + optfile + "\""; output.Empty(); errors.Empty(); wxExecute(command, output, errors, wxEXEC_SYNC); if (wxFileExists(optfile)) { if (optfile.size() < oldsize) { entry->importFile(optfile); wxRemoveFile(optfile); wxRemoveFile(pngfile); } else errormessages += "PNGCrush failed to reduce file size further.\n"; crushed = true; } else errormessages += "PNGCrush failed to create optimized file.\n"; crushsize = entry->getSize(); // send app output to console if wanted if (0) { string crushlog = ""; if (errors.GetCount()) { crushlog += "PNGCrush error messages:\n"; for (size_t i = 0; i < errors.GetCount(); ++i) crushlog += errors[i] + "\n"; errormessages += crushlog; } if (output.GetCount()) { crushlog += "PNGCrush output messages:\n"; for (size_t i = 0; i < output.GetCount(); ++i) crushlog += output[i] + "\n"; } wxLogMessage(crushlog); } } // Run PNGOut if (!pngpatho.IsEmpty() && wxFileExists(pngpatho)) { wxFileName fn(pngpatho); fn.SetExt("opt"); string pngfile = fn.GetFullPath(); fn.SetExt("png"); string optfile = fn.GetFullPath(); entry->exportFile(pngfile); string command = path_pngout + " /y \"" + pngfile + "\" \"" + optfile + "\""; output.Empty(); errors.Empty(); wxExecute(command, output, errors, wxEXEC_SYNC); if (wxFileExists(optfile)) { if (optfile.size() < oldsize) { entry->importFile(optfile); wxRemoveFile(optfile); wxRemoveFile(pngfile); } else errormessages += "PNGout failed to reduce file size further.\n"; outed = true; } else if (!crushed) // Don't treat it as an error if PNGout couldn't create a smaller file than PNGCrush errormessages += "PNGout failed to create optimized file.\n"; outsize = entry->getSize(); // send app output to console if wanted if (0) { string pngoutlog = ""; if (errors.GetCount()) { pngoutlog += "PNGOut error messages:\n"; for (size_t i = 0; i < errors.GetCount(); ++i) pngoutlog += errors[i] + "\n"; errormessages += pngoutlog; } if (output.GetCount()) { pngoutlog += "PNGOut output messages:\n"; for (size_t i = 0; i < output.GetCount(); ++i) pngoutlog += output[i] + "\n"; } wxLogMessage(pngoutlog); } } // Run deflopt if (!pngpathd.IsEmpty() && wxFileExists(pngpathd)) { wxFileName fn(pngpathd); fn.SetExt("png"); string pngfile = fn.GetFullPath(); entry->exportFile(pngfile); string command = path_deflopt + " /sf \"" + pngfile + "\""; output.Empty(); errors.Empty(); wxExecute(command, output, errors, wxEXEC_SYNC); entry->importFile(pngfile); wxRemoveFile(pngfile); deflsize = entry->getSize(); // send app output to console if wanted if (0) { string defloptlog = ""; if (errors.GetCount()) { defloptlog += "DeflOpt error messages:\n"; for (size_t i = 0; i < errors.GetCount(); ++i) defloptlog += errors[i] + "\n"; errormessages += defloptlog; } if (output.GetCount()) { defloptlog += "DeflOpt output messages:\n"; for (size_t i = 0; i < output.GetCount(); ++i) defloptlog += output[i] + "\n"; } wxLogMessage(defloptlog); } } output.Clear(); errors.Clear(); // Rewrite special chunks if (alphchunk) modifyalPhChunk(entry, true); if (grabchunk) setGfxOffsets(entry, offsets.x, offsets.y); wxLogMessage("PNG %s size %i =PNGCrush=> %i =PNGout=> %i =DeflOpt=> %i =+grAb/alPh=> %i", entry->getName(), oldsize, crushsize, outsize, deflsize, entry->getSize()); if (!crushed && !outed && !errormessages.IsEmpty()) { ExtMessageDialog dlg(NULL, "Optimizing Report"); dlg.setMessage("The following issues were encountered while optimizing:"); dlg.setExt(errormessages); dlg.ShowModal(); return false; } return true; }
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(); } }
void LabelDialog::OnExport(wxCommandEvent &event) { int cnt = mData.GetCount(); // Silly user (could just disable the button, but that's a hassle ;-)) if (cnt == 0) { wxMessageBox(_("No labels to export.")); return; } wxString fName; fName = FileSelector(_("Export Labels As:"), NULL, _("labels.txt"), wxT("txt"), wxT("*.txt"), wxFD_SAVE | wxFD_OVERWRITE_PROMPT | wxRESIZE_BORDER, this); if (fName == wxT("")) return; // Move existing files out of the way. Otherwise wxTextFile will // append to (rather than replace) the current file. if (wxFileExists(fName)) { #ifdef __WXGTK__ wxString safetyFileName = fName + wxT("~"); #else wxString safetyFileName = fName + wxT(".bak"); #endif if (wxFileExists(safetyFileName)) wxRemoveFile(safetyFileName); wxRename(fName, safetyFileName); } wxTextFile f(fName); #ifdef __WXMAC__ wxFile *temp = new wxFile(); temp->Create(fName); delete temp; #else f.Create(); #endif f.Open(); if (!f.IsOpened()) { wxMessageBox(_("Couldn't write to file: ") + fName); return; } // Transfer our collection to a temporary label track LabelTrack *lt = new LabelTrack(mDirManager); int i; for (i = 0; i < cnt; i++) { RowData *rd = mData[i]; lt->AddLabel(rd->stime, rd->etime, rd->title); } // Export them and clean lt->Export(f); delete lt; #ifdef __WXMAC__ f.Write(wxTextFileType_Mac); #else f.Write(); #endif f.Close(); }
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; }
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 }
void XmlResApp::DeleteTempFiles(const wxArrayString& flist) { for (size_t i = 0; i < flist.GetCount(); i++) wxRemoveFile(parOutputPath + wxFILE_SEP_PATH + flist[i]); }
wxArrayString DirectCommands::GetCompileFileCommand(ProjectBuildTarget* target, ProjectFile* pf) const { wxArrayString ret; wxArrayString ret_generated; // is it compilable? if (!pf || !pf->compile) return ret; if (pf->compilerVar.IsEmpty()) { Manager::Get()->GetLogManager()->DebugLog(_("Cannot resolve compiler var for project file.")); return ret; } Compiler* compiler = target ? CompilerFactory::GetCompiler(target->GetCompilerID()) : m_pCompiler; if (!compiler) { Manager::Get()->GetLogManager()->DebugLog(_("Can't access compiler for file.")); return ret; } const pfDetails& pfd = pf->GetFileDetails(target); wxString object = (compiler->GetSwitches().UseFlatObjects) ? pfd.object_file_flat : pfd.object_file; wxString object_dir = (compiler->GetSwitches().UseFlatObjects) ? pfd.object_dir_flat_native : pfd.object_dir_native; // create output dir if (!object_dir.IsEmpty() && !CreateDirRecursively(object_dir, 0755)) Manager::Get()->GetLogManager()->DebugLog(_("Can't create object output directory:\n") + object_dir); // lookup file's type const FileType ft = FileTypeOf(pf->relativeFilename); bool is_resource = ft == ftResource; bool is_header = ft == ftHeader; // allowed resources under all platforms: makes sense when cross-compiling for // windows under linux. // and anyway, if the user is dumb enough to try to compile resources without // having a resource compiler, (s)he deserves the upcoming build error ;) wxString compiler_cmd; if (!is_header || compiler->GetSwitches().supportsPCH) { const CompilerTool* tool = compiler->GetCompilerTool(is_resource ? ctCompileResourceCmd : ctCompileObjectCmd, pf->file.GetExt()); // does it generate other files to compile? for (size_t i = 0; i < pf->generatedFiles.size(); ++i) AppendArray(GetCompileFileCommand(target, pf->generatedFiles[i]), ret_generated); // recurse pfCustomBuild& pcfb = pf->customBuild[compiler->GetID()]; if (pcfb.useCustomBuildCommand) compiler_cmd = pcfb.buildCommand; else if (tool) compiler_cmd = tool->command; else compiler_cmd = wxEmptyString; wxString source_file; if (compiler->GetSwitches().UseFullSourcePaths) source_file = UnixFilename(pfd.source_file_absolute_native); else source_file = pfd.source_file; #ifdef command_line_generation Manager::Get()->GetLogManager()->DebugLog(F(_T("GetCompileFileCommand[1]: compiler_cmd='%s', source_file='%s', object='%s', object_dir='%s'."), compiler_cmd.wx_str(), source_file.wx_str(), object.wx_str(), object_dir.wx_str())); #endif // for resource files, use short from if path because if windres bug with spaces-in-paths if (is_resource && compiler->GetSwitches().UseFullSourcePaths) source_file = pf->file.GetShortPath(); QuoteStringIfNeeded(source_file); #ifdef command_line_generation Manager::Get()->GetLogManager()->DebugLog(F(_T("GetCompileFileCommand[2]: source_file='%s'."), source_file.wx_str())); #endif m_pGenerator->GenerateCommandLine(compiler_cmd, target, pf, source_file, object, pfd.object_file_flat, pfd.dep_file); } if (!is_header && compiler_cmd.IsEmpty()) { ret.Add( wxString(COMPILER_SIMPLE_LOG) + _("Skipping file (no compiler program set): ") + pfd.source_file_native ); return ret; } switch (compiler->GetSwitches().logging) { case clogFull: ret.Add(wxString(COMPILER_SIMPLE_LOG) + compiler_cmd); break; case clogSimple: if (is_header) ret.Add( wxString(COMPILER_SIMPLE_LOG) + _("Pre-compiling header: ") + pfd.source_file_native ); else ret.Add( wxString(COMPILER_SIMPLE_LOG) + _("Compiling: ") + pfd.source_file_native ); break; case clogNone: // fall-through default: break; } AddCommandsToArray(compiler_cmd, ret); if (is_header) ret.Add(wxString(COMPILER_WAIT)); if (ret_generated.GetCount()) { // not only append commands for (any) generated files to be compiled // but also insert a "pause" to allow this file to generate its files first if (!is_header) // if is_header, the "pause" has already been added ret.Add(wxString(COMPILER_WAIT)); AppendArray(ret_generated, ret); } // if it's a PCH, delete the previously generated PCH to avoid problems // (it 'll be recreated anyway) if ( (ft == ftHeader) && pf->compile ) { wxString object_abs = (compiler->GetSwitches().UseFlatObjects) ? pfd.object_file_flat_absolute_native : pfd.object_file_absolute_native; if ( !wxRemoveFile(object_abs) ) Manager::Get()->GetLogManager()->DebugLog(_("Cannot remove old PCH file:\n") + object_abs); } return ret; }
bool DirManager::EnsureSafeFilename(wxFileName fName) { // Quick check: If it's not even in our alias list, // then the file name is A-OK. #if 0 printf("file name: %s\n", fName.GetFullPath().c_str()); printf("string list:\n"); wxStringListNode *node = aliasList.GetFirst(); while (node) { wxString string = node->GetData(); printf("%s\n", string.c_str()); node = node->GetNext(); } #endif if (!aliasList.Member(fName.GetFullPath())) return true; // If any of the following commands fail, your guess is as // good as mine why. The following error message is the // best we can do - we'll use it if any of the renames, // creates, or deletes fail. wxString errStr = _( "Error: is directory write-protected or disk full?" ); /* i18n-hint: 'old' is part of a filename used when a file is renamed. */ // Figure out what the new name for the existing file would be. /* i18n-hint: e.g. Try to go from "mysong.wav" to "mysong-old1.wav". */ // Keep trying until we find a filename that doesn't exist. wxFileName renamedFile = fName; int i = 0; do { i++; /* i18n-hint: This is the pattern for filenames that are created when a file needs to be backed up to a different name. For example, mysong would become mysong-old1, mysong-old2, etc. */ renamedFile.SetName(wxString::Format(_("%s-old%d"), fName.GetName().c_str(), i)); } while (wxFileExists(FILENAME(renamedFile.GetFullPath()))); // Test creating a file by that name to make sure it will // be possible to do the rename wxFile testFile(FILENAME(renamedFile.GetFullPath()), wxFile::write); if (!testFile.IsOpened()) { wxMessageBox(errStr); return false; } if (!wxRemoveFile(FILENAME(renamedFile.GetFullPath()))) { wxMessageBox(errStr); return false; } printf(_("Renamed file: %s\n"), (const char *)renamedFile.GetFullPath()); // Go through our block files and see if any indeed point to // the file we're concerned about. If so, point the block file // to the renamed file and when we're done, perform the rename. bool needToRename = false; wxBusyCursor busy; blockFileHash->BeginFind(); wxNode *n = blockFileHash->Next(); while(n) { BlockFile *b = (BlockFile *)n->GetData(); // don't worry, we don't rely on this cast unless IsAlias is true AliasBlockFile *ab = (AliasBlockFile*)b; if (b->IsAlias() && ab->GetAliasedFile() == fName) { needToRename = true; printf(_("Changing block %s\n"), (const char *)b->GetFileName().GetFullName()); ab->ChangeAliasedFile(renamedFile); } n = blockFileHash->Next(); } if (needToRename) { if (!wxRenameFile(FILENAME(fName.GetFullPath()), FILENAME(renamedFile.GetFullPath()))) { // ACK!!! The renaming was unsuccessful!!! // (This shouldn't happen, since we tried creating a // file of this name and then deleted it just a // second earlier.) But we'll handle this scenario // just in case!!! // Put things back where they were blockFileHash->BeginFind(); n = blockFileHash->Next(); while(n) { BlockFile *b = (BlockFile *)n->GetData(); AliasBlockFile *ab = (AliasBlockFile*)b; if (b->IsAlias() && ab->GetAliasedFile() == renamedFile) ab->ChangeAliasedFile(fName); n = blockFileHash->Next(); } // Print error message and cancel the export wxMessageBox(errStr); return false; } aliasList.Delete(fName.GetFullPath()); aliasList.Add(renamedFile.GetFullPath()); } // Success!!! Either we successfully renamed the file, // or we didn't need to! return true; }
bool cbMGMakefile::SaveMakefile() { bool l_Ret = false; wxString l_FullFilename = m_Path + m_Filename; if ( m_Overwrite && wxFileExists( l_FullFilename ) ) wxRemoveFile( l_FullFilename ); wxTextFile l_File; if ( !l_File.Create( l_FullFilename ) ) { wxString lMsg = _( "File " ) + l_FullFilename + _(" is exists!\nOverwrite?" ); if (wxID_YES == cbMessageBox(lMsg, _("Warning"), wxICON_EXCLAMATION | wxYES_NO, (wxWindow *)Manager::Get()->GetAppWindow())) { wxRemoveFile( l_FullFilename ); } else { return l_Ret; } } l_File.AddLine( sHeader ); { wxString lHeaderVersion = sHeaderVersion; /* FIXME (shl#1#): Add HeaderVersion replacing */ wxString lTmp; lTmp = wxString::Format(_T("%d"),AutoVersion::MAJOR); lHeaderVersion.Replace(_T("$MAJOR"),lTmp,true); lTmp = wxString::Format(_T("%d"),AutoVersion::MINOR); lHeaderVersion.Replace(_T("$MINOR"),lTmp,true); lTmp = wxString::Format(_T("%d"),AutoVersion::BUILD); lHeaderVersion.Replace(_T("$BUILD"),lTmp,true); lTmp = wxString::Format(_T("%d"),AutoVersion::REVISION); lHeaderVersion.Replace(_T("$REVISION"),lTmp,true); l_File.AddLine( lHeaderVersion ); } l_File.AddLine( wxEmptyString ); long l_TargetsCount = m_pProj->GetBuildTargetsCount(); if ( l_TargetsCount < 1 ) { wxString l_Msg = _( "Can't found targets!\n" "C::B MakefileGen could not complete the operation." ); cbMessageBox( l_Msg, _( "Error" ), wxICON_ERROR | wxOK, (wxWindow *)Manager::Get()->GetAppWindow() ); Manager::Get()->GetMessageManager()->DebugLog( l_Msg ); return l_Ret; } m_DependenciesIsNotExistsIsNoProblem = false; if ( m_AllTargets ) { for ( long i = 0; i < l_TargetsCount; i++ ) { ProjectBuildTarget *l_BuildTarget = m_pProj->GetBuildTarget( i ); if ( l_BuildTarget ) { if ( !m_ProceedTargets.IsEmpty() ) { m_ProceedTargets += _T(", "); } m_ProceedTargets += l_BuildTarget->GetTitle(); l_Ret = formFileForTarget( l_BuildTarget, l_File ); if ( l_Ret ) { l_File.Write(); } else { break; } } } } else { ProjectBuildTarget *l_BuildTarget = m_pProj->GetBuildTarget( m_pProj->GetActiveBuildTarget() ); if ( l_BuildTarget ) { m_ProceedTargets += l_BuildTarget->GetTitle(); l_Ret = formFileForTarget( l_BuildTarget, l_File ); if ( l_Ret ) { l_File.Write(); } } } l_File.Close(); return l_Ret; }
void CallGraph::OnShowCallGraph(wxCommandEvent& event) { // myLog("wxThread::IsMain(%d)", (int)wxThread::IsMain()); IConfigTool* config_tool = m_mgr->GetConfigTool(); MacroManager* macro = MacroManager::Instance(); wxASSERT(macro); config_tool->ReadObject(wxT("CallGraph"), &confData); if(!wxFileExists(GetGprofPath()) || !wxFileExists(GetDotPath())) return MessageBox(_T("Failed to locate required tools (gprof, dot). Please check the plugin settings."), wxICON_ERROR); clCxxWorkspace* ws = m_mgr->GetWorkspace(); if(!ws) return MessageBox(_("Unable to get opened workspace."), wxICON_ERROR); wxFileName ws_cfn = ws->GetWorkspaceFileName(); wxString projectName = ws->GetActiveProjectName(); wxString errMsg; ProjectPtr proj = ws->FindProjectByName( projectName, errMsg ); wxString projPath = proj->GetProjectPath(); BuildMatrixPtr mtx = ws->GetBuildMatrix(); if(!mtx) return MessageBox(_("Unable to get current build matrix."), wxICON_ERROR); wxString build_config_name = mtx->GetSelectedConfigurationName(); BuildConfigPtr bldConf = ws->GetProjBuildConf(projectName, build_config_name); if(!bldConf) return MessageBox(_("Unable to get opened workspace."), wxICON_ERROR); wxString projOutputFn = macro->Expand( bldConf->GetOutputFileName(), m_mgr, projectName, build_config_name ); #ifdef __WXMSW__ if( ! projOutputFn.Lower().EndsWith( wxT(".exe") ) ) projOutputFn += wxT(".exe"); #endif //__WXMSW__ // myLog("WorkspaceFileName = \"%s\"", ws_cfn.GetFullPath()); // myLog("projectName \"%s\"", projectName); // myLog("build_config_name = \"%s\"", build_config_name); // myLog("projOutputFn = \"%s\"", projOutputFn); // myLog("projPath = \"%s\"", projPath); wxFileName cfn(projPath + wxFileName::GetPathSeparator() + projOutputFn); cfn.Normalize(); // base path const wxString base_path = ws_cfn.GetPath(); // check source binary exists wxString bin_fpath = cfn.GetFullPath(); if(!cfn.Exists()) { bin_fpath = wxFileSelector("Please select the binary to analyze", base_path, "", ""); if(bin_fpath.IsEmpty()) return MessageBox("selected binary was canceled", wxICON_ERROR); cfn.Assign(bin_fpath, wxPATH_NATIVE); } if(!cfn.IsFileExecutable()) return MessageBox("bin/exe isn't executable", wxICON_ERROR); // check 'gmon.out' file exists wxFileName gmon_cfn( cfn.GetPath() + wxFileName::GetPathSeparator() + GMON_FILENAME_OUT); gmon_cfn.Normalize(); wxString gmonfn = gmon_cfn.GetFullPath(); if(!gmon_cfn.Exists()) { gmonfn = wxFileSelector("Please select the gprof file", gmon_cfn.GetPath(), "gmon", "out"); if(gmonfn.IsEmpty()) return MessageBox("selected gprof was canceled", wxICON_ERROR); gmon_cfn.Assign(gmonfn, wxPATH_NATIVE); } wxString bin, arg1, arg2; bin = GetGprofPath(); arg1 = bin_fpath; arg2 = gmonfn; wxString cmdgprof = wxString::Format("%s %s %s", bin, arg1, arg2); // myLog("about to wxExecute(\"%s\")", cmdgprof); wxProcess* proc = new wxProcess(wxPROCESS_REDIRECT); // wxStopWatch sw; const int err = ::wxExecute(cmdgprof, wxEXEC_SYNC, proc); // on sync returns 0 (success), -1 (failure / "couldn't be started") // myLog("wxExecute() returned err %d, had pid %d", err, (int)proc->GetPid()); wxInputStream* process_is = proc->GetInputStream(); if(!process_is || !process_is->CanRead()) return MessageBox(_("wxProcess::GetInputStream() can't be opened, aborting"), wxICON_ERROR); // start parsing and writing to dot language file GprofParser pgp; pgp.GprofParserStream(process_is); // myLog("gprof done (read %d lines)", (int) pgp.lines.GetCount()); delete proc; ConfCallGraph conf; config_tool->ReadObject(wxT("CallGraph"), &conf); DotWriter dotWriter; // DotWriter dotWriter.SetLineParser(&(pgp.lines)); int suggestedThreshold = pgp.GetSuggestedNodeThreshold(); if(suggestedThreshold <= conf.GetTresholdNode()) { suggestedThreshold = conf.GetTresholdNode(); dotWriter.SetDotWriterFromDialogSettings(m_mgr); } else { dotWriter.SetDotWriterFromDetails(conf.GetColorsNode(), conf.GetColorsEdge(), suggestedThreshold, conf.GetTresholdEdge(), conf.GetHideParams(), conf.GetStripParams(), conf.GetHideNamespaces()); wxString suggest_msg = wxString::Format(_("The CallGraph plugin has suggested node threshold %d to speed-up " "the call graph creation. You can alter it on the call graph panel."), suggestedThreshold); MessageBox(suggest_msg, wxICON_INFORMATION); } dotWriter.WriteToDotLanguage(); // build output dir cfn.Assign(base_path, ""); cfn.AppendDir(CALLGRAPH_DIR); cfn.Normalize(); if(!cfn.DirExists()) cfn.Mkdir(wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL); cfn.SetFullName(DOT_FILENAME_TXT); wxString dot_fn = cfn.GetFullPath(); dotWriter.SendToDotAppOutputDirectory(dot_fn); cfn.SetFullName(DOT_FILENAME_PNG); wxString output_png_fn = cfn.GetFullPath(); // delete any existing PNG if(wxFileExists(output_png_fn)) wxRemoveFile(output_png_fn); wxString cmddot_ln; cmddot_ln << GetDotPath() << " -Tpng -o" << output_png_fn << " " << dot_fn; // myLog("wxExecute(\"%s\")", cmddot_ln); wxExecute(cmddot_ln, wxEXEC_SYNC | wxEXEC_HIDE_CONSOLE); // myLog("dot done"); if(!wxFileExists(output_png_fn)) return MessageBox(_("Failed to open file CallGraph.png. Please check the project settings, rebuild the project " "and try again."), wxICON_INFORMATION); // show image and create table in the editor tab page uicallgraphpanel* panel = new uicallgraphpanel( m_mgr->GetEditorPaneNotebook(), m_mgr, output_png_fn, base_path, suggestedThreshold, &(pgp.lines)); wxString tstamp = wxDateTime::Now().Format(wxT(" %Y-%m-%d %H:%M:%S")); wxString title = wxT("Call graph for \"") + output_png_fn + wxT("\" " + tstamp); m_mgr->AddEditorPage(panel, title); }
void EDA_BASE_FRAME::CheckForAutoSaveFile( const wxFileName& aFileName, const wxString& aBackupFileExtension ) { wxCHECK_RET( aFileName.IsOk(), wxT( "Invalid file name!" ) ); wxCHECK_RET( !aBackupFileExtension.IsEmpty(), wxT( "Invalid backup file extension!" ) ); wxFileName autoSaveFileName = aFileName; // Check for auto save file. autoSaveFileName.SetName( AUTOSAVE_PREFIX_FILENAME + aFileName.GetName() ); wxLogTrace( traceAutoSave, wxT( "Checking for auto save file " ) + autoSaveFileName.GetFullPath() ); if( !autoSaveFileName.FileExists() ) return; wxString msg = wxString::Format( _( "Well this is potentially embarrassing!\n" "It appears that the last time you were editing the file\n" "'%s'\n" "it was not saved properly. Do you wish to restore the last saved edits you made?" ), GetChars( aFileName.GetFullName() ) ); int response = wxMessageBox( msg, Pgm().App().GetAppName(), wxYES_NO | wxICON_QUESTION, this ); // Make a backup of the current file, delete the file, and rename the auto save file to // the file name. if( response == wxYES ) { // Get the backup file name. wxFileName backupFileName = aFileName; backupFileName.SetExt( aBackupFileExtension ); // If an old backup file exists, delete it. If an old copy of the file exists, rename // it to the backup file name if( aFileName.FileExists() ) { // Remove the old file backup file. if( backupFileName.FileExists() ) wxRemoveFile( backupFileName.GetFullPath() ); // Rename the old file to the backup file name. if( !wxRenameFile( aFileName.GetFullPath(), backupFileName.GetFullPath() ) ) { msg.Printf( _( "Could not create backup file <%s>" ), GetChars( backupFileName.GetFullPath() ) ); wxMessageBox( msg ); } } if( !wxRenameFile( autoSaveFileName.GetFullPath(), aFileName.GetFullPath() ) ) { wxMessageBox( _( "The auto save file could not be renamed to the board file name." ), Pgm().App().GetAppName(), wxOK | wxICON_EXCLAMATION, this ); } } else { wxLogTrace( traceAutoSave, wxT( "Removing auto save file " ) + autoSaveFileName.GetFullPath() ); // Remove the auto save file when using the previous file as is. wxRemoveFile( autoSaveFileName.GetFullPath() ); } }
bool SCH_EDIT_FRAME::SaveEEFile( SCH_SCREEN* aScreen, bool aSaveUnderNewName, bool aCreateBackupFile ) { wxString msg; wxFileName schematicFileName; FILE* f; bool success; if( aScreen == NULL ) aScreen = GetScreen(); // If no name exists in the window yet - save as new. if( aScreen->GetFileName().IsEmpty() ) aSaveUnderNewName = true; // Construct the name of the file to be saved schematicFileName = aScreen->GetFileName(); if( aSaveUnderNewName ) { wxFileDialog dlg( this, _( "Schematic Files" ), wxGetCwd(), schematicFileName.GetFullName(), SchematicFileWildcard, wxFD_SAVE | wxFD_OVERWRITE_PROMPT ); if( dlg.ShowModal() == wxID_CANCEL ) return false; schematicFileName = dlg.GetPath(); if( schematicFileName.GetExt() != SchematicFileExtension ) schematicFileName.SetExt( SchematicFileExtension ); } else { // Sheet file names are relative to the root sheet path which is the current // working directory. The IsWritable function expects the path to be set. if( schematicFileName.GetPath().IsEmpty() ) schematicFileName.Assign( wxFileName::GetCwd(), schematicFileName.GetFullName() ); } if( !IsWritable( schematicFileName ) ) return false; /* Create backup if requested */ if( aCreateBackupFile && schematicFileName.FileExists() ) { wxFileName backupFileName = schematicFileName; /* Rename the old file to a '.bak' one: */ backupFileName.SetExt( SchematicBackupFileExtension ); if( backupFileName.FileExists() ) wxRemoveFile( backupFileName.GetFullPath() ); if( !wxRenameFile( schematicFileName.GetFullPath(), backupFileName.GetFullPath() ) ) { msg.Printf( _( "Could not save backup of file <%s>" ), GetChars( schematicFileName.GetFullPath() ) ); DisplayError( this, msg ); } } /* Save */ wxLogTrace( traceAutoSave, wxT( "Saving file <" ) + schematicFileName.GetFullPath() + wxT( ">" ) ); if( ( f = wxFopen( schematicFileName.GetFullPath(), wxT( "wt" ) ) ) == NULL ) { msg.Printf( _( "Failed to create file <%s>" ), GetChars( schematicFileName.GetFullPath() ) ); DisplayError( this, msg ); return false; } success = aScreen->Save( f ); if( success ) { // Delete auto save file. wxFileName autoSaveFileName = schematicFileName; autoSaveFileName.SetName( wxT( "$" ) + schematicFileName.GetName() ); if( autoSaveFileName.FileExists() ) { wxLogTrace( traceAutoSave, wxT( "Removing auto save file <" ) + autoSaveFileName.GetFullPath() + wxT( ">" ) ); wxRemoveFile( autoSaveFileName.GetFullPath() ); } // Update the screen and frame info. if( aSaveUnderNewName ) aScreen->SetFileName( schematicFileName.GetFullPath() ); aScreen->ClrSave(); aScreen->ClrModify(); msg.Printf( _( "File %s saved" ), GetChars( aScreen->GetFileName() ) ); SetStatusText( msg, 0 ); } else { DisplayError( this, _( "File write operation failed." ) ); } fclose( f ); return success; }
void PrintPostScriptDialog::PrintShow() { wxString s; #ifdef PRINT__RUN_CMD wxString buf; #endif bool overview; long minyards; text_minyards->GetValue().ToLong(&minyards); if (minyards < 10 || minyards > 100) { wxLogError(wxT("Yards entered invalid. Please enter a number between 10 and 100.")); return; } overview = GetConfiguration_PrintPSOverview(); switch (GetConfiguration_PrintPSModes()) { case CC_PRINT_ACTION_PREVIEW: { #ifdef PRINT__RUN_CMD s = wxFileName::CreateTempFileName(wxT("cc_")); buf.sprintf(wxT("%s %s \"%s\""), GetConfiguration_PrintViewCmd().c_str(), GetConfiguration_PrintViewCmd().c_str(), s.c_str()); #endif } break; case CC_PRINT_ACTION_FILE: s = wxFileSelector(wxT("Print to file"), wxEmptyString, wxEmptyString, wxEmptyString, eps ? wxT("*.eps"):wxT("*.ps"), wxFD_SAVE|wxFD_OVERWRITE_PROMPT); if (s.empty()) return; break; case CC_PRINT_ACTION_PRINTER: { #ifdef PRINT__RUN_CMD s = wxFileName::CreateTempFileName(wxT("cc_")); buf.sprintf(wxT("%s %s \"%s\""), GetConfiguration_PrintCmd().c_str(), GetConfiguration_PrintOpts().c_str(), s.c_str()); #else #endif } break; default: break; } std::ostringstream buffer; bool doLandscape = GetConfiguration_PrintPSLandscape(); bool doCont = GetConfiguration_PrintPSDoCont(); bool doContSheet = GetConfiguration_PrintPSDoContSheet(); PrintShowToPS printShowToPS(*mShow, doLandscape, doCont, doContSheet); int n = printShowToPS(buffer, eps, overview, mShow->GetCurrentSheetNum(), minyards, mIsSheetPicked); // stream to file: { wxFFileOutputStream outstream(s); outstream.Write(buffer.str().c_str(), buffer.str().size()); } #ifdef PRINT__RUN_CMD switch (GetConfiguration_PrintPSModes()) { case CC_PRINT_ACTION_FILE: break; default: system(buf.utf8_str()); wxRemoveFile(s); break; } #endif wxString tempbuf; tempbuf.sprintf(wxT("Printed %d pages."), n); (void)wxMessageBox(tempbuf, mShow->GetTitle()); }
bool wxMakeMetafilePlaceable(const wxString& filename, int x1, int y1, int x2, int y2, float scale, bool useOriginAndExtent) { // I'm not sure if this is the correct way of suggesting a scale // to the client application, but it's the only way I can find. int unitsPerInch = (int)(576/scale); mfPLACEABLEHEADER header; header.key = 0x9AC6CDD7L; header.hmf = 0; header.bbox.left = (int)(x1); header.bbox.top = (int)(y1); header.bbox.right = (int)(x2); header.bbox.bottom = (int)(y2); header.inch = unitsPerInch; header.reserved = 0; // Calculate checksum WORD *p; mfPLACEABLEHEADER *pMFHead = &header; for (p =(WORD *)pMFHead,pMFHead -> checksum = 0; p < (WORD *)&pMFHead ->checksum; ++p) pMFHead ->checksum ^= *p; FILE *fd = wxFopen(filename.fn_str(), wxT("rb")); if (!fd) return false; wxString tempFileBuf = wxFileName::CreateTempFileName(wxT("mf")); if (tempFileBuf.empty()) return false; FILE *fHandle = wxFopen(tempFileBuf.fn_str(), wxT("wb")); if (!fHandle) return false; fwrite((void *)&header, sizeof(unsigned char), sizeof(mfPLACEABLEHEADER), fHandle); // Calculate origin and extent int originX = x1; int originY = y1; int extentX = x2 - x1; int extentY = (y2 - y1); // Read metafile header and write METAHEADER metaHeader; fread((void *)&metaHeader, sizeof(unsigned char), sizeof(metaHeader), fd); if (useOriginAndExtent) metaHeader.mtSize += 15; else metaHeader.mtSize += 5; fwrite((void *)&metaHeader, sizeof(unsigned char), sizeof(metaHeader), fHandle); // Write SetMapMode, SetWindowOrigin and SetWindowExt records char modeBuffer[8]; char originBuffer[10]; char extentBuffer[10]; METARECORD *modeRecord = (METARECORD *)&modeBuffer; METARECORD *originRecord = (METARECORD *)&originBuffer; METARECORD *extentRecord = (METARECORD *)&extentBuffer; modeRecord->rdSize = 4; modeRecord->rdFunction = META_SETMAPMODE; modeRecord->rdParm[0] = MM_ANISOTROPIC; originRecord->rdSize = 5; originRecord->rdFunction = META_SETWINDOWORG; originRecord->rdParm[0] = originY; originRecord->rdParm[1] = originX; extentRecord->rdSize = 5; extentRecord->rdFunction = META_SETWINDOWEXT; extentRecord->rdParm[0] = extentY; extentRecord->rdParm[1] = extentX; fwrite((void *)modeBuffer, sizeof(char), 8, fHandle); if (useOriginAndExtent) { fwrite((void *)originBuffer, sizeof(char), 10, fHandle); fwrite((void *)extentBuffer, sizeof(char), 10, fHandle); } int ch = -2; while (ch != EOF) { ch = getc(fd); if (ch != EOF) { putc(ch, fHandle); } } fclose(fHandle); fclose(fd); wxRemoveFile(filename); wxCopyFile(tempFileBuf, filename); wxRemoveFile(tempFileBuf); return true; }
bool LIB_EDIT_FRAME::SaveActiveLibrary( bool newFile ) { wxFileName fn; wxString msg; m_canvas->EndMouseCapture( ID_NO_TOOL_SELECTED, m_canvas->GetDefaultCursor() ); PART_LIB* lib = GetCurLib(); if( !lib ) { DisplayError( this, _( "No library specified." ) ); return false; } if( GetScreen()->IsModify() ) { if( IsOK( this, _( "Include last component changes?" ) ) ) SaveOnePart( lib, false ); } if( newFile ) { PROJECT& prj = Prj(); SEARCH_STACK* search = prj.SchSearchS(); // Get a new name for the library wxString default_path = prj.GetRString( PROJECT::SCH_LIB_PATH ); if( !default_path ) default_path = search->LastVisitedPath(); wxFileDialog dlg( this, _( "Part Library Name:" ), default_path, wxEmptyString, SchematicLibraryFileWildcard, wxFD_SAVE | wxFD_OVERWRITE_PROMPT ); if( dlg.ShowModal() == wxID_CANCEL ) return false; fn = dlg.GetPath(); // The GTK file chooser doesn't return the file extension added to // file name so add it here. if( fn.GetExt().IsEmpty() ) fn.SetExt( SchematicLibraryFileExtension ); prj.SetRString( PROJECT::SCH_LIB_PATH, fn.GetPath() ); } else { fn = wxFileName( lib->GetFullFileName() ); msg.Printf( _( "Modify library file '%s' ?" ), GetChars( fn.GetFullPath() ) ); if( !IsOK( this, msg ) ) return false; } // Verify the user has write privileges before attempting to // save the library file. if( !IsWritable( fn ) ) return false; ClearMsgPanel(); wxFileName libFileName = fn; wxFileName backupFileName = fn; // Rename the old .lib file to .bak. if( libFileName.FileExists() ) { backupFileName.SetExt( wxT( "bak" ) ); if( backupFileName.FileExists() ) wxRemoveFile( backupFileName.GetFullPath() ); if( !wxRenameFile( libFileName.GetFullPath(), backupFileName.GetFullPath() ) ) { libFileName.MakeAbsolute(); msg = wxT( "Failed to rename old component library file " ) + backupFileName.GetFullPath(); DisplayError( this, msg ); } } try { FILE_OUTPUTFORMATTER libFormatter( libFileName.GetFullPath() ); if( !lib->Save( libFormatter ) ) { msg.Printf( _( "Error occurred while saving library file '%s'" ), GetChars( fn.GetFullPath() ) ); AppendMsgPanel( _( "*** ERROR: ***" ), msg, RED ); DisplayError( this, msg ); return false; } } catch( ... /* IO_ERROR ioe */ ) { libFileName.MakeAbsolute(); msg.Printf( _( "Failed to create component library file '%s'" ), GetChars( libFileName.GetFullPath() ) ); DisplayError( this, msg ); return false; } wxFileName docFileName = libFileName; docFileName.SetExt( DOC_EXT ); // Rename .doc file to .bck. if( docFileName.FileExists() ) { backupFileName.SetExt( wxT( "bck" ) ); if( backupFileName.FileExists() ) wxRemoveFile( backupFileName.GetFullPath() ); if( !wxRenameFile( docFileName.GetFullPath(), backupFileName.GetFullPath() ) ) { msg = wxT( "Failed to save old library document file " ) + backupFileName.GetFullPath(); DisplayError( this, msg ); } } try { FILE_OUTPUTFORMATTER docFormatter( docFileName.GetFullPath() ); if( !lib->SaveDocs( docFormatter ) ) { msg.Printf( _( "Error occurred while saving library documentation file <%s>" ), GetChars( docFileName.GetFullPath() ) ); AppendMsgPanel( _( "*** ERROR: ***" ), msg, RED ); DisplayError( this, msg ); return false; } } catch( ... /* IO_ERROR ioe */ ) { docFileName.MakeAbsolute(); msg.Printf( _( "Failed to create component document library file <%s>" ), GetChars( docFileName.GetFullPath() ) ); DisplayError( this, msg ); return false; } msg.Printf( _( "Library file '%s' OK" ), GetChars( fn.GetFullName() ) ); fn.SetExt( DOC_EXT ); wxString msg1; msg1.Printf( _( "Documentation file '%s' OK" ), GetChars( fn.GetFullPath() ) ); AppendMsgPanel( msg, msg1, BLUE ); return true; }
bool SCH_EDIT_FRAME::SaveEEFile( SCH_SCREEN* aScreen, bool aSaveUnderNewName, bool aCreateBackupFile ) { wxString msg; wxFileName schematicFileName; bool success; if( aScreen == NULL ) aScreen = GetScreen(); // If no name exists in the window yet - save as new. if( aScreen->GetFileName().IsEmpty() ) aSaveUnderNewName = true; // Construct the name of the file to be saved schematicFileName = Prj().AbsolutePath( aScreen->GetFileName() ); if( aSaveUnderNewName ) { wxFileDialog dlg( this, _( "Schematic Files" ), wxPathOnly( Prj().GetProjectFullName() ), schematicFileName.GetFullName(), SchematicFileWildcard, wxFD_SAVE | wxFD_OVERWRITE_PROMPT ); if( dlg.ShowModal() == wxID_CANCEL ) return false; schematicFileName = dlg.GetPath(); if( schematicFileName.GetExt() != SchematicFileExtension ) schematicFileName.SetExt( SchematicFileExtension ); } if( !IsWritable( schematicFileName ) ) return false; // Create backup if requested if( aCreateBackupFile && schematicFileName.FileExists() ) { wxFileName backupFileName = schematicFileName; // Rename the old file to a '.bak' one: backupFileName.SetExt( SchematicBackupFileExtension ); if( backupFileName.FileExists() ) wxRemoveFile( backupFileName.GetFullPath() ); if( !wxRenameFile( schematicFileName.GetFullPath(), backupFileName.GetFullPath() ) ) { msg.Printf( _( "Could not save backup of file '%s'" ), GetChars( schematicFileName.GetFullPath() ) ); DisplayError( this, msg ); } } // Save wxLogTrace( traceAutoSave, wxT( "Saving file <" ) + schematicFileName.GetFullPath() + wxT( ">" ) ); FILE* f = wxFopen( schematicFileName.GetFullPath(), wxT( "wt" ) ); if( !f ) { msg.Printf( _( "Failed to create file '%s'" ), GetChars( schematicFileName.GetFullPath() ) ); DisplayError( this, msg ); return false; } success = aScreen->Save( f ); if( success ) { // Delete auto save file. wxFileName autoSaveFileName = schematicFileName; autoSaveFileName.SetName( AUTOSAVE_PREFIX_FILENAME + schematicFileName.GetName() ); if( autoSaveFileName.FileExists() ) { wxLogTrace( traceAutoSave, wxT( "Removing auto save file <" ) + autoSaveFileName.GetFullPath() + wxT( ">" ) ); wxRemoveFile( autoSaveFileName.GetFullPath() ); } // Update the screen and frame info. if( aSaveUnderNewName ) aScreen->SetFileName( schematicFileName.GetFullPath() ); aScreen->ClrSave(); aScreen->ClrModify(); msg.Printf( _( "File %s saved" ), GetChars( aScreen->GetFileName() ) ); SetStatusText( msg, 0 ); } else { DisplayError( this, _( "File write operation failed." ) ); } fclose( f ); return success; }
/* 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; }