Example #1
0
void File::open(const Filename &filepath, const char *mode) {

	// Clean up previously opened file
	close();

	_file = fopen(filepath.getFullPath().c_str(), mode);
	if (!_file) {
		std::string fixedPath = fixPathCase(filepath.getFullPath());
		_file = fopen(fixedPath.c_str(), mode);
	}

	FileMode m = FILEMODE_READ;
	do {
		switch(*mode) {
		case 'w': m = FILEMODE_WRITE; break;
		case 'r': m = FILEMODE_READ; break;
		case 'b': m = FileMode(m | FILEMODE_BINARY); break;
		case '+': m = FileMode(m | FILEMODE_READ | FILEMODE_WRITE); break;
		default: throw FileException(std::string("Unsupported FileMode ") + mode);
		}
	} while (*++mode);
	_mode = m;

	_name = filepath;
	_xormode = 0;

	if (!_file)
		throw FileException("Could not open file " + filepath.getFullPath());
}
void Compartment_Report_HDF5_File_Reader::open_data_set
(Cell_GID cell_ID, const char * dataset_name, H5ID & file, H5ID & dataset) const
{
    // Opening file for current cell
    std::string cell_name = "a" + boost::lexical_cast<std::string>(cell_ID);
    Filename filename = _path / (cell_name + ".h5");

    file.reset(H5Fopen(filename.string().c_str(), H5F_ACC_RDONLY, H5P_DEFAULT),
               H5Fclose);
    if (!file)
    {
        throw_exception(
            File_Open_Error("Compartment_Report_HDF5_File_Reader: error "
                            "opening file:" + filename.string()),
            FATAL_LEVEL, __FILE__, __LINE__);
    }

    // Opening the dataset
    std::string dataset_full_name = 
        "/" + cell_name + "/" + (_report_name + "/") + dataset_name;
    H5E_BEGIN_TRY
        dataset.reset(H5Dopen(file, dataset_full_name.c_str()), H5Dclose);
    H5E_END_TRY;
    if (!dataset)
    {
        throw_exception(
            File_Parse_Error("Compartment_Report_HDF5_File_Reader: "
                             "Dataset " + dataset_full_name + " not found "
                             "in file: " + filename.string()),
            FATAL_LEVEL, __FILE__, __LINE__);
    }
}
Example #3
0
/*********************************************************************\
	Function name    : CCompareTableDialog::SaveResult
	Description      :
	Created at       : 10.10.01, @ 22:16:07
	Created by       : Thomas Kunert
	Modified by      :
\*********************************************************************/
void CCompareTableDialog::SaveResult()
{
	Filename fn;
	if (!fn.FileSelect(FILESELECTTYPE_ANYTHING, FILESELECT_SAVE, String())) return;

	Int32 lMaxLen = 0;

	Int32 a, lNumItems;
	lNumItems = m_wndOutputList.GetItemCount();

	for (a = 0; a < lNumItems; a++)
	{
		BaseContainer data;
		m_wndOutputList.GetItem(a, &data);
		lMaxLen = LMax(lMaxLen, data.GetString(COMPARE_LIST_NAME).GetLength());
	}
	lMaxLen += 2;

	AutoAlloc <BaseFile> pFile;
	if (!pFile)
		return;

	pFile->Open(fn, FILEOPEN_WRITE);
	for (a = 0; a < lNumItems; a++)
	{
		BaseContainer data;
		m_wndOutputList.GetItem(a, &data);
		String str = data.GetString(COMPARE_LIST_NAME);
		WriteString(pFile, str);
		Int32 b = lMaxLen - str.GetLength();
		while (b--) WriteString(pFile, " ");
		WriteString(pFile, data.GetString(COMPARE_LIST_DATA));
		LineBreak(pFile, "");
	}
}
Example #4
0
void Level::load_from_file(const Filename& filename)
{
    clear();
    status = GOOD;

    level_filename = filename.get_rootless();

    FileFormat fmt = get_file_format(filename);
    if (fmt == FORMAT_BINARY) {
        // load an original .LVL file from L1/ONML/...
        load_from_binary(filename);
    }
    else if (fmt == FORMAT_LEMMINI) {
        // load an .INI file from Lemmini
        load_from_lemmini(filename);
    }
    else {
        // load the regular Lix format
        std::vector <IO::Line> lines;
        if (IO::fill_vector_from_file(lines, filename.get_rootful())) {
            load_from_vector(lines);
        }
        else status = BAD_FILE_NOT_FOUND;
    }
    load_finalize();
}
Example #5
0
void IsisMain() {
  
  UserInterface &ui = Application::GetUserInterface();
  bool append = ui.GetBoolean("APPEND");
  Pvl input (ui.GetFilename("FROM"));
  Pvl output;

  // Check to see if output file exists
  Filename outFile = ui.GetFilename("TO");
  if (outFile.exists()&&!append) {
    string msg = "Output file [" + outFile.Expanded() + "] already exists.";
    msg += " Append option set to False.";
    throw iException::Message(iException::User,msg,_FILEINFO_);
  }

  int numErrors = 0;
  // Search for errors and add to output
  for (int i =0; i < input.Objects(); i++) {
    PvlObject o = input.Object(i);
    if (o.HasGroup("Error")) {
      output.AddObject(o);
      numErrors++;
    }
  }
  PvlKeyword errors("TotalErrors",numErrors);
  output.AddKeyword(errors);
  // write output to file
  if (!append) {
    output.Write(outFile.Expanded());
  } else {
    output.Append(outFile.Expanded());
  }
  cout << errors << endl;
}
void ApplinkDialog::Timer(const BaseContainer &msg)
{
	Bool b;
	GetBool(IDC_CHK_PROMPT, b);
	if(b)
	{
		Filename fn;
		fn.SetDirectory(gPreferences.GetString(IDC_EXCH_FOLDER));
		fn.SetFile("export.txt");
        
		if(GeFExist(fn))
		{
			GePrint("File exists!");
			SetTimer(0);
			if(GeOutString("To import a new object?", GEMB_OKCANCEL) == GEMB_R_OK)
			{
				GePrint("Start import!");
				BaseDocument* doc = GetActiveDocument();
				ApplinkImporter* importer = NewObjClear(ApplinkImporter);
				importer->Execute(doc, &gPreferences);
				SetTimer(1000);
			}
			else
			{
				SetBool(IDC_CHK_PROMPT, false);
			}
		}
	}
}
/**
 * Program entry point.
 */
int main(int argc, char *argv[ ])
{
	SetupSharedThread::install();
	SetupSharedDebug::install(4096);

	{
		SetupSharedFoundation::Data data(SetupSharedFoundation::Data::D_console);
#ifdef WIN32
		char buffer[1024];
		GetModuleFileName(GetModuleHandle(NULL), buffer, 1024);
		Filename configName;
		configName.setName(buffer);
		configName.setName("templateCompiler.cfg");
		data.configFile = configName.getFullFilename().c_str();
#endif
		SetupSharedFoundation::install (data);
	}

	SetupSharedRegex::install();

	SetupSharedCompression::install();
	SetupSharedFile::install(false);

	// setup the random number generator
	// @todo need a better seed
	SetupSharedRandom::install(static_cast<uint32>(time(NULL)));

	int result = processArgs(argc, argv);

	// cleanup
	SetupSharedFoundation::remove();
	PerThreadData::threadRemove();

	return result;
}	// main
Example #8
0
Level::FileFormat Level::get_file_format(const Filename& filename)
{
    if (! ::exists(filename.get_rootful().c_str())) return FORMAT_NOTHING;
    std::ifstream file(filename.get_rootful().c_str(), std::ios::binary);
    // the length check before the read() was necessary for me on Linux
    // to get the Debugger past this, it got stuck on read() when nothing
    // was wrong.
    file.seekg (0, std::ios::end);
    if (file.tellg() < 8) {
        file.close();
        return FORMAT_NOTHING;
    }
    file.seekg(0, std::ios::beg);
    unsigned char buf[8];
    file.read((char*) &buf, 8);
    file.close();

    // A binary file has two-byte numbers in big endian
    // for rate, lixes, required, seconds at the beginning.
    // Neither should be > 0x00FF. If all of them are,
    // this is an ASCII file which shouldn't have '\0' chars.
    if (buf[0] == '\0' || buf[2] == '\0' || buf[4] == '\0' || buf[6] == '\0')
        return FORMAT_BINARY;

    // This isn't a binary file. Is it a Lemmini file?
    // Lemmini files start with "# LVL".
    else if (buf[0] == '#' && buf[1] == ' ' && buf[2] == 'L' && buf[3] == 'V')
        return FORMAT_LEMMINI;

    else return FORMAT_LIX;
}
void ApplinkExporter::ExportChannel(BaseDocument* document, BaseFile* file, BaseMaterial& material, LONG shaderId, LONG colorId, const String s)
{
	String str = s + " ";

	// get texture strength and base colour
	Vector color = getParameterVector(material, colorId);

	str += RealToString(color.x, NULL, 6) + " " + RealToString(color.y, NULL, 6) + " " + RealToString(color.z, NULL, 6) + "\n";
	this->WriteString(str, file);

	// fetch bitmap shader, if available
	BaseList2D* bitmapLink = ApplinkExporter::getParameterLink(material, shaderId, Xbitmap);

	if(bitmapLink)
	{
		// if we are here, we've got a bitmap shader -> let's create an imagemap texture
		Filename bitmapPath = ApplinkExporter::getParameterFilename(*bitmapLink, BITMAPSHADER_FILENAME);
		Filename fullBitmapPath;
		GenerateTexturePath(document->GetDocumentPath(), bitmapPath, Filename(), &fullBitmapPath);

		str = "map_" + s + " ";
		str += fullBitmapPath.GetString() + "\n";
		this->WriteString(str, file);
	}
}
/**
 * Processes the args sent to main.
 */
int processArgs(int argc, char *argv[ ])
{
	if (argc < 3)
	{
		printSyntax();
		return 0;
	}

	//if (strcmp(argv[1], "-edit") == 0)
	//{
	//	for (int i = 2; i < argc; ++i)
	//	{
	//		int result = checkOut(argv[i]);
	//		if (result != 0)
	//			return result;
	//	}
	//}
	//else if (strcmp(argv[1], "-submit") == 0)
	//{
	//	for (int i = 2; i < argc; ++i)
	//	{
	//		int result = checkIn(argv[i]);
	//		if (result != 0)
	//			return result;
	//	}
	//}
	if (strcmp(argv[1], "-compile") == 0)
	{
		Filename filename;
		for (int i = 2; i < argc; ++i)
		{
			File::setBasePath("");
			filename.clear();
			filename.setExtension(TEMPLATE_DEFINITION_EXTENSION);
			filename.setName(argv[i]);
			File fp(filename, "rt");
			if (!fp.isOpened())
			{
				fprintf(stderr, "cannot open file %s\n", argv[i]);
				return -1;
			}
			else
			{
				File::setBasePath(filename.getPath().c_str());
				int result = parseTemplateDefinitionFile(fp);
				fp.close();
				if (result != 0)
					return result;
			}
		}
	}
	else
	{
		printSyntax();
		return 0;
	}

	return 0;
}	// processArgs
Example #11
0
/*********************************************************************\
	Function name    : CLanguageList::Init
	Description      :
	Created at       : 26.09.01, @ 16:11:23
	Created by       : Thomas Kunert
	Modified by      :
\*********************************************************************/
void CLanguageList::Init()
{
	Filename resourcepath = GeGetStartupPath() + Filename("resource");

	if (GetC4DVersion() >= 16000) {
		// R16 has a new resource directory structure. The c4d_language.str
		// files we are searching for are in resource/modules/c4dplugin/strings_xx.
		// Fix for https://github.com/nr-plugins/resedit/issues/4
		resourcepath = resourcepath + "modules" + "c4dplugin";
	}

	AutoAlloc <BrowseFiles> pBrowse;
	pBrowse->Init(resourcepath, false);

	while (pBrowse->GetNext())
	{
		if (pBrowse->IsDir())
		{
			Filename fn = pBrowse->GetFilename();
			if (fn.GetString().SubStr(0, 8).ToLower() == "strings_")
			{
				String idx = fn.GetString();
				idx.Delete(0, 8);

				Filename stringname = resourcepath + fn+Filename("c4d_language.str");
				AutoAlloc <BaseFile> pFile;
				if (!pFile)
					return;
				if (!GeFExist(stringname))
				{
					GeOutString("Missing c4d_language.str to identify the string directory!!!", GEMB_ICONEXCLAMATION);
				}
				else if (pFile->Open(stringname))
				{
					Int32 len = pFile->GetLength();
					Char *buffer = NewMemClear(Char,len + 2);
					if (buffer)
					{
						pFile->ReadBytes(buffer,len);
						buffer[len]=0;

						Int32 i;

						for (i = 0; i < len && buffer[i] >= ' '; i++) { }
						buffer[i] = 0;

						for (i--; i > 0 && buffer[i]== ' '; i--) { }
						buffer[i + 1] = 0;

						AddLanguage(buffer, idx);
						DeleteMem(buffer);
					}
				}
			}
		}
	}

	CriticalAssert(GetNumLanguages() > 0);
}
Example #12
0
Bool ApplinkExporter::WriteMatsFile(BaseDocument* document, BaseContainer* bc)
{
	Filename filenameMTL;
	filenameMTL.SetDirectory(bc->GetString(IDC_TMP_FOLDER));
	filenameMTL.SetFile(document->GetDocumentName());
	filenameMTL.SetSuffix("mtl");
	
	GePrint(filenameMTL.GetString());

	AutoAlloc<BaseFile> fileMTL;
		
	if (!fileMTL->Open(filenameMTL, FILEOPEN_WRITE, FILEDIALOG_NONE, GeGetByteOrder())) return FALSE;
	
	for(LONG i=0; i < materialArray.GetCount(); i++)
	{
		BaseMaterial* mat = materialArray[i];
		
		String str;
		str = "newmtl " + mat->GetName() + "\n";
		this->WriteString(str, fileMTL);

		//Ka
		str = "Ka 0.300000 0.300000 0.300000\n";
		this->WriteString(str, fileMTL);

/////////////////////////////////////////////////////////

////////////////////////////////////////////////////////
		//Kd
		if(getParameterLong(*mat, MATERIAL_USE_COLOR))
		{
			ExportChannel(document, fileMTL, *mat, MATERIAL_COLOR_SHADER, MATERIAL_COLOR_COLOR, "Kd");
		}

		//Ks
		if(getParameterLong(*mat, MATERIAL_USE_REFLECTION))
		{
			ExportChannel(document, fileMTL, *mat, MATERIAL_REFLECTION_SHADER, MATERIAL_REFLECTION_COLOR, "Ks");
		}

		//Ns
		str = "Ns 50.000000\n";
		this->WriteString(str, fileMTL);

		//Tr
		str = "Tr 0.000000\n";
		this->WriteString(str, fileMTL);

		//illum
		str = "illum 2\n";
		this->WriteString(str, fileMTL);
		this->WriteEndLine(fileMTL);
	}

	fileMTL->Close();

	return TRUE;
}
Bool CSVNodeData::UpdateCSVTable(GvNode* node, GvRun* run, GvCalc* calc) {
    BaseDocument* doc = node->GetDocument();
    if (m_initCsv) return TRUE;

    // Obtain data to update the CSV Table. If *all* of those
    // succeeded, the CSV table is updated.
    GvPortCalc pCalc(node, &m_values, run, calc);
    Bool header;
    LONG delimiter;
    Filename filename;

    GvPort* pHeader = pCalc.GetInPort(CSVNODE_HEADER);
    if (pHeader && pHeader->GetBool(&header, run)) ;
    else return TRUE;

    GvPort* pDelimiter = pCalc.GetInPort(CSVNODE_DELIMITER);
    if (pDelimiter && pDelimiter->GetInteger(&delimiter, run)) ;
    else return TRUE;

    Bool ok = FALSE;
    GvPort* pFilename = pCalc.GetInPort(CSVNODE_FILENAME);
    filename = GvGetPortGeData(node, pFilename, run, &ok).GetFilename();
    if (!ok) return TRUE;

    // We now initialize the CSV Table and want to prevent any
    // further initialization in the calculation cycle.
    m_initCsv = TRUE;

    // Validate and set the data to the CSV Table object.
    if (m_pHeader != header) {
        m_forceUpdate = TRUE;
    }
    m_pHeader = header;
    m_table.SetHasHeader(header);

    if (delimiter < 0 || delimiter > 255) {
        delimiter = CSVNODE_DELIMITER_COMMA;
    }
    if (m_pDelimiter != delimiter) {
        m_forceUpdate = TRUE;
    }
    m_pDelimiter = delimiter;
    m_table.SetDelimiter((CHAR) delimiter);

    // Make the CSV Filename relative to the node's document if the file
    // does not exist.
    if (doc && filename.Content() && !GeFExist(filename)) {
        filename = doc->GetDocumentPath() + filename;
    }

    // Update the CSV Table.
    Bool updated = FALSE;
    Bool success = m_table.Init(filename, m_forceUpdate, &updated);
    m_forceUpdate = FALSE;

    return success;
}
Example #14
0
bool DeriveProduct::execute(PlugInArgList* pInArgList, PlugInArgList* pOutArgList)
{
   StepResource pStep("Execute Wizard Item", "app", "58FE5CAB-E941-4E60-BA55-B29D70715FC4");
   pStep->addProperty("Item", getName());
   mpStep = pStep.get();

   if (!extractInputArgs(pInArgList))
   {
      reportError("Unable to extract input arguments.", "5E158F48-6089-4A88-ABD0-55C717BD13E2");
      return false;
   }
   View* pView = pInArgList->getPlugInArgValue<View>("View");
   if (pView == NULL)
   {
      std::vector<Window*> windows;
      Service<DesktopServices>()->getWindows(SPATIAL_DATA_WINDOW, windows);
      if (!windows.empty())
      {
         pView = static_cast<SpatialDataWindow*>(windows.front())->getSpatialDataView();
      }
   }
   if (pView == NULL)
   {
      reportError("No view provided.", "852F585B-D239-4C0A-B993-70EE68EC8DEE");
      return false;
   }

   ProductWindow* pProductWindow = Service<DesktopServices>()->deriveProduct(pView);
   if (pProductWindow == NULL)
   {
      reportError("Unable to derive product", "E24BB5A5-A675-4897-9C48-A4E4109379DF");
      return false;
   }

   // Load a template if one is specified
   Filename* pTemplate = pInArgList->getPlugInArgValue<Filename>("Template");
   if (pTemplate != NULL)
   {
      if (!pProductWindow->getProductView()->loadTemplate(pTemplate->getFullPathAndName()))
      {
         reportError("Could not load the requested template!", "C99CE97E-3F0F-4CBB-8460-28D96D55596B");
         return false;
      }
   }

   // Set the output values
   if (!pOutArgList->setPlugInArgValue("Window", pProductWindow) ||
      !pOutArgList->setPlugInArgValue("View", pProductWindow->getProductView()))
   {
      reportError("Could not set the data set output value!", "3C53EDAE-DC70-4141-9759-ECD3EB9BE186");
      return false;
   }

   reportComplete();
   pStep->finalize(Message::Success);
   return true;
}
Example #15
0
//Function to translate the labels
void TranslateLrocNacLabels ( Filename &labelFile, Cube *ocube ) {

    //Pvl to store the labels
    Pvl outLabel;
    //Set up the directory where the translations are
    PvlGroup dataDir(Preference::Preferences().FindGroup("DataDirectory"));
    iString transDir = (string) dataDir["Lro"] + "/translations/";
    Pvl labelPvl(labelFile.Expanded());

    //Translate the Instrument group
    Filename transFile(transDir + "lronacInstrument.trn");
    PvlTranslationManager instrumentXlator(labelPvl, transFile.Expanded());
    instrumentXlator.Auto(outLabel);

    //Translate the Archive group
    transFile = transDir + "lronacArchive.trn";
    PvlTranslationManager archiveXlater(labelPvl, transFile.Expanded());
    archiveXlater.Auto(outLabel);

    // Set up the BandBin groups
    PvlGroup bbin("BandBin");
    bbin += PvlKeyword("FilterName", "BroadBand");
    bbin += PvlKeyword("Center", 0.650, "micrometers");
    bbin += PvlKeyword("Width", 0.150, "micrometers");

    Pvl lab(labelFile.Expanded());

    //Set up the Kernels group
    PvlGroup kern("Kernels");
    if (lab.FindKeyword("FRAME_ID")[0] == "LEFT")
        kern += PvlKeyword("NaifFrameCode", -85600);
    else
        kern += PvlKeyword("NaifFrameCode", -85610);

    PvlGroup inst = outLabel.FindGroup("Instrument", Pvl::Traverse);
    if (lab.FindKeyword("FRAME_ID")[0] == "LEFT") {
        inst.FindKeyword("InstrumentId") = "NACL";
        inst.FindKeyword("InstrumentName") = "LUNAR RECONNAISSANCE ORBITER NARROW ANGLE CAMERA LEFT";
        g_flip = false;
    }
    else {
        inst.FindKeyword("InstrumentId") = "NACR";
        inst.FindKeyword("InstrumentName") = "LUNAR RECONNAISSANCE ORBITER NARROW ANGLE CAMERA RIGHT";
    }

    inst += PvlKeyword("SpatialSumming", lab.FindKeyword("CROSSTRACK_SUMMING")[0] );
    inst += PvlKeyword("SampleFirstPixel", 0 );

    //Add all groups to the output cube
    ocube->PutGroup(inst);
    ocube->PutGroup(outLabel.FindGroup("Archive", Pvl::Traverse));
    ocube->PutGroup(bbin);
    ocube->PutGroup(kern);
}
Example #16
0
void DirList::set_current_dir(const Filename& s) {
    if (current_dir == s) return;
    // Wenn wirklich neu...
    if (s.is_child_of(base_dir)) {
        current_dir = Filename(s.get_dir_rootful());
    }
    else {
        current_dir = base_dir;
    }
    load_current_dir();
}
 Status BinCommon::rd_value(CommandInitiator* thread, Filename& value)  
 {
   uint size;
   Status status = rd_value(thread, size);
   if (status == OK && size > 0) {
     value = Filename(size+1);
     if ((status = rd_bytes(thread, size, (char*)value.data())) != OK) return status;
     ((char*)value.data())[size]=0;
   } else {
     value = Filename();
   }
   return status;   
 }
Example #18
0
void IsisMain() {

  // Open the input cube
  UserInterface &ui = Application::GetUserInterface();
  Filename fname = ui.GetFilename("FROM");
  string name = fname.Basename();
  bool rmv = ui.GetBoolean("REMOVE");

  // Run a standard deviation filter on the cube
  string inFile = ui.GetFilename("FROM");
  string outFile = name + ".step1.cub";
  string parameters = "FROM=" + inFile + " TO=" + outFile 
    + " toldef=stddev flattol=10 line=9 samp=9 minimum=9 tolmin=4.0 tolmax=4.0"
    + " replace=null";
  Isis::iApp ->Exec("noisefilter",parameters);

  // Run a standard deviation filter on the cube 
  inFile = outFile;
  outFile = name + ".step2.cub";
  parameters = "FROM=" + inFile + " TO=" + outFile + 
    " toldef=stddev flattol=10 line=3 samp=3 minimum=3 tolmin=3.5 tolmax=3.5";
  Isis::iApp ->Exec("noisefilter",parameters);
  if (rmv) remove(inFile.c_str());

  // Run a standard deviation filter on the cube
  inFile = outFile;
  outFile = name + ".step3.cub";
  parameters = "FROM=" + inFile + " TO=" + outFile 
    + " toldef=stddev flattol=10 samp=9 line=9 minimum=9 tolmin=4.0 tolmax=4.0"
    + " replace=null";
  Isis::iApp ->Exec("noisefilter",parameters);
  if (rmv) remove(inFile.c_str());

  // Run a standard deviation filter on the cube
  inFile = outFile;
  outFile = name + ".step4.cub";
  parameters = "FROM=" + inFile + " TO=" + outFile + 
    " toldef=stddev samp=3 line=3 minimum=3 tolmin=3.5 tolmax=3.5";
  Isis::iApp ->Exec("noisefilter",parameters);
  if (rmv) remove(inFile.c_str());

  // Run a lowpass filter on the cube
  inFile = outFile;
  outFile = ui.GetFilename("TO");
  parameters = "FROM=" + inFile + " TO=" + outFile + 
    " filter=outside samp=3 line=3 minimum=5 replacement=null";
  Isis::iApp ->Exec("lowpass",parameters);
  if (rmv) remove(inFile.c_str());
}
Example #19
0
/*********************************************************************\
	Function name    : CLanguageList::Init
	Description      :
	Created at       : 26.09.01, @ 16:11:23
	Created by       : Thomas Kunert
	Modified by      :
\*********************************************************************/
void CLanguageList::Init()
{
	Filename resourcepath = GeGetStartupPath() + Filename("resource");
	AutoAlloc <BrowseFiles> pBrowse;
	pBrowse->Init(resourcepath, false);

	while (pBrowse->GetNext())
	{
		if (pBrowse->IsDir())
		{
			Filename fn = pBrowse->GetFilename();
			if (fn.GetString().SubStr(0, 8).ToLower() == "strings_")
			{
				String idx = fn.GetString();
				idx.Delete(0, 8);

				Filename stringname = resourcepath + fn+Filename("c4d_language.str");
				AutoAlloc <BaseFile> pFile;
				if (!pFile)
					return;
				if (!GeFExist(stringname))
				{
					GeOutString("Missing c4d_language.str to identify the string directory!!!", GEMB_ICONEXCLAMATION);
				}
				else if (pFile->Open(stringname))
				{
					Int32 len = pFile->GetLength();
					Char *buffer = NewMemClear(Char,len + 2);
					if (buffer)
					{
						pFile->ReadBytes(buffer,len);
						buffer[len]=0;

						Int32 i;

						for (i = 0; i < len && buffer[i] >= ' '; i++) { }
						buffer[i] = 0;

						for (i--; i > 0 && buffer[i]== ' '; i--) { }
						buffer[i + 1] = 0;

						AddLanguage(buffer, idx);
						DeleteMem(buffer);
					}
				}
			}
		}
	}
}
Example #20
0
DirList::DirList(const int x,  const int y,
                 const int xl, const int yl,
                 const Filename& bdir, const Filename& cdir)
:
    Frame(x, y, xl, yl),
    page         (0),
    bottom_button(yl/20-1),
    base_dir     (bdir.get_dir_rootful()),
    current_dir  (cdir.is_child_of(bdir) ? Filename(cdir.get_dir_rootful())
                                         : base_dir),
    clicked      (false)
{
    load_current_dir();
    set_undraw_color(color[COL_API_M]);
}
Example #21
0
void IsisMain () {
  // Grab the file to import
  UserInterface &ui = Application::GetUserInterface();
  Filename in = ui.GetFilename("FROM");
  Filename out = ui.GetFilename("TO");
 
  // Make sure it is a Clementine EDR
  bool projected;
  try {
    Pvl lab(in.Expanded());
    projected = lab.HasObject("IMAGE_MAP_PROJECTION");
    iString id;
    id = (string)lab["DATA_SET_ID"];
    id.ConvertWhiteSpace();
    id.Compress();
    id.Trim(" ");
    if (id.find("CLEM") == string::npos) {
      string msg = "Invalid DATA_SET_ID [" + id + "]";
      throw iException::Message(iException::Pvl,msg,_FILEINFO_);
    }
  }
  catch (iException &e) {
    string msg = "Input file [" + in.Expanded() + 
                 "] does not appear to be " +
                 "in Clementine EDR format";
    throw iException::Message(iException::Io,msg, _FILEINFO_);
  }

  //Checks if in file is rdr
  if( projected ) {
    string msg = "[" + in.Name() + "] appears to be an rdr file.";
    msg += " Use pds2isis.";
    throw iException::Message(iException::User,msg, _FILEINFO_);
  }

  //Decompress the file
  long int lines = 0;
  long int samps = 0;
  iString filename = in.Expanded();
  pdsi = PDSR((char *)filename.c_str(),&lines,&samps);

  ProcessByLine p;
  CubeAttributeOutput cubeAtt("+unsignedByte+1.0:254.0");
  Cube *ocube = p.SetOutputCube(ui.GetFilename("TO"), cubeAtt, pdsi->image_ncols, pdsi->image_nrows);
  p.StartProcess (WriteLine);
  TranslateLabels(in, ocube);
  p.EndProcess ();
}
Example #22
0
void TranslateHiriseEdrLabels (Filename &labelFile, Cube *ocube) {

    //Create a PVL to store the translated labels
    Pvl outLabel;

    // Get the directory where the MRO HiRISE translation tables are.
    PvlGroup dataDir (Preference::Preferences().FindGroup("DataDirectory"));
    iString transDir = (string) dataDir["Mro"] + "/translations/";

    // Get a filename for the HiRISE EDR label
    Pvl labelPvl (labelFile.Expanded());

    // Translate the Instrument group
    Filename transFile (transDir + "hiriseInstrument.trn");
    PvlTranslationManager instrumentXlater (labelPvl, transFile.Expanded());
    instrumentXlater.Auto (outLabel);

    // Translate the BandBin group
    transFile  = transDir + "hiriseBandBin.trn";
    PvlTranslationManager bandBinXlater (labelPvl, transFile.Expanded());
    bandBinXlater.Auto (outLabel);

    // Translate the Archive group
    transFile  = transDir + "hiriseArchive.trn";
    PvlTranslationManager archiveXlater (labelPvl, transFile.Expanded());
    archiveXlater.Auto (outLabel);

    // Create the Instrument group keyword CcdId from the ProductId
    // SCS 28-03-06 Do it in the instrument translation table instead of here
//  PvlGroup &archiveGroup(outLabel.FindGroup("Archive", Pvl::Traverse));
//  iString productId = (string)archiveGroup.FindKeyword("ProductId");
//  productId.Token("_");
//  productId.Token("_");
//  productId = productId.Token("_");
//  outLabel.FindGroup("Instrument", Pvl::Traverse) +=
//      PvlKeyword ("CcdId", productId);

    // Create the Kernel Group
    PvlGroup kerns("Kernels");
    kerns += PvlKeyword("NaifIkCode", "-74699");

    // Write the Instrument, BandBin, Archive, and Kernels groups to the output
    // cube label
    ocube->PutGroup (outLabel.FindGroup("Instrument", Pvl::Traverse));
    ocube->PutGroup (outLabel.FindGroup("BandBin", Pvl::Traverse));
    ocube->PutGroup (outLabel.FindGroup("Archive", Pvl::Traverse));
    ocube->PutGroup (kerns);
}
/**
 * Tests if a template file name is valid for this definition.
 *
 * @param name		the template file name
 *
 * @return true if the name is valid, false if not
 */
bool TemplateDefinitionFile::isValidTemplateName(const Filename & name) const
{
	if (m_templateNameFilter.empty())
	{
		if (m_baseDefinitionFile != NULL)
			return m_baseDefinitionFile->isValidTemplateName(name);
		else
			return true;
	}

	int const maxCaptureCount       = 10;
	int const matchDataElementCount = maxCaptureCount * 3;
	int       matchData[matchDataElementCount];

	int const matchCode = pcre_exec(m_filterCompiledRegex, NULL, name.getName().c_str(), name.getName().length(), 0, 0, matchData, matchDataElementCount);
	bool const result = (matchCode >= 0);

	if (matchCode < -1)
	{
		fprintf(stderr, "ERROR: pcre_exec() failed, error code [%d].\n", matchCode);
		return false;
	}

	return result;
}	// TemplateDefinitionFile::isValidTemplateName
Example #24
0
bool WavelengthExporter::extractInputArgs(PlugInArgList* pArgList)
{
   VERIFY(pArgList != NULL);

   mpProgress = pArgList->getPlugInArgValue<Progress>(Executable::ProgressArg());

   mpWavelengths = pArgList->getPlugInArgValue<Wavelengths>(Wavelengths::WavelengthsArg());
   if (mpWavelengths == NULL)
   {
      string message = "The " + Wavelengths::WavelengthsArg() + " input value is invalid.";
      if (mpProgress != NULL)
      {
         mpProgress->updateProgress(message, 0, ERRORS);
      }

      mpStep->finalize(Message::Failure, message);
      return false;
   }

   Filename* pFilename = pArgList->getPlugInArgValue<Filename>(Wavelengths::WavelengthFileArg());
   if (pFilename == NULL)
   {
      string message = "The " + Wavelengths::WavelengthFileArg() + " input value is not present.";
      if (mpProgress != NULL)
      {
         mpProgress->updateProgress(message, 0, ERRORS);
      }

      mpStep->finalize(Message::Failure, message);
      return false;
   }

   mFilename = pFilename->getFullPathAndName();
   if (mFilename.empty() == true)
   {
      string message = "The " + Wavelengths::WavelengthFileArg() + " input value is invalid.";
      if (mpProgress != NULL)
      {
         mpProgress->updateProgress(message, 0, ERRORS);
      }

      mpStep->finalize(Message::Failure, message);
      return false;
   }

   return true;
}
Example #25
0
bool Editor::search_criterion_hazard(const Filename& s) {
    if (s.get_extension() == gloB->ext_object_definitions) return false;
    const Object* ob = ObjLib::get(s);
    return ob && (ob->type == Object::TRAP
     ||           ob->type == Object::WATER
     ||           ob->type == Object::FLING
     ||           ob->type == Object::TRAMPOLINE);
}
Example #26
0
/*********************************************************************\
	Function name    : CResEditBrowser::BrowsePath
	Description      :
	Created at       : 26.09.01, @ 11:59:42
	Created by       : Thomas Kunert
	Modified by      :
\*********************************************************************/
void CResEditBrowser::BrowsePath(Filename fn)
{
	AutoAlloc <BrowseFiles> pBrowse;
	pBrowse->Init(fn, false);

	Filename fnBrowse;
	TreeViewItem* pNewItem;

	//TRACE_STRING(fn.GetString());

	while (pBrowse->GetNext())
	{
		fnBrowse = pBrowse->GetFilename();
		if (pBrowse->IsDir())
		{
			BrowsePath(fn + fnBrowse);
			continue;
		}
		pNewItem = nullptr;
		if (fnBrowse.CheckSuffix("res"))
			pNewItem = m_wndTreeView.AddItem(fnBrowse.GetFileString(), m_pDialogsItem);
		else if (fnBrowse.CheckSuffix("tif") || fnBrowse.CheckSuffix("jpg") || fnBrowse.CheckSuffix("bmp"))
			pNewItem = m_wndTreeView.AddItem(fnBrowse.GetFileString(), m_pImagesItem);

		if (pNewItem)
			pNewItem->GetData()->SetString(ITEM_PATH_NAME, (fn + fnBrowse).GetString());
	}
}
Example #27
0
/**
 * Prepends a path to our path, unless our path is an an absolute path.
 *
 * @param path		the path to prepend
 */
void Filename::prependPath(const Filename &path)
{
	if (m_path.size() != 0 && m_path[0] != PATH_SEPARATOR)
	{
		m_path = path.getPath() + m_path;
		convertToSystemPath(m_path);
		makeFullPath();
	}
}	// Filename::prependPath
int main(int argc, char* argv[])
{
  printWorkingDir();

  char* fileName = "..\\..\\..\\..\\data\\tests\\testVFS.p3d";

  if( !file_exists(fileName) )
  {
    printf("Multifile could not be found\n");
    return -1;
  }

  VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr();
  bool bResult = vfs->mount(fileName, ".", VirtualFileSystem::MF_read_only);
  if( !bResult )
  {
    printf("Could not mount multifile\n");
    return -1;
  }
  else
  {
    printf("Multifile mounted\n");
  }

  PT(VirtualFileList) vfl = vfs->scan_directory(Filename("."));
  if( vfl == 0 ) printf("Scanning failed\n");

  int numFiles = vfl->get_num_files();
  printf("Found %d files\n",numFiles);

  for(int i=0; i<numFiles; i++ )
  {
    VirtualFile* vf = vfl->get_file(i);
    Filename fn = vf->get_filename();
    std:string str = fn.get_basename();
    printf( "%d: %s\n", i, str.c_str() );
  }

  //vfs->mount("./foo.mf", ".", VirtualFileSystem::MF_read_only);
  //istream* is = vfs.open_read_file("test",true);
  //cout << vfs;
  printf("Test\n");
	return 0;
}
Example #29
0
void AssetEnumerator::CreateFromFilename(const Filename& filename)
	{
	// First, try and get the directory from the archive manager, if it is present
	if (ArchiveManager::IsInstanceCreated())
		{
		archiveDirectory_=siArchiveManager->GetDirectory(filename.GetStringId());
		}

	// If we couldn't get the directory from the archive manager, try to get it from the file system, if it is present
	if (!archiveDirectory_ && Platform::GetPlatform_FileSystem())
		{
		directory_=Platform::GetPlatform_FileSystem()->CreateDirectoryObject(filename.GetString());
		}

	// If we couldn't get the directory from neither the archive manager nor the filesystem, we trigger an assert for
	// debug builds, and just reports the directory as being empty for release builds.
	Assert(archiveDirectory_ || directory_,
		"Error creating AssetEnumerator - No filesystem or archive manager present, or directory not found.");
	}
Example #30
0
/**
 * Appends a path to our path. If the path is an absolute path, replaces our path.
 *
 * @param path		the path to append
 */
void Filename::appendPath(const Filename &path)
{
	std::string localpath = path.getPath();
	convertToSystemPath(localpath);
	if (localpath.size() != 0 && localpath[0] == PATH_SEPARATOR)
		m_path = localpath;
	else
		m_path += localpath;
	makeFullPath();
}	// Filename::appendPath