void archiveSolutionFiles(const std::string &fileName)
{
  // extract tag from db fileName, use fileName as tag otherwise
  std::vector<std::string> split = SplitFileName(fileName);
  std::string dir = split[0] + "archive/";
  std::string tag = split[1];
  if (!tag.compare(0,6,"onelab"))
    tag.assign(tag.substr(6)); // cut off 'onelab' if present

  // add tag to all solution files in the db, and rename them on disk
  std::vector<onelab::string> strings;
  onelab::server::instance()->get(strings,"0Metamodel/9Solution files");
  if(strings.size()){
    std::vector<std::string> names = strings[0].getChoices();
    if(names.size()){
      for(unsigned int j = 0; j < names.size(); j++){
	std::vector<std::string> split = SplitFileName(names[j]);
	std::string old = names[j];
	CreateSingleDir(dir);
	names[j] = dir + split[1] + tag + split[2];
	Msg::Info("Renaming '%s' into '%s'", old.c_str(), names[j].c_str());
	rename(old.c_str(), names[j].c_str());
      }
      strings[0].setValue(names[0]);
      strings[0].setChoices(names);
      onelab::server::instance()->set(strings[0]);
#if defined(HAVE_FLTK)
      FlGui::instance()->rebuildTree(true);
#endif
    }
  }
}
void archiveOutputFiles(const std::string &fileName)
{
  std::string stamp;
  std::vector<onelab::string> ps;
  onelab::server::instance()->get(ps,"0Metamodel/9Tag");
  if(ps.size() && ps[0].getValue().size())
    stamp.assign(timeStamp() + "_" + ps[0].getValue());
  else
    stamp.assign(timeStamp());

  // add time stamp in all output files in the db, and rename them on disk
  std::vector<onelab::string> strings;
  onelab::server::instance()->get(strings);
  for(unsigned int i = 0; i < strings.size(); i++){
    if(strings[i].getName().find("9Output files") != std::string::npos){
      std::vector<std::string> names = strings[i].getChoices();
      names.push_back(strings[i].getValue());
      for(unsigned int j = 0; j < names.size(); j++){
        std::vector<std::string> split = SplitFileName(names[j]);
        int n = split[1].size();
        // if name is not already stamped
        if(n < 18 || split[1][n-3] != '-' || split[1][n-6] != '-' ||
           split[1][n-9] != '_'){
          std::string old = names[j];
          CreateSingleDir(split[0] + "archive/");
          names[j] = split[0] + "archive/" + split[1] + stamp + split[2];
          Msg::Info("Renaming '%s' into '%s'", old.c_str(), names[j].c_str());
          rename(old.c_str(), names[j].c_str());
        }
      }
      strings[i].setValue(names.back());
      names.pop_back();
      strings[i].setChoices(names);
      onelab::server::instance()->set(strings[i]);
    }
  }

  // save stamped db
  {
    std::vector<std::string> split = SplitFileName(fileName);
    CreateSingleDir(split[0] + "archive/");
    saveDb(split[0] + "archive/" + split[1] + stamp + split[2]);
  }

#if defined(HAVE_FLTK)
  FlGui::instance()->rebuildTree(true);
#endif
}
Example #3
0
 size_t GetFileList( const char *_path, std::vector<std::string> &list, bool recur )
 {
     size_t s = list.size();
     char path[MAX_PATH], n[128];
     strcpy( path, _path );
     int pos = SplitFileName( path );
     path[pos] = '\0';
     strcpy( n, &path[pos+1] );
     WIN32_FIND_DATA fdata;
     HANDLE h = FindFirstFile( _path, &fdata );
     if( h == INVALID_HANDLE_VALUE ) return list.size() - s;
     do
     {
         char p[MAX_PATH];
         sprintf( p, "%s\\%s", path, fdata.cFileName );
         list.push_back( p );
         if( recur && 
             fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY &&
             strcmp( "..", fdata.cFileName ) &&
             strcmp( ".", fdata.cFileName ) )
         {
             char p[MAX_PATH];
             sprintf( p, "%s\\%s\\%s", path, fdata.cFileName, n );
             GetFileList( p, list, recur );
         }
     } while( FindNextFile( h, &fdata ) );
     FindClose( h );
     return list.size() - s;
 }
Example #4
0
HRESULT	CShaders::AddCShader(LPCWSTR szFileName, LPCSTR szEntryPoint, LPCSTR szShaderName, const D3D_SHADER_MACRO *pDefines, OUT SHADERID *pSID)
{
	HRESULT hr;
	ID3DBlob* pSBlob = NULL;
	ID3D11ComputeShader *CStmp = NULL;

static wchar_t wszTex[64];
	mbstowcs(wszTex, szShaderName, 63);
	wstring sPath, sFileName;
	SplitFileName(wstring(szFileName), L"/\\", sPath, sFileName);

	wstring sSourceFile = sPath + L"/\\Sources\\" + sFileName;
#ifdef AUTSHADERS_SAVE_TO_FILE
	hr = CompileShaderFromFile( sSourceFile.c_str(), szEntryPoint, "cs_5_0", &pSBlob, pDefines);
	if ( FAILED(hr) ) { 
		MessageBox( NULL, L"Unable to compilte .fx file. Please, reinstall the programm.", L"Error", MB_OK ); 
		return hr;
	}
#endif

	wstring sTargetFileName = sPath + L"/\\" + wszTex + wstring(L".cso");
	V_RETURN(WriteReadShader(&pSBlob, sTargetFileName.c_str()));

	hr = AUTGetD3DDevice()->CreateComputeShader( pSBlob->GetBufferPointer(), pSBlob->GetBufferSize(), NULL, &CStmp );
	SAFE_RELEASE(pSBlob);
	if( FAILED( hr ) )
		return hr;

	ComputeShaders.push_back(CStmp);
	*pSID = ComputeShaders.size() - 1;

	AUTMapIDsPush(szShaderName, *pSID);

	return S_OK;
}
Example #5
0
bool CPdbCache::DeletePdbFile(std::wstring sPath)
{
    FixSlashesInFilePath(sPath);

    // First check if file is located inside of a search directory
    bool bMatch = false;
    std::map<std::wstring, _SearchDirInfo>::iterator it;
    for(it=m_aSearchDirs.begin(); it!=m_aSearchDirs.end(); it++)
    {
        _SearchDirInfo& info = it->second;
        int pos = sPath.find(info.m_sPath);
        if(pos==0)
        {
            // The file is located in this search path
            bMatch = true;
            break;
        }
    }
    if(!bMatch)
        return false; // File is not in PDB cache search path

    // Remove the file itself
    int nRes = RemoveFile(sPath);
    if(nRes!=0)
        return false; // Error deleting file

    std::wstring sDir;
    std::wstring sFile;
    std::wstring sBaseFileName;
    std::wstring sExtension;
    std::wstring sSubDirName;
    SplitFileName(sPath, sDir, sFile, sBaseFileName, sExtension);
    SplitFileName(sDir, sSubDirName, sFile, sBaseFileName, sExtension);

    // Remove the containing folder (if empty)
    RmDir(sDir, true);

    // Remove the outer containing folder (if empty)
    RmDir(sSubDirName, true);

    return true;
}
Example #6
0
std::string FixRelativePath(const std::string &reference, const std::string &in)
{
  if(in.empty()) return "";

  if(in[0] == '/' || in[0] == '\\' ||
     (in.size() > 3 && in[1] == ':' && (in[2] == '/' || in[2] == '\\'))){
    // do nothing: 'in' is an absolute path
    return in;
  }
  else{
    // append 'in' to the path of the reference file
    std::vector<std::string> split = SplitFileName(reference);
    return split[0] + in;
  }
}
Example #7
0
HRESULT	CShaders::AddVShader(LPCWSTR szFileName, LPCSTR szEntryPoint, LPCSTR szShaderName, INPUTLAYOUTID _ILID, const D3D_SHADER_MACRO *pDefines, OUT SHADERID *pSID)
{
	HRESULT hr;
	ID3DBlob* pSBlob = NULL;
	ID3D11VertexShader *VStmp = NULL;

	ID3D11Device *pD3DDevice = AUTGetD3DDevice();
	
static wchar_t wszTex[64];
	mbstowcs(wszTex, szShaderName, 63);
	wstring sPath, sFileName;
	SplitFileName(wstring(szFileName), L"/\\", sPath, sFileName);

	wstring sSourceFile = sPath + L"/\\Sources\\" + sFileName;
#ifdef AUTSHADERS_SAVE_TO_FILE
	hr = CompileShaderFromFile( sSourceFile.c_str(), szEntryPoint, "vs_5_0", &pSBlob, pDefines);
	if ( FAILED(hr) ) { 
		MessageBox( NULL, L"Unable to compilte .fx file. Please, reinstall the programm.", L"Error", MB_OK ); 
		return hr;
	}
#endif

	wstring sTargetFileName = sPath + L"/\\" + wszTex + wstring(L".vso");
	V_RETURN(WriteReadShader(&pSBlob, sTargetFileName.c_str()));

	hr = pD3DDevice->CreateVertexShader( pSBlob->GetBufferPointer(), pSBlob->GetBufferSize(), NULL, &VStmp );
	if( FAILED( hr ) )
		return hr;

	if (_ILID != -1)
	{
		CInputLayout *pLayout = InputLayouts.at(_ILID);
		hr = pD3DDevice->CreateInputLayout( pLayout->pILDesc, pLayout->dwNumElems, 
			pSBlob->GetBufferPointer(), pSBlob->GetBufferSize(), &pLayout->pInputLayout );
		SAFE_RELEASE(pSBlob);
		if (FAILED(hr))
			return hr;
	}

	VertexShaders.push_back(VStmp);
	*pSID = VertexShaders.size() - 1;

	AUTMapIDsPush(szShaderName, *pSID);

	return S_OK;
}
Example #8
0
static void addGmshPathToEnvironmentVar(const std::string &name)
{
  std::vector<std::string> split = SplitFileName(CTX::instance()->argv0);
  std::string path;
  char *tmp = getenv(name.c_str());
  if(tmp){
    path = tmp;
#if defined(WIN32)
    path += ";" + split[0];
#else
    path += ":" + split[0];
#endif
  }
  else
    path = split[0];
  SetEnvironmentVar(name.c_str(), path.c_str());
}
Example #9
0
void add_compound(std::string type, List_T *list, std::string fileName)
{
  std::ostringstream sstream;
  if(SplitFileName(fileName)[2] != ".geo") sstream << "CreateTopology;\n";
  if (type == "Surface"){
    sstream << "Compound " << type << "(" << NEWSURFACE()+1000 << ") = {"
	    << list2string(list) << "};";
  }
  else if (type == "Line"){
    sstream << "Compound " << type << "(" << NEWLINE()+1000 << ") = {"
	    << list2string(list) << "};";
  }
  else{
    sstream << "Compound " << type << "(" << NEWREG() << ") = {"
	    << list2string(list) << "};";
  }
  add_infile(sstream.str(), fileName);
}
Example #10
0
bool PView::write(const std::string &fileName, int format, bool append)
{
  Msg::StatusBar(true, "Writing '%s'...", fileName.c_str());

  bool ret;
  switch(format){
  case 0: ret = _data->writePOS(fileName, false, false, append); break; // ASCII
  case 1: ret = _data->writePOS(fileName, true, false, append); break; // binary
  case 2: ret = _data->writePOS(fileName, false, true, append); break; // parsed
  case 3: ret = _data->writeSTL(fileName); break;
  case 4: ret = _data->writeTXT(fileName); break;
  case 5: ret = _data->writeMSH(fileName, CTX::instance()->mesh.mshFileVersion,
                                CTX::instance()->mesh.binary, true, false,
                                0, true, CTX::instance()->post.forceNodeData,
                                CTX::instance()->post.forceElementData); break;
  case 6: ret = _data->writeMED(fileName); break;
  case 7: ret = writeX3D(fileName); break;
  case 10:
    {
      std::string ext = SplitFileName(fileName)[2];
      if(ext == ".pos")
        ret = _data->writePOS(fileName, false, true, append);
      else if(ext == ".stl")
        ret = _data->writeSTL(fileName);
      else if(ext == ".msh")
        ret = _data->writeMSH(fileName, CTX::instance()->mesh.mshFileVersion,
                              CTX::instance()->mesh.binary, true, false,
                              0, true, CTX::instance()->post.forceNodeData,
                              CTX::instance()->post.forceElementData);
      else if(ext == ".med")
        ret = _data->writeMED(fileName);
      else
        ret = _data->writeTXT(fileName);
      break;
    }
  default: ret = false; Msg::Error("Unknown view format %d", format); break;
  }

  if(ret) Msg::StatusBar(true, "Done writing '%s'", fileName.c_str());
  return ret;
}
Example #11
0
bool CFileFinder::FindFirstFile(std::wstring sSearchPattern, CFindFileInfo* pFileInfo)
{
    // Validate input param
    if(pFileInfo==NULL)
        return false;

    // Save search pattern
    m_sSearchPattern = sSearchPattern;

    // Get directory name
    std::wstring sFileName;
    std::wstring sBaseFileName;
    std::wstring sExtension;
    SplitFileName(sSearchPattern, m_sDirectory, sFileName, sBaseFileName, sExtension);

#ifdef _WIN32

    m_sDirectory+='\\';

    // Replace '/' with '\\'
    std::replace(m_sSearchPattern.begin(), m_sSearchPattern.end(), '/', '\\');

    m_hFind = ::FindFirstFileW(m_sSearchPattern.c_str(), &m_ffd);
    if(m_hFind==INVALID_HANDLE_VALUE)
        return false;

    pFileInfo->m_sRelFileName = m_ffd.cFileName;
    pFileInfo->m_sFileName = m_sDirectory+m_ffd.cFileName;
    pFileInfo->m_bIsRegular = (m_ffd.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)==0;
    pFileInfo->m_bIsDirectory = (m_ffd.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)!=0;
    return true;
#else

    m_sDirectory+='/';

    // Replace '\\' with '/'
    std::replace(m_sSearchPattern.begin(), m_sSearchPattern.end(), '\\', '/');

    m_dirp = opendir(strconv::w2utf8(m_sDirectory).c_str());

    while(m_dirp)
    {
        //int errno = 0;
        struct dirent* pd = readdir(m_dirp);
        if(pd==NULL)
        {
            break;
        }

        if(strcmp(pd->d_name, ".")!=0 &&
                strcmp(pd->d_name, "..")!=0)
        {
            pFileInfo->m_sFileName = m_sDirectory;
            pFileInfo->m_sFileName += strconv::utf82w(pd->d_name);
            pFileInfo->m_sRelFileName = strconv::utf82w(pd->d_name);
            pFileInfo->m_bIsRegular = true;
            pFileInfo->m_bIsDirectory = false;
            struct stat st;
            if(0==stat(strconv::w2utf8(pFileInfo->m_sFileName).c_str(), &st))
            {
                pFileInfo->m_bIsRegular = S_ISREG(st.st_mode);
                pFileInfo->m_bIsDirectory = S_ISDIR(st.st_mode);
            }

            return true;
        }
    }

    return false;
#endif


}
Example #12
0
std::string GetFileNameWithoutPath(const std::string &fileName)
{
  std::vector<std::string> s = SplitFileName(fileName);
  return s[1] + s[2];
}
void solver_batch_cb(void *data)
{
  int num = (intptr_t)data;
  std::string name, exe, host;

  if(num == -1){
    // no solver to run
    return;
  }
  else if(num == -2){
    // just run local Gmsh client
  }
  else if(num >= 0){
    // run local Gmsh client + solver num
    name = opt_solver_name(num, GMSH_GET, "");
    exe = opt_solver_executable(num, GMSH_GET, "");
    host = opt_solver_remote_login(num, GMSH_GET, "");
    if(exe.empty()){
      Msg::Error("Solver executable name not provided");
      return;
    }
  }
  else{
    Msg::Error("Unknown client to run in batch mode (%d)", num);
    return;
  }

  onelab::number n("0Metamodel/Batch", CTX::instance()->batch);
  n.setVisible(false);
  onelab::server::instance()->set(n);

  // create client
  onelab::localNetworkClient *c = 0;
  onelab::string o;
  if(name.size()){
    c = new gmshLocalNetworkClient(name, exe, host);
    c->setIndex(num);
    o = c->getName() + "/Action";
  }

  // initialize
  onelabUtils::runGmshClient("initialize", CTX::instance()->solver.autoMesh);
  if(c){
    o.setValue("initialize");
    onelab::server::instance()->set(o);
    c->run();
  }

  // load db
  if(CTX::instance()->solver.autoSaveDatabase){
    std::string db = SplitFileName(GModel::current()->getFileName())[0] + "onelab.db";
    if(!StatFile(db)) loadDb(db);
  }

  // check
  onelabUtils::runGmshClient("check", CTX::instance()->solver.autoMesh);
  if(c){
    onelabUtils::guessModelName(c);
    o.setValue("check");
    onelab::server::instance()->set(o);
    c->run();
  }

  // compute
  initializeLoops();
  do{
    onelabUtils::runGmshClient("compute", CTX::instance()->solver.autoMesh);
    if(c){
      onelabUtils::guessModelName(c);
      o.setValue("compute");
      onelab::server::instance()->set(o);
      c->run();
      onelab::server::instance()->setChanged(false, c->getName());
    }
  } while(incrementLoops());

  if(CTX::instance()->solver.autoSaveDatabase ||
     CTX::instance()->solver.autoArchiveOutputFiles){
    std::string db = SplitFileName(GModel::current()->getFileName())[0] + "onelab.db";
    if(CTX::instance()->solver.autoArchiveOutputFiles) archiveOutputFiles(db);
    if(CTX::instance()->solver.autoSaveDatabase) saveDb(db);
  }
}
Example #14
0
string FilenameFilePart(const string& name) {
  string file_part;
  SplitFileName(name, NULL, &file_part);
  return file_part;
}
Example #15
0
int print_pgf(const std::string &name, const int num, const int cnt, 
              PixelBuffer *buffer, double *eulerAngles,
              int *viewport, double *proj, double *model)
{
  int ypix = buffer->getHeight();
  int xpix = buffer->getWidth();

  std::string base = SplitFileName(name)[1];
  std::string path = SplitFileName(name)[0];
  std::string pngfilen = path + base + ".png";
  std::string pgffilen = path + base + ".pgf";
  std::string texfilen = path + base + ".tex";
  FILE *fp = Fopen(pngfilen.c_str(), "wb");
  if(!fp){
    Msg::Error("Unable to open file '%s'", pngfilen.c_str());
    return 1;
  }
  create_png(fp, buffer, 100);
  fclose(fp);

  // write pgf
  int twoDim = (int)opt_print_pgf_two_dim(0, GMSH_GET, 0);
  int exportAxis = (int)opt_print_pgf_export_axis(0, GMSH_GET, 0);
  if (cnt > 1)
    Msg::Warning("PGF colorbar output works only with a single visible "
                 "scale. Consider disabling all but one. I can only create a "
                 "single colorbar. Colorbar will be suppressed");

  int samples;
  std::string colmap_s, colbar_s, post_axis_s;
  // color map
  if (cnt == 1) { // one post processing view scale visible
    int intType = (int) opt_view_intervals_type(num, GMSH_GET, 0);
    if(assembleColmapStr(num, intType, samples, colmap_s) != 0) {
      Msg::Error("Unable to assemble colormap for PGF output");
      return 1;
    }
    if(assemblePostAxis(num, intType, post_axis_s) != 0) {
      Msg::Error("Unable to assemble post processing axis for PGF output");
      return 1;
    }
    if(assembleColbarStr(num, intType, samples, colbar_s) != 0) {
      Msg::Error("Unable to assemble colorbar for PGF output");
      return 1;
    }
  }
  else {
    colbar_s.assign("\t]\n"); // close axis without colorbar and dummy plot
  }

  std::string axis_s, plot_s;
  axis_s.assign("\\begin{tikzpicture}\n\\begin{axis}[\n\twidth=.5\\linewidth,"
                "%% set figure width here\n");
  if (twoDim) {
    if (assemble2d(num, exportAxis, axis_s, plot_s, eulerAngles) != 0) {
      return 1;
    }
  }
  else { // 3d
    if (assemble3d(num, exportAxis, axis_s, plot_s, eulerAngles,
                   viewport, proj, model, ypix, xpix) != 0) {
      return 1;
    }
  }
  char tmp[265];
  sprintf(tmp,"\t    {%s.png};\n", base.c_str());
  plot_s.append(tmp);

  fp = Fopen(pgffilen.c_str(), "wb");
  if(!fp){
    Msg::Error("Unable to open file '%s'", pgffilen.c_str());
    return 1;
  }
  fprintf(fp, "%s", colmap_s.c_str());
  fprintf(fp, "%s", axis_s.c_str());
  fprintf(fp, "%s", post_axis_s.c_str());
  fprintf(fp, "%s", colbar_s.c_str());
  fprintf(fp, "%s", plot_s.c_str());
  fprintf(fp, "\\end{axis}\n\\end{tikzpicture}%%\n");
  fclose(fp);

  if (twoDim)  {
    // try to trim the png...
    char tmp[2048];
    if (system(NULL)) {
      std::string pngname = name;
      pngname.replace(pngname.end()-3, pngname.end(), "png");
      sprintf(tmp, "convert -trim %s %s", pngname.c_str(), pngname.c_str());
      Msg::Info("Running:");
      Msg::Info(tmp);
      int ret = system(tmp);
      Msg::Info("Conversion returned value %d", ret);
      if (ret == 0) // success
        Msg::Info("Automatic trim successful.");
      else {
        Msg::Warning("Cannot automatically trim output png.");
        sprintf(tmp, "One should now manually crop the margins, using e.g."
                "gimp or `convert -trim %s %s` to get rid of any remaining"
                "margins.", pngfilen.c_str(), pngfilen.c_str());
        Msg::Warning(tmp);
      }
    }
    else {
      Msg::Warning("Cannot automatically trim output png.");
      sprintf(tmp, "One should now manually crop the margins, using e.g."
              "gimp or `convert -trim %s %s` to get rid of any remaining"
              "margins.", pngfilen.c_str(), pngfilen.c_str());
      Msg::Warning(tmp);
    }
  }

  // try to add transparency, do not(!) crop otherwise the transformation
  // matrix is wrong!!!!
  if (!twoDim)  {
    char tmp[2048];
    if (system(NULL)) {
      std::string pngname = name;
      pngname.replace(pngname.end()-3, pngname.end(), "png");
      sprintf(tmp, "convert -transparent white %s %s",
              pngname.c_str(), pngname.c_str());
      Msg::Info("Running:");
      Msg::Info(tmp);
      int ret = system(tmp);
      Msg::Info("Conversion returned value %d", ret);
      if (ret == 0) // success
        Msg::Info("Automatic transparent white background successful.");
      else {
        Msg::Warning("Cannot automatically add transparency to png.");
        sprintf(tmp, "One should now manually add a transparent layer in "
                "order to not obstruct the axis. e.g. using gimp or "
                "convert -transparent white %s %s`.",
                pngfilen.c_str(), pngfilen.c_str());
        Msg::Warning(tmp);
      }
    }
    else { // exit (EXIT_FAILURE);
      Msg::Warning("Cannot automatically add transparency to output png.");
      sprintf(tmp, "One should now manually add a transparent layer in "
              "order to not obstruct the axis. e.g. using gimp or "
              "`convert -transparent white %s %s`.",
              pngfilen.c_str(), pngfilen.c_str());
      Msg::Warning(tmp);
    }
  }

  // try to write a helper tex file just in case it does not exist
  fp = Fopen(texfilen.c_str(), "r");
  if(fp){
    fclose(fp);
    Msg::Info("File '%s' exists, please add '\\input{%s}' by yourself.",
              texfilen.c_str(), pgffilen.c_str());
  }
  else {
    fp = Fopen(texfilen.c_str(), "w");
    fprintf(fp,"\\documentclass{article}\n\\usepackage{pgfplots}\n"
            "\\pgfplotsset{compat=1.8}\n\\begin{document}\n");
    fprintf(fp,"\n\\input{%s}\n", pgffilen.c_str());
    fprintf(fp,"\n\\end{document}\n");
    fclose(fp);
  }
  return 0;
}
Example #16
0
string FilenamePathPart(const string& name) {
  string path_part;
  SplitFileName(name, &path_part, NULL);
  return path_part;
}
Example #17
0
bool
CPdbCache::FindPdb(
    std::wstring sGUIDnAge,
    std::wstring sPdbFileName,
    std::wstring sImageFileName,
    CPdbReader** ppPdbReader,
    CPeReader** ppPeReader,
    int* pnEntry,
    std::string* psErrorMsg,
    bool bExactMatchBuildAge
)
{
    // Init output variables
    if(ppPdbReader!=NULL)
        *ppPdbReader = NULL;

    if(ppPeReader!=NULL)
        *ppPeReader = NULL;

    if(pnEntry!=NULL)
        *pnEntry = -1;

    if(psErrorMsg)
        *psErrorMsg = "Unspecified error";

    // Validate input

    if(sGUIDnAge.empty() ||
            sPdbFileName.empty())
    {
        if(psErrorMsg)
            *psErrorMsg = "Either GUIDnAge or path should be specified";
        return false; // Either GUIDnAge or path should be specified
    }

    if(ppPdbReader==NULL ||
            ppPeReader==NULL ||
            pnEntry==NULL)
    {
        if(psErrorMsg)
            *psErrorMsg = "Output variables should be set";
        return false; // Output variables should be set
    }

    bool bStatus = false;
    CPdbReader* pPdbReader = NULL;
    CPeReader* pPeReader = NULL;
    std::wstring sDir;
    std::wstring sFile;
    std::wstring sBaseName;
    std::wstring sExt;
    std::wstring sPdbName;
    std::wstring sPeName;
    std::map<std::wstring, _SearchDirInfo>::iterator it;
    int nEntry = -1;
    std::string sErrorMsg;

    // Fix slashes in file path (OS dependent)
    FixSlashesInFilePath(sPdbFileName);
    FixSlashesInFilePath(sImageFileName);

    // If GUID+Age is specified, check if we have a PDB with such GUID+Age loaded
    if(!sGUIDnAge.empty())
    {
        eFindExistingEntryResult res = FindExistingEntry(sGUIDnAge, sPdbFileName,
                                       sImageFileName, &pPdbReader, &pPeReader, &nEntry, bExactMatchBuildAge);
        if(res==FEE_FOUND)
        {
            sErrorMsg = "Success";
            bStatus = true;
            goto cleanup;
        }

        if(res==FEE_PENDING_DELETE)
        {
            sErrorMsg = "File is found in cache, but it is marked for deletion";
            bStatus = false;
            goto cleanup;
        }
    }

    // Try to find matching PDB file from search dirs

    // Get image file base name (without path and extension)
    SplitFileName(sPdbFileName, sDir, sFile, sBaseName, sExt);
    sPdbName = sBaseName + L".pdb";
    SplitFileName(sImageFileName, sDir, sFile, sBaseName, sExt);
    sPeName = sBaseName + L".";
    sPeName += sExt;

    for(it=m_aSearchDirs.begin(); it!=m_aSearchDirs.end(); it++)
    {
        _SearchDirInfo& sdi = it->second;

        bStatus = SearchDirectory(sdi.m_sPath, sdi.m_SearchMode, sdi.m_bSearchRecursively,
                                  sPdbName, sPeName, sGUIDnAge, &pPdbReader, &pPeReader, &nEntry, sErrorMsg, bExactMatchBuildAge);
        if(bStatus)
            break;
    }

    sErrorMsg = "Exhausted search";

cleanup:

    if(bStatus)
    {
        // Return the results
        *ppPdbReader = pPdbReader;
        *ppPeReader = pPeReader;
        *pnEntry = nEntry;
    }

    if(psErrorMsg)
        *psErrorMsg = sErrorMsg;

    return bStatus;
}
Example #18
0
void add_infile(std::string text, std::string fileName, bool forceDestroy)
{
  std::vector<std::string> split = SplitFileName(fileName);
  std::string noExt = split[0] + split[1], ext = split[2];
#if defined(HAVE_COMPRESSED_IO) && defined(HAVE_LIBZ)
  bool compressed = false;
  if(ext == ".gz"){
    ext = SplitFileName(noExt)[2];
    compressed = true;
  }
#endif
  // make sure we don't add stuff in a non-geo file
  if(!CTX::instance()->expertMode) {
    if(ext.size() && ext != ".geo" && ext != ".GEO" ){
      std::ostringstream sstream;
      sstream <<
        "A scripting command is going to be appended to a non-`.geo' file. Are\n"
        "you sure you want to proceed?\n\n"
        "You probably want to create a new `.geo' file containing the command\n"
        "`Merge \"" << split[1] + split[2] << "\";' and use that file instead.\n\n"
        "(To disable this warning in the future, select `Enable expert mode'\n"
        "in the option dialog.)";
      int ret = Msg::GetAnswer(sstream.str().c_str(), 2, "Cancel", "Proceed as is",
                               "Create new `.geo' file");
      if(ret == 2){
        std::string newFileName = split[0] + split[1] + ".geo";
        if(CTX::instance()->confirmOverwrite) {
          if(!StatFile(newFileName)){
            std::ostringstream sstream;
            sstream << "File '" << fileName << "' already exists.\n\n"
              "Do you want to replace it?";
            if(!Msg::GetAnswer(sstream.str().c_str(), 0, "Cancel", "Replace"))
              return;
          }
        }
        FILE *fp = Fopen(newFileName.c_str(), "w");
        if(!fp) {
          Msg::Error("Unable to open file '%s'", newFileName.c_str());
          return;
        }
        fprintf(fp, "Merge \"%s\";\n%s\n", (split[1] + split[2]).c_str(), text.c_str());
        fclose(fp);
        OpenProject(newFileName);
        return;
      }
      else if(ret == 0)
        return;
    }
  }

#if defined(HAVE_PARSER)
  std::string tmpFileName = CTX::instance()->homeDir + CTX::instance()->tmpFileName;
  gmshFILE gmsh_yyin_old = gmsh_yyin;
  FILE *tmp_file;
  if(!(tmp_file = Fopen(tmpFileName.c_str(), "w"))) {
    Msg::Error("Unable to open temporary file '%s'", tmpFileName.c_str());
    return;
  }
  fprintf(tmp_file, "%s\n", text.c_str());
  fclose(tmp_file);
  gmsh_yyin = gmshopen(tmpFileName.c_str(), "r");
  while(!gmsheof(gmsh_yyin)) {
    gmsh_yyparse();
  }
  gmshclose(gmsh_yyin);
  gmsh_yyin = gmsh_yyin_old;

  if(forceDestroy){
    // we need to start from scratch (e.g. if the command just parsed
    // could have deleted some entities)
    GModel::current()->destroy();
  }
  GModel::current()->importGEOInternals();
  CTX::instance()->mesh.changed = ENT_ALL;

  // here we have to be explicit otherwise we append compressed stuff to ascii
  // file!
#if defined(HAVE_COMPRESSED_IO) && defined(HAVE_LIBZ)
  if(compressed){
    gmshFILE fp = gmshopen(fileName.c_str(), "a");
    if(!fp) {
      Msg::Error("Unable to open file '%s'", fileName.c_str());
      return;
    }
    gmshprintf(fp, "%s\n", text.c_str());
    gmshclose(fp);
  }
  else{
    FILE *fp = Fopen(fileName.c_str(), "a");
    if(!fp) {
      Msg::Error("Unable to open file '%s'", fileName.c_str());
      return;
    }
    fprintf(fp, "%s\n", text.c_str());
    fclose(fp);
  }
#else
  FILE *fp = Fopen(fileName.c_str(), "a");
  if(!fp) {
    Msg::Error("Unable to open file '%s'", fileName.c_str());
    return;
  }
  fprintf(fp, "%s\n", text.c_str());
  fclose(fp);
#endif

#else
  Msg::Error("GEO file creation not available without Gmsh parser");
#endif

  // mark all Gmsh data as changed in onelab (will force e.g. a reload and a
  // remesh)
#if defined(HAVE_ONELAB)
  onelab::server::instance()->setChanged(true, "Gmsh");
#endif
#if defined(HAVE_ONELAB2)
  OnelabDatabase::instance()->setChanged(true, "Gmsh");
#endif
}
Example #19
0
void PluginManager::registerDefaultPlugins()
{
  if(CTX::instance()->solver.plugins){
    // nothing here yet
  }

  if(CTX::instance()->post.plugins){
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("StreamLines", GMSH_RegisterStreamLinesPlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("Particles", GMSH_RegisterParticlesPlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("CutGrid", GMSH_RegisterCutGridPlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("Isosurface", GMSH_RegisterIsosurfacePlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("CutPlane", GMSH_RegisterCutPlanePlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("CutSphere", GMSH_RegisterCutSpherePlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("CutBox", GMSH_RegisterCutBoxPlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("Skin", GMSH_RegisterSkinPlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("MathEval", GMSH_RegisterMathEvalPlugin()));
# if 1 // experimental (Amaury)
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("AnalyseCurvedMesh", GMSH_RegisterAnalyseCurvedMeshPlugin()));
#endif
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("CurvedBndDist", GMSH_RegisterCurvedBndDistPlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("ModifyComponent", GMSH_RegisterModifyComponentPlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("ExtractElements", GMSH_RegisterExtractElementsPlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("CutParametric", GMSH_RegisterCutParametricPlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("MakeSimplex", GMSH_RegisterMakeSimplexPlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("Smooth", GMSH_RegisterSmoothPlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("Transform", GMSH_RegisterTransformPlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("LongitudeLatitude",GMSH_RegisterLongituteLatitudePlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("Warp", GMSH_RegisterWarpPlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("SphericalRaise", GMSH_RegisterSphericalRaisePlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("HarmonicToTime", GMSH_RegisterHarmonicToTimePlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("ModulusPhase", GMSH_RegisterModulusPhasePlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("Integrate", GMSH_RegisterIntegratePlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("MinMax", GMSH_RegisterMinMaxPlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("Gradient", GMSH_RegisterGradientPlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("Curl", GMSH_RegisterCurlPlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("Divergence", GMSH_RegisterDivergencePlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("Annotate", GMSH_RegisterAnnotatePlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("Remove", GMSH_RegisterRemovePlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("Eigenvectors", GMSH_RegisterEigenvectorsPlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("Eigenvalues", GMSH_RegisterEigenvaluesPlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("Lambda2", GMSH_RegisterLambda2Plugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("Probe", GMSH_RegisterProbePlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("Triangulate", GMSH_RegisterTriangulatePlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("ExtractEdges", GMSH_RegisterExtractEdgesPlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("FieldFromAmplitudePhase", GMSH_RegisterFieldFromAmplitudePhasePlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("NearToFarField", GMSH_RegisterNearToFarFieldPlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("Bubbles", GMSH_RegisterBubblesPlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("DiscretizationError", GMSH_RegisterDiscretizationErrorPlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("Scal2Tens", GMSH_RegisterScal2TensPlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("Scal2Vec", GMSH_RegisterScal2VecPlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("NewView", GMSH_RegisterNewViewPlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("SimplePartition", GMSH_RegisterSimplePartitionPlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("Crack", GMSH_RegisterCrackPlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("FaultZone", GMSH_RegisterFaultZonePlugin()));
#if defined(HAVE_TETGEN)
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("Tetrahedralize", GMSH_RegisterTetrahedralizePlugin()));
#endif
#if defined(HAVE_KBIPACK)
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("Homology", GMSH_RegisterHomologyComputationPlugin()));
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("HomologyPost", GMSH_RegisterHomologyPostProcessingPlugin()));
#endif
#if defined(HAVE_SOLVER)
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("Distance", GMSH_RegisterDistancePlugin()));
#endif
#if defined(HAVE_ANN)
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("NearestNeighbor", GMSH_RegisterNearestNeighborPlugin()));
#endif
#if defined(HAVE_DINTEGRATION)
    allPlugins.insert(std::pair<std::string, GMSH_Plugin*>
                      ("CutMesh", GMSH_RegisterCutMeshPlugin()));
#endif
  }

#if defined(HAVE_FLTK)
  char *pluginsHome = getenv("GMSHPLUGINSHOME");
  if(!pluginsHome) return;
  struct dirent **list;
  int nbFiles = fl_filename_list(pluginsHome, &list);
  if(nbFiles <= 0)
    return;
  for(int i = 0; i < nbFiles; i++) {
    std::string ext = SplitFileName(list[i]->d_name)[2];
    if(ext == ".so" || ext == ".dll")
      addPlugin(list[i]->d_name);
  }
  for(int i = 0; i < nbFiles; i++)
    free(list[i]);
  free(list);
#endif
}
Example #20
0
int onelab_cb(std::string action)
{
  if(action == "stop"){
    onelab::string o("GetDP/Action", "stop");
    o.setVisible(false);
    o.setNeverChanged(true);
    onelab::server::instance()->set(o);
    onelabStop = true;
    return 0;
  }

  if(locked) return -1;
  locked = true;

  if(action == "reset"){
    onelab::server::instance()->clear();
    onelabUtils::runGmshClient(action, true);
    action = "check";
  }

  Msg::ResetErrorCounter();

  if(action == "compute"){
    onelabUtils::initializeLoop("1");
    onelabUtils::initializeLoop("2");
    onelabUtils::initializeLoop("3");
  }

  do{
    // run Gmsh (only if necessary)
    onelabUtils::runGmshClient(action, true);

    // run GetDP (always -- to not confuse the user)
    onelab::string o("GetDP/Action", action);
    o.setVisible(false);
    o.setNeverChanged(true);
    onelab::server::instance()->set(o);

    std::vector<std::string> args;
    args.push_back("getdp");
    std::vector<onelab::string> ps;
    onelab::server::instance()->get(ps, "GetDP/1ModelName");
    if(ps.empty()){
      std::vector<std::string> split = SplitFileName(GModel::current()->getFileName());
      std::string name(split[0] + split[1]);
      onelab::string o("GetDP/1ModelName", name, "Model name");
      o.setKind("file");
      onelab::server::instance()->set(o);
      ps.push_back(o);
    }
    args.push_back(ps[0].getValue());
    if(action == "check")
      onelab::server::instance()->get(ps, "GetDP/9CheckCommand");
    else if(action == "compute")
      onelab::server::instance()->get(ps, "GetDP/9ComputeCommand");
    else
      ps.clear();
    std::vector<std::string> c = commandToVector(ps.empty() ? "" : ps[0].getValue().c_str());
    args.insert(args.end(), c.begin(), c.end());
    args.push_back("-onelab");
    args.push_back("GetDP");
    GetDP(args, onelab::server::instance());
  } while(action == "compute" && !onelabStop && (onelabUtils::incrementLoop("3") ||
                                                 onelabUtils::incrementLoop("2") ||
                                                 onelabUtils::incrementLoop("1")));
  locked = false;
  return onelab::server::instance()->getChanged();
}