wxString PHPCodeCompletion::ExpandRequire(const wxFileName& curfile, const wxString& require)
{
    PHPScanner_t scanner = ::phpLexerNew("<?php " + require);
    if(!scanner) return "";

    wxString outFile;
    phpLexerToken token;
    while(::phpLexerNext(scanner, token)) {
        if(token.IsAnyComment()) continue;
        switch(token.type) {
        case kPHP_T_REQUIRE:
        case kPHP_T_REQUIRE_ONCE:
            break;
        case kPHP_T_CONSTANT_ENCAPSED_STRING: {
            wxString str = token.text;
            str.Trim().Trim(false);
            // strip the " or ' from the string
            str.Remove(0, 1).RemoveLast();
            outFile << str;
            break;
        }
        case kPHP_T_FILE:
            outFile << curfile.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR);
            break;
        case kPHP_T_DIR:
            outFile << curfile.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR);
            break;
        }
    }

    wxFileName fileName(outFile);
    if(fileName.IsOk() && fileName.IsRelative()) {
        wxArrayString paths;
        paths.Add(curfile.GetPath());
        // Relative path, we try to resolve it by looking at the include path give to us
        PHPProject::Ptr_t proj = PHPWorkspace::Get()->GetActiveProject();
        if(proj) {
            wxArrayString incpaths = proj->GetSettings().GetIncludePathAsArray();
            paths.insert(paths.end(), incpaths.begin(), incpaths.end());
        }

        for(size_t i = 0; i < paths.GetCount(); ++i) {
            wxFileName tmpFile = fileName;
            if(tmpFile.MakeAbsolute(paths.Item(i))) {
                wxString fullpath = tmpFile.GetFullPath();
                if(wxFileName::Exists(fullpath)) {
                    fileName = tmpFile;
                    break;
                }
            }
        }
    }

    if(fileName.IsOk()) {
        fileName.Normalize();
        outFile = fileName.GetFullPath();
    }
    ::phpLexerDestroy(&scanner);
    return outFile;
}
void ClassWizardDlg::DoForceDirectory(const wxFileName & filename)
{
    wxFileName parentname(filename);
    parentname.RemoveLastDir();

    if ((filename != parentname) && (parentname.GetDirCount() >= 1) )
        DoForceDirectory(parentname);

    if (!wxDirExists(filename.GetPath()))
        wxMkdir(filename.GetPath());
}
void PHPCodeCompletion::Open(const wxFileName& workspaceFile)
{
    Close();
    m_lookupTable.Open(workspaceFile.GetPath());

    // Cache the symbols into the OS caching, this is done by simply reading the entire file content and
    // then closing it
    wxFileName fnDBFile(workspaceFile.GetPath(), "phpsymbols.db");
    fnDBFile.AppendDir(".codelite");
    JobQueueSingleton::Instance()->PushJob(new PHPSymbolsCacher(this, fnDBFile.GetFullPath()));
}
Example #4
0
wxArrayString FSOExecutable::GetBinariesFromRootFolder(const wxFileName& path, const wxString& globPattern, bool quiet) {
	wxArrayString files;
	wxDir folder(path.GetPath());
	wxString filename;

#if IS_APPLE // Binaries are directories on OSX.
	bool cont = folder.GetFirst(&filename, globPattern, wxDIR_DIRS);
#else
	bool cont = folder.GetFirst(&filename, globPattern, wxDIR_FILES);
#endif

	while (cont) {
#if IS_LINUX
		if ( !IsFileToIgnore(filename) ) {
#endif
		files.Add(filename);
#if IS_LINUX
		}
#endif
		cont = folder.GetNext(&filename);
	}

	// filter out launcher binaries (at least on OSX)
	for (int i = files.GetCount() - 1; i >= 0; --i) {
		if (files[i].Lower().Find(_T("launcher")) != wxNOT_FOUND) {
			files.RemoveAt(i);
		}
	}
	
#if IS_APPLE
	// find actual (Unix) executable inside .app bundle and call the path to it the "executable"
	for (wxArrayString::iterator it = files.begin(), end = files.end(); it != end; ++it) {
		wxString pathToBin = 
			wxDir::FindFirst(path.GetPath(wxPATH_GET_SEPARATOR) + *it + _T("/Contents/MacOS"),
							 _T("*"),
							 wxDIR_FILES);
		pathToBin.Replace(path.GetPath(wxPATH_GET_SEPARATOR), _T(""));
		*it = pathToBin;
	}
#endif
	
	if (!quiet) {
		wxString execType = globPattern.Lower().Find(_T("fred")) == wxNOT_FOUND ? _T("FS2") : _T("FRED2");
		wxLogInfo(_T(" Found %d %s Open executables in '%s'"),
			files.GetCount(), execType.c_str(), path.GetPath().c_str());
		
		for (size_t i = 0, n = files.GetCount(); i < n; ++i) {
			wxLogDebug(_T("Found executable: %s"), files.Item(i).c_str());
		}
	}

	return files;
}
Example #5
0
static wxString GetDefaultPath(const wxFileName& fileName)
{
    wxString str = fileName.GetPath();
    if (str.empty())
        str = wxGetCwd();
    return str;
}
void CDialogPromptNewerFile::SetupURL(const wxFileName &fn)
{
  const wxString sDir = fn.GetPath();
  m_sDirURL.Alloc(sDir.Len() + 8);
  m_sDirURL = "file:///";
  m_sDirURL.Append(sDir);
}
Example #7
0
bool App::OnInit() {
   SetAppName(u8"flutterrust");
   SetAppDisplayName(u8"flutterrust");

   const wxFileName exeFileName{wxStandardPaths::Get().GetExecutablePath()};
   const std::string exePath = exeFileName.GetPath().ToStdString();
   try {
      Creature::loadTypes(exePath + static_cast<char>(wxFileName::GetPathSeparator()) +
                          u8"CreatureTable.txt");
      mainFrame = new MainFrame{exePath};
   } catch (const std::exception& e) {
      wxMessageDialog dialog{nullptr, u8"Exception caught.  Terminating.\n",
                             u8"Fatal error", wxICON_ERROR | wxOK};
      dialog.SetExtendedMessage(std::string{typeid(e).name()} + ": \"" + e.what() + '"');
      dialog.ShowModal();
      return false;  // Exit the application immediately.
   } catch (...) {
      wxMessageDialog(nullptr, u8"Unknown exception caught.  Terminating.",
                      u8"Fatal error", wxICON_ERROR | wxOK)
          .ShowModal();
      return false;
   }

   mainFrame->Show(true);
   SetTopWindow(mainFrame);

   return true;  // Continue processing.
}
Example #8
0
bool PHPWorkspace::CanCreateProjectAtPath(const wxFileName& projectFileName, bool prompt) const
{
    wxString newpath = projectFileName.GetPath(wxPATH_GET_SEPARATOR | wxPATH_GET_VOLUME);
    const PHPProject::Map_t& projects = GetProjects();
    PHPProject::Map_t::const_iterator iter = projects.begin();
    for(; iter != projects.end(); ++iter) {
        if(newpath.StartsWith(iter->second->GetFilename().GetPath(wxPATH_GET_SEPARATOR | wxPATH_GET_VOLUME))) {
            // The new path is a sub folder of a project
            if(prompt) {
                wxString message;
                message << _("Unable to create a project at the selected path\n") << _("Path '") << newpath
                        << _("' is already part of project '") << iter->second->GetName() << "'";
                ::wxMessageBox(message, "CodeLite", wxOK | wxICON_ERROR | wxCENTER);
            }
            return false;

        } else if(iter->second->GetFilename().GetPath(wxPATH_GET_SEPARATOR | wxPATH_GET_VOLUME).StartsWith(newpath)) {
            // The new project is a parent of an existing project
            if(prompt) {
                wxString message;
                message << _("Unable to create a project at the selected path\n") << _("Project '")
                        << iter->second->GetName() << _("' is located under this path");
                ::wxMessageBox(message, "CodeLite", wxOK | wxICON_ERROR | wxCENTER);
            }
            return false;
        }
    }
    return true;
}
void DIALOG_TEMPLATE_SELECTOR::AddPage( const wxString& aTitle, wxFileName& aPath )
{
    wxNotebookPage* newPage = new wxNotebookPage( m_notebook, wxID_ANY );
    m_notebook->AddPage( newPage, aTitle );

    TEMPLATE_SELECTION_PANEL* p = new TEMPLATE_SELECTION_PANEL( newPage );
    m_panels.push_back( p );

    // Get a list of files under the template path to include as choices...
    wxArrayString files;
    wxDir dir, sub;

    if ( dir.Open( aPath.GetPath() ) )
    {
        wxString filename;
        bool cont = dir.GetFirst( &filename, wxEmptyString, wxDIR_FILES | wxDIR_DIRS );

        while( cont )
        {
            if( sub.Open( aPath.GetPathWithSep() + filename ) )
            {
                files.Add( filename );
                PROJECT_TEMPLATE* pt = new PROJECT_TEMPLATE( aPath.GetPathWithSep() + filename );
                AddTemplate( m_notebook->GetPageCount() - 1, pt );
            }

            cont = dir.GetNext( &filename );
        }
    }
}
Example #10
0
    virtual wxDirTraverseResult OnFile(const wxString& filename) {
        wxFileName temp = filename;
        wxString shastr = wxT("0");
        unsigned long ovlversion = 0;
        int modtime = temp.GetModificationTime().GetTicks();
        wxFileOffset size = 0;

        if (wxFile::Access(filename.c_str(), wxFile::read)) {
            m_sha.Reset();
            /*
            wxFile f(filename, wxFile::read);
            counted_array_ptr<unsigned char> buf(new unsigned char[f.Length()]);
            size = f.Length();
            f.Read(buf.get(), f.Length());
            m_sha.Input(buf.get(), f.Length());
            */
            size = m_sha.Input(filename);
            shastr = m_sha.Result();

            if (filename.Lower().EndsWith(wxT(".common.ovl"))) {
                cOVLDump dovl;
                dovl.Load(filename.mb_str(wxConvFile));
                ovlversion = dovl.GetVersion();
            }
        }

        temp.MakeRelativeTo(m_root.GetPath(wxPATH_GET_SEPARATOR | wxPATH_GET_VOLUME));
        m_buf.Format("insert into vanilla values ('%q', '%q', %d, %lld, %ld);", temp.GetFullPath().mb_str(wxConvUTF8).data(), shastr.mb_str(wxConvUTF8).data(), modtime, size, ovlversion);
        m_db->ExecuteUpdate(m_buf);
        m_pd.Pulse(temp.GetFullPath());
        return wxDIR_CONTINUE;
    }
Example #11
0
bool AmeJobMan::makeDirs(wxFileName f){
	wxFileName p = f.GetPath();
	if(f.DirExists())
		return true;
	if(!p.DirExists() && !makeDirs(p))
		return false;
	return f.Mkdir();
}
Example #12
0
long wxExMake(wxExFrameWithHistory* frame, const wxFileName& makefile)
{
  return frame->GetProcess()->Execute(
    wxConfigBase::Get()->Read("Make", "make") + " " +
      wxConfigBase::Get()->Read("MakeSwitch", "-f") + " " +
      makefile.GetFullPath(),
    wxEXEC_ASYNC,
    makefile.GetPath());
}
Example #13
0
bool ClangPlugin::IsSourceOf(const wxFileName& candidateFile, const wxFileName& activeFile, bool& isCandidate)
{
    if (candidateFile.GetName().CmpNoCase(activeFile.GetName()) == 0)
    {
        isCandidate = (candidateFile.GetName() != activeFile.GetName());
        if (FileTypeOf(candidateFile.GetFullName()) == ftSource)
        {
            if (candidateFile.GetPath() != activeFile.GetPath())
            {
                wxArrayString fileArray;
                wxDir::GetAllFiles(candidateFile.GetPath(wxPATH_GET_VOLUME), &fileArray, candidateFile.GetName() + wxT(".*"), wxDIR_FILES | wxDIR_HIDDEN);
                for (size_t i = 0; i < fileArray.GetCount(); ++i)
                    if (wxFileName(fileArray[i]).GetFullName() == activeFile.GetFullName())
                        return false;
            }
            return candidateFile.FileExists();
        }
    }
    return false;
}
Example #14
0
bool FormatOptions::HasConfigForFile(const wxFileName& fileName, const wxString& configName) const
{
    wxFileName configFile(fileName.GetPath(), configName);
    while(configFile.GetDirCount()) {
        if(configFile.FileExists()) {
            return true;
        }
        configFile.RemoveLastDir();
    }
    return false;
}
Example #15
0
static bool normalizeAbsolutePaths( const wxFileName& aPathA,
                                        const wxFileName& aPathB,
                                        wxString*         aResultPath )
{
    wxCHECK_MSG( aPathA.IsAbsolute(), false, aPathA.GetPath() + " is not an absolute path." );
    wxCHECK_MSG( aPathB.IsAbsolute(), false, aPathB.GetPath() + " is not an absolute path." );

    if( aPathA.GetPath() == aPathB.GetPath() )
        return true;

    if( ( aPathA.GetDirCount() > aPathB.GetDirCount() )
      || ( aPathA.HasVolume() && !aPathB.HasVolume() )
      || ( !aPathA.HasVolume() && aPathB.HasVolume() )
      || ( ( aPathA.HasVolume() && aPathB.HasVolume() )
         && ( aPathA.GetVolume() != aPathB.GetVolume() ) ) )
        return false;

    wxArrayString aDirs = aPathA.GetDirs();
    wxArrayString bDirs = aPathB.GetDirs();

    size_t i = 0;

    while( i < aDirs.GetCount() )
    {
        if( aDirs[i] != bDirs[i] )
            return false;

        i++;
    }

    if( aResultPath )
    {
        while( i < bDirs.GetCount() )
        {
            *aResultPath += bDirs[i] + wxT( "/" );
            i++;
        }
    }

    return true;
}
Example #16
0
void FileUtils::OpenFileExplorerAndSelect(const wxFileName& filename)
{
#ifdef __WXMSW__
    wxString strPath = filename.GetFullPath();
    if(strPath.Contains(" ")) { strPath.Prepend("\"").Append("\""); }
    wxString cmd;
    cmd << "explorer /select," << strPath;
    ::wxExecute(cmd);
#else
    OpenFileExplorer(filename.GetPath());
#endif
}
Example #17
0
bool
CxxPreProcessor::ExpandInclude(const wxFileName& currentFile, const wxString& includeStatement, wxFileName& outFile)
{
    wxString includeName = includeStatement;
    includeName.Replace("\"", "");
    includeName.Replace("<", "");
    includeName.Replace(">", "");

    // Try the current file's directory first
    wxArrayString paths = m_includePaths;
    paths.Insert(currentFile.GetPath(), 0);

    if(m_noSuchFiles.count(includeStatement)) {
        // wxPrintf("No such file hit\n");
        return false;
    }

    std::map<wxString, wxString>::iterator iter = m_fileMapping.find(includeStatement);
    if(iter != m_fileMapping.end()) {
        // if this file has a mapped file, it means that we either
        // already scanned it or could not find a match for it
        // wxPrintf("File already been scanned\n");
        return false;
    }

    for(size_t i = 0; i < paths.GetCount(); ++i) {
        wxString tmpfile;
        tmpfile << paths.Item(i) << "/" << includeName;
        wxFileName fn(tmpfile);
        tmpfile = fn.GetFullPath();
        // CL_DEBUG(" ... Checking include file: %s\n", fn.GetFullPath());
        struct stat buff;
        if((stat(tmpfile.mb_str(wxConvUTF8).data(), &buff) == 0)) {
            CL_DEBUG1(" ==> Creating scanner for file: %s\n", tmpfile);
            wxFileName fixedFileName(tmpfile);
            if(fixedFileName.FileExists()) {
                fixedFileName.Normalize(wxPATH_NORM_DOTS);
                tmpfile = fixedFileName.GetFullPath();
                m_fileMapping.insert(std::make_pair(includeStatement, tmpfile));
                outFile = fixedFileName;
                return true;
            } else {
                CL_DEBUG("Including a folder :/ : %s", fixedFileName.GetFullPath());
            }
        }
    }

    // remember that we could not locate this include statement
    m_noSuchFiles.insert(includeStatement);
    m_fileMapping.insert(std::make_pair(includeStatement, wxString()));
    return false;
}
Example #18
0
wxString PHPWorkspace::GetProjectFromFile(const wxFileName& filename) const
{
    PHPProject::Map_t::const_iterator iter =
        std::find_if(m_projects.begin(), m_projects.end(), [&](const PHPProject::Map_t::value_type& v) {
            wxString path = filename.GetPath();
            return path.StartsWith(v.second->GetFilename().GetPath());
        });

    if(iter != m_projects.end()) {
        return iter->second->GetName();
    }
    return wxEmptyString;
}
bool clEditorConfig::LoadForFile(const wxFileName& filename, wxFileName& editorConfigFile)
{
    editorConfigFile = wxFileName(filename.GetPath(), ".editorconfig");

    bool foundFile = false;
    while(editorConfigFile.GetDirCount()) {
        if(editorConfigFile.FileExists()) {
            foundFile = true;
            break;
        }
        editorConfigFile.RemoveLastDir();
    }

    if(!foundFile) return false;

    wxString content;
    if(!FileUtils::ReadFileContent(editorConfigFile, content)) {
        clDEBUG() << "Failed to read file:" << editorConfigFile << clEndl;
        return false;
    }

    clEditorConfigSection section;
    m_sections.push_back(section);
    clEditorConfigSection* cursection = &(m_sections.back());
    wxUnusedVar(cursection); // for debug purposes
    wxArrayString lines = ::wxStringTokenize(content, "\n", wxTOKEN_STRTOK);
    for(size_t i = 0; i < lines.size(); ++i) {
        // Remove comments
        wxString strLine = lines.Item(i);
        strLine = strLine.BeforeFirst('#');
        strLine = strLine.BeforeFirst(';');

        strLine.Trim().Trim(false);

        if(strLine.IsEmpty()) continue;

        // Process the line
        if(strLine.StartsWith("[") && strLine.EndsWith("]")) {
            strLine.RemoveLast().Remove(0, 1); // remove the []
            clEditorConfigSection section;
            section.patterns = ProcessSection(strLine);
            m_sections.push_back(section);
            cursection = &(m_sections.back());

        } else {
            ProcessDirective(strLine);
        }
    }
    clDEBUG() << "Using .editorconfig file:" << editorConfigFile << clEndl;
    return true;
}
void sg_treediff_cache::NotifyExplorerToRefreshPath(SG_context * pCtx, wxFileName path, bool bSpecific)
{
	SG_string * pstrFullPath = NULL;
	wxString fullName = path.GetFullName();

	SG_ERR_CHECK(  SG_STRING__ALLOC__SZ(pCtx, &pstrFullPath, path.GetFullPath().ToUTF8())  );

	//Use %s to handle getting a path that has a %s in it.
	//SG_ERR_CHECK(  SG_UTF8__INTERN_FROM_OS_BUFFER(pCtx, pstrFullPath, path.GetFullPath().ToStdWstring())  );
	//SG_log__report_verbose(pCtx, "FS_CHANGE(%s):	%s", (const char *)ExplainAction(dwAction), SG_string__sz(pstrFullPath)); 

	{
		clearCache(pCtx); 
		if (!m_bIsWin7) //if we're running on XP or Vista
		{
			wxCriticalSectionLocker lock(m_notify_critical_section);
			m_bHaveGottenNewFileChanges = true;
			//For some reason, on XP and Vista, we need to notify for every folder up to the root.
			if (path.FileExists() || path.DirExists())
			{
				if (m_aPathsToNotify.Index(path.GetFullPath()) == wxNOT_FOUND)
					m_aPathsToNotify.Add(path.GetFullPath());
			}

			wxFileName currentDir = wxFileName::DirName(path.GetPath(wxPATH_GET_VOLUME));
			wxFileName topDir = GetTopDir();
			//currentDir = topDir;
			
			while (topDir.GetDirCount() < currentDir.GetDirCount())
			{
				if (m_aPathsToNotify.Index(currentDir.GetFullPath()) == wxNOT_FOUND)
					m_aPathsToNotify.Add(currentDir.GetFullPath());
				currentDir.RemoveLastDir();
			}
		}
		else
		{
			wxCriticalSectionLocker lock(m_notify_critical_section);
			m_bHaveGottenNewFileChanges = true;
			//On Win 7, just notifying for the top of the working folder 
			//will cause a recursive refresh down the tree.
			if (m_aPathsToNotify.Index(GetTopDir().GetFullPath()) == wxNOT_FOUND)
				m_aPathsToNotify.Add(GetTopDir().GetFullPath());
			if (bSpecific)
				m_aPathsToNotify.Add(path.GetFullPath());
		}
	}
fail:
	return;
}
Example #21
0
bool FSOExecutable::IsRootFolderValid(const wxFileName& path, bool quiet) {
	if ( !path.IsOk() ) {
		if (!quiet) {
			wxLogError(_T(" New root folder %s is not OK"), path.GetFullPath().c_str());			
		}
		return false;
	}
	if ( path.GetPath().IsEmpty() ) {
		if (!quiet) {
			wxLogError(_T(" Root folder %s is empty"), path.GetFullPath().c_str());
		}
		return false;
	}
	return HasFSOExecutables(path);
}
void GPCB_FPL_CACHE::Load()
{
    wxDir dir( m_lib_path.GetPath() );

    if( !dir.IsOpened() )
    {
        THROW_IO_ERROR( wxString::Format( _( "footprint library path '%s' does not exist" ),
                                          m_lib_path.GetPath().GetData() ) );
    }

    wxString fpFileName;
    wxString wildcard = wxT( "*." ) + GedaPcbFootprintLibFileExtension;

    if( !dir.GetFirst( &fpFileName, wildcard, wxDIR_FILES ) )
        return;

    do
    {
        wxFileName fn( m_lib_path.GetPath(), fpFileName );

        // reader now owns fp, will close on exception or return
        FILE_LINE_READER reader( fn.GetFullPath() );
        std::string      name = TO_UTF8( fn.GetName() );
        MODULE*          footprint = parseMODULE( &reader );

        // The footprint name is the file name without the extension.
        footprint->SetFPID( FPID( fn.GetName() ) );
        m_modules.insert( name, new GPCB_FPL_CACHE_ITEM( footprint, fn.GetName() ) );

    } while( dir.GetNext( &fpFileName ) );

    // Remember the file modification time of library file when the
    // cache snapshot was made, so that in a networked environment we will
    // reload the cache as needed.
    m_mod_time = GetLibModificationTime();
}
Example #23
0
wxString BatchCommands::BuildCleanFileName(const wxString &fileName, const wxString &extension)
{
   const wxFileName newFileName{ fileName };
   wxString justName = newFileName.GetName();
   wxString pathName = newFileName.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR);

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

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

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

   return cleanedName;
}
Example #24
0
/** Devpak installation quiet mode
*  This procedure installs the devpak without any of the GUI
*  windows. Used for command line option /quiet
*/
bool InstallDevPak::DoSilentInstall(wxFileName filename)
{
    // Procedure
    // =========
    // 1. Prompt for devpak file to install
    // 2. Extract the devpak INI descriptor
    // 3. Parse the INI descriptor for the files/directories to install
    // 4. Replace any macros in the directory names
    // 5. Extract the files/directories from the devpak archive

    // wxFileName filename(wxFileSelector(wxT("Choose a devpak to open"),"","","", wxT("All supported package formats (*.DevPak) |*.devpak|All files (*.*)|*.*")));
    if ( filename.FileExists() )
    {
        // work with the file
        wxString archiveFile;
        wxString archiveDir = filename.GetPath();

        if (archiveDir.IsEmpty()) { // If empty, then we are in the current working directory
            archiveDir = ::wxGetCwd();
            archiveFile = ::wxGetCwd() + wxFILE_SEP_PATH + filename.GetFullPath();
        } else
            archiveFile = filename.GetFullPath();

        // Get a temporary directory to unpack things
        ::wxSetWorkingDirectory(wxStandardPaths::Get().GetTempDir());

        DevPakInfo info;

        if (!InstallDevPak::GetPackageInfo(&info, archiveFile)) {
            InstallDevPak::ShowLog("No *.DevPackage file found. DevPak format incorrect or corrupted.");
            return false;
        }

        if (!InstallDevPak::ProcessDirs(archiveDir, &info))
            return false;

        wxListBox lbInstalledFiles; // This doesn't get used
        if (!InstallDevPak::ExtractArchive(archiveFile, info, &lbInstalledFiles)) {
            InstallDevPak::ShowLog("Extract archive failed on " + archiveFile);
            return false;
        }

    }
    return true;
}
void GPCB_FPL_CACHE::Remove( const wxString& aFootprintName )
{
    std::string footprintName = TO_UTF8( aFootprintName );

    MODULE_CITER it = m_modules.find( footprintName );

    if( it == m_modules.end() )
    {
        THROW_IO_ERROR( wxString::Format( _( "library <%s> has no footprint '%s' to delete" ),
                                          m_lib_path.GetPath().GetData(),
                                          aFootprintName.GetData() ) );
    }

    // Remove the module from the cache and delete the module file from the library.
    wxString fullPath = it->second->GetFileName().GetFullPath();
    m_modules.erase( footprintName );
    wxRemoveFile( fullPath );
}
wxFileName CompilationDatabase::ConvertCodeLiteCompilationDatabaseToCMake(const wxFileName& compile_file)
{
    wxFFile fp(compile_file.GetFullPath(), wxT("rb"));
    if( fp.IsOpened() ) {
        wxString content;
        fp.ReadAll(&content, wxConvUTF8);

        if( content.IsEmpty() )
            return wxFileName();
        
        JSONRoot root(cJSON_Array);
        JSONElement arr = root.toElement();
        wxArrayString lines = ::wxStringTokenize(content, "\n\r", wxTOKEN_STRTOK);
        for(size_t i=0; i<lines.GetCount(); ++i) {
            wxArrayString parts = ::wxStringTokenize(lines.Item(i), wxT("|"), wxTOKEN_STRTOK);
            if( parts.GetCount() != 3 )
                continue;

            wxString file_name = wxFileName(parts.Item(0).Trim().Trim(false)).GetFullPath();
            wxString cwd       = parts.Item(1).Trim().Trim(false);
            wxString cmp_flags = parts.Item(2).Trim().Trim(false);

            JSONElement element = JSONElement::createObject();
            element.addProperty("directory", cwd);
            element.addProperty("command",   cmp_flags);
            element.addProperty("file",      file_name);
            arr.arrayAppend( element );
        }
        
        wxFileName fn(compile_file.GetPath(), "compile_commands.json");
        root.save( fn );
        // Delete the old file
        {
            wxLogNull nl;
            fp.Close();
            if ( compile_file.Exists() ) {
                ::wxRemoveFile( compile_file.GetFullPath() );
            }
        }
        return fn;
    }
    return wxFileName();
}
Example #27
0
void FileChangeWatcher::SetFile(const wxFileName& fileName)
{

    // If the file is in the same directory, we don't need to update anything.
    bool sameDirectory = (fileName.GetPath() == m_fileName.GetPath());

    m_fileName = fileName;
    UpdateFileAttributes();

    if (!sameDirectory || m_handle == NULL)
    {

        if (m_thread != NULL)
        {
            EndThread();
        }

        if (m_handle != NULL)
        {
            FindCloseChangeNotification(m_handle);
            m_handle = NULL;
        }

        m_handle = FindFirstChangeNotification(m_fileName.GetPath(), FALSE, FILE_NOTIFY_CHANGE_ATTRIBUTES);

        // Sometimes the return is NULL and sometimes it's INVALID_HANDLE_VALUE
        // in error conditions.
        if (m_handle == INVALID_HANDLE_VALUE)
        {
            m_handle = NULL;
        }

        if (m_handle != NULL)
        {
            DWORD threadId;
            m_thread = CreateThread(NULL, 0, ThreadProc, this, 0, &threadId);
        }
    
    }

}
Example #28
0
void BundleManager::SetDirModDate(wxFileName& path, const wxDateTime& modDate) {
#ifdef __WXMSW__
	wxLogDebug(wxT("SetDirModDate: %s %s"), modDate.FormatDate(), modDate.FormatTime());
	HANDLE hDir = ::CreateFile (
		path.GetPath(),
		GENERIC_READ,
		FILE_SHARE_READ|FILE_SHARE_DELETE,
		NULL,
		OPEN_EXISTING,
		FILE_FLAG_BACKUP_SEMANTICS,
		NULL);

	FILETIME ftWrite;
	ConvertWxToFileTime(&ftWrite, modDate);

	::SetFileTime(hDir, &ftWrite, &ftWrite, &ftWrite);

	::CloseHandle(hDir);
#else
	path.SetTimes(NULL, &modDate, NULL);
#endif
}
Example #29
0
void t4p::SetSettingsDirLocation(const wxFileName& settingsDir) {
    wxFileName bootstrapConfigFile;
    wxStandardPaths paths = wxStandardPaths::Get();
    wxFileName executableDir(paths.GetExecutablePath());

    // the settings dir is in the same directory as the executable. save
    // settings dir in the local bootstrap file
    if (settingsDir.GetPathWithSep().Find(executableDir.GetPathWithSep()) != wxNOT_FOUND) {
        bootstrapConfigFile.Assign(paths.GetExecutablePath());
        bootstrapConfigFile.SetFullName(wxT(".triumph4php-bootstrap.ini"));
    } else {
        // save settings dire in the global bootstrap config file
        bootstrapConfigFile.AssignDir(paths.GetUserConfigDir());
        bootstrapConfigFile.SetFullName(wxT(".triumph4php-bootstrap.ini"));
    }
    wxString bootstrapFullPath = bootstrapConfigFile.GetFullPath();
    wxFileConfig bootstrapConfig(wxT("bootstrap"), wxEmptyString,
                                 bootstrapFullPath, wxEmptyString, wxCONFIG_USE_LOCAL_FILE);
    wxString s = settingsDir.GetPath();
    bootstrapConfig.Write(wxT("SettingsDirectory"), s);
    bootstrapConfig.Flush();
}
/**
 * Writes the checksums in a file.
 *
 * After the writing of the file, the state of the file should be unmodified
 * and the file name must be modified to <CODE>fileName</CODE>.
 * The paths of the files in the ChecksumData must be relative to the path of 
 * <CODE>fileName</CODE>.
 *
 * As wxChecksums always reads files in binary mode, all the file are marked
 * as binary files.
 *
 * @param  fileName  The file name in which the checksums are written.
 * @return <CODE>true</CODE> if the checksums have been written successfully,
 *         <CODE>false</CODE> otherwise.
 */
bool MD5File::write(const wxFileName& fileName)
{
  wxLogNull      logNo;   // No log
  wxString       line;    // line of text
  wxDateTime     d;       // A date
  wxFileName     nameRel; // File name with a relative path
  wxFileName     nameAbs; // File name with ab absolute path
  wxCOff_t       length;  // Length of the file
  wxPathFormat   format;  // Format of the path separators in the file
  
  wxFileOutputStream output(fileName.GetFullPath());
  if (!output.Ok())
    return false;
  wxTextOutputStream text(output, static_cast<wxEOL>(AppPrefs::get()->readLong(prMD5_WRITE_EOL)));

  // Gets the path separator
  format = static_cast<wxPathFormat>(AppPrefs::get()->readLong(prMD5_WRITE_PATH_SEPARATOR));

  // Write header
  if (AppPrefs::get()->readBool(prMD5_WRITE_GEN_AND_DATE))
  {
    d = wxDateTime::Now();
    line.Printf(wxT("; Generated by %s on %s at %s\n"), ::getAppName().c_str(),
                d.Format(wxT("%Y-%m-%d")).c_str(), d.Format(wxT("%H:%M:%S")).c_str());
    text.WriteString(line);
    text.WriteString(wxT(";\n"));
  }
  
  // Write the size and the date of the files
  if (AppPrefs::get()->readBool(prMD5_WRITE_FILE_SIZE_AND_DATE))
  {
    MChecksumData::const_iterator it = getChecksumDataBegin();
    MChecksumData::const_iterator end = getChecksumDataEnd();
    
    while (it != end)
    {
      const ChecksumData& cd = it->second;
      nameAbs = cd.getFileName();
      if (!nameAbs.IsAbsolute())
        nameAbs.MakeAbsolute(wxFileName(this->getFileName()).GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR));
      nameRel = nameAbs;
      if (!nameRel.IsRelative())
        nameRel.MakeRelativeTo(fileName.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR));

      if ((length = wxCGetFileLength(nameAbs.GetFullPath())) != static_cast<wxCOff_t>(wxInvalidOffset))
      {
        #if defined(wxC_USE_LARGE_FILES)
        text.WriteString(wxString::Format(wxT("; %12" wxLongLongFmtSpec "u  "), length));
        #else
        text.WriteString(wxString::Format(wxT("; %12u  "), length));
        #endif
        d = nameAbs.GetModificationTime();
        text << d.Format(wxT("%H:%M.%S")) << wxT(" ") << d.Format(wxT("%Y-%m-%d"));
        text << wxT(" ") << nameRel.GetFullPath(format) << wxT("\n");
      }
      it++;
    }
  }
  
  // Write checksums
  MChecksumData::const_iterator it = getChecksumDataBegin();
  MChecksumData::const_iterator end = getChecksumDataEnd();
    
  while (it != end)
  {
    const ChecksumData& cd = it->second;
    nameAbs = cd.getFileName();
    if (!nameAbs.IsAbsolute())
      nameAbs.MakeAbsolute(wxFileName(this->getFileName()).GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR));
    nameRel = nameAbs;
    if (!nameRel.IsRelative())
      nameRel.MakeRelativeTo(fileName.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR));

    text << cd.getChecksum().Lower() << wxT(" *")
         << nameRel.GetFullPath(format) << wxT("\n");
    it++;
  }
  
  if (output.IsOk())
  {
    // Modify file paths if the path of the checksum file has been modified.
    {
      MChecksumData::iterator it = getChecksumDataBeginI();
      MChecksumData::iterator end = getChecksumDataEndI();

      while (it != end)
      {
        ChecksumData& cd = it->second;
        nameAbs = cd.getFileName();
        if (!nameAbs.IsAbsolute())
          nameAbs.MakeAbsolute(wxFileName(this->getFileName()).GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR));
        nameRel = nameAbs;
        if (!nameRel.IsRelative())
          nameRel.MakeRelativeTo(fileName.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR));

        cd.setFileName(nameRel);
        it++;
      }
    }
    
    this->setFileName(fileName.GetFullPath());
    this->setModified(false);
    return true;
  }
  else
    return false;
}