<commit_before>/*=========================================================================
 *
 *  Copyright RTK Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

#ifndef _rtkThreeDCircularProjectionGeometryXMLFile_cxx
#define _rtkThreeDCircularProjectionGeometryXMLFile_cxx

#include "rtkThreeDCircularProjectionGeometryXMLFile.h"

#include <itksys/SystemTools.hxx>
#include <itkMetaDataObject.h>
#include <itkIOCommon.h>

#include <iomanip>

namespace rtk
{

ThreeDCircularProjectionGeometryXMLFileReader::
ThreeDCircularProjectionGeometryXMLFileReader():
  m_Geometry(GeometryType::New() ),
  m_CurCharacterData(""),
  m_InPlaneAngle(0.),
  m_OutOfPlaneAngle(0.),
  m_GantryAngle(0.),
  m_SourceToIsocenterDistance(0.),
  m_SourceOffsetX(0.),
  m_SourceOffsetY(0.),
  m_SourceToDetectorDistance(0.),
  m_ProjectionOffsetX(0.),
  m_ProjectionOffsetY(0.),
  m_Version(0)
{
  this->m_OutputObject = &(*m_Geometry);
}

int
ThreeDCircularProjectionGeometryXMLFileReader::
CanReadFile(const char *name)
{
  if(!itksys::SystemTools::FileExists(name) ||
     itksys::SystemTools::FileIsDirectory(name) ||
     itksys::SystemTools::FileLength(name) == 0)
    return 0;
  return 1;
}

void
ThreeDCircularProjectionGeometryXMLFileReader::
StartElement(const char * name,const char **atts)
{
  m_CurCharacterData = "";
  this->StartElement(name);

  // Check on last version of file format. Warning if not.
  if( std::string(name) == "RTKThreeDCircularGeometry" )
    {
    while( (*atts) != ITK_NULLPTR )
      {
      if( std::string(atts[0]) == "version" )
        m_Version = atoi(atts[1]);
      atts += 2;
      }
    if(m_Version != this->CurrentVersion)
      itkGenericExceptionMacro(<< "Incompatible version of input geometry (v" << m_Version
                               << ") with current geometry (v" << this->CurrentVersion
                               << "). You must re-generate your geometry file again.");
    }
}

void
ThreeDCircularProjectionGeometryXMLFileReader::
StartElement(const char * itkNotUsed(name))
{
}

void
ThreeDCircularProjectionGeometryXMLFileReader::
EndElement(const char *name)
{
  if(itksys::SystemTools::Strucmp(name, "InPlaneAngle") == 0)
    m_InPlaneAngle = atof(this->m_CurCharacterData.c_str() );

  if(itksys::SystemTools::Strucmp(name, "GantryAngle") == 0 ||
     itksys::SystemTools::Strucmp(name, "Angle") == 0) // Second one for backward compatibility
    m_GantryAngle = atof(this->m_CurCharacterData.c_str() );

  if(itksys::SystemTools::Strucmp(name, "OutOfPlaneAngle") == 0)
    m_OutOfPlaneAngle = atof(this->m_CurCharacterData.c_str() );

  if(itksys::SystemTools::Strucmp(name, "SourceToIsocenterDistance") == 0)
    m_SourceToIsocenterDistance = atof(this->m_CurCharacterData.c_str() );

  if(itksys::SystemTools::Strucmp(name, "SourceOffsetX") == 0)
    m_SourceOffsetX = atof(this->m_CurCharacterData.c_str() );

  if(itksys::SystemTools::Strucmp(name, "SourceOffsetY") == 0)
    m_SourceOffsetY = atof(this->m_CurCharacterData.c_str() );

  if(itksys::SystemTools::Strucmp(name, "SourceToDetectorDistance") == 0)
    m_SourceToDetectorDistance = atof(this->m_CurCharacterData.c_str() );

  if(itksys::SystemTools::Strucmp(name, "ProjectionOffsetX") == 0)
    m_ProjectionOffsetX = atof(this->m_CurCharacterData.c_str() );

  if(itksys::SystemTools::Strucmp(name, "ProjectionOffsetY") == 0)
    m_ProjectionOffsetY = atof(this->m_CurCharacterData.c_str() );

  if(itksys::SystemTools::Strucmp(name, "Matrix") == 0)
    {
    std::istringstream iss(this->m_CurCharacterData);
    double value = 0.;
    for(unsigned int i=0; i<m_Matrix.RowDimensions; i++)
      for(unsigned int j=0; j<m_Matrix.ColumnDimensions; j++)
        {
        iss >> value;
        m_Matrix[i][j] = value;
        }
    }

  if(itksys::SystemTools::Strucmp(name, "Projection") == 0)
    {
    this->m_OutputObject->AddProjection(m_SourceToIsocenterDistance,
                                        m_SourceToDetectorDistance,
                                        m_GantryAngle,
                                        m_ProjectionOffsetX,
                                        m_ProjectionOffsetY,
                                        m_OutOfPlaneAngle,
                                        m_InPlaneAngle,
                                        m_SourceOffsetX,
                                        m_SourceOffsetY);
    for(unsigned int i=0; i<m_Matrix.RowDimensions; i++)
      for(unsigned int j=0; j<m_Matrix.ColumnDimensions; j++)
        {
        // Tolerance can not be vcl_numeric_limits<double>::epsilon(), too strict
        // 0.001 is a random choice to catch "large" inconsistencies
        if( fabs(m_Matrix[i][j]-m_OutputObject->GetMatrices().back()[i][j]) > 0.001 )
          {
          itkGenericExceptionMacro(<< "Matrix and parameters are not consistent."
                                   << std::endl << "Read matrix from geometry file: "
                                   << std::endl << m_Matrix
                                   << std::endl << "Computed matrix from parameters:"
                                   << std::endl << m_OutputObject->GetMatrices().back());
          }
        }
    }
}

void
ThreeDCircularProjectionGeometryXMLFileReader::
CharacterDataHandler(const char *inData, int inLength)
{
  for(int i = 0; i < inLength; i++)
    m_CurCharacterData = m_CurCharacterData + inData[i];
}

int
ThreeDCircularProjectionGeometryXMLFileWriter::
CanWriteFile(const char * name)
{
  std::ofstream output(name);

  if(output.fail() )
    return false;
  return true;
}

int
ThreeDCircularProjectionGeometryXMLFileWriter::
WriteFile()
{
  if(this->m_InputObject->GetGantryAngles().size() == 0)
    itkGenericExceptionMacro(<< "Geometry object is empty, cannot write it");

  std::ofstream output(this->m_Filename.c_str() );
  const int     maxDigits = 15;

  output.precision(maxDigits);
  std::string indent("  ");

  this->WriteStartElement("?xml version=\"1.0\"?",output);
  output << std::endl;
  this->WriteStartElement("!DOCTYPE RTKGEOMETRY",output);
  output << std::endl;
  std::ostringstream startWithVersion;
  startWithVersion << "RTKThreeDCircularGeometry version=\""
                   << ThreeDCircularProjectionGeometryXMLFileReader::CurrentVersion
                   << '"';
  this->WriteStartElement(startWithVersion.str().c_str(),output);
  output << std::endl;

  // First, we test for each of the 9 parameters per projection if it's constant
  // over all projection images except GantryAngle which is supposed to be different
  // for all projections. If 0. for OutOfPlaneAngle, InPlaneAngle, projection and source
  // offsets X and Y, it is not written (default value).
  bool bSIDGlobal =
          WriteGlobalParameter(output, indent,
                               this->m_InputObject->GetSourceToIsocenterDistances(),
                               "SourceToIsocenterDistance");
  bool bSDDGlobal =
          WriteGlobalParameter(output, indent,
                               this->m_InputObject->GetSourceToDetectorDistances(),
                               "SourceToDetectorDistance");
  bool bSourceXGlobal =
          WriteGlobalParameter(output, indent,
                               this->m_InputObject->GetSourceOffsetsX(),
                               "SourceOffsetX");
  bool bSourceYGlobal =
          WriteGlobalParameter(output, indent,
                               this->m_InputObject->GetSourceOffsetsY(),
                               "SourceOffsetY");
  bool bProjXGlobal =
          WriteGlobalParameter(output, indent,
                               this->m_InputObject->GetProjectionOffsetsX(),
                               "ProjectionOffsetX");
  bool bProjYGlobal =
          WriteGlobalParameter(output, indent,
                               this->m_InputObject->GetProjectionOffsetsY(),
                               "ProjectionOffsetY");
  bool bInPlaneGlobal =
          WriteGlobalParameter(output, indent,
                               this->m_InputObject->GetInPlaneAngles(),
                               "InPlaneAngle",
                               true);
  bool bOutOfPlaneGlobal =
          WriteGlobalParameter(output, indent,
                               this->m_InputObject->GetOutOfPlaneAngles(),
                               "OutOfPlaneAngle",
                               true);

  // Second, write per projection parameters (if corresponding parameter is not global)
  const double radiansToDegrees = 45. / vcl_atan(1.);
  for(unsigned int i = 0; i<this->m_InputObject->GetMatrices().size(); i++)
    {
    output << indent;
    this->WriteStartElement("Projection",output);
    output << std::endl;

    // Only the GantryAngle is necessarily projection specific
    WriteLocalParameter(output, indent,
                        radiansToDegrees * this->m_InputObject->GetGantryAngles()[i],
                        "GantryAngle");
    if(!bSIDGlobal)
      WriteLocalParameter(output, indent,
                          this->m_InputObject->GetSourceToIsocenterDistances()[i],
                          "SourceToIsocenterDistance");
    if(!bSDDGlobal)
      WriteLocalParameter(output, indent,
                          this->m_InputObject->GetSourceToDetectorDistances()[i],
                          "SourceToDetectorDistance");
    if(!bSourceXGlobal)
      WriteLocalParameter(output, indent,
                          this->m_InputObject->GetSourceOffsetsX()[i],
                          "SourceOffsetX");
    if(!bSourceYGlobal)
      WriteLocalParameter(output, indent,
                          this->m_InputObject->GetSourceOffsetsY()[i],
                          "SourceOffsetY");
    if(!bProjXGlobal)
      WriteLocalParameter(output, indent,
                          this->m_InputObject->GetProjectionOffsetsX()[i],
                          "ProjectionOffsetX");
    if(!bProjYGlobal)
      WriteLocalParameter(output, indent,
                          this->m_InputObject->GetProjectionOffsetsY()[i],
                          "ProjectionOffsetY");
    if(!bInPlaneGlobal)
      WriteLocalParameter(output, indent,
                          radiansToDegrees * this->m_InputObject->GetInPlaneAngles()[i],
                          "InPlaneAngle");
    if(!bOutOfPlaneGlobal)
      WriteLocalParameter(output, indent,
                          radiansToDegrees * this->m_InputObject->GetOutOfPlaneAngles()[i],
                          "OutOfPlaneAngle");

    //Matrix
    output << indent << indent;
    this->WriteStartElement("Matrix",output);
    output << std::endl;
    for(unsigned int j=0; j<3; j++)
      {
      output << indent << indent << indent;
      for(unsigned int k=0; k<4; k++)
        output << std::setw(maxDigits+4)
               << this->m_InputObject->GetMatrices()[i][j][k]
               << ' ';
      output.seekp(-1, std::ios_base::cur);
      output<< std::endl;
      }
    output << indent << indent;
    this->WriteEndElement("Matrix",output);
    output << std::endl;

    output << indent;
    this->WriteEndElement("Projection",output);
    output << std::endl;
    }

  this->WriteEndElement("RTKThreeDCircularGeometry",output);
  output << std::endl;

  return 0;
}

bool
ThreeDCircularProjectionGeometryXMLFileWriter::
WriteGlobalParameter(std::ofstream &output,
                     const std::string &indent,
                     const std::vector<double> &v,
                     const std::string &s,
                     bool convertToDegrees)
{
  // Test if all values in vector v are equal. Return false if not.
  for(size_t i=0; i<v.size(); i++)
    if(v[i] != v[0])
      return false;

  // Write value in file if not 0.
  if (0. != v[0])
    {
    double val = v[0];
    if(convertToDegrees)
      val *= 45. / vcl_atan(1.);
    std::string ss(s);
    output << indent;
    this->WriteStartElement(ss, output);
    output << val;
    this->WriteEndElement(ss,output);
    output << std::endl;
    }
  return true;
}

void
ThreeDCircularProjectionGeometryXMLFileWriter::
WriteLocalParameter(std::ofstream &output, const std::string &indent, const double &v, const std::string &s)
{
  std::string ss(s);
  output << indent << indent;
  this->WriteStartElement(ss, output);
  output << v;
  this->WriteEndElement(ss, output);
  output << std::endl;
}

}

#endif
<commit_msg>Fix to allow re-usage of the same geometry reader for two different files.<commit_after>/*=========================================================================
 *
 *  Copyright RTK Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

#ifndef _rtkThreeDCircularProjectionGeometryXMLFile_cxx
#define _rtkThreeDCircularProjectionGeometryXMLFile_cxx

#include "rtkThreeDCircularProjectionGeometryXMLFile.h"

#include <itksys/SystemTools.hxx>
#include <itkMetaDataObject.h>
#include <itkIOCommon.h>

#include <iomanip>

namespace rtk
{

ThreeDCircularProjectionGeometryXMLFileReader::
ThreeDCircularProjectionGeometryXMLFileReader():
  m_Geometry(GeometryType::New() ),
  m_CurCharacterData(""),
  m_InPlaneAngle(0.),
  m_OutOfPlaneAngle(0.),
  m_GantryAngle(0.),
  m_SourceToIsocenterDistance(0.),
  m_SourceOffsetX(0.),
  m_SourceOffsetY(0.),
  m_SourceToDetectorDistance(0.),
  m_ProjectionOffsetX(0.),
  m_ProjectionOffsetY(0.),
  m_Version(0)
{
  this->m_OutputObject = &(*m_Geometry);
}

int
ThreeDCircularProjectionGeometryXMLFileReader::
CanReadFile(const char *name)
{
  if(!itksys::SystemTools::FileExists(name) ||
     itksys::SystemTools::FileIsDirectory(name) ||
     itksys::SystemTools::FileLength(name) == 0)
    return 0;
  return 1;
}

void
ThreeDCircularProjectionGeometryXMLFileReader::
StartElement(const char * name,const char **atts)
{
  m_CurCharacterData = "";
  this->StartElement(name);

  // Check on last version of file format. Warning if not.
  if( std::string(name) == "RTKThreeDCircularGeometry" )
    {
    while( (*atts) != ITK_NULLPTR )
      {
      if( std::string(atts[0]) == "version" )
        m_Version = atoi(atts[1]);
      atts += 2;
      }
    if(m_Version != this->CurrentVersion)
      itkGenericExceptionMacro(<< "Incompatible version of input geometry (v" << m_Version
                               << ") with current geometry (v" << this->CurrentVersion
                               << "). You must re-generate your geometry file again.");
    this->m_OutputObject->Clear();
    }
}

void
ThreeDCircularProjectionGeometryXMLFileReader::
StartElement(const char * itkNotUsed(name))
{
}

void
ThreeDCircularProjectionGeometryXMLFileReader::
EndElement(const char *name)
{
  if(itksys::SystemTools::Strucmp(name, "InPlaneAngle") == 0)
    m_InPlaneAngle = atof(this->m_CurCharacterData.c_str() );

  if(itksys::SystemTools::Strucmp(name, "GantryAngle") == 0 ||
     itksys::SystemTools::Strucmp(name, "Angle") == 0) // Second one for backward compatibility
    m_GantryAngle = atof(this->m_CurCharacterData.c_str() );

  if(itksys::SystemTools::Strucmp(name, "OutOfPlaneAngle") == 0)
    m_OutOfPlaneAngle = atof(this->m_CurCharacterData.c_str() );

  if(itksys::SystemTools::Strucmp(name, "SourceToIsocenterDistance") == 0)
    m_SourceToIsocenterDistance = atof(this->m_CurCharacterData.c_str() );

  if(itksys::SystemTools::Strucmp(name, "SourceOffsetX") == 0)
    m_SourceOffsetX = atof(this->m_CurCharacterData.c_str() );

  if(itksys::SystemTools::Strucmp(name, "SourceOffsetY") == 0)
    m_SourceOffsetY = atof(this->m_CurCharacterData.c_str() );

  if(itksys::SystemTools::Strucmp(name, "SourceToDetectorDistance") == 0)
    m_SourceToDetectorDistance = atof(this->m_CurCharacterData.c_str() );

  if(itksys::SystemTools::Strucmp(name, "ProjectionOffsetX") == 0)
    m_ProjectionOffsetX = atof(this->m_CurCharacterData.c_str() );

  if(itksys::SystemTools::Strucmp(name, "ProjectionOffsetY") == 0)
    m_ProjectionOffsetY = atof(this->m_CurCharacterData.c_str() );

  if(itksys::SystemTools::Strucmp(name, "Matrix") == 0)
    {
    std::istringstream iss(this->m_CurCharacterData);
    double value = 0.;
    for(unsigned int i=0; i<m_Matrix.RowDimensions; i++)
      for(unsigned int j=0; j<m_Matrix.ColumnDimensions; j++)
        {
        iss >> value;
        m_Matrix[i][j] = value;
        }
    }

  if(itksys::SystemTools::Strucmp(name, "Projection") == 0)
    {
    this->m_OutputObject->AddProjection(m_SourceToIsocenterDistance,
                                        m_SourceToDetectorDistance,
                                        m_GantryAngle,
                                        m_ProjectionOffsetX,
                                        m_ProjectionOffsetY,
                                        m_OutOfPlaneAngle,
                                        m_InPlaneAngle,
                                        m_SourceOffsetX,
                                        m_SourceOffsetY);
    for(unsigned int i=0; i<m_Matrix.RowDimensions; i++)
      for(unsigned int j=0; j<m_Matrix.ColumnDimensions; j++)
        {
        // Tolerance can not be vcl_numeric_limits<double>::epsilon(), too strict
        // 0.001 is a random choice to catch "large" inconsistencies
        if( fabs(m_Matrix[i][j]-m_OutputObject->GetMatrices().back()[i][j]) > 0.001 )
          {
          itkGenericExceptionMacro(<< "Matrix and parameters are not consistent."
                                   << std::endl << "Read matrix from geometry file: "
                                   << std::endl << m_Matrix
                                   << std::endl << "Computed matrix from parameters:"
                                   << std::endl << m_OutputObject->GetMatrices().back());
          }
        }
    }
}

void
ThreeDCircularProjectionGeometryXMLFileReader::
CharacterDataHandler(const char *inData, int inLength)
{
  for(int i = 0; i < inLength; i++)
    m_CurCharacterData = m_CurCharacterData + inData[i];
}

int
ThreeDCircularProjectionGeometryXMLFileWriter::
CanWriteFile(const char * name)
{
  std::ofstream output(name);

  if(output.fail() )
    return false;
  return true;
}

int
ThreeDCircularProjectionGeometryXMLFileWriter::
WriteFile()
{
  if(this->m_InputObject->GetGantryAngles().size() == 0)
    itkGenericExceptionMacro(<< "Geometry object is empty, cannot write it");

  std::ofstream output(this->m_Filename.c_str() );
  const int     maxDigits = 15;

  output.precision(maxDigits);
  std::string indent("  ");

  this->WriteStartElement("?xml version=\"1.0\"?",output);
  output << std::endl;
  this->WriteStartElement("!DOCTYPE RTKGEOMETRY",output);
  output << std::endl;
  std::ostringstream startWithVersion;
  startWithVersion << "RTKThreeDCircularGeometry version=\""
                   << ThreeDCircularProjectionGeometryXMLFileReader::CurrentVersion
                   << '"';
  this->WriteStartElement(startWithVersion.str().c_str(),output);
  output << std::endl;

  // First, we test for each of the 9 parameters per projection if it's constant
  // over all projection images except GantryAngle which is supposed to be different
  // for all projections. If 0. for OutOfPlaneAngle, InPlaneAngle, projection and source
  // offsets X and Y, it is not written (default value).
  bool bSIDGlobal =
          WriteGlobalParameter(output, indent,
                               this->m_InputObject->GetSourceToIsocenterDistances(),
                               "SourceToIsocenterDistance");
  bool bSDDGlobal =
          WriteGlobalParameter(output, indent,
                               this->m_InputObject->GetSourceToDetectorDistances(),
                               "SourceToDetectorDistance");
  bool bSourceXGlobal =
          WriteGlobalParameter(output, indent,
                               this->m_InputObject->GetSourceOffsetsX(),
                               "SourceOffsetX");
  bool bSourceYGlobal =
          WriteGlobalParameter(output, indent,
                               this->m_InputObject->GetSourceOffsetsY(),
                               "SourceOffsetY");
  bool bProjXGlobal =
          WriteGlobalParameter(output, indent,
                               this->m_InputObject->GetProjectionOffsetsX(),
                               "ProjectionOffsetX");
  bool bProjYGlobal =
          WriteGlobalParameter(output, indent,
                               this->m_InputObject->GetProjectionOffsetsY(),
                               "ProjectionOffsetY");
  bool bInPlaneGlobal =
          WriteGlobalParameter(output, indent,
                               this->m_InputObject->GetInPlaneAngles(),
                               "InPlaneAngle",
                               true);
  bool bOutOfPlaneGlobal =
          WriteGlobalParameter(output, indent,
                               this->m_InputObject->GetOutOfPlaneAngles(),
                               "OutOfPlaneAngle",
                               true);

  // Second, write per projection parameters (if corresponding parameter is not global)
  const double radiansToDegrees = 45. / vcl_atan(1.);
  for(unsigned int i = 0; i<this->m_InputObject->GetMatrices().size(); i++)
    {
    output << indent;
    this->WriteStartElement("Projection",output);
    output << std::endl;

    // Only the GantryAngle is necessarily projection specific
    WriteLocalParameter(output, indent,
                        radiansToDegrees * this->m_InputObject->GetGantryAngles()[i],
                        "GantryAngle");
    if(!bSIDGlobal)
      WriteLocalParameter(output, indent,
                          this->m_InputObject->GetSourceToIsocenterDistances()[i],
                          "SourceToIsocenterDistance");
    if(!bSDDGlobal)
      WriteLocalParameter(output, indent,
                          this->m_InputObject->GetSourceToDetectorDistances()[i],
                          "SourceToDetectorDistance");
    if(!bSourceXGlobal)
      WriteLocalParameter(output, indent,
                          this->m_InputObject->GetSourceOffsetsX()[i],
                          "SourceOffsetX");
    if(!bSourceYGlobal)
      WriteLocalParameter(output, indent,
                          this->m_InputObject->GetSourceOffsetsY()[i],
                          "SourceOffsetY");
    if(!bProjXGlobal)
      WriteLocalParameter(output, indent,
                          this->m_InputObject->GetProjectionOffsetsX()[i],
                          "ProjectionOffsetX");
    if(!bProjYGlobal)
      WriteLocalParameter(output, indent,
                          this->m_InputObject->GetProjectionOffsetsY()[i],
                          "ProjectionOffsetY");
    if(!bInPlaneGlobal)
      WriteLocalParameter(output, indent,
                          radiansToDegrees * this->m_InputObject->GetInPlaneAngles()[i],
                          "InPlaneAngle");
    if(!bOutOfPlaneGlobal)
      WriteLocalParameter(output, indent,
                          radiansToDegrees * this->m_InputObject->GetOutOfPlaneAngles()[i],
                          "OutOfPlaneAngle");

    //Matrix
    output << indent << indent;
    this->WriteStartElement("Matrix",output);
    output << std::endl;
    for(unsigned int j=0; j<3; j++)
      {
      output << indent << indent << indent;
      for(unsigned int k=0; k<4; k++)
        output << std::setw(maxDigits+4)
               << this->m_InputObject->GetMatrices()[i][j][k]
               << ' ';
      output.seekp(-1, std::ios_base::cur);
      output<< std::endl;
      }
    output << indent << indent;
    this->WriteEndElement("Matrix",output);
    output << std::endl;

    output << indent;
    this->WriteEndElement("Projection",output);
    output << std::endl;
    }

  this->WriteEndElement("RTKThreeDCircularGeometry",output);
  output << std::endl;

  return 0;
}

bool
ThreeDCircularProjectionGeometryXMLFileWriter::
WriteGlobalParameter(std::ofstream &output,
                     const std::string &indent,
                     const std::vector<double> &v,
                     const std::string &s,
                     bool convertToDegrees)
{
  // Test if all values in vector v are equal. Return false if not.
  for(size_t i=0; i<v.size(); i++)
    if(v[i] != v[0])
      return false;

  // Write value in file if not 0.
  if (0. != v[0])
    {
    double val = v[0];
    if(convertToDegrees)
      val *= 45. / vcl_atan(1.);
    std::string ss(s);
    output << indent;
    this->WriteStartElement(ss, output);
    output << val;
    this->WriteEndElement(ss,output);
    output << std::endl;
    }
  return true;
}

void
ThreeDCircularProjectionGeometryXMLFileWriter::
WriteLocalParameter(std::ofstream &output, const std::string &indent, const double &v, const std::string &s)
{
  std::string ss(s);
  output << indent << indent;
  this->WriteStartElement(ss, output);
  output << v;
  this->WriteEndElement(ss, output);
  output << std::endl;
}

}

#endif
<|endoftext|>


<commit_before>#include "CoolProp.h"
using namespace CoolProp;
int main()
{
    // First type (slowest, most string processing, exposed in DLL)
    double r0A = PropsSI("Dmolar","T",298,"P",1e5,"Propane[0.5]&Ethane[0.5]"); // Default backend is HEOS
    double r0B = PropsSI("Dmolar","T",298,"P",1e5,"HEOS::Propane[0.5]&Ethane[0.5]");
    double r0C = PropsSI("Dmolar","T",298,"P",1e5,"REFPROP::Propane[0.5]&Ethane[0.5]");

    std::vector<double> z(2,0.5);
    // Second type (C++ only, a bit faster)
    double r1A = PropsSI("Dmolar","T",298,"P",1e5,"Propane&Ethane", z);
    double r1B = PropsSI("Dmolar","T",298,"P",1e5,"HEOS::Propane&Ethane", z);
    double r1C = PropsSI("Dmolar","T",298,"P",1e5,"REFPROP::Propane&Ethane", z);

    return EXIT_SUCCESS;
}<commit_msg>Updated mixture propssi snippet<commit_after>#include "CoolProp.h"
using namespace CoolProp;
int main()
{
    // First type (slowest, due to most string processing, exposed in DLL)
    std::cout << PropsSI("Dmolar","T",298,"P",1e5,"Propane[0.5]&Ethane[0.5]") << std::endl; // Default backend is HEOS
    std::cout << PropsSI("Dmolar","T",298,"P",1e5,"HEOS::Propane[0.5]&Ethane[0.5]") << std::endl;
    std::cout << PropsSI("Dmolar","T",298,"P",1e5,"REFPROP::Propane[0.5]&Ethane[0.5]") << std::endl;

    std::vector<double> z(2,0.5);
    // Second type (C++ only, a bit faster)
    std::cout << PropsSI("Dmolar","T",298,"P",1e5,"Propane&Ethane", z) << std::endl;
    std::cout << PropsSI("Dmolar","T",298,"P",1e5,"HEOS::Propane&Ethane", z) << std::endl;
    std::cout << PropsSI("Dmolar","T",298,"P",1e5,"REFPROP::Propane&Ethane", z) << std::endl;

    return EXIT_SUCCESS;
}<|endoftext|>


<commit_before>/*VRP*********************************************************************
 *
 * vehicle routing problems
 *      A collection of C++ classes for developing VRP solutions
 *      and specific solutions developed using these classes.
 *
 * Copyright 2014 Stephen Woodbridge <woodbri@imaptools.com>
 * Copyright 2014 Vicky Vergara <vicky_vergara@hotmail.com>
 *
 * This is free software; you can redistribute and/or modify it under
 * the terms of the MIT License. Please file LICENSE for details.
 *
 ********************************************************************VRP*/

#include <exception>
#include <string.h>

#include "signalhandler.h"
#include "vrptools.h"

#ifdef DOSTATS
#include "timer.h"
#endif

#ifdef DOVRPLOG
#include "logger.h"
#endif

#include "trashprob.h"
#include "feasableSol.h"
#include "tabuopt.h"

int vrp_trash_collection( container_t *containers, unsigned int container_count,
                          otherloc_t *otherlocs, unsigned int otherloc_count,
                          vehicle_t *vehicles, unsigned int vehicle_count,
                          ttime_t *ttimes, unsigned int ttime_count,
                          unsigned int iteration,
                          int check,
                          vehicle_path_t **vehicle_paths, int *vehicle_path_count,
                          char **err_msg ) {

    try {
        // register the signal handler
        REG_SIGINT

	#ifdef DOVRPLOG
        if ( not google::IsGoogleLoggingInitialized() ) {
            FLAGS_log_dir = "/tmp/";
            google::InitGoogleLogging( "vrp_trash_collection" );
            FLAGS_logtostderr = 0;
            FLAGS_stderrthreshold = google::FATAL;
            FLAGS_minloglevel = google::INFO;
        }
	#endif

        TrashProb prob(containers,container_count,otherlocs,otherloc_count,ttimes,ttime_count,vehicles,vehicle_count) ;

        if ( check ) {
            std::string err = prob.whatIsWrong();
            if ( err == "" )
                *err_msg = strdup("OK");
            else
                *err_msg = strdup( err.c_str() );
            return 0;
        }

        if ( not prob.isValid() ) {
            std::string err = prob.whatIsWrong();
            *err_msg = strdup( err.c_str() );
            return -1;
        }

        THROW_ON_SIGINT

        FeasableSol tp( prob );
        tp.computeCosts();

        THROW_ON_SIGINT

        TabuOpt ts( tp , iteration);

        Solution best = ts.getBestSolution();
        best.computeCosts();

        int count = 0;
        *vehicle_paths = ts.getSolutionForPg( count );
        *vehicle_path_count = count;

        if ( count == -1 ) {
            *err_msg = ( char * ) "Failed to allocate memory for results!";
            return -1;
        }

        twc->cleanUp();
    }
    catch ( std::exception &e ) {
        *err_msg = ( char * ) e.what();
        return -1;
    }
    catch ( ... ) {
        *err_msg = ( char * ) "Caught unknown expection!";
        return -1;
    }

    return EXIT_SUCCESS;
}
<commit_msg>Fixed crashing issue in postgresql integration.<commit_after>/*VRP*********************************************************************
 *
 * vehicle routing problems
 *      A collection of C++ classes for developing VRP solutions
 *      and specific solutions developed using these classes.
 *
 * Copyright 2014 Stephen Woodbridge <woodbri@imaptools.com>
 * Copyright 2014 Vicky Vergara <vicky_vergara@hotmail.com>
 *
 * This is free software; you can redistribute and/or modify it under
 * the terms of the MIT License. Please file LICENSE for details.
 *
 ********************************************************************VRP*/

#include <exception>
#include <string.h>

#include "signalhandler.h"
#include "vrptools.h"

#ifdef DOSTATS
#include "timer.h"
#endif

#ifdef DOVRPLOG
#include "logger.h"
#endif

#include "trashprob.h"
#include "feasableSol.h"
#include "tabuopt.h"

int vrp_trash_collection( container_t *containers, unsigned int container_count,
                          otherloc_t *otherlocs, unsigned int otherloc_count,
                          vehicle_t *vehicles, unsigned int vehicle_count,
                          ttime_t *ttimes, unsigned int ttime_count,
                          unsigned int iteration,
                          int check,
                          vehicle_path_t **vehicle_paths, int *vehicle_path_count,
                          char **err_msg ) {

    try {
        // register the signal handler
        REG_SIGINT

	#ifdef DOVRPLOG
        if ( not google::IsGoogleLoggingInitialized() ) {
            FLAGS_log_dir = "/tmp/";
            google::InitGoogleLogging( "vrp_trash_collection" );
            FLAGS_logtostderr = 0;
            FLAGS_stderrthreshold = google::FATAL;
            FLAGS_minloglevel = google::INFO;
        }
	#endif

        TrashProb prob(containers,container_count,otherlocs,otherloc_count,ttimes,ttime_count,vehicles,vehicle_count) ;

        if ( check ) {
            std::string err = prob.whatIsWrong();
            if ( err == "" )
                *err_msg = strdup("OK");
            else
                *err_msg = strdup( err.c_str() );
            return 0;
        }

        if ( not prob.isValid() ) {
            std::string err = prob.whatIsWrong();
            *err_msg = strdup( err.c_str() );
            return -1;
        }

        THROW_ON_SIGINT

        FeasableSol tp( prob );
        tp.computeCosts();

        THROW_ON_SIGINT

        TabuOpt ts( tp , iteration);

        Solution best = ts.getBestSolution();
        best.computeCosts();

        int count = 0;
        *vehicle_paths = ts.getSolutionForPg( count );
        *vehicle_path_count = count;

        if ( count == -1 ) {
            *err_msg = strdup( "Failed to allocate memory for results!" );
            return -1;
        }

        twc->cleanUp();
    }
    catch ( std::exception &e ) {
        *err_msg = strdup( e.what() );
        return -1;
    }
    catch ( ... ) {
        *err_msg = strdup( "Caught unknown expection!" );
        return -1;
    }

    *err_msg = (char *)0;

    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/views/widget/desktop_native_widget_helper_aura.h"

#include "ui/aura/root_window.h"
#include "ui/aura/desktop/desktop_activation_client.h"
#include "ui/aura/desktop/desktop_dispatcher_client.h"
#include "ui/aura/desktop/desktop_root_window_event_filter.h"
#include "ui/aura/client/dispatcher_client.h"
#include "ui/views/widget/native_widget_aura.h"

#if defined(OS_WIN)
#include "ui/base/win/hwnd_subclass.h"
#include "ui/views/widget/widget_message_filter.h"
#endif

namespace views {

DesktopNativeWidgetHelperAura::DesktopNativeWidgetHelperAura(
    NativeWidgetAura* widget)
    : widget_(widget),
      is_embedded_window_(false) {
}

DesktopNativeWidgetHelperAura::~DesktopNativeWidgetHelperAura() {}

void DesktopNativeWidgetHelperAura::PreInitialize(
    const Widget::InitParams& params) {
  // We don't want the status bubble or the omnibox to get their own root
  // window on the desktop; on Linux
  //
  // TODO(erg): This doesn't map perfectly to what I want to do. TYPE_POPUP is
  // used for lots of stuff, like dragged tabs, and I only want this to trigger
  // for the status bubble and the omnibox.
  if (params.type == Widget::InitParams::TYPE_POPUP) {
    is_embedded_window_ = true;
    return;
  } else if (params.type == Widget::InitParams::TYPE_CONTROL) {
    return;
  }

  gfx::Rect bounds = params.bounds;
  if (bounds.IsEmpty()) {
    // We must pass some non-zero value when we initialize a RootWindow. This
    // will probably be SetBounds()ed soon.
    bounds.set_size(gfx::Size(100, 100));
  }
  root_window_.reset(new aura::RootWindow(bounds));
  root_window_->Init();
  root_window_->SetEventFilter(
      new aura::DesktopRootWindowEventFilter(root_window_.get()));
  root_window_->AddRootWindowObserver(this);

  aura::client::SetActivationClient(
      root_window_.get(),
      new aura::DesktopActivationClient(root_window_.get()));
  aura::client::SetDispatcherClient(root_window_.get(),
                                    new aura::DesktopDispatcherClient);
}

void DesktopNativeWidgetHelperAura::PostInitialize() {
#if defined(OS_WIN)
  subclass_.reset(new ui::HWNDSubclass(root_window_->GetAcceleratedWidget()));
  subclass_->SetFilter(new WidgetMessageFilter(root_window_.get(),
                                               widget_->GetWidget()));
#endif
}

void DesktopNativeWidgetHelperAura::ShowRootWindow() {
  if (root_window_.get())
    root_window_->ShowRootWindow();
}

aura::RootWindow* DesktopNativeWidgetHelperAura::GetRootWindow() {
  return root_window_.get();
}

gfx::Rect DesktopNativeWidgetHelperAura::ModifyAndSetBounds(
    const gfx::Rect& bounds) {
  gfx::Rect out_bounds = bounds;
  if (root_window_.get() && !out_bounds.IsEmpty()) {
    root_window_->SetHostBounds(out_bounds);
    out_bounds.set_x(0);
    out_bounds.set_y(0);
  } else if (is_embedded_window_) {
    // The caller expects windows we consider "embedded" to be placed in the
    // screen coordinate system. So we need to offset the root window's
    // position (which is in screen coordinates) from these bounds.
    aura::RootWindow* root =
        widget_->GetNativeWindow()->GetRootWindow()->GetRootWindow();
    gfx::Point point = root->GetHostOrigin();
    out_bounds.set_x(out_bounds.x() - point.x());
    out_bounds.set_y(out_bounds.y() - point.y());
  }

  return out_bounds;
}

gfx::Rect DesktopNativeWidgetHelperAura::ChangeRootWindowBoundsToScreenBounds(
    const gfx::Rect& bounds) {
  gfx::Rect out_bounds = bounds;
  if (root_window_.get()) {
    out_bounds.Offset(root_window_->GetHostOrigin());
  } else if (is_embedded_window_) {
    aura::RootWindow* root =
        widget_->GetNativeWindow()->GetRootWindow()->GetRootWindow();
    out_bounds.Offset(root->GetHostOrigin());
  }
  return out_bounds;
}

////////////////////////////////////////////////////////////////////////////////
// DesktopNativeWidgetHelperAura, aura::RootWindowObserver implementation:

void DesktopNativeWidgetHelperAura::OnRootWindowResized(
    const aura::RootWindow* root,
    const gfx::Size& old_size) {
  DCHECK_EQ(root, root_window_.get());
  widget_->SetBounds(gfx::Rect(root->GetHostSize()));
}

void DesktopNativeWidgetHelperAura::OnRootWindowHostClosed(
    const aura::RootWindow* root) {
  DCHECK_EQ(root, root_window_.get());
  widget_->GetWidget()->Close();
}

}  // namespace views
<commit_msg>Aura desktop: Don't move the window to the origin when we get an external size change.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/views/widget/desktop_native_widget_helper_aura.h"

#include "ui/aura/root_window.h"
#include "ui/aura/desktop/desktop_activation_client.h"
#include "ui/aura/desktop/desktop_dispatcher_client.h"
#include "ui/aura/desktop/desktop_root_window_event_filter.h"
#include "ui/aura/client/dispatcher_client.h"
#include "ui/views/widget/native_widget_aura.h"

#if defined(OS_WIN)
#include "ui/base/win/hwnd_subclass.h"
#include "ui/views/widget/widget_message_filter.h"
#endif

namespace views {

DesktopNativeWidgetHelperAura::DesktopNativeWidgetHelperAura(
    NativeWidgetAura* widget)
    : widget_(widget),
      is_embedded_window_(false) {
}

DesktopNativeWidgetHelperAura::~DesktopNativeWidgetHelperAura() {}

void DesktopNativeWidgetHelperAura::PreInitialize(
    const Widget::InitParams& params) {
  // We don't want the status bubble or the omnibox to get their own root
  // window on the desktop; on Linux
  //
  // TODO(erg): This doesn't map perfectly to what I want to do. TYPE_POPUP is
  // used for lots of stuff, like dragged tabs, and I only want this to trigger
  // for the status bubble and the omnibox.
  if (params.type == Widget::InitParams::TYPE_POPUP) {
    is_embedded_window_ = true;
    return;
  } else if (params.type == Widget::InitParams::TYPE_CONTROL) {
    return;
  }

  gfx::Rect bounds = params.bounds;
  if (bounds.IsEmpty()) {
    // We must pass some non-zero value when we initialize a RootWindow. This
    // will probably be SetBounds()ed soon.
    bounds.set_size(gfx::Size(100, 100));
  }
  root_window_.reset(new aura::RootWindow(bounds));
  root_window_->Init();
  root_window_->SetEventFilter(
      new aura::DesktopRootWindowEventFilter(root_window_.get()));
  root_window_->AddRootWindowObserver(this);

  aura::client::SetActivationClient(
      root_window_.get(),
      new aura::DesktopActivationClient(root_window_.get()));
  aura::client::SetDispatcherClient(root_window_.get(),
                                    new aura::DesktopDispatcherClient);
}

void DesktopNativeWidgetHelperAura::PostInitialize() {
#if defined(OS_WIN)
  subclass_.reset(new ui::HWNDSubclass(root_window_->GetAcceleratedWidget()));
  subclass_->SetFilter(new WidgetMessageFilter(root_window_.get(),
                                               widget_->GetWidget()));
#endif
}

void DesktopNativeWidgetHelperAura::ShowRootWindow() {
  if (root_window_.get())
    root_window_->ShowRootWindow();
}

aura::RootWindow* DesktopNativeWidgetHelperAura::GetRootWindow() {
  return root_window_.get();
}

gfx::Rect DesktopNativeWidgetHelperAura::ModifyAndSetBounds(
    const gfx::Rect& bounds) {
  gfx::Rect out_bounds = bounds;
  if (root_window_.get() && !out_bounds.IsEmpty()) {
    root_window_->SetHostBounds(out_bounds);
    out_bounds.set_x(0);
    out_bounds.set_y(0);
  } else if (is_embedded_window_) {
    // The caller expects windows we consider "embedded" to be placed in the
    // screen coordinate system. So we need to offset the root window's
    // position (which is in screen coordinates) from these bounds.
    aura::RootWindow* root =
        widget_->GetNativeWindow()->GetRootWindow()->GetRootWindow();
    gfx::Point point = root->GetHostOrigin();
    out_bounds.set_x(out_bounds.x() - point.x());
    out_bounds.set_y(out_bounds.y() - point.y());
  }

  return out_bounds;
}

gfx::Rect DesktopNativeWidgetHelperAura::ChangeRootWindowBoundsToScreenBounds(
    const gfx::Rect& bounds) {
  gfx::Rect out_bounds = bounds;
  if (root_window_.get()) {
    out_bounds.Offset(root_window_->GetHostOrigin());
  } else if (is_embedded_window_) {
    aura::RootWindow* root =
        widget_->GetNativeWindow()->GetRootWindow()->GetRootWindow();
    out_bounds.Offset(root->GetHostOrigin());
  }
  return out_bounds;
}

////////////////////////////////////////////////////////////////////////////////
// DesktopNativeWidgetHelperAura, aura::RootWindowObserver implementation:

void DesktopNativeWidgetHelperAura::OnRootWindowResized(
    const aura::RootWindow* root,
    const gfx::Size& old_size) {
  DCHECK_EQ(root, root_window_.get());
  widget_->SetBounds(gfx::Rect(root->GetHostOrigin(),
                               root->GetHostSize()));
}

void DesktopNativeWidgetHelperAura::OnRootWindowHostClosed(
    const aura::RootWindow* root) {
  DCHECK_EQ(root, root_window_.get());
  widget_->GetWidget()->Close();
}

}  // namespace views
<|endoftext|>


<commit_before>#include "DA2Music.h"

using namespace std;

cDA2Music::cDA2Music(){
	int i;
	FILE* f;

  song[1].MaxTrack = 3;
  song[2].MaxTrack = 2;
  song[3].MaxTrack = 3;
  song[4].MaxTrack = 2;
  song[5].MaxTrack = 1;

  strcpy(song[0].FileName,"Battle");
  strcpy(song[1].FileName,"TownA");
  strcpy(song[2].FileName,"TownB");
  strcpy(song[3].FileName,"Travel");
  strcpy(song[4].FileName,"Dungeon");
  strcpy(song[5].FileName,"CutScene");

  for(i=0;i<6;i++){
    song[i].Track = 1;
    song[i].position = sf::Time::Zero;
  }

	f=fopen("music/SCORE.DAT","rt");
	for(i=0;i<500;i++) fscanf(f,"%d\n",&Music[i]);
	fclose(f);

  LastPlayed = -1;
  NowPlaying = -1;
	Volume = 5;
	bChangeSong=false;
}

cDA2Music::~cDA2Music(){
  /*1
	for(int i=0;i<6;i++){
    BASS_MusicFree(song[i].handle);
  }
  */
}

void cDA2Music::ChangeSong(int map){
  char strSong[256];
	int i;

	if(map<0) i=snBattle;
  else if (map==99999) i=snCutScene;
	else i=Music[map];

  if(i == NowPlaying) return;

  //If song is not loaded, load it at last position
  if(song[i].song.getStatus() == sf::Music::Stopped) {
		sprintf(strSong,"music/%s%d.ogg",song[i].FileName,song[i].Track);
    LoadSong(i, strSong, song[i].position, true);
  } else if(song[i].song.getStatus() == sf::Music::Paused){
    song[i].song.play();
	}

  LastPlayed = NowPlaying;
  NowPlaying = i;
  bChangeSong = true;
}

void cDA2Music::CheckState() {
	if(NowPlaying==-1) return;

	bool bFade=false;
	char strSong[256];
	//DWORD freq;
	float vol;
	int pan;
  int i;

  //Handle songs changing due to map change
  if(bChangeSong){

    //Check if songs are playing, if not load the new one
    if(LastPlayed > -1) {
			if(song[LastPlayed].song.getStatus()==sf::Music::Stopped) {
				song[LastPlayed].Track++;
        if(song[LastPlayed].Track > song[LastPlayed].MaxTrack) song[LastPlayed].Track = 1;
        song[LastPlayed].position = sf::Time::Zero;
				sprintf(strSong,"music/%s%d.ogg",song[LastPlayed].FileName,song[LastPlayed].Track);
        LoadSong(LastPlayed, strSong, sf::Time::Zero, false);
			}
		}

    if(song[NowPlaying].song.getStatus() == sf::Music::Stopped){
      song[NowPlaying].Track++;
      if(song[NowPlaying].Track > song[NowPlaying].MaxTrack) song[NowPlaying].Track = 1;
      song[NowPlaying].position = sf::Time::Zero;
			sprintf(strSong,"music/%s%d.ogg",song[NowPlaying].FileName,song[NowPlaying].Track);
      LoadSong(NowPlaying, strSong, sf::Time::Zero, false);
    }

    //Fade out old song
    Uint32 timeNow=SDL_GetTicks();
		Uint32 dTime=timeNow-musicTime;
		if(dTime > 300 || dTime<0){
			musicTime=timeNow;
			bFade=true;
		}

    if(LastPlayed > -1 && song[LastPlayed].song.getStatus()==sf::Music::Playing) {
      vol = song[LastPlayed].song.getVolume();
      if(bFade) {
        vol = vol-1;
        song[LastPlayed].song.setVolume(vol);
      }
			if(vol <= 0) {
				//Store song position and free resources
				song[LastPlayed].position = song[LastPlayed].song.getPlayingOffset();
        song[LastPlayed].song.pause();
				//bChangeSong = false;
        vol = 0;
			}
		}

    //Fade in new song
    vol = song[NowPlaying].song.getVolume();
    if(bFade) vol = vol+1;
    if(vol > Volume*10){
      //fail safe - turn off all other channels
      for(i=0;i<6;i++){
        if(i==NowPlaying) continue;
        if(song[i].song.getStatus()==sf::Music::Playing){
          song[i].position=song[i].song.getPlayingOffset();
          song[i].song.pause();
        }
      }
      vol = Volume*10;
      bChangeSong = false;
    }
    song[NowPlaying].song.setVolume(vol);

    return;
  }

  //Check if song needs changing
  if(song[NowPlaying].song.getStatus() == sf::Music::Stopped){
    song[NowPlaying].Track++;
    if(song[NowPlaying].Track > song[NowPlaying].MaxTrack) song[NowPlaying].Track = 1;
    song[NowPlaying].position = sf::Time::Zero;
		sprintf(strSong,"music/%s%d.ogg",song[NowPlaying].FileName,song[NowPlaying].Track);
    LoadSong(NowPlaying, strSong, sf::Time::Zero, false);
  }
}

bool cDA2Music::Init(){
  /*1
	BASS_Init(1, 44100, 0, 0, 0);
	PlayTheme();
	return true;
  */
}

void cDA2Music::KillSong(int map){
	int i=Music[map];
  song[i].song.stop();
}

void cDA2Music::KillTheme(){
	DA2ThemeStream.stop();
}

void cDA2Music::LoadSong(int i, char* fn, sf::Time offset, bool silent){
  song[i].song.openFromFile(fn);
  song[i].song.setPlayingOffset(offset);
  //song[i].song.setVolume(0);
	song[i].song.setVolume(Volume*10);
  song[i].song.play();
}

void cDA2Music::PlayTheme(){
  DA2ThemeStream.setLoop(true);
	DA2ThemeStream.openFromFile("music/theme.ogg");
  DA2ThemeStream.play();
}

void cDA2Music::SetVolume(int vol){
	Volume=vol;
	song[NowPlaying].song.setVolume(Volume*10);
}<commit_msg>ditto<commit_after>#include "DA2Music.h"

using namespace std;

cDA2Music::cDA2Music(){
	int i;
	FILE* f;

  song[1].MaxTrack = 3;
  song[2].MaxTrack = 2;
  song[3].MaxTrack = 3;
  song[4].MaxTrack = 2;
  song[5].MaxTrack = 1;

  strcpy(song[0].FileName,"Battle");
  strcpy(song[1].FileName,"TownA");
  strcpy(song[2].FileName,"TownB");
  strcpy(song[3].FileName,"Travel");
  strcpy(song[4].FileName,"Dungeon");
  strcpy(song[5].FileName,"Cutscene");

  for(i=0;i<6;i++){
    song[i].Track = 1;
    song[i].position = sf::Time::Zero;
  }

	f=fopen("music/SCORE.DAT","rt");
	for(i=0;i<500;i++) fscanf(f,"%d\n",&Music[i]);
	fclose(f);

  LastPlayed = -1;
  NowPlaying = -1;
	Volume = 5;
	bChangeSong=false;
}

cDA2Music::~cDA2Music(){
  /*1
	for(int i=0;i<6;i++){
    BASS_MusicFree(song[i].handle);
  }
  */
}

void cDA2Music::ChangeSong(int map){
  char strSong[256];
	int i;

	if(map<0) i=snBattle;
  else if (map==99999) i=snCutScene;
	else i=Music[map];

  if(i == NowPlaying) return;

  //If song is not loaded, load it at last position
  if(song[i].song.getStatus() == sf::Music::Stopped) {
		sprintf(strSong,"music/%s%d.ogg",song[i].FileName,song[i].Track);
    LoadSong(i, strSong, song[i].position, true);
  } else if(song[i].song.getStatus() == sf::Music::Paused){
    song[i].song.play();
	}

  LastPlayed = NowPlaying;
  NowPlaying = i;
  bChangeSong = true;
}

void cDA2Music::CheckState() {
	if(NowPlaying==-1) return;

	bool bFade=false;
	char strSong[256];
	//DWORD freq;
	float vol;
	int pan;
  int i;

  //Handle songs changing due to map change
  if(bChangeSong){

    //Check if songs are playing, if not load the new one
    if(LastPlayed > -1) {
			if(song[LastPlayed].song.getStatus()==sf::Music::Stopped) {
				song[LastPlayed].Track++;
        if(song[LastPlayed].Track > song[LastPlayed].MaxTrack) song[LastPlayed].Track = 1;
        song[LastPlayed].position = sf::Time::Zero;
				sprintf(strSong,"music/%s%d.ogg",song[LastPlayed].FileName,song[LastPlayed].Track);
        LoadSong(LastPlayed, strSong, sf::Time::Zero, false);
			}
		}

    if(song[NowPlaying].song.getStatus() == sf::Music::Stopped){
      song[NowPlaying].Track++;
      if(song[NowPlaying].Track > song[NowPlaying].MaxTrack) song[NowPlaying].Track = 1;
      song[NowPlaying].position = sf::Time::Zero;
			sprintf(strSong,"music/%s%d.ogg",song[NowPlaying].FileName,song[NowPlaying].Track);
      LoadSong(NowPlaying, strSong, sf::Time::Zero, false);
    }

    //Fade out old song
    Uint32 timeNow=SDL_GetTicks();
		Uint32 dTime=timeNow-musicTime;
		if(dTime > 300 || dTime<0){
			musicTime=timeNow;
			bFade=true;
		}

    if(LastPlayed > -1 && song[LastPlayed].song.getStatus()==sf::Music::Playing) {
      vol = song[LastPlayed].song.getVolume();
      if(bFade) {
        vol = vol-1;
        song[LastPlayed].song.setVolume(vol);
      }
			if(vol <= 0) {
				//Store song position and free resources
				song[LastPlayed].position = song[LastPlayed].song.getPlayingOffset();
        song[LastPlayed].song.pause();
				//bChangeSong = false;
        vol = 0;
			}
		}

    //Fade in new song
    vol = song[NowPlaying].song.getVolume();
    if(bFade) vol = vol+1;
    if(vol > Volume*10){
      //fail safe - turn off all other channels
      for(i=0;i<6;i++){
        if(i==NowPlaying) continue;
        if(song[i].song.getStatus()==sf::Music::Playing){
          song[i].position=song[i].song.getPlayingOffset();
          song[i].song.pause();
        }
      }
      vol = Volume*10;
      bChangeSong = false;
    }
    song[NowPlaying].song.setVolume(vol);

    return;
  }

  //Check if song needs changing
  if(song[NowPlaying].song.getStatus() == sf::Music::Stopped){
    song[NowPlaying].Track++;
    if(song[NowPlaying].Track > song[NowPlaying].MaxTrack) song[NowPlaying].Track = 1;
    song[NowPlaying].position = sf::Time::Zero;
		sprintf(strSong,"music/%s%d.ogg",song[NowPlaying].FileName,song[NowPlaying].Track);
    LoadSong(NowPlaying, strSong, sf::Time::Zero, false);
  }
}

bool cDA2Music::Init(){
  /*1
	BASS_Init(1, 44100, 0, 0, 0);
	PlayTheme();
	return true;
  */
}

void cDA2Music::KillSong(int map){
	int i=Music[map];
  song[i].song.stop();
}

void cDA2Music::KillTheme(){
	DA2ThemeStream.stop();
}

void cDA2Music::LoadSong(int i, char* fn, sf::Time offset, bool silent){
  song[i].song.openFromFile(fn);
  song[i].song.setPlayingOffset(offset);
  //song[i].song.setVolume(0);
	song[i].song.setVolume(Volume*10);
  song[i].song.play();
}

void cDA2Music::PlayTheme(){
  DA2ThemeStream.setLoop(true);
	DA2ThemeStream.openFromFile("music/theme.ogg");
  DA2ThemeStream.play();
}

void cDA2Music::SetVolume(int vol){
	Volume=vol;
	song[NowPlaying].song.setVolume(Volume*10);
}<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "webkit/chromeos/fileapi/cros_mount_point_provider.h"

#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "base/message_loop_proxy.h"
#include "base/stringprintf.h"
#include "base/synchronization/lock.h"
#include "base/utf_string_conversions.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebSecurityOrigin.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebCString.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebFileSystem.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebString.h"
#include "webkit/chromeos/fileapi/file_access_permissions.h"
#include "webkit/fileapi/file_system_callback_dispatcher.h"
#include "webkit/fileapi/file_system_operation.h"
#include "webkit/fileapi/file_system_util.h"
#include "webkit/fileapi/native_file_util.h"
#include "webkit/glue/webkit_glue.h"

namespace chromeos {

typedef struct {
  const char* local_root_path;
  const char* web_root_path;
} FixedExposedPaths;

const char kChromeUIScheme[] = "chrome";

// Top level file system elements exposed in FileAPI in ChromeOS:
FixedExposedPaths fixed_exposed_paths[] = {
    {"/home/chronos/user/", "Downloads"},
    {"/media",              "archive"},
    {"/media",              "removable"},
};

CrosMountPointProvider::CrosMountPointProvider(
    scoped_refptr<quota::SpecialStoragePolicy> special_storage_policy)
    : special_storage_policy_(special_storage_policy),
      file_access_permissions_(new FileAccessPermissions()),
      local_file_util_(
          new fileapi::LocalFileUtil(new fileapi::NativeFileUtil())) {
  for (size_t i = 0; i < arraysize(fixed_exposed_paths); i++) {
    mount_point_map_.insert(std::pair<std::string, FilePath>(
        std::string(fixed_exposed_paths[i].web_root_path),
        FilePath(std::string(fixed_exposed_paths[i].local_root_path))));
  }
}

CrosMountPointProvider::~CrosMountPointProvider() {
}

// TODO(zelidrag) share with SandboxMountPointProvider impl.
std::string GetOriginIdentifierFromURL(
    const GURL& url) {
  WebKit::WebSecurityOrigin web_security_origin =
      WebKit::WebSecurityOrigin::createFromString(UTF8ToUTF16(url.spec()));
  return web_security_origin.databaseIdentifier().utf8();
}

bool CrosMountPointProvider::GetRootForVirtualPath(
    const FilePath& virtual_path, FilePath* root_path) {
  std::vector<FilePath::StringType> components;
  virtual_path.GetComponents(&components);
  if (components.size() < 1) {
    return false;
  }

  base::AutoLock locker(lock_);
  // Check if this root mount point is exposed by this provider.
  MountPointMap::iterator iter = mount_point_map_.find(components[0]);
  if (iter == mount_point_map_.end()) {
    return false;
  }
  *root_path = iter->second;
  return true;
}

void CrosMountPointProvider::ValidateFileSystemRoot(
    const GURL& origin_url,
    fileapi::FileSystemType type,
    bool create,
    const ValidateFileSystemCallback& callback) {
  // Nothing to validate for external filesystem.
  DCHECK(type == fileapi::kFileSystemTypeExternal);
  callback.Run(base::PLATFORM_FILE_OK);
}

FilePath CrosMountPointProvider::GetFileSystemRootPathOnFileThread(
    const GURL& origin_url,
    fileapi::FileSystemType type,
    const FilePath& virtual_path,
    bool create) {
  DCHECK(type == fileapi::kFileSystemTypeExternal);
  FilePath root_path;
  if (!GetRootForVirtualPath(virtual_path, &root_path))
    return FilePath();

  return root_path;
}

bool CrosMountPointProvider::IsAccessAllowed(const GURL& origin_url,
                                             fileapi::FileSystemType type,
                                             const FilePath& virtual_path) {
  if (type != fileapi::kFileSystemTypeExternal)
    return false;

  // Permit access to mount points from internal WebUI.
  if (origin_url.SchemeIs(kChromeUIScheme))
    return true;

  std::string extension_id = origin_url.host();
  // Check first to make sure this extension has fileBrowserHander permissions.
  if (!special_storage_policy_->IsFileHandler(extension_id))
    return false;

  return file_access_permissions_->HasAccessPermission(extension_id,
                                                       virtual_path);
}

// TODO(zelidrag): Share this code with SandboxMountPointProvider impl.
bool CrosMountPointProvider::IsRestrictedFileName(const FilePath& path) const {
  return false;
}

void CrosMountPointProvider::AddMountPoint(FilePath mount_point) {
  base::AutoLock locker(lock_);
  mount_point_map_.erase(mount_point.BaseName().value());
  mount_point_map_.insert(std::pair<std::string, FilePath>(
      mount_point.BaseName().value(), mount_point.DirName()));
}

void CrosMountPointProvider::RemoveMountPoint(FilePath mount_point) {
  base::AutoLock locker(lock_);
  mount_point_map_.erase(mount_point.BaseName().value());
}

void CrosMountPointProvider::GrantFullAccessToExtension(
    const std::string& extension_id) {
  DCHECK(special_storage_policy_->IsFileHandler(extension_id));
  if (!special_storage_policy_->IsFileHandler(extension_id))
    return;
  for (MountPointMap::const_iterator iter = mount_point_map_.begin();
       iter != mount_point_map_.end();
       ++iter) {
    GrantFileAccessToExtension(extension_id, FilePath(iter->first));
  }
}

void CrosMountPointProvider::GrantFileAccessToExtension(
    const std::string& extension_id, const FilePath& virtual_path) {
  // All we care about here is access from extensions for now.
  DCHECK(special_storage_policy_->IsFileHandler(extension_id));
  if (!special_storage_policy_->IsFileHandler(extension_id))
    return;
  file_access_permissions_->GrantAccessPermission(extension_id, virtual_path);
}

void CrosMountPointProvider::RevokeAccessForExtension(
      const std::string& extension_id) {
  file_access_permissions_->RevokePermissions(extension_id);
}

std::vector<FilePath> CrosMountPointProvider::GetRootDirectories() const {
  std::vector<FilePath> root_dirs;
  for (MountPointMap::const_iterator iter = mount_point_map_.begin();
       iter != mount_point_map_.end();
       ++iter) {
    root_dirs.push_back(iter->second.Append(iter->first));
  }
  return root_dirs;
}

fileapi::FileSystemFileUtil* CrosMountPointProvider::GetFileUtil() {
  return local_file_util_.get();
}

fileapi::FileSystemOperationInterface*
CrosMountPointProvider::CreateFileSystemOperation(
    const GURL& origin_url,
    fileapi::FileSystemType file_system_type,
    const FilePath& virtual_path,
    scoped_ptr<fileapi::FileSystemCallbackDispatcher> dispatcher,
    base::MessageLoopProxy* file_proxy,
    fileapi::FileSystemContext* context) const {
  // TODO(satorux,zel): instantiate appropriate FileSystemOperation that
  // implements async/remote operations.
  return new fileapi::FileSystemOperation(
      dispatcher.Pass(), file_proxy, context);
}

bool CrosMountPointProvider::GetVirtualPath(const FilePath& filesystem_path,
                                           FilePath* virtual_path) {
  for (MountPointMap::const_iterator iter = mount_point_map_.begin();
       iter != mount_point_map_.end();
       ++iter) {
    FilePath mount_prefix = iter->second.Append(iter->first);
    *virtual_path = FilePath(iter->first);
    if (mount_prefix.AppendRelativePath(filesystem_path, virtual_path)) {
      return true;
    } else if (mount_prefix == filesystem_path) {
      FilePath root = FilePath(FILE_PATH_LITERAL("/"));
      *virtual_path = root.Append(iter->first);
      return true;
    }
  }
  return false;
}

}  // namespace chromeos
<commit_msg>[cros] Fix the GetVirtualPath to always return the path without leading slash (as expected by clients).<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "webkit/chromeos/fileapi/cros_mount_point_provider.h"

#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "base/message_loop_proxy.h"
#include "base/stringprintf.h"
#include "base/synchronization/lock.h"
#include "base/utf_string_conversions.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebSecurityOrigin.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebCString.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebFileSystem.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebString.h"
#include "webkit/chromeos/fileapi/file_access_permissions.h"
#include "webkit/fileapi/file_system_callback_dispatcher.h"
#include "webkit/fileapi/file_system_operation.h"
#include "webkit/fileapi/file_system_util.h"
#include "webkit/fileapi/native_file_util.h"
#include "webkit/glue/webkit_glue.h"

namespace chromeos {

typedef struct {
  const char* local_root_path;
  const char* web_root_path;
} FixedExposedPaths;

const char kChromeUIScheme[] = "chrome";

// Top level file system elements exposed in FileAPI in ChromeOS:
FixedExposedPaths fixed_exposed_paths[] = {
    {"/home/chronos/user/", "Downloads"},
    {"/media",              "archive"},
    {"/media",              "removable"},
};

CrosMountPointProvider::CrosMountPointProvider(
    scoped_refptr<quota::SpecialStoragePolicy> special_storage_policy)
    : special_storage_policy_(special_storage_policy),
      file_access_permissions_(new FileAccessPermissions()),
      local_file_util_(
          new fileapi::LocalFileUtil(new fileapi::NativeFileUtil())) {
  for (size_t i = 0; i < arraysize(fixed_exposed_paths); i++) {
    mount_point_map_.insert(std::pair<std::string, FilePath>(
        std::string(fixed_exposed_paths[i].web_root_path),
        FilePath(std::string(fixed_exposed_paths[i].local_root_path))));
  }
}

CrosMountPointProvider::~CrosMountPointProvider() {
}

// TODO(zelidrag) share with SandboxMountPointProvider impl.
std::string GetOriginIdentifierFromURL(
    const GURL& url) {
  WebKit::WebSecurityOrigin web_security_origin =
      WebKit::WebSecurityOrigin::createFromString(UTF8ToUTF16(url.spec()));
  return web_security_origin.databaseIdentifier().utf8();
}

bool CrosMountPointProvider::GetRootForVirtualPath(
    const FilePath& virtual_path, FilePath* root_path) {
  std::vector<FilePath::StringType> components;
  virtual_path.GetComponents(&components);
  if (components.size() < 1) {
    return false;
  }

  base::AutoLock locker(lock_);
  // Check if this root mount point is exposed by this provider.
  MountPointMap::iterator iter = mount_point_map_.find(components[0]);
  if (iter == mount_point_map_.end()) {
    return false;
  }
  *root_path = iter->second;
  return true;
}

void CrosMountPointProvider::ValidateFileSystemRoot(
    const GURL& origin_url,
    fileapi::FileSystemType type,
    bool create,
    const ValidateFileSystemCallback& callback) {
  // Nothing to validate for external filesystem.
  DCHECK(type == fileapi::kFileSystemTypeExternal);
  callback.Run(base::PLATFORM_FILE_OK);
}

FilePath CrosMountPointProvider::GetFileSystemRootPathOnFileThread(
    const GURL& origin_url,
    fileapi::FileSystemType type,
    const FilePath& virtual_path,
    bool create) {
  DCHECK(type == fileapi::kFileSystemTypeExternal);
  FilePath root_path;
  if (!GetRootForVirtualPath(virtual_path, &root_path))
    return FilePath();

  return root_path;
}

bool CrosMountPointProvider::IsAccessAllowed(const GURL& origin_url,
                                             fileapi::FileSystemType type,
                                             const FilePath& virtual_path) {
  if (type != fileapi::kFileSystemTypeExternal)
    return false;

  // Permit access to mount points from internal WebUI.
  if (origin_url.SchemeIs(kChromeUIScheme))
    return true;

  std::string extension_id = origin_url.host();
  // Check first to make sure this extension has fileBrowserHander permissions.
  if (!special_storage_policy_->IsFileHandler(extension_id))
    return false;

  return file_access_permissions_->HasAccessPermission(extension_id,
                                                       virtual_path);
}

// TODO(zelidrag): Share this code with SandboxMountPointProvider impl.
bool CrosMountPointProvider::IsRestrictedFileName(const FilePath& path) const {
  return false;
}

void CrosMountPointProvider::AddMountPoint(FilePath mount_point) {
  base::AutoLock locker(lock_);
  mount_point_map_.erase(mount_point.BaseName().value());
  mount_point_map_.insert(std::pair<std::string, FilePath>(
      mount_point.BaseName().value(), mount_point.DirName()));
}

void CrosMountPointProvider::RemoveMountPoint(FilePath mount_point) {
  base::AutoLock locker(lock_);
  mount_point_map_.erase(mount_point.BaseName().value());
}

void CrosMountPointProvider::GrantFullAccessToExtension(
    const std::string& extension_id) {
  DCHECK(special_storage_policy_->IsFileHandler(extension_id));
  if (!special_storage_policy_->IsFileHandler(extension_id))
    return;
  for (MountPointMap::const_iterator iter = mount_point_map_.begin();
       iter != mount_point_map_.end();
       ++iter) {
    GrantFileAccessToExtension(extension_id, FilePath(iter->first));
  }
}

void CrosMountPointProvider::GrantFileAccessToExtension(
    const std::string& extension_id, const FilePath& virtual_path) {
  // All we care about here is access from extensions for now.
  DCHECK(special_storage_policy_->IsFileHandler(extension_id));
  if (!special_storage_policy_->IsFileHandler(extension_id))
    return;
  file_access_permissions_->GrantAccessPermission(extension_id, virtual_path);
}

void CrosMountPointProvider::RevokeAccessForExtension(
      const std::string& extension_id) {
  file_access_permissions_->RevokePermissions(extension_id);
}

std::vector<FilePath> CrosMountPointProvider::GetRootDirectories() const {
  std::vector<FilePath> root_dirs;
  for (MountPointMap::const_iterator iter = mount_point_map_.begin();
       iter != mount_point_map_.end();
       ++iter) {
    root_dirs.push_back(iter->second.Append(iter->first));
  }
  return root_dirs;
}

fileapi::FileSystemFileUtil* CrosMountPointProvider::GetFileUtil() {
  return local_file_util_.get();
}

fileapi::FileSystemOperationInterface*
CrosMountPointProvider::CreateFileSystemOperation(
    const GURL& origin_url,
    fileapi::FileSystemType file_system_type,
    const FilePath& virtual_path,
    scoped_ptr<fileapi::FileSystemCallbackDispatcher> dispatcher,
    base::MessageLoopProxy* file_proxy,
    fileapi::FileSystemContext* context) const {
  // TODO(satorux,zel): instantiate appropriate FileSystemOperation that
  // implements async/remote operations.
  return new fileapi::FileSystemOperation(
      dispatcher.Pass(), file_proxy, context);
}

bool CrosMountPointProvider::GetVirtualPath(const FilePath& filesystem_path,
                                           FilePath* virtual_path) {
  for (MountPointMap::const_iterator iter = mount_point_map_.begin();
       iter != mount_point_map_.end();
       ++iter) {
    FilePath mount_prefix = iter->second.Append(iter->first);
    *virtual_path = FilePath(iter->first);
    if (mount_prefix == filesystem_path) {
      return true;
    } else if (mount_prefix.AppendRelativePath(filesystem_path, virtual_path)) {
      return true;
    }
  }
  return false;
}

}  // namespace chromeos
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef INCLUDED_OOXML_FACTORY_HXX
#define INCLUDED_OOXML_FACTORY_HXX

#include <hash_map>
#include <boost/shared_ptr.hpp>

#ifndef INCLUDED_WW8_RESOURCE_MODEL_HXX
#include <resourcemodel/WW8ResourceModel.hxx>
#endif

#ifndef INCLUDED_OOXML_FAST_TOKENS_HXX
#include <ooxml/OOXMLFastTokens.hxx>
#endif

#ifndef INCLUDED_OOXML_FAST_CONTEXT_HANDLER_HXX
#include "OOXMLFastContextHandler.hxx"
#endif

namespace writerfilter {
namespace ooxml {

using namespace std;

enum ResourceType_t {
    RT_NoResource,
    RT_Table,
    RT_Stream,
    RT_List,
    RT_Integer,
    RT_Properties,
    RT_Hex,
    RT_String,
    RT_BooleanValue,
    RT_ListValue,
    RT_Shape,
    RT_Boolean,
    RT_HexValue,
    RT_IntegerValue,
    RT_StringValue,
    RT_XNote,
    RT_TextTableCell,
    RT_TextTableRow,
    RT_TextTable,
    RT_PropertyTable
};

typedef hash_map<Token_t, ResourceType_t> AttributeToResourceMap;
typedef boost::shared_ptr<AttributeToResourceMap> AttributeToResourceMapPointer;
typedef hash_map<Id, AttributeToResourceMapPointer> AttributesMap;

typedef hash_map<rtl::OUString, sal_Int32, ::rtl::OUStringHash> ListValueMap;
typedef boost::shared_ptr<ListValueMap> ListValueMapPointer;
typedef hash_map<Id, ListValueMapPointer> ListValuesMap;

struct CreateElement
{
    ResourceType_t m_nResource;
    Id m_nId;

    CreateElement(ResourceType_t nResource, Id nId);
    CreateElement();
};

typedef hash_map<Token_t, CreateElement> CreateElementMap;
typedef boost::shared_ptr<CreateElementMap> CreateElementMapPointer;
typedef hash_map<Id, CreateElementMapPointer> CreateElementsMap;
typedef hash_map<Id, string> IdToStringMap;
typedef boost::shared_ptr<IdToStringMap> IdToStringMapPointer;

typedef hash_map<Id, Token_t> TokenToIdMap;
typedef boost::shared_ptr<TokenToIdMap> TokenToIdMapPointer;
typedef hash_map<Id, TokenToIdMapPointer> TokenToIdsMap;

class OOXMLFactory_ns {
    virtual ~OOXMLFactory_ns();
public:
    typedef boost::shared_ptr<OOXMLFactory_ns> Pointer_t;

    virtual void startAction(OOXMLFastContextHandler * pHandler);
    virtual void charactersAction(OOXMLFastContextHandler * pHandler, const ::rtl::OUString & rString);
    virtual void endAction(OOXMLFastContextHandler * pHandler);
    virtual string getDefineName(Id nId) const;

    AttributeToResourceMapPointer getAttributeToResourceMap(Id nId);
    ListValueMapPointer getListValueMap(Id nId);
    CreateElementMapPointer getCreateElementMap(Id nId);
    TokenToIdMapPointer getTokenToIdMap(Id nId);

protected:
    AttributesMap m_AttributesMap;
    ListValuesMap m_ListValuesMap;
    CreateElementsMap m_CreateElementsMap;
    TokenToIdsMap m_TokenToIdsMap;

    virtual AttributeToResourceMapPointer createAttributeToResourceMap(Id nId) = 0;
    virtual ListValueMapPointer createListValueMap(Id nId) = 0;
    virtual CreateElementMapPointer createCreateElementMap(Id nId) = 0;
    virtual TokenToIdMapPointer createTokenToIdMap(Id nId) = 0;
};

class OOXMLFactory
{
public:
    typedef boost::shared_ptr<OOXMLFactory> Pointer_t;

    static Pointer_t getInstance();

    uno::Reference< xml::sax::XFastContextHandler> createFastChildContext
    (OOXMLFastContextHandler * pHandler, Token_t Element);

    uno::Reference< xml::sax::XFastContextHandler> createFastChildContextFromStart
    (OOXMLFastContextHandler * pHandler, Token_t Element);

    void attributes(OOXMLFastContextHandler * pHandler,
                    const uno::Reference< xml::sax::XFastAttributeList > & Attribs);

    void characters(OOXMLFastContextHandler * pHandler,
                    const ::rtl::OUString & rString);

    void startAction(OOXMLFastContextHandler * pHandler, Token_t nToken);
    void endAction(OOXMLFastContextHandler * pHandler, Token_t nToken);

    virtual ~OOXMLFactory();

private:
    static Pointer_t m_Instance;

    OOXMLFactory();
    OOXMLFactory_ns::Pointer_t getFactoryForNamespace(Id id);

    uno::Reference< xml::sax::XFastContextHandler>
    createFastChildContextFromFactory(OOXMLFastContextHandler * pHandler,
                                      OOXMLFactory_ns::Pointer_t pFactory,
                                      Token_t Element);
};

}
}

#endif // INCLUDED_OOXML_FACTORY_HXX
<commit_msg>virtual d'tor protected<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef INCLUDED_OOXML_FACTORY_HXX
#define INCLUDED_OOXML_FACTORY_HXX

#include <hash_map>
#include <boost/shared_ptr.hpp>

#ifndef INCLUDED_WW8_RESOURCE_MODEL_HXX
#include <resourcemodel/WW8ResourceModel.hxx>
#endif

#ifndef INCLUDED_OOXML_FAST_TOKENS_HXX
#include <ooxml/OOXMLFastTokens.hxx>
#endif

#ifndef INCLUDED_OOXML_FAST_CONTEXT_HANDLER_HXX
#include "OOXMLFastContextHandler.hxx"
#endif

namespace writerfilter {
namespace ooxml {

using namespace std;

enum ResourceType_t {
    RT_NoResource,
    RT_Table,
    RT_Stream,
    RT_List,
    RT_Integer,
    RT_Properties,
    RT_Hex,
    RT_String,
    RT_BooleanValue,
    RT_ListValue,
    RT_Shape,
    RT_Boolean,
    RT_HexValue,
    RT_IntegerValue,
    RT_StringValue,
    RT_XNote,
    RT_TextTableCell,
    RT_TextTableRow,
    RT_TextTable,
    RT_PropertyTable
};

typedef hash_map<Token_t, ResourceType_t> AttributeToResourceMap;
typedef boost::shared_ptr<AttributeToResourceMap> AttributeToResourceMapPointer;
typedef hash_map<Id, AttributeToResourceMapPointer> AttributesMap;

typedef hash_map<rtl::OUString, sal_Int32, ::rtl::OUStringHash> ListValueMap;
typedef boost::shared_ptr<ListValueMap> ListValueMapPointer;
typedef hash_map<Id, ListValueMapPointer> ListValuesMap;

struct CreateElement
{
    ResourceType_t m_nResource;
    Id m_nId;

    CreateElement(ResourceType_t nResource, Id nId);
    CreateElement();
};

typedef hash_map<Token_t, CreateElement> CreateElementMap;
typedef boost::shared_ptr<CreateElementMap> CreateElementMapPointer;
typedef hash_map<Id, CreateElementMapPointer> CreateElementsMap;
typedef hash_map<Id, string> IdToStringMap;
typedef boost::shared_ptr<IdToStringMap> IdToStringMapPointer;

typedef hash_map<Id, Token_t> TokenToIdMap;
typedef boost::shared_ptr<TokenToIdMap> TokenToIdMapPointer;
typedef hash_map<Id, TokenToIdMapPointer> TokenToIdsMap;

class OOXMLFactory_ns {
public:
    typedef boost::shared_ptr<OOXMLFactory_ns> Pointer_t;

    virtual void startAction(OOXMLFastContextHandler * pHandler);
    virtual void charactersAction(OOXMLFastContextHandler * pHandler, const ::rtl::OUString & rString);
    virtual void endAction(OOXMLFastContextHandler * pHandler);
    virtual string getDefineName(Id nId) const;

    AttributeToResourceMapPointer getAttributeToResourceMap(Id nId);
    ListValueMapPointer getListValueMap(Id nId);
    CreateElementMapPointer getCreateElementMap(Id nId);
    TokenToIdMapPointer getTokenToIdMap(Id nId);

protected:
    virtual ~OOXMLFactory_ns();

    AttributesMap m_AttributesMap;
    ListValuesMap m_ListValuesMap;
    CreateElementsMap m_CreateElementsMap;
    TokenToIdsMap m_TokenToIdsMap;

    virtual AttributeToResourceMapPointer createAttributeToResourceMap(Id nId) = 0;
    virtual ListValueMapPointer createListValueMap(Id nId) = 0;
    virtual CreateElementMapPointer createCreateElementMap(Id nId) = 0;
    virtual TokenToIdMapPointer createTokenToIdMap(Id nId) = 0;
};

class OOXMLFactory
{
public:
    typedef boost::shared_ptr<OOXMLFactory> Pointer_t;

    static Pointer_t getInstance();

    uno::Reference< xml::sax::XFastContextHandler> createFastChildContext
    (OOXMLFastContextHandler * pHandler, Token_t Element);

    uno::Reference< xml::sax::XFastContextHandler> createFastChildContextFromStart
    (OOXMLFastContextHandler * pHandler, Token_t Element);

    void attributes(OOXMLFastContextHandler * pHandler,
                    const uno::Reference< xml::sax::XFastAttributeList > & Attribs);

    void characters(OOXMLFastContextHandler * pHandler,
                    const ::rtl::OUString & rString);

    void startAction(OOXMLFastContextHandler * pHandler, Token_t nToken);
    void endAction(OOXMLFastContextHandler * pHandler, Token_t nToken);

    virtual ~OOXMLFactory();

private:
    static Pointer_t m_Instance;

    OOXMLFactory();
    OOXMLFactory_ns::Pointer_t getFactoryForNamespace(Id id);

    uno::Reference< xml::sax::XFastContextHandler>
    createFastChildContextFromFactory(OOXMLFastContextHandler * pHandler,
                                      OOXMLFactory_ns::Pointer_t pFactory,
                                      Token_t Element);
};

}
}

#endif // INCLUDED_OOXML_FACTORY_HXX
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: controlpropertymap.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: fs $ $Date: 2002-10-25 07:37:42 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc..
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _XMLOFF_FORMS_CONTROLPROPERTYMAP_HXX_
#define _XMLOFF_FORMS_CONTROLPROPERTYMAP_HXX_

#ifndef _XMLOFF_PROPERTYSETMAPPER_HXX
#include "xmlprmap.hxx"
#endif
#ifndef _XMLOFF_XMLEXPPR_HXX
#include "xmlexppr.hxx"
#endif

struct XMLPropertyMapEntry;
//.........................................................................
namespace xmloff
{
//.........................................................................

    extern XMLPropertyMapEntry aControlStyleProperties[];

    void initializePropertyMaps();

    //=====================================================================
    //= OFormExportPropertyMapper
    //=====================================================================
    class OFormExportPropertyMapper : public SvXMLExportPropertyMapper
    {
    public:
        OFormExportPropertyMapper( const UniReference< XMLPropertySetMapper >& _rMapper );

        void handleSpecialItem(
            SvXMLAttributeList&                         _rAttrList,
            const XMLPropertyState&                     _rProperty,
            const SvXMLUnitConverter&                   _rUnitConverter,
            const SvXMLNamespaceMap&                    _rNamespaceMap,
            const ::std::vector< XMLPropertyState >*    _pProperties,
            sal_uInt32                                  _nIdx
        ) const;
    };

//.........................................................................
}   // namespace xmloff
//.........................................................................

#endif // _XMLOFF_FORMS_CONTROLPROPERTYMAP_HXX_

/*************************************************************************
 * history:
 *  $Log: not supported by cvs2svn $
 *  Revision 1.1  2000/12/18 15:15:39  fs
 *  initial checkin - property maps
 *
 *
 *  Revision 1.0 14.12.00 10:26:48  fs
 ************************************************************************/

<commit_msg>#104402# -aControlStyleProperties / +getControlStypePropertyMap - problems with order of initialization of static variables<commit_after>/*************************************************************************
 *
 *  $RCSfile: controlpropertymap.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: fs $ $Date: 2002-12-20 08:21:52 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc..
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _XMLOFF_FORMS_CONTROLPROPERTYMAP_HXX_
#define _XMLOFF_FORMS_CONTROLPROPERTYMAP_HXX_

#ifndef _XMLOFF_PROPERTYSETMAPPER_HXX
#include "xmlprmap.hxx"
#endif
#ifndef _XMLOFF_XMLEXPPR_HXX
#include "xmlexppr.hxx"
#endif

struct XMLPropertyMapEntry;
//.........................................................................
namespace xmloff
{
//.........................................................................

    const XMLPropertyMapEntry* getControlStylePropertyMap( );

    void initializePropertyMaps();

    //=====================================================================
    //= OFormExportPropertyMapper
    //=====================================================================
    class OFormExportPropertyMapper : public SvXMLExportPropertyMapper
    {
    public:
        OFormExportPropertyMapper( const UniReference< XMLPropertySetMapper >& _rMapper );

        void handleSpecialItem(
            SvXMLAttributeList&                         _rAttrList,
            const XMLPropertyState&                     _rProperty,
            const SvXMLUnitConverter&                   _rUnitConverter,
            const SvXMLNamespaceMap&                    _rNamespaceMap,
            const ::std::vector< XMLPropertyState >*    _pProperties,
            sal_uInt32                                  _nIdx
        ) const;
    };

//.........................................................................
}   // namespace xmloff
//.........................................................................

#endif // _XMLOFF_FORMS_CONTROLPROPERTYMAP_HXX_

/*************************************************************************
 * history:
 *  $Log: not supported by cvs2svn $
 *  Revision 1.2  2002/10/25 07:37:42  fs
 *  #104402# +OFormExportPropertyMapper - handle the data-style attribute to store grid column styles
 *
 *  Revision 1.1  2000/12/18 15:15:39  fs
 *  initial checkin - property maps
 *
 *
 *  Revision 1.0 14.12.00 10:26:48  fs
 ************************************************************************/

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: XMLTextFrameContext.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: mtg $ $Date: 2001-02-23 14:39:03 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _XMLTEXTFRAMECONTEXT_HXX
#define _XMLTEXTFRAMECONTEXT_HXX

#ifndef _COM_SUN_STAR_TEXT_TEXTCONTENTANCHORTYPE_HPP
#include <com/sun/star/text/TextContentAnchorType.hpp>
#endif

#ifndef _XMLOFF_XMLICTXT_HXX
#include "xmlictxt.hxx"
#endif

namespace com { namespace sun { namespace star {
    namespace text { class XTextCursor; }
    namespace beans { class XPropertySet; }
} } }

#define XML_TEXT_FRAME_TEXTBOX 1
#define XML_TEXT_FRAME_GRAPHIC 2
#define XML_TEXT_FRAME_STAR 3
#define XML_TEXT_FRAME_OLE 4
#define XML_TEXT_FRAME_APPLET 5
#define XML_TEXT_FRAME_PLUGIN 6
#define XML_TEXT_FRAME_FLOATING_FRAME 7

class XMLTextFrameContext : public SvXMLImportContext
{
    ::com::sun::star::uno::Reference <
        ::com::sun::star::text::XTextCursor > xOldTextCursor;
    ::com::sun::star::uno::Reference <
        ::com::sun::star::beans::XPropertySet > xPropSet;

    const ::rtl::OUString sWidth;
    const ::rtl::OUString sRelativeWidth;
    const ::rtl::OUString sHeight;
    const ::rtl::OUString sRelativeHeight;
    const ::rtl::OUString sSizeType;
    const ::rtl::OUString sIsSyncWidthToHeight;
    const ::rtl::OUString sIsSyncHeightToWidth;
    const ::rtl::OUString sHoriOrientPosition;
    const ::rtl::OUString sVertOrientPosition;
    const ::rtl::OUString sChainNextName;
    const ::rtl::OUString sAnchorType;
    const ::rtl::OUString sAnchorPageNo;
    const ::rtl::OUString sGraphicURL;
    const ::rtl::OUString sGraphicFilter;
    const ::rtl::OUString sAlternativeText;
    const ::rtl::OUString sFrameStyleName;
    const ::rtl::OUString sGraphicRotation;
    const ::rtl::OUString sTextBoxServiceName;
    const ::rtl::OUString sGraphicServiceName;

    ::rtl::OUString sDesc;
    sal_uInt16 nType;

public:

    TYPEINFO();

    XMLTextFrameContext( SvXMLImport& rImport,
            sal_uInt16 nPrfx,
            const ::rtl::OUString& rLName,
            const ::com::sun::star::uno::Reference<
                ::com::sun::star::xml::sax::XAttributeList > & xAttrList,
            ::com::sun::star::text::TextContentAnchorType eAnchorType,
            sal_uInt16 nType );
    virtual ~XMLTextFrameContext();

    virtual void EndElement();

    SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix,
                const ::rtl::OUString& rLocalName,
                 const ::com::sun::star::uno::Reference<
                    ::com::sun::star::xml::sax::XAttributeList > & xAttrList );

    void SetHyperlink( const ::rtl::OUString& rHRef,
                       const ::rtl::OUString& rName,
                       const ::rtl::OUString& rTargetFrameName,
                       sal_Bool bMap );
};

#endif
<commit_msg>re-arranged support for applet/plugin parameters<commit_after>/*************************************************************************
 *
 *  $RCSfile: XMLTextFrameContext.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: mtg $ $Date: 2001-03-09 16:02:08 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _XMLTEXTFRAMECONTEXT_HXX
#define _XMLTEXTFRAMECONTEXT_HXX

#ifndef _COM_SUN_STAR_TEXT_TEXTCONTENTANCHORTYPE_HPP
#include <com/sun/star/text/TextContentAnchorType.hpp>
#endif

#ifndef _XMLOFF_XMLICTXT_HXX
#include "xmlictxt.hxx"
#endif

namespace com { namespace sun { namespace star {
    namespace text { class XTextCursor; }
    namespace beans { class XPropertySet; }
} } }

#define XML_TEXT_FRAME_TEXTBOX 1
#define XML_TEXT_FRAME_GRAPHIC 2
#define XML_TEXT_FRAME_STAR 3
#define XML_TEXT_FRAME_OLE 4
#define XML_TEXT_FRAME_APPLET 5
#define XML_TEXT_FRAME_PLUGIN 6
#define XML_TEXT_FRAME_FLOATING_FRAME 7

typedef ::std::map < const ::rtl::OUString, ::rtl::OUString, less_functor> ParamMap;

class XMLTextFrameContext : public SvXMLImportContext
{
    ::com::sun::star::uno::Reference <
        ::com::sun::star::text::XTextCursor > xOldTextCursor;
    ::com::sun::star::uno::Reference <
        ::com::sun::star::beans::XPropertySet > xPropSet;

    const ::rtl::OUString sWidth;
    const ::rtl::OUString sRelativeWidth;
    const ::rtl::OUString sHeight;
    const ::rtl::OUString sRelativeHeight;
    const ::rtl::OUString sSizeType;
    const ::rtl::OUString sIsSyncWidthToHeight;
    const ::rtl::OUString sIsSyncHeightToWidth;
    const ::rtl::OUString sHoriOrientPosition;
    const ::rtl::OUString sVertOrientPosition;
    const ::rtl::OUString sChainNextName;
    const ::rtl::OUString sAnchorType;
    const ::rtl::OUString sAnchorPageNo;
    const ::rtl::OUString sGraphicURL;
    const ::rtl::OUString sGraphicFilter;
    const ::rtl::OUString sAlternativeText;
    const ::rtl::OUString sFrameStyleName;
    const ::rtl::OUString sGraphicRotation;
    const ::rtl::OUString sTextBoxServiceName;
    const ::rtl::OUString sGraphicServiceName;

    ::rtl::OUString sDesc;
    sal_uInt16 nType;
    ParamMap aParamMap;

public:

    TYPEINFO();

    XMLTextFrameContext( SvXMLImport& rImport,
            sal_uInt16 nPrfx,
            const ::rtl::OUString& rLName,
            const ::com::sun::star::uno::Reference<
                ::com::sun::star::xml::sax::XAttributeList > & xAttrList,
            ::com::sun::star::text::TextContentAnchorType eAnchorType,
            sal_uInt16 nType );
    virtual ~XMLTextFrameContext();

    virtual void EndElement();

    SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix,
                const ::rtl::OUString& rLocalName,
                 const ::com::sun::star::uno::Reference<
                    ::com::sun::star::xml::sax::XAttributeList > & xAttrList );

    void SetHyperlink( const ::rtl::OUString& rHRef,
                       const ::rtl::OUString& rName,
                       const ::rtl::OUString& rTargetFrameName,
                       sal_Bool bMap );
};

#endif
<|endoftext|>