Пример #1
0
FileMap::FileMap(uint32 _size) : size(_size) {
  if (!size)
    throw FileIOException("Filemap of 0 bytes not possible");
  data = (uchar8*)_aligned_malloc(size + FILEMAP_MARGIN, 16);
  if (!data) {
    throw FileIOException("Not enough memory to open file.");
  }
  mOwnAlloc = true;
}
Пример #2
0
    void XercesParser::parseXMLFile(XMLHandler& handler, const String& filename, const String& schemaName, const String& resourceGroup)
    {
        XERCES_CPP_NAMESPACE_USE;

        XercesHandler xercesHandler(handler);

        // create parser
        SAX2XMLReader* reader = createReader(xercesHandler);

        try
        {
            // set up schema
            initialiseSchema(reader, schemaName, filename, resourceGroup);
            // do parse
            doParse(reader, filename, resourceGroup);
        }
        catch(const XMLException& exc)
        {
            if (exc.getCode() != XMLExcepts::NoError)
            {
                delete reader;

                char* excmsg = XMLString::transcode(exc.getMessage());
                String message("XercesParser::parseXMLFile - An error occurred at line nr. " + PropertyHelper::uintToString((uint)exc.getSrcLine()) + " while parsing XML file '" + filename + "'.  Additional information: ");
                message += excmsg;
                XMLString::release(&excmsg);

                throw FileIOException(message);
            }

        }
        catch(const SAXParseException& exc)
        {
            delete reader;

            char* excmsg = XMLString::transcode(exc.getMessage());
            String message("XercesParser::parseXMLFile - An error occurred at line nr. " + PropertyHelper::uintToString((uint)exc.getLineNumber()) + " while parsing XML file '" + filename + "'.  Additional information: ");
            message += excmsg;
            XMLString::release(&excmsg);

            throw FileIOException(message);
        }
        catch(...)
        {
            delete reader;

            Logger::getSingleton().logEvent("XercesParser::parseXMLFile - An unexpected error occurred while parsing XML file '" + filename + "'.", Errors);
            throw;
        }

        // cleanup
        delete reader;
    }
Пример #3
0
void DS::FileStream::open(const char* filename, const char* mode)
{
    close();
    m_file = fopen(filename, mode);
    if (!m_file)
        throw FileIOException(strerror(errno));
}
Пример #4
0
/** write the image to disk */
void GeoImage::write()
{
  QString fname = value("file");
  Q_ASSERT(!fname.isEmpty());
  switch (type_) {
  case PBM:
  case PGM:
  case PPM:
    qDebug("GeoImage::write: Format %d not supported", type_);
    break;
  default:{
    FILE *of = fopen(fname.toLatin1().constData(), "w");
    if (!of) {
      qWarning("GeoImage::write: (ERROR) Can't open file %s for writing!\n",
	      fname.toLatin1().constData());
      throw FileIOException(FileIOException::OPEN_FAILED, fname, 
			    __FILE__":GeoImage::write", __LINE__);
      return;
    }
    pfm_geo_set(geoWest(),geoNorth(),geoEast(),geoSouth());
    pfm_writepfm_type(of, data_, cols_, rows_, 1, -1, type_);
    fclose(of);
    break;
  }
  }
}
Пример #5
0
void ThrowFIE(const char* fmt, ...) {
  va_list val;
  va_start(val, fmt);
  char buf[8192];
  vsprintf_s(buf, 8192, fmt, val);
  va_end(val);
  _RPT1(0, "EXCEPTION: %s\n", buf);
  throw FileIOException(buf);
}
Пример #6
0
void XercesParser::parseXML(XMLHandler& handler, const RawDataContainer& source, const String& schemaName)
{
    XERCES_CPP_NAMESPACE_USE;

    XercesHandler xercesHandler(handler);

    // create parser
    SAX2XMLReader* reader = createReader(xercesHandler);

    CEGUI_TRY
    {
        // set up schema
        initialiseSchema(reader, schemaName);
        // do parse
        doParse(reader, source);
    }
    CEGUI_CATCH(const XMLException& exc)
    {
        if (exc.getCode() != XMLExcepts::NoError)
        {
            delete reader;

            char* excmsg = XMLString::transcode(exc.getMessage());
            String message("An error occurred at line nr. " + PropertyHelper<uint>::toString((uint)exc.getSrcLine()) + " while parsing XML.  Additional information: ");
            message += excmsg;
            XMLString::release(&excmsg);

            CEGUI_THROW(FileIOException(message));
        }

    }
    CEGUI_CATCH(const SAXParseException& exc)
    {
        delete reader;

        char* excmsg = XMLString::transcode(exc.getMessage());
        String message("An error occurred at line nr. " + PropertyHelper<uint>::toString((uint)exc.getLineNumber()) + " while parsing XML.  Additional information: ");
        message += excmsg;
        XMLString::release(&excmsg);

        CEGUI_THROW(FileIOException(message));
    }
Пример #7
0
//----------------------------------------------------------------------------//
void WindowManager::saveLayoutToFile(const Window& window,
                                     const String& filename) const
{
    std::ofstream stream(filename.c_str());

    if (!stream.good())
        throw FileIOException(
            "failed to create stream for writing.");

    writeLayoutToStream(window, stream);
}
Пример #8
0
    TinyXMLDocument::TinyXMLDocument(XMLHandler& handler, const String& filename, const String& schemaName, const String& resourceGroup)
    {
        d_handler = &handler;

        // use resource provider to load file data
        // Fixed using patch from tracker item #000057
        // cegui_mk2-0.4.1-fixtinyxml.patch
        RawDataContainer rawXMLData;
        System::getSingleton().getResourceProvider()->loadRawDataContainer(filename, rawXMLData, resourceGroup);

        // Create a buffer with extra bytes for a newline and a terminating null
        size_t size = rawXMLData.getSize();
        char* buf = new char[size + 2];
        memcpy(buf, rawXMLData.getDataPtr(), size);
        // PDT: The addition of the newline is a kludge to resolve an issue
        // whereby parse returns 0 if the xml file has no newline at the end but
        // is otherwise well formed.
        buf[size] = '\n';
        buf[size+1] = 0;

        // Parse the document
        CEGUI_TINYXML_NAMESPACE::TiXmlDocument doc;
        if (!doc.Parse((const char*)buf))
        {
            // error detected, cleanup out buffers
            delete[] buf;
            System::getSingleton().getResourceProvider()->
                unloadRawDataContainer(rawXMLData);
            // throw exception
            throw FileIOException("TinyXMLParser: an error occurred while "
                                  "parsing the XML document '" + filename +
                                  "' - check it for potential errors!.");
        }

        const CEGUI_TINYXML_NAMESPACE::TiXmlElement* currElement = doc.RootElement();
        if (currElement)
        {
            try
            {
                // function called recursively to parse xml data
                processElement(currElement);
            }
            catch(...)
            {
                delete [] buf;
                System::getSingleton().getResourceProvider()->unloadRawDataContainer(rawXMLData);
                throw;
            }
        } // if (currElement)

        // Free memory
        delete [] buf;
        System::getSingleton().getResourceProvider()->unloadRawDataContainer(rawXMLData);
    }
Пример #9
0
/** load image info - not the data */
void GeoImage::load()
{
  QString fname = filename();
  qDebug("GeoImage::load(%s)", fname.toLatin1().constData());
  FILE *fp;
  fp = fopen(fname.toLatin1().constData(), "r");
  if (!fp) {
    qDebug("#  (ERROR)GeoImage::load(%s) Can't open file for reading!",
           fname.toLatin1().constData());

    throw FileIOException(FileIOException::FILE_NOT_EXISTS, fname);
  }
  int pxmtype;
  xelval max_x;
  freeData();
  float minval_, maxval_;

  if (pfm_readpfm_header(fp, &cols_, &rows_, &minval_, &maxval_, &pxmtype))
    type_ = (IMGTYPE) pxmtype;  //0 = FALSE, 1 = TRUE
  else {                        /* now check for all the other p?m-formats */
    pnm_readpnminit(fp, &cols_, &rows_, &max_x, &pxmtype);
    rewind(fp);
    minval_ = 0.0;
    maxval_ = (float) max_x;
    if (pxmtype == PBM_FORMAT || pxmtype == RPBM_FORMAT)
      type_ = PBM;
    if (pxmtype == PGM_FORMAT || pxmtype == RPGM_FORMAT)
      type_ = PGM;
    if (pxmtype == PPM_FORMAT || pxmtype == RPPM_FORMAT)
      type_ = PPM;
  }
  fclose(fp);
  qDebug("##  Image: (%d, %d) %f - %f, type: %d",
         cols_, rows_, minval_, maxval_, type_);
  if (type_ == UNKNOWN)
    qDebug("##  (ERROR) unknown image type!");
#ifdef WIN32
  replace("size_x", &QString::number(cols_));
  replace("size_y", &QString::number(rows_));
  resolutionX_ = (geoEast_ - geoWest_) / cols_;
  replace("res_x", &QString::number(resolutionX_));
  resolutionY_ = (geoNorth_ - geoSouth_) / rows_;
  replace("res_y", &QString::number(resolutionY_));
#else
  replace("size_x", cols_);
  replace("size_y", rows_);
  resolutionX_ = (geoEast_ - geoWest_) / cols_;
  replace("res_x", resolutionX_);
  resolutionY_ = (geoNorth_ - geoSouth_) / rows_;
  replace("res_y", resolutionY_);
#endif
}
Пример #10
0
    std::string PicoJsonIF::readData(std::string fileName) {
        std::ifstream ifs(fileName, std::ifstream::in);
        //assert(!ifs.fail());

        if (ifs.fail()) {
            throw FileIOException("PicoJsonIF::readData() : cannot open file, fileName = " + fileName);
        }
        std::string contents;
        ifs.seekg(0, std::ios::end);
        contents.resize(ifs.tellg());
        ifs.seekg(0, std::ios::beg);
        ifs.read(&contents[0], contents.size());
        ifs.close();
        return (contents);
    }
Пример #11
0
    TinyXMLDocument::TinyXMLDocument(XMLHandler& handler, const RawDataContainer& source, const String& /*schemaName*/)
    {
        d_handler = &handler;

        // Create a buffer with extra bytes for a newline and a terminating null
        size_t size = source.getSize();
        char* buf = new char[size + 2];
        memcpy(buf, source.getDataPtr(), size);
        // PDT: The addition of the newline is a kludge to resolve an issue
        // whereby parse returns 0 if the xml file has no newline at the end but
        // is otherwise well formed.
        buf[size] = '\n';
        buf[size+1] = 0;

        // Parse the document
        TiXmlDocument doc;
        if (!doc.Parse((const char*)buf))
        {
            // error detected, cleanup out buffers
            delete[] buf;

            // throw exception
            throw FileIOException("an error occurred while "
                "parsing the XML document - check it for potential errors!.");
        }

        const TiXmlElement* currElement = doc.RootElement();
        if (currElement)
        {
            try
            {
                // function called recursively to parse xml data
                processElement(currElement);
            }
            catch (...)
            {
                delete [] buf;

                throw;
            }
        } // if (currElement)

        // Free memory
        delete [] buf;
    }
Пример #12
0
	/*************************************************************************
	SAX2 Handler methods
	*************************************************************************/
	void Animate_xmlHandler::elementStart(const String& element, const XMLAttributes& attributes)
	{
		// handle an Animate element (extract all element attributes and use data to define an Animate)
		if(element == AnimateManagerElement)
		{
		}
		else if(element == AnimateElement)
		{
			String	name(attributes.getValueAsString(AnimateNameAttribute));

			bool loop = attributes.getValueAsBool(AnimatePlayLoop);
	
			int id = attributes.getValueAsInteger(AnimateID, -1);

			int totalTime = attributes.getValueAsInteger(AnimateTime, -1);

			bool alpha = attributes.getValueAsBool( AnimateAlphaMode );

			int  loopType = attributes.getValueAsInteger(AnimateAlphaType, 1 );

			d_animate = AnimateManager::getSingleton().createAnimate(name, id, loop, totalTime, alpha, loopType );
		}
		else if (element == AniamteItemElement )
		{
			if(d_animate == 0)
			{
				throw GenericException("Aniamte::xmlHandler::startElement - Invalid file struct.");
			}
			const Image* pImage = PropertyHelper::stringToImage(attributes.getValueAsString(AniamteImage));
			if(pImage)
			{
				d_animate->defineAnimateKey(pImage);
				AnimateManager::getSingleton().addAnimateImageset(pImage->getImagesetName());
			}
		}
		else
		{
			throw FileIOException("Aniamte::xmlHandler::startElement - Unexpected data was found while parsing the animatefile: '" + element + "' is unknown.");
		}
	}
Пример #13
0
/*************************************************************************
    Define a glyph mapping (handle a <Mapping /> XML element)
*************************************************************************/
void Font::defineMapping (const XMLAttributes& attributes)
{
    throw FileIOException("Font::defineMapping - The <Mapping> XML element is not supported for this font type");
}
Пример #14
0
//----------------------------------------------------------------------------//
RapidXMLDocument::RapidXMLDocument(XMLHandler& handler,
                                   const String& filename,
                                   const String& /*schemaName*/,
                                   const String& resourceGroup)
{
    d_handler = &handler;

    // use resource provider to load file data
    RawDataContainer rawXMLData;
    System::getSingleton().getResourceProvider()->
        loadRawDataContainer(filename, rawXMLData, resourceGroup);

    // Create a buffer with extra bytes for a newline and a terminating null
    size_t size = rawXMLData.getSize();
    char* buf = new char[size + 2];
    memcpy(buf, rawXMLData.getDataPtr(), size);
    // PDT: The addition of the newline is a kludge to resolve an issue
    // whereby parse returns 0 if the xml file has no newline at the end but
    // is otherwise well formed.
    buf[size] = '\n';
    buf[size + 1] = 0;

    // Parse the document
    rapidxml::xml_document<> doc;    // character type defaults to char

    try
    {
        doc.parse<0>(buf);          // 0 means default parse flags
    }
    catch (...)
    {
        // error detected, cleanup out buffers
        delete[] buf;
        System::getSingleton().getResourceProvider()->
        unloadRawDataContainer(rawXMLData);
        // throw exception
        throw FileIOException("RapidXMLParser: an error occurred while "
                              "parsing the XML document '" + filename +
                              "' - check it for potential errors!.");
    }

    rapidxml::xml_node<>* currElement = doc.first_node();

    if (currElement)
    {
        try
        {
            // function called recursively to parse xml data
            processElement(currElement);
        }
        catch (...)
        {
            delete[] buf;
            System::getSingleton().getResourceProvider()->
                unloadRawDataContainer(rawXMLData);
            throw;
        }
    }

    // Free memory
    delete[] buf;
    System::getSingleton().getResourceProvider()->
        unloadRawDataContainer(rawXMLData);
}
Пример #15
0
/** return data */
const void *GeoImage::data()
{
  if (data_)
    return (void *) data_;
  qDebug("GeoImage::data() - load data");
  QString fname = filename();
  qDebug("GeoImage::data() %s", fname.toLatin1().constData());

  FILE *fp;
  fp = fopen(fname.toLatin1().constData(), "r");
  if (!fp) {
    qDebug("#  (ERROR)GeoImage::load(%s) Can't open file for reading!",
           fname.toLatin1().constData());
    throw FileIOException(FileIOException::FILE_NOT_EXISTS, fname, 
			  __FILE__":GeoImage::data", __LINE__);
    return 0;
  }
  int cols, rows;
  //float minval, maxval;
  switch (type_) {
  case PFM_FLOAT:
  case PFM_UINT:
  case PFM_SINT:
  case PFM_SINT16:
  case PFM_UINT16:
  case PFM_BYTE:
  case PFM_3BYTE:
    data_ = pfm_readpfm_type(fp, &cols, &rows, &minval_, &maxval_, type_, 0);
    testSize(cols, rows, type_);
    break;
  case PBM:
    data_ = (void *) pbm_readpbm(fp, &cols, &rows);
    minval_ = 0.0, maxval_ = 1.0;
    testSize(cols, rows, type_);
    break;
  case PGM:{
      gray maxval, **data_g;
      data_g = pgm_readpgm(fp, &cols, &rows, &maxval);
      data_ = (void *) data_g;
      minval_ = 0.0, maxval_ = (float) maxval;
      testSize(cols, rows, type_);
    }
    break;
  case PPM:
    pixval maxval;
    pixel **dat_p;
    dat_p = ppm_readppm(fp, &cols, &rows, &maxval);
    data_ = (void *) dat_p;
    minval_ = 0.0, maxval_ = (float) maxval;
    testSize(cols, rows, type_);
    break;
  default:
    qDebug("Unknown type %d",type_);
    fclose(fp);
    return 0;
  }
  fclose(fp);
  if (data_) dataSize_=rows_*cols_*sizeOfData(type_);
  cache_.useImage(this);
  return data_;
}
Пример #16
0
/*************************************************************************
SAX2 Handler methods
*************************************************************************/
void Font_xmlHandler::elementStart(const String& element, const XMLAttributes& attributes)
{
    // handle a Mapping element
    if (element == MappingElement)
    {
        if (!d_font->d_freetype)
        {
            String	image_name(attributes.getValueAsString(MappingImageAttribute));
            utf32 codepoint = (utf32)attributes.getValueAsInteger(MappingCodepointAttribute);
            int horzAdvance = attributes.getValueAsInteger(MappingHorzAdvanceAttribute, -1);

            Font::glyphDat	mapDat;
            mapDat.d_image = &d_font->d_glyph_images->getImage(image_name);

            // calculate advance width if it was not specified
            if (horzAdvance == AutoGenerateHorzAdvance)
            {
                horzAdvance = (int)(mapDat.d_image->getWidth() + mapDat.d_image->getOffsetX());
            }

            mapDat.d_horz_advance_unscaled = horzAdvance;
            mapDat.d_horz_advance = (uint)(((float)horzAdvance) * (d_font->d_autoScale ? d_font->d_horzScaling : 1.0f));
            d_font->d_cp_map[codepoint] = mapDat;
        }
        else
        {
            Logger::getSingleton().logEvent((utf8*)"Mapping element encountered.  This element is invalid for dynamic fonts.", Informative);
        }
    }
    // handle root Font element
    else if (element == FontElement)
    {
        // get name of font we are creating
        String font_name(attributes.getValueAsString(FontNameAttribute));

        // get filename for the font
        String filename(attributes.getValueAsString(FontFilenameAttribute));
        // get resource group for font file.
        String resourceGroup(attributes.getValueAsString(FontResourceGroupAttribute));

        Logger::getSingleton().logEvent("Started creation of Font '" + font_name + "' via XML file.", Informative);

        //
        // load auto-scaling configuration
        //
        float hres, vres;
        bool auto_scale;

        // get native horizontal resolution
        hres = (float)attributes.getValueAsInteger(FontNativeHorzResAttribute, 640);

        // get native vertical resolution
        vres = (float)attributes.getValueAsInteger(FontNativeVertResAttribute, 480);

        // get auto-scaling setting
        auto_scale = attributes.getValueAsBool(FontAutoScaledAttribute, false);

        //
        // get type of font
        //
        String	font_type(attributes.getValueAsString(FontTypeAttribute));

        // dynamic (ttf) font
        if (font_type == FontTypeDynamic)
        {
            // get size of font
            uint size = (uint)attributes.getValueAsInteger(FontSizeAttribute, 12);

            // extract codepoint range
            utf32 first_codepoint = (utf32)attributes.getValueAsInteger(FontFirstCodepointAttribute, 32);
            utf32 last_codepoint = (utf32)attributes.getValueAsInteger(FontLastCodepointAttribute, 127);

            // build string containing the required code-points.
            for (; first_codepoint <= last_codepoint; ++first_codepoint)
            {
                d_glyphSet += first_codepoint;
            }

            uint flags = attributes.getValueAsBool(FontAntiAliasedAttribute, true) ? 0 : NoAntiAlias;

            // perform pre-initialisation
            d_font->setNativeResolution(Size(hres, vres));
            d_font->setAutoScalingEnabled(auto_scale);

            // Finalise construction of font without glyphs.
            // Glyphs will defined after we know which ones we need.
            d_font->constructor_impl(font_name, filename, resourceGroup, size, flags, String(""));
        }
        // static (Imageset based) font
        else if (font_type == FontTypeStatic)
        {
            d_font->d_name = font_name;
            d_font->d_freetype = false;

            // load the Imageset
            d_font->d_glyph_images = ImagesetManager::getSingleton().createImageset(filename, resourceGroup);

            d_font->setNativeResolution(Size(hres, vres));
            d_font->setAutoScalingEnabled(auto_scale);
        }
        // error (should never happen)
        else
        {
            throw FileIOException("Font::xmlHandler::startElement - The unknown Font:Type attribute value '" + font_type + "' was encountered while processing the Font file.");
        }

        d_font->d_sourceFilename = filename;
    }
    // Glyph element
    else if (element == GlyphElement)
    {
        if (d_font->d_freetype)
        {
            utf32 codepoint = (utf32)attributes.getValueAsInteger(GlyphCodepointAttribute);

            if (d_glyphSet.find(codepoint) == String::npos)
            {
                d_glyphSet.append(1, codepoint);
            }
        }
        else
        {
            Logger::getSingleton().logEvent((utf8*)"Glyph element encountered.  This element is invalid for static fonts.", Informative);
        }
    }
    // GlyphRange element
    else if (element == GlyphRangeElement)
    {
        if (d_font->d_freetype)
        {
            utf32 start = (utf32)attributes.getValueAsInteger(GlyphRangeStartCodepointAttribute);
            utf32 end	= (utf32)attributes.getValueAsInteger(GlyphRangeEndCodepointAttribute);

            for (utf32 codepoint = start; codepoint <= end; ++codepoint)
            {
                if (d_glyphSet.find(codepoint) == String::npos)
                {
                    d_glyphSet.append(1, codepoint);
                }
            }

        }
        else
        {
            Logger::getSingleton().logEvent((utf8*)"GlyphRange element encountered.  This element is invalid for static fonts.", Informative);
        }
    }
    // GlyphSet element
    else if (element == GlyphSetElement)
    {
        if (d_font->d_freetype)
        {
            String glyphs(attributes.getValueAsString(GlyphSetGlyphsAttribute));

            for (String::size_type i = 0; i < glyphs.length(); ++i)
            {
                utf32 codepoint = glyphs[i];

                if (d_glyphSet.find(codepoint) == String::npos)
                {
                    d_glyphSet.append(1, codepoint);
                }

            }

        }
        else
        {
            Logger::getSingleton().logEvent((utf8*)"GlyphSet element encountered.  This element is invalid for static fonts.", Informative);
        }
    }
    // anything else is an error which *should* have already been caught by XML validation
    else
    {
        throw FileIOException("Font::xmlHandler::startElement - Unexpected data was found while parsing the Font file: '" + element + "' is unknown.");
    }

}
Пример #17
0
ssize_t DS::BlobStream::writeBytes(const void* buffer, size_t count)
{
    throw FileIOException("Cannot write to read-only stream");
}
Пример #18
0
/** Generate a mask image (pbm)  */
QString GeoImage::mask(float west, float north, float east, float south,
                       int id, QString prefixDir, QString fname)
{

#define GenMaskBlockStorage(T) \
{ \
	T* iptr; \
	bit *optr; \
	int x,y; \
	for (y = 0; y < dy; y++) { \
	  if (y<-ry1 || y>=rows_-ry1) iptr=0; \
	  else iptr = ((T*)data_p)+(y + ry1)*cols_+rx1; \
	 	optr = dat_b_out[y]; \
	  for (x = 0; x < dx; x++) { \
	    if (!iptr || x<-rx1 || x>=cols_-rx1) *optr=0; \
	  	else *optr=(*iptr==(T)id?1:0); \
	   	optr ++; \
	    if (iptr) iptr ++; \
	  } \
	} \
}

#define GenMaskRowStorage(T) \
{ \
	T* iptr; \
	bit *optr; \
	int x,y; \
	for (y = 0; y < dy; y++) { \
	  if (y<-ry1 || y>=rows_-ry1) iptr=0; \
	  else iptr = (((T**)data_p)[y + ry1]) + rx1; \
	 	optr = dat_b_out[y]; \
	  for (x = 0; x < dx; x++) { \
	    if (!iptr || x<-rx1 || x>=cols_-rx1) *optr=0; \
	  	else *optr=(*iptr==(T)id?1:0); \
	   	optr ++; \
	    if (iptr) iptr ++; \
	  } \
	} \
}

  if (fname.isEmpty()) {        //create output filname
    Q_ASSERT(contains("key"));
    QString dir = CleanUp::mkdir(CleanUp::getTmpDirPID(), prefixDir);
    fname.sprintf("%s/%f_%f_%f_%f.pbm", 
		  dir.toLatin1().constData(),
                  west, north, east, south);
    qDebug("GeoImage::mask: create output filename %s",fname.toLatin1().constData());
  }
  qDebug("#  GeoImage::mask %s (%f, %f, %f, %f)", fname.toLatin1().constData(),
         west, north, east, south);
  QFile f(fname);
  if (f.exists()) {
    qDebug("mask %s already exists",fname.toLatin1().constData());
    return fname;
  }  

  const void *data_p = data();        //get pointer to data
  Q_ASSERT(data_p);
  if (type_ == UNKNOWN)
    throw ImageException(ImageException::UnknownType,  filename(),
			 __FILE__":GeoImage::mask", __LINE__);
  int dx, dy, rx1, ry1, rx2, ry2;
  picBBox(west, north, east, south, rx1, ry2, rx2, ry1);
  qDebug("GeoImage::mask: picBBox: (%f, %f, %f, %f) (rx1=%d, ry2=%d, rx2=%d, ry1=%d",
	 west, north, east, south, rx1, ry2, rx2, ry1);
  dx = rx2 - rx1 + 1;
  dy = ry2 - ry1 + 1;
  if (dx <= 0 || dy <= 0) {
    throw ImageException(ImageException::Dimension, rx1, rx2, dx, ry1, ry2, dy, 
			 __FILE__":GeoImage::mask", __LINE__);
  }

  FILE *of = fopen(fname.toLatin1().constData(), "w");
  if (!of) {
    throw FileIOException(FileIOException::OPEN_FAILED, fname, 
			  __FILE__":GeoImage::mask", __LINE__);
    return "";
  }

  bit **dat_b_out = pbm_allocarray(dx, dy);
  switch (type_) {
  case PFM_FLOAT:
    GenMaskBlockStorage(float);
    break;
  case PFM_UINT:
    GenMaskBlockStorage(unsigned int);
    break;
  case PFM_SINT:
    GenMaskBlockStorage(signed int);
    break;
  case PFM_UINT16:
    GenMaskBlockStorage(unsigned short);
    break;
  case PFM_SINT16:
    GenMaskBlockStorage(signed short);
    break;
  case PBM:{
      bit *iptr;
      bit *optr;
      int x, y;
      for (y = 0; y < dy; y++) {
        iptr = (((bit **) data_p)[y + ry1]) + rx1;
        optr = dat_b_out[y];
        for (x = 0; x < dx; x++) {
          *optr = (*iptr == (bit) id ? 1 : 0);
          optr++;
          iptr++;
        }
      }
    }
//              GenMaskRowStorage(bit);
    break;
  case PFM_BYTE:
    GenMaskBlockStorage(unsigned char);
    break;
  default:
    pbm_freearray(dat_b_out, dy);
    fclose(of);
    return "";
    break;
  }
  pbm_writepbm(of, (bit **) dat_b_out, dx, dy, 0);
  pbm_freearray(dat_b_out, dy);

  fclose(of);
  return fname;
#undef GenMaskBlockStorage
#undef GenMaskRowStorage
}
Пример #19
0
/** write a scrap of the data,
  * return the filename,
  * if the file exist do nothing
  * argument fname is optional
  * the coordinates of the image part are geodata e.g. Gauss Krueger **/
QString
  GeoImage::part(float west, float north, float east, float south,
                 QString fname)
{
  if (fname.isEmpty()) {        //create output filname
    Q_ASSERT(contains("key"));
    QString dir = CleanUp::getTmpDir();
    fname.sprintf("%s/%s_%f_%f_%f_%f", 
		  dir.toLatin1().constData(), 
		  value("key").toLatin1().constData(),
                  west, north, east, south);
  }
  qDebug("#  GeoImage::part %s (%f, %f, %f, %f)", 
	 fname.toLatin1().constData(), west,
         north, east, south);
  QFile f(fname);
  if (f.exists())
    return fname;

  const void *data_p = data();        //get pointer to data
  Q_ASSERT(data_p);
  if (type_ == UNKNOWN)
    return 0;
  int dx, dy, i, j, rx1, ry1, rx2, ry2;
  picBBox(west, north, east, south, rx1, ry2, rx2, ry1);
  dx = rx2 - rx1 + 1;
  dy = ry2 - ry1 + 1;
  if (dx <= 0 || dy <= 0) {
    qDebug("#  (ERROR) GeoImage::part: (dx=%d=%d-%d || dy=%d=%d-%d)", dx, rx2,
           rx1, dy, ry2, ry1);
    throw ImageException(rx1,rx2,dx,ry1,ry2,dy); 
  }

  FILE *of = fopen(fname.toLatin1().constData(), "w");
  if (!of) {
    throw FileIOException(FileIOException::OPEN_FAILED,fname);
  }

  switch (type_) {
  case PBM:{
      bit *bpi, *bpo, **dat_b_out = pbm_allocarray(dx, dy);
      bit **dat_b = (bit **) data_p;
      for (i = 0; i < dy; i++) {
        bpi = dat_b[i + ry1] + rx1;
        bpo = dat_b_out[i];
        for (j = 0; j < dx; j++) {
          *bpo = *bpi;
          bpo++;
          bpi++;
        }
      }
      pbm_writepbm(of, (bit **) dat_b_out, dx, dy, 0);
      pbm_freearray(dat_b_out, dy);
    }
    break;
  case PGM:{
      gray *gpi, *gpo, **dat_g_out = pgm_allocarray(dx, dy);
      gray **dat_g = (gray **) data_p;
      gray maxval = 0;
      for (i = 0; i < dy; i++) {
        gpi = dat_g[i + ry1] + rx1;
        gpo = dat_g_out[i];
        for (j = 0; j < dx; j++) {
          *gpo = *gpi;
          if (*gpi > maxval)
            maxval = *gpi;
          gpo++;
          gpi++;
        }
      }
      pgm_writepgm(of, (gray **) dat_g_out, dx, dy, maxval, 0);
      pgm_freearray(dat_g_out, dy);
    }
    break;
  case PPM:{
      pixel *ppi, *ppo, **dat_p_out = ppm_allocarray(dx, dy);
      pixel **dat_p = (pixel **) data_p;
      pixval maxval = 255;      //! should be calculated
      for (i = 0; i < dy; i++) {
        ppi = dat_p[i + ry1] + rx1;
        ppo = dat_p_out[i];
        for (j = 0; j < dx; j++) {
          *ppo = *ppi;
          ppo++;
          ppi++;
        }
      }
      ppm_writeppm(of, (pixel **) dat_p_out, dx, dy, maxval, 0);
      ppm_freearray(dat_p_out, dy);
    }
    break;
  default:
    pfm_geo_set(geoWest(),geoNorth(),geoEast(),geoSouth());
    pfm_writepfm_region_type(of, data_, cols_, rows_, minval_, maxval_,
                             rx1, ry1, rx2, ry2, type_);
    break;
  }
  fclose(of);
  return fname;
}
//----------------------------------------------------------------------------//
void MinizipResourceProvider::loadRawDataContainer(const String& filename,
                                                   RawDataContainer& output,
                                                   const String& resourceGroup)
{
    const String final_filename = getFinalFilename(filename, resourceGroup);

    if (d_pimpl->d_loadLocal && doesFileExist(final_filename))
    {
        DefaultResourceProvider::loadRawDataContainer(filename,
                                                      output,
                                                      resourceGroup);
        return;
    }

    if (d_pimpl->d_zfile == 0)
    {
        throw InvalidRequestException(
            "'" + final_filename + "' cannot be "
            "loaded because the archive has not been set");
    }

#if CEGUI_STRING_CLASS == CEGUI_STRING_CLASS_STD
    if (unzLocateFile(d_pimpl->d_zfile, final_filename.c_str(), 0) != UNZ_OK)
#elif CEGUI_STRING_CLASS == CEGUI_STRING_CLASS_UNICODE
    if (unzLocateFile(d_pimpl->d_zfile, final_filename.toUtf8String().c_str(), 0) != UNZ_OK)
#endif
    {
        throw InvalidRequestException("'" + final_filename +
            "' does not exist");
    }

    unz_file_info file_info;

    if (unzGetCurrentFileInfo(d_pimpl->d_zfile, &file_info,
                              0, 0, 0, 0, 0, 0) != UNZ_OK)
    {
        throw FileIOException("'" + final_filename +
            "' error reading file header");
    }

    if (unzOpenCurrentFile(d_pimpl->d_zfile) != Z_OK)
    {
        throw FileIOException("'" + final_filename +
            "' error opening file");
    }

    std::uint64_t size = file_info.uncompressed_size;
    std::uint8_t* buffer = new std::uint8_t[size];

    if (unzReadCurrentFile(d_pimpl->d_zfile, buffer, size) < 0)
    {
        throw FileIOException("'" + final_filename +
            "' error reading file");
    }

    if (unzCloseCurrentFile(d_pimpl->d_zfile) != UNZ_OK)
    {
        throw GenericException("'" + final_filename +
            "' error validating file");
    }

    output.setData(buffer);
    output.setSize(size);
}
Пример #21
0
/*************************************************************************
Handler methods
*************************************************************************/
void Scheme_xmlHandler::elementStart(const String& element, const XMLAttributes& attributes)
{
	// handle alias element
	if (element == WindowAliasElement)
	{
		Scheme::AliasMapping	alias;

		alias.aliasName	 = attributes.getValueAsString(AliasAttribute);
        alias.targetName = attributes.getValueAsString(TargetAttribute);
		d_scheme->d_aliasMappings.push_back(alias);
	}
	// handle an Imageset element
	else if (element == ImagesetElement)
	{
		Scheme::LoadableUIElement	imageset;

        imageset.name = attributes.getValueAsString(NameAttribute);
        imageset.filename = attributes.getValueAsString(FilenameAttribute);
        imageset.resourceGroup = attributes.getValueAsString(ResourceGroupAttribute);

		d_scheme->d_imagesets.push_back(imageset);
	}
    // handle an ImagesetFromImage element
    else if (element == ImagesetFromImageElement)
    {
        Scheme::LoadableUIElement	imageset;

        imageset.name = attributes.getValueAsString(NameAttribute);
        imageset.filename = attributes.getValueAsString(FilenameAttribute);
        imageset.resourceGroup = attributes.getValueAsString(ResourceGroupAttribute);

        d_scheme->d_imagesetsFromImages.push_back(imageset);
    }
	// handle a font element
	else if (element == FontElement)
	{
		Scheme::LoadableUIElement	font;

        font.name = attributes.getValueAsString(NameAttribute);
        font.filename = attributes.getValueAsString(FilenameAttribute);
        font.resourceGroup = attributes.getValueAsString(ResourceGroupAttribute);

		d_scheme->d_fonts.push_back(font);
	}
	// handle a WindowSet element
	else if (element == WindowSetElement)
	{
		Scheme::UIModule	module;
        module.name		= attributes.getValueAsString(FilenameAttribute);
		module.module	= NULL;

		module.factories.clear();
		d_scheme->d_widgetModules.push_back(module);
	}
	// handle a WindowFactory element
	else if (element == WindowFactoryElement)
	{
		Scheme::UIElementFactory factory;

        factory.name = attributes.getValueAsString(NameAttribute);

		d_scheme->d_widgetModules[d_scheme->d_widgetModules.size() - 1].factories.push_back(factory);
	}
	// handle root Scheme element
	else if (element == GUISchemeElement)
	{
		// get name of scheme we are creating
        d_scheme->d_name = attributes.getValueAsString(NameAttribute);

		Logger::getSingleton().logEvent("Started creation of Scheme '" + d_scheme->d_name + "' via XML file.", Informative);

		if (SchemeManager::getSingleton().isSchemePresent(d_scheme->d_name))
		{
			throw	AlreadyExistsException((utf8*)"A GUI Scheme named '" + d_scheme->d_name + "' is already present in the system.");
		}

	}
    else if (element == FalagardMappingElement)
    {
        Scheme::FalagardMapping fmap;
        fmap.windowName = attributes.getValueAsString(WindowTypeAttribute);
        fmap.targetName = attributes.getValueAsString(TargetTypeAttribute);
        fmap.lookName   = attributes.getValueAsString(LookNFeelAttribute);

        d_scheme->d_falagardMappings.push_back(fmap);
    }
    else if (element == LookNFeelElement)
    {
        Scheme::LoadableUIElement lnf;
        lnf.filename      = attributes.getValueAsString(FilenameAttribute);
        lnf.resourceGroup = attributes.getValueAsString(ResourceGroupAttribute);

        d_scheme->d_looknfeels.push_back(lnf);
    }
	// anything else is an error which *should* have already been caught by XML validation
	else
	{
		throw FileIOException("Scheme::xmlHandler::startElement - Unexpected data was found while parsing the Scheme file: '" + element + "' is unknown.");
	}

}