Beispiel #1
0
void GcbApp::CheckDirectories()
{
	wxArrayString requiredDir;

	requiredDir.push_back("3d");
	requiredDir.push_back("bin");
	requiredDir.push_back("database");
	requiredDir.push_back("images");
	requiredDir.push_back("maps");
	requiredDir.push_back("scenarios");
	requiredDir.push_back("scripts");
	requiredDir.push_back("sound");
	requiredDir.push_back("xml");

	for (size_t n=0; n<requiredDir.size(); n++)
	{
		wxString dirToCheck = requiredDir[n];
		if (!wxDir::Exists(dirToCheck))
		{
			wxMessageBox(wxString::Format("Missing required directory (%s), please repair or reinstall application", dirToCheck.c_str()));
			throw "missing directory";
		}
	}

	if (!wxDir::Exists("log"))
	{
		wxMkdir("log");
	}
	if (!wxDir::Exists("aar"))
	{
		wxMkdir("aar");
	}
}
Beispiel #2
0
bool BundleManager::InstallBundle() {
	wxASSERT(m_currentBundle);

	// Create temp dir
	wxString tempDir = wxStandardPaths::Get().GetTempDir();
	tempDir += wxFILE_SEP_PATH + m_currentBundle->m_name;
	if (wxDirExists(tempDir)) {
		// Delete old first
		DelTree(tempDir);
	}
	wxMkdir(tempDir);

	// Show progress dialog
	wxProgressDialog dlg(_("Downloading..."), m_currentBundle->m_name, 200, this, wxPD_AUTO_HIDE|wxPD_APP_MODAL);

	// Download bundle
	const wxString& repoUrl = GetCurrentRepoUrl();
	const wxString url = repoUrl + m_currentBundle->m_name + wxT('/');
	wxFileName path(tempDir, wxEmptyString);
	if (!DownloadDir(url, path, dlg)) {
		DelTree(tempDir); // clean up
		return false;
	}

	// Set modDate to match repo
	// Windows does not support changing dates on directories under FAT so
	// to make sure it works we set the date on info.plist instead
	path.SetFullName(wxT("info.plist"));
	path.SetTimes(NULL, &m_currentBundle->m_modDate, NULL);

	// Delete installed version (if any)
	wxString installPath = dynamic_cast<IAppPaths*>(wxTheApp)->GetAppDataPath() + wxT("InstalledBundles") + wxFILE_SEP_PATH;
	if (!wxDirExists(installPath)) wxMkdir(installPath);
	installPath += m_currentBundle->m_name;
	if (wxDirExists(installPath)) DelTree(installPath);

	// Move bundle to install dir
	wxRenameFile(tempDir, installPath);

	// Update list
	bool inList = false;
	for (vector<cxBundleInfo>::iterator p = m_installedBundles.begin(); p != m_installedBundles.end(); ++p) {
		if (p->dirName == m_currentBundle->m_name) {
			p->modDate = m_currentBundle->m_modDate;
			inList = true;
			break;
		}
	}
	if (!inList) {
		cxBundleInfo bi(-1, m_currentBundle->m_name, m_currentBundle->m_modDate);
		m_installedBundles.push_back(bi);
	}

	// Update the UI
	m_bundleList->SetItemImage(m_currentSel, 1); // up-to-date image
	SelectItem(m_currentSel, true);

	m_needBundleReload = true;
	return true;
}
Beispiel #3
0
bool CopyDirWithFilebackupRename( wxString from, wxString to, bool overwrite )
{
    wxString sep = wxFileName::GetPathSeparator();

    // append a slash if there is not one (for easier parsing)
    // because who knows what people will pass to the function.
    if ( !to.EndsWith( sep ) ) {
            to += sep;
    }
    // for both dirs
    if ( !from.EndsWith( sep ) ) {
            from += sep;
    }

    // first make sure that the source dir exists
    if(!wxDir::Exists(from)) {
            wxLogError(from + _T(" does not exist.  Can not copy directory.") );
            return false;
    }

    if (!wxDirExists(to))
        wxMkdir(to);

    wxDir dir(from);
    wxString filename;
    bool bla = dir.GetFirst(&filename);

    if (bla){
        do {

            if (wxDirExists(from + filename) )
            {
                wxMkdir(to + filename);
                CopyDir(from + filename, to + filename, overwrite);
            }
            else{
                //if files exists move it to backup, this way we can use this func on windows to replace 'active' files
                if ( wxFileExists( to + filename ) ) {
                    //delete prev backup
                    if ( wxFileExists( to + filename + _T(".old") ) ) {
                        wxRemoveFile( to + filename + _T(".old")  );
                    }
                    //make backup
                    if ( !wxRenameFile( to + filename, to + filename + _T(".old") ) ) {
						wxLogError( _T("could not rename %s, copydir aborted"), (to + filename).c_str() );
                        return false;
                    }
                }
                //do the actual copy
                if ( !wxCopyFile(from + filename, to + filename, overwrite) ) {
					wxLogError( _T("could not copy %s to %s, copydir aborted"), (from + filename).c_str(), (to + filename).c_str() );
                    return false;
                }
            }
        }
        while (dir.GetNext(&filename) );
    }
    return true;
}
Beispiel #4
0
// -----------------------------------------------------------------------------
// Checks for and creates necessary application directories. Returns true
// if all directories existed and were created successfully if needed,
// false otherwise
// -----------------------------------------------------------------------------
bool initDirectories()
{
	// If we're passed in a INSTALL_PREFIX (from CMAKE_INSTALL_PREFIX),
	// use this for the installation prefix
#if defined(__WXGTK__) && defined(INSTALL_PREFIX)
	wxStandardPaths::Get().SetInstallPrefix(INSTALL_PREFIX);
#endif // defined(__UNIX__) && defined(INSTALL_PREFIX)

	// Setup app dir
	dir_app = StrUtil::Path::pathOf(wxStandardPaths::Get().GetExecutablePath().ToStdString(), false);

	// Check for portable install
	if (wxFileExists(path("portable", Dir::Executable)))
	{
		// Setup portable user/data dirs
		dir_data = dir_app;
		dir_res  = dir_app;
		dir_user = dir_app + dir_separator + "config";
	}
	else
	{
		// Setup standard user/data dirs
		dir_user = wxStandardPaths::Get().GetUserDataDir();
		dir_data = wxStandardPaths::Get().GetDataDir();
		dir_res  = wxStandardPaths::Get().GetResourcesDir();
	}

	// Create user dir if necessary
	if (!wxDirExists(dir_user))
	{
		if (!wxMkdir(dir_user))
		{
			wxMessageBox(wxString::Format("Unable to create user directory \"%s\"", dir_user), "Error", wxICON_ERROR);
			return false;
		}
	}

	// Create temp dir if necessary
	dir_temp = dir_user + dir_separator + "temp";
	if (!wxDirExists(dir_temp))
	{
		if (!wxMkdir(dir_temp))
		{
			wxMessageBox(wxString::Format("Unable to create temp directory \"%s\"", dir_temp), "Error", wxICON_ERROR);
			return false;
		}
	}

	// Check data dir
	if (!wxDirExists(dir_data))
		dir_data = dir_app; // Use app dir if data dir doesn't exist

	// Check res dir
	if (!wxDirExists(dir_res))
		dir_res = dir_app; // Use app dir if res dir doesn't exist

	return true;
}
Beispiel #5
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);
        }
    }
}
Beispiel #6
0
bool EditorConfig::Load()
{
    m_cacheLongValues.clear();
    m_cacheStringValues.clear();

    // first try to load the user's settings
    m_fileName = clStandardPaths::Get().GetUserDataDir() + wxFileName::GetPathSeparator() + wxT("config/codelite.xml");
    wxString localFileName = m_fileName.GetFullPath();

    {
        // Make sure that the directory exists
        wxLogNull noLog;
        wxMkdir(m_fileName.GetPath());
        wxMkdir(clStandardPaths::Get().GetUserDataDir() + wxFileName::GetPathSeparator() + wxT("lexers"));
    }

    bool userSettingsLoaded(false);
    bool loadSuccess(false);

    if(!m_fileName.FileExists()) {
        loadSuccess = DoLoadDefaultSettings();

        if(loadSuccess) {
            // Copy the content of the default codelite.xml file into the user's local file
            wxCopyFile(m_fileName.GetFullPath(), localFileName);
        }

    } else {
        userSettingsLoaded = true;
        loadSuccess = m_doc->Load(m_fileName.GetFullPath());
    }

    if(!loadSuccess) {
        return false;
    }

    // Check the codelite-version for this file
    wxString version;
    bool found = m_doc->GetRoot()->GetPropVal(wxT("Version"), &version);
    if(userSettingsLoaded) {
        if(!found || (found && version != this->m_version)) {
            if(DoLoadDefaultSettings() == false) {
                return false;
            }
        }
    }

    // load CodeLite lexers
    // LoadLexers(false);

    // make sure that the file name is set to .xml and not .default
    m_fileName = clStandardPaths::Get().GetUserDataDir() + wxFileName::GetPathSeparator() + wxT("config/codelite.xml");
    return true;
}
Beispiel #7
0
void SetUpWorkingDirectories(const char* argv0)
{
    // set up working directories
    workingDir = wxGetCwd().c_str();
#ifdef __WXGTK__
    if (getenv("CN3D_HOME") != NULL)
        programDir = getenv("CN3D_HOME");
    else
#endif
    if (wxIsAbsolutePath(argv0))
        programDir = wxPathOnly(argv0).c_str();
    else if (wxPathOnly(argv0) == "")
        programDir = workingDir;
    else
        programDir = workingDir + wxFILE_SEP_PATH + wxPathOnly(argv0).c_str();
    workingDir = workingDir + wxFILE_SEP_PATH;
    programDir = programDir + wxFILE_SEP_PATH;

    // find or create preferences folder
    wxString localDir;
    wxSplitPath((wxFileConfig::GetLocalFileName("unused")).c_str(), &localDir, NULL, NULL);
    wxString prefsDirLocal = localDir + wxFILE_SEP_PATH + "Cn3D_User";
    wxString prefsDirProg = wxString(programDir.c_str()) + wxFILE_SEP_PATH + "Cn3D_User";
    if (wxDirExists(prefsDirLocal))
        prefsDir = prefsDirLocal.c_str();
    else if (wxDirExists(prefsDirProg))
        prefsDir = prefsDirProg.c_str();
    else {
        // try to create the folder
        if (wxMkdir(prefsDirLocal) && wxDirExists(prefsDirLocal))
            prefsDir = prefsDirLocal.c_str();
        else if (wxMkdir(prefsDirProg) && wxDirExists(prefsDirProg))
            prefsDir = prefsDirProg.c_str();
    }
    if (prefsDir.size() == 0)
        WARNINGMSG("Can't create Cn3D_User folder at either:"
            << "\n    " << prefsDirLocal
            << "\nor  " << prefsDirProg);
    else
        prefsDir += wxFILE_SEP_PATH;

    // set data dir, and register the path in C toolkit registry (mainly for BLAST code)
#ifdef __WXMAC__
    dataDir = programDir + "../Resources/data/";
#else
    dataDir = programDir + "data" + wxFILE_SEP_PATH;
#endif

    TRACEMSG("working dir: " << workingDir.c_str());
    TRACEMSG("program dir: " << programDir.c_str());
    TRACEMSG("data dir: " << dataDir.c_str());
    TRACEMSG("prefs dir: " << prefsDir.c_str());
}
Beispiel #8
0
bool AudacityApp::InitCleanSpeech()
{
   wxString cwd = FROMFILENAME(::wxGetCwd());
   wxString presetsFromPrefs = gPrefs->Read(wxT("/Directories/PresetsDir"), wxT(""));
   wxString presets = wxT("");

   #ifdef __WXGTK__
   if (presetsFromPrefs.GetChar(0) != wxT('/'))
      presetsFromPrefs = wxT("");
   #endif

   #ifdef __WXMSW__
   wxString presetsDefaultLoc = cwd + wxT("\\presets");
   #else
   wxString presetsDefaultLoc = cwd + wxT("/presets");
   #endif

   // Stop wxWindows from printing its own error messages (not used ... does this really do anything?)
   wxLogNull logNo;

   // Try temp dir that was stored in prefs first
   if (presetsFromPrefs != wxT("")) {
      if (wxDirExists(FILENAME(presetsFromPrefs)))
         presets = presetsFromPrefs;
      else if (wxMkdir(FILENAME(presetsFromPrefs)))
         presets = presetsFromPrefs;
   }

   // If that didn't work, try the default location
   if ((presets == wxT("")) && (presetsDefaultLoc != wxT(""))) {
      if (wxDirExists(FILENAME(presetsDefaultLoc)))
         presets = presetsDefaultLoc;
      else if (wxMkdir(FILENAME(presetsDefaultLoc)))
         presets = presetsDefaultLoc;
   }

   if (presets == wxT("")) {
      // Failed
      wxMessageBox(_("Audacity could not find a place to store\n.csp CleanSpeech preset files\nAudacity is now going to exit. \nInstallation may be corrupt."));
      return false;
   }

   // The permissions don't always seem to be set on
   // some platforms.  Hopefully this fixes it...
   #ifdef __UNIX__
   chmod(FILENAME(presets).fn_str(), 0755);
   #endif

   gPrefs->Write(wxT("/Directories/PresetsDir"), presets);
   return true;
}
SubversionPasswordDb::SubversionPasswordDb()
{
	// disable logging
	wxLog::EnableLogging(false);
	wxString configDir(wxStandardPaths::Get().GetUserDataDir());
	wxMkdir(configDir);
	
	configDir << wxFileName::GetPathSeparator() << wxT("subversion");
	wxMkdir(configDir);
	
	wxLog::EnableLogging(true);
	
	configDir << wxFileName::GetPathSeparator() << wxT("passwords.ini");
	m_fileConfig = new wxFileConfig(wxEmptyString, wxEmptyString, configDir, wxEmptyString, wxCONFIG_USE_LOCAL_FILE);
}
Beispiel #10
0
bool TranslationMemoryUpdater::UpdateFromRPM(const wxString& filename)
{
    #define TMP_DIR "/tmp/poedit-rpm-tpm"
    if (!wxMkdir(TMP_DIR)) return false;
    
    wxString cmd;
    cmd.Printf(_T("sh -c '(cd %s ; rpm2cpio %s | cpio -i -d --quiet \"*.mo\")'"),
               TMP_DIR, filename.c_str());
    if (wxExecute(cmd, true) != 0)
    {
        wxLogError(_("Cannot extract catalogs from RPM file."));
        wxExecute("rm -rf " TMP_DIR, true);
        return false;
    }

    bool res = true;
    wxArrayString files;
    if (wxDir::GetAllFiles(TMP_DIR, &files, "*.mo") != (size_t)-1)
    {
        size_t cnt = files.GetCount();
        for (size_t i = 0; res && i < cnt; i++)
        {
            if (!IsForLang(files[i], m_mem->GetLanguage())) continue;
            if (!UpdateFromMO(files[i])) 
                res = false;
        }
    }

    wxLog::FlushActive();
    wxExecute("rm -rf " TMP_DIR, true);
    return res;
    #undef TMP_DIR
}
Beispiel #11
0
void wxGenericDirDialog::OnOK(wxCommandEvent& WXUNUSED(event))
{
    m_path = m_input->GetValue();
    // Does the path exist? (User may have typed anything in m_input)
    if (wxDirExists(m_path)) {
        // OK, path exists, we're done.
        EndModal(wxID_OK);
        return;
    }
    // Interact with user, find out if the dir is a typo or to be created
    wxString msg;
    msg.Printf(_("The directory '%s' does not exist\nCreate it now?"),
               m_path.c_str());
    wxMessageDialog dialog(this, msg, _("Directory does not exist"),
                           wxYES_NO | wxICON_WARNING);

    if ( dialog.ShowModal() == wxID_YES ) {
        // Okay, let's make it
        wxLogNull log;
        if (wxMkdir(m_path)) {
            // The new dir was created okay.
            EndModal(wxID_OK);
            return;
        }
        else {
            // Trouble...
            msg.Printf(_("Failed to create directory '%s'\n(Do you have the required permissions?)"),
                       m_path.c_str());
            wxMessageDialog errmsg(this, msg, _("Error creating directory"), wxOK | wxICON_ERROR);
            errmsg.ShowModal();
            // We still don't have a valid dir. Back to the main dialog.
        }
    }
    // User has answered NO to create dir.
}
Beispiel #12
0
bool InstallLangFiles()
{
	if (!wxDirExists(langDir))
		wxMkDir(langDir,wxS_DIR_DEFAULT);

	const int langFileCount = 3;
	LangFileDef langFiles[] = 
	{
		DEFINE_LANGFILE(en_us),
		DEFINE_LANGFILE(en_gb),
		DEFINE_LANGFILE(ru_ru),
		// DEFINE_LANGFILE(es_mx), translation is not complete yet
	};

	for (int i = 0; i < langFileCount; i++)
	{
		wxString dir = Path::Combine(langDir, langFiles[i].m_dirName);

		if (!wxDirExists(dir) && !wxMkdir(dir))
		{
			wxLogError(_("Can't install localizations. Failed to create directory."));
			return false;
		}

		// Write the file.
		wxString moFileName = Path::Combine(dir, "MultiMC.mo");
		wxMemoryInputStream inStream(langFiles[i].m_data, langFiles[i].m_dataSize);
		wxFFileOutputStream outStream(moFileName);
		outStream.Write(inStream);
	}
}
void HumanoidDataLogger::saveData()
{
	const wxDateTime now = wxDateTime::UNow();
	
	wxString dataDirectory(dataSaveDirectory.c_str(),wxConvUTF8);
	wxString curFilePath = dataDirectory + wxT("/recentData.dat");
	
	dataDirectory += now.FormatISODate();
	wxString dataFile =  now.FormatISODate() + wxT("_") + now.FormatISOTime() + wxT(".dat");
	dataFile.Replace(wxT(":"), wxT("-"));
	
	wxString dataPath = dataDirectory + wxT("/") + dataFile;
	
	if(! wxDirExists(dataDirectory))
	{
		wxMkdir(dataDirectory);	
	}
	
	stringstream ss;
	ss << dataPath.mb_str();
	setFile(ss.str());
	writeRecords();
	
	FILE * curFile = fopen(curFilePath.mb_str(),"w");
	fprintf(curFile, "%s",ss.str().c_str());
	fclose(curFile);
}
Beispiel #14
0
bool clCxxWorkspace::OpenReadOnly(const wxString& fileName, wxString& errMsg)
{
    m_buildMatrix.Reset(NULL);
    wxFileName workSpaceFile(fileName);
    if(!workSpaceFile.FileExists()) {
        return false;
    }
    m_fileName = workSpaceFile;
    m_doc.Load(m_fileName.GetFullPath());
    if(!m_doc.IsOk()) {
        return false;
    }

    m_saveOnExit = false;

    // Make sure we have the WORKSPACE/.codelite folder exists
    {
        wxLogNull nolog;
        wxMkdir(GetPrivateFolder());
    }

    // Load all projects
    wxXmlNode* child = m_doc.GetRoot()->GetChildren();
    std::vector<wxXmlNode*> removedChildren;
    wxString tmperr;
    while(child) {
        if(child->GetName() == wxT("Project")) {
            wxString projectPath = child->GetPropVal(wxT("Path"), wxEmptyString);
            DoAddProject(projectPath, errMsg);
        }
        child = child->GetNext();
    }
    DoUpdateBuildMatrix();
    return true;
}
Beispiel #15
0
TempDirectory::TempDirectory() : m_counter(0)
{
#ifdef HAVE_MKDTEMP
    wxString path = wxFileName::GetTempDir();
    path += _T("/poeditXXXXXX");
    wxCharBuffer buf(path.fn_str());
    if ( mkdtemp(buf.data()) == NULL )
    {
        wxLogError(_("Cannot create temporary directory."));
        return;
    }
    m_dir = wxConvFile.cMB2WX(buf.data());
#else
    for ( ;; )
    {
        wxString name = wxFileName::CreateTempFileName(_T("poedit"));
        if ( name.empty() )
        {
            wxLogError(_("Cannot create temporary directory."));
            return;
        }

        wxLogNull null;
        if ( wxRemoveFile(name) && wxMkdir(name, 0700) )
        {
            m_dir = name;
            wxLogTrace(_T("poedit.tmp"), _T("created temp dir %s"), name.c_str());
            break;
        }
        // else: try again
    }
#endif
}
Beispiel #16
0
bool Springsettings::OnInit()
{
	wxSetEnv( _T("UBUNTU_MENUPROXY"), _T("0") );
    //this triggers the Cli Parser amongst other stuff
    if (!wxApp::OnInit())
        return false;

	SetAppName(_T("SpringSettings"));
	const wxString configdir = TowxString(SlPaths::GetConfigfileDir());
	if ( !wxDirExists(configdir) )
		wxMkdir(configdir);

	if (!m_crash_handle_disable) {
	#if wxUSE_ON_FATAL_EXCEPTION
		wxHandleFatalExceptions( true );
	#endif
	#if defined(__WXMSW__) && defined(ENABLE_DEBUG_REPORT)
		//this undocumented function acts as a workaround for the dysfunctional
		// wxUSE_ON_FATAL_EXCEPTION on msw when mingw is used (or any other non SEH-capable compiler )
		SetUnhandledExceptionFilter(filter);
	#endif
	}

    //initialize all loggers
	//TODO non-constant parameters
	wxLogChain* logchain  = 0;
	wxLogWindow* loggerwin = InitializeLoggingTargets( 0, m_log_console, m_log_file_path, m_log_window_show, m_log_verbosity, logchain );
	//this needs to called _before_ mainwindow instance is created

#ifdef __WXMSW__
	wxString path = wxPathOnly( wxStandardPaths::Get().GetExecutablePath() ) + wxFileName::GetPathSeparator() + _T("locale");
#else
	#if defined(LOCALE_INSTALL_DIR)
		wxString path ( _T(LOCALE_INSTALL_DIR) );
	#else
		// use a dummy name here, we're only interested in the base path
		wxString path = wxStandardPaths::Get().GetLocalizedResourcesDir(_T("noneWH"),wxStandardPaths::ResourceCat_Messages);
		path = path.Left( path.First(_T("noneWH") ) );
	#endif
#endif
	m_translationhelper = new wxTranslationHelper( GetAppName().Lower(), path );

    SetSettingsStandAlone( true );

	// configure unitsync paths before trying to load
	SlPaths::ReconfigureUnitsync();

	//unitsync first load, NEEDS to be blocking
	LSL::usync().ReloadUnitSyncLib();

	settings_frame* frame = new settings_frame(NULL,GetAppName());
    SetTopWindow(frame);
    frame->Show();

    if ( loggerwin ) { // we got a logwindow, lets set proper parent win
        loggerwin->GetFrame()->SetParent( frame );
    }

    return true;
}
Beispiel #17
0
cbWorkspace::cbWorkspace(const wxString& filename) :
    m_IsOK(true),
    m_IsDefault(true),
    m_Modified(false),
    m_Filename(DEFAULT_WORKSPACE),
    m_Title(_("Default workspace"))
{
    //ctor
    if ( filename.Matches(DEFAULT_WORKSPACE) || filename.IsEmpty() )
    {
        // if no filename given, use the default workspace
        wxString tmp = ConfigManager::GetConfigFolder() + wxFILE_SEP_PATH;

        if (!wxDirExists(tmp))
            wxMkdir(tmp, 0755);

        tmp << wxFILE_SEP_PATH << DEFAULT_WORKSPACE;
        m_Filename = tmp;
    }
    else
    {
        m_Filename = filename;
        m_IsDefault = false;
    }

    if ( !filename.IsEmpty() )
    {
        Load();
    }
}
/* PaletteManager::loadCustomPalettes
 * Loads any files in the '<userdir>/palettes' directory as palettes,
 * with names from the files (minus the file extension)
 *******************************************************************/
bool PaletteManager::loadCustomPalettes()
{
	// If the directory doesn't exist create it
	if (!wxDirExists(appPath("palettes", DIR_USER)))
		wxMkdir(appPath("palettes", DIR_USER));

	// Open the custom palettes directory
	wxDir res_dir;
	res_dir.Open(appPath("palettes", DIR_USER));

	// Go through each file in the directory
	string filename = wxEmptyString;
	bool files = res_dir.GetFirst(&filename, wxEmptyString, wxDIR_FILES);
	while (files)
	{
		// Load palette data
		Palette8bit* pal = new Palette8bit();
		MemChunk mc;
		mc.importFile(res_dir.GetName() + "/" + filename);
		pal->loadMem(mc);

		// Add the palette
		wxFileName fn(filename);
		addPalette(pal, fn.GetName());

		// Next file
		files = res_dir.GetNext(&filename);
	}

	return true;
}
/* static */
void AutoCaptureMechanism::Save(wxBitmap* screenshot, const wxString& fileName)
{
    // make sure default_dir exists
    if (!wxDirExists(default_dir))
        wxMkdir(default_dir);

    wxFileName fullFileName(default_dir, "appear-" + fileName +
        "-" + wxPlatformInfo::Get().GetPortIdShortName() + ".png");

    // do not overwrite already existing files with this name
#if defined(__INTEL_COMPILER) && 1 /* VDM auto patch */
#   pragma ivdep
#   pragma swp
#   pragma unroll
#   pragma prefetch
#   if 0
#       pragma simd noassert
#   endif
#endif /* VDM auto patch */
    while (fullFileName.FileExists())
        fullFileName.SetName(fullFileName.GetName() + "_");

    // save the screenshot as a PNG
    screenshot->SaveFile(fullFileName.GetFullPath(), wxBITMAP_TYPE_PNG);
}
Beispiel #20
0
int main(int argc, char **argv) 
{
	//Initialize the wxWidgets library
	wxInitializer initializer;
	wxLog::EnableLogging(false);
	
	//parse the input
	wxCmdLineParser parser;
	parser.SetCmdLine(argc, argv);
	parser.SetDesc(cmdLineDesc);
	
	if (parser.Parse() != 0) {
		return -1;
	}

	for (size_t i=0; i< parser.GetParamCount(); i++) {
		wxString argument = parser.GetParam(i);
		if( !wxDir::Exists(argument) ){
			argument.Replace(wxT("\\"), wxT("/"));
			wxArrayString arr = wxStringTokenize(argument, wxT("/"), wxTOKEN_STRTOK);
			wxString path;
			for(size_t i=0; i<arr.GetCount(); i++){
				path << arr.Item(i) << wxT("/");
				wxMkdir(path, 0777);
			}
		}
	}

	return 0;
}
Beispiel #21
0
bool vfsLocalFile::Create(const wxString& path)
{
	ConLog.Warning("vfsLocalFile::Create('%s')", path.wx_str());
	for(uint p=1; p < path.Len() && path[p] != '\0' ; p++)
	{
		for(; p < path.Len() && path[p] != '\0'; p++)
			if(path[p] == '\\') break;

		if(p == path.Len() || path[p] == '\0')
			break;

		const wxString& dir = path(0, p);
		if(!wxDirExists(dir))
		{
			ConLog.Write("create dir: %s", dir.wx_str());
			wxMkdir(dir);
		}
	}

	//create file
	if(path(path.Len() - 1, 1) != '\\' && !wxFileExists(path))
	{
		wxFile f;
		return f.Create(path);
	}

	return true;
}
Beispiel #22
0
void Path::CreateDirectoryPath(const wxFileName &path){
    if(!path.IsDir() || path.DirExists())
        return;

    wxArrayString folders = path.GetDirs();
    wxString workingpath;
    //We need to do things differently with a unc path
    if(path.GetFullPath().Left(2) == "\\\\")
        workingpath = "\\\\?\\UNC\\" + path.GetVolume() + "\\";
    else
        workingpath = "\\\\?\\" + path.GetVolume() + wxFileName::GetVolumeSeparator() + wxFILE_SEP_PATH;
 
    for(unsigned int i = 0; i < folders.GetCount(); i++){
        workingpath = workingpath + folders.Item(i) + wxFILE_SEP_PATH;
#ifdef __WXMSW__
        if(!wxDirExists(workingpath) && !CreateDirectory(workingpath.fn_str(), NULL)){ 
#else
        if(!wxDirExists(workingpath) && !wxMkdir(workingpath)){
#endif
		    wxLogError(_("Could not create") + " " + workingpath);
	    }
    }
}

wxFileName Path::Normalise(const wxFileName &filename){
    wxString path = Path::Normalise(filename.GetFullPath());
    return wxFileName(path);
}
Beispiel #23
0
void AppPath::CreateConfigDirInUserHome() const
{
	if (wxDirExists(usr_dir))
		return;
	wxLogNull nolog; // disable error message
	wxMkdir(usr_dir);
}
/* TranslationEditorDialog::onBtnSave
 * Called when the 'Save Translation' button is clicked
 *******************************************************************/
void TranslationEditorDialog::onBtnSave(wxCommandEvent& e)
{
	// If the directory doesn't exist create it
	string dir = appPath("translations", DIR_USER);
	if (!wxDirExists(dir))
		wxMkdir(dir);

	// Create save file dialog
	wxFileDialog dialog_save(this, "Save Translation to File", dir, wxEmptyString,
	                         "Text File (*.txt)|*.txt", wxFD_SAVE|wxFD_OVERWRITE_PROMPT, wxDefaultPosition);

	// Run the dialog & check that the user didn't cancel
	if (dialog_save.ShowModal() == wxID_OK)
	{
		// Get translation as text string
		string str = translation.asText();

		// Open file for writing
		wxFile file(dialog_save.GetPath(), wxFile::write);

		// Write string to file
		file.Write(str);

		// Close file
		file.Close();
	}
}
Beispiel #25
0
bool CopyDirectory( const wxString& from, const wxString& to ) {
	wxDir src( from );
	if ( !src.IsOpened() ) {
		return false;
	}

	wxMkdir( to );
	wxDir dst( to );
	if ( !dst.IsOpened() ) {
		return false;
	}

	wxString filename;

	// copy directories
	if ( src.GetFirst( &filename, wxEmptyString, wxDIR_DIRS | wxDIR_HIDDEN ) ) {
		do {
			if ( !CopyDirectory( wxFileName( from, filename ).GetFullPath(), wxFileName( to, filename ).GetFullPath() ) ) {
				return false;
			}
		} while ( src.GetNext( &filename ) );
	}

	// copy files
	if ( src.GetFirst( &filename, wxEmptyString, wxDIR_FILES | wxDIR_HIDDEN ) ) {
		do {
			if ( !wxCopyFile( wxFileName( from, filename ).GetFullPath(), wxFileName( to, filename ).GetFullPath() ) ) {
				return false;
			}
		} while ( src.GetNext( &filename ) );
	}

	return true;
}
Beispiel #26
0
//////////////////////////////////////////////////////////////////////////
// Get system wide configuration file names
//////////////////////////////////////////////////////////////////////////
wxString sysSettings::GetConfigFile(configFileName cfgname)
{
	if (cfgname == PGPASS)
	{
		wxStandardPaths stdp;
		wxString fname = stdp.GetUserConfigDir();
#ifdef WIN32
		fname += wxT("\\postgresql");
		if (!wxDirExists(fname))
			wxMkdir(fname);
		switch(cfgname)
		{
			case PGPASS:
				fname += wxT("\\pgpass.conf");
				break;
		}
#else
		switch(cfgname)
		{
			case PGPASS:
				fname += wxT("/.pgpass");
				break;
		}
#endif
		return fname;
	}
	return wxT("");
}
bool CreateDir(const wxString& full_path, int perms)
{
    if (!wxDirExists(full_path) && !wxMkdir(full_path, perms))
        return false;

    return true;
}
Beispiel #28
0
wxDebugReport::wxDebugReport()
{
    // get a temporary directory name
    wxString appname = GetReportName();

    // we can't use CreateTempFileName() because it creates a file, not a
    // directory, so do our best to create a unique name ourselves
    //
    // of course, this doesn't protect us against malicious users...
    wxFileName fn;
    fn.AssignTempFileName(appname);
#if wxUSE_DATETIME
    m_dir.Printf(wxT("%s%c%s_dbgrpt-%lu-%s"),
                 fn.GetPath().c_str(), wxFILE_SEP_PATH, appname.c_str(),
                 wxGetProcessId(),
                 wxDateTime::Now().Format(wxT("%Y%m%dT%H%M%S")).c_str());
#else
    m_dir.Printf(wxT("%s%c%s_dbgrpt-%lu"),
                 fn.GetPath().c_str(), wxFILE_SEP_PATH, appname.c_str(),
                 wxGetProcessId());
#endif

    // as we are going to save the process state there use restrictive
    // permissions
    if ( !wxMkdir(m_dir, 0700) )
    {
        wxLogSysError(_("Failed to create directory \"%s\""), m_dir.c_str());
        wxLogError(_("Debug report couldn't be created."));

        Reset();
    }
}
ScriptValueP export_set(SetP const& set, vector<CardP> const& cards, ExportTemplateP const& exp, String const& outname) {
	wxBusyCursor wait;
	// export info for script
	ExportInfo info;
	info.export_template = exp;
	info.set = set;
	WITH_DYNAMIC_ARG(export_info, &info);
	// create directory?
	if (exp->create_directory) {
		if (outname.empty()) throw Error(_("No output filename specified for export"));
		wxFileName fn(outname);
		info.directory_relative = fn.GetName() + _("-files");
		fn.SetFullName(info.directory_relative);
		info.directory_absolute = fn.GetFullPath();
		if (!wxDirExists(info.directory_absolute)) {
			wxMkdir(info.directory_absolute);
		}
	}
	// run export script
	Context& ctx = set->getContext();
	LocalScope scope(ctx);
	ctx.setVariable(_("cards"),     to_script(&cards));
	ctx.setVariable(_("options"),   to_script(&settings.exportOptionsFor(*exp)));
	ctx.setVariable(_("directory"), to_script(info.directory_relative));
	ScriptValueP result = exp->script.invoke(ctx);
	// Save to file
	if (!outname.empty()) {
		// TODO: write as image?
		// write as string
		wxFileOutputStream file(outname);
		wxTextOutputStream stream(file);
		stream.WriteString(result->toString());
	}
	return result;
}
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;
}