<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkPLYReader.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$
  Thanks:    Mike Dresser MD/PhD
             Director of Core Facility for Imaging
             Program in Molecular and Cell Biology
             Oklahoma Medical Research Foundation

Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

 * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
   of any contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

 * Modified source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=========================================================================*/
#include <ctype.h>
#include <string.h>
#include "vtkPLYReader.h"
#include "vtkPLY.h"
#include "vtkFloatArray.h"
#include "vtkObjectFactory.h"
#ifndef true
#define true 1
#endif
#ifndef false
#define false 0
#endif

//---------------------------------------------------------------------------
vtkPLYReader* vtkPLYReader::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkPLYReader");
  if(ret)
    {
    return (vtkPLYReader*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  return new vtkPLYReader;
}

// Construct object with merging set to true.
vtkPLYReader::vtkPLYReader()
{
  this->FileName = NULL;
}

vtkPLYReader::~vtkPLYReader()
{
  if (this->FileName)
    {
    delete [] this->FileName;
    }
}

typedef struct _plyVertex {
  float x[3];             // the usual 3-space position of a vertex
} plyVertex;

typedef struct _plyFace {
  unsigned char intensity; // optional face attributes
  unsigned char red;
  unsigned char green;
  unsigned char blue;
  unsigned char nverts;   // number of vertex indices in list
  int *verts;             // vertex index list
} plyFace;

void vtkPLYReader::Execute()
{
  PlyProperty vertProps[] = {
    {"x", PLY_FLOAT, PLY_FLOAT, offsetof(plyVertex,x[0]), 0, 0, 0, 0},
    {"y", PLY_FLOAT, PLY_FLOAT, offsetof(plyVertex,x[1]), 0, 0, 0, 0},
    {"z", PLY_FLOAT, PLY_FLOAT, offsetof(plyVertex,x[2]), 0, 0, 0, 0},
  };
  PlyProperty faceProps[] = {
    {"vertex_indices", PLY_INT, PLY_INT, offsetof(plyFace,verts),
     1, PLY_UCHAR, PLY_UCHAR, offsetof(plyFace,nverts)},
    {"intensity", PLY_UCHAR, PLY_UCHAR, offsetof(plyFace,intensity), 0, 0, 0, 0},
    {"red", PLY_UCHAR, PLY_UCHAR, offsetof(plyFace,red), 0, 0, 0, 0},
    {"green", PLY_UCHAR, PLY_UCHAR, offsetof(plyFace,green), 0, 0, 0, 0},
    {"blue", PLY_UCHAR, PLY_UCHAR, offsetof(plyFace,blue), 0, 0, 0, 0},
  };

  int i, j, k;
  int numPts, numPolys;
  vtkPolyData *output = (vtkPolyData *)this->GetOutput();

  if (!this->FileName)
    {
    vtkErrorMacro(<<"A File Name must be specified.");
    return;
    }

  // open a PLY file for reading
  PlyFile *ply;
  int nelems, fileType, numElems, nprops;
  char **elist, *elemName;
  float version;

  if ( !(ply = vtkPLY::ply_open_for_reading(this->FileName, &nelems, &elist,
                                            &fileType, &version)) )
    {
    vtkErrorMacro(<<"Could not open PLY file");
    return;
    }

  // Check to make sure that we can read geometry
  PlyElement *elem;
  int index;
  if ( (elem = vtkPLY::find_element (ply, "vertex")) == NULL ||
       vtkPLY::find_property (elem, "x", &index) == NULL ||
       vtkPLY::find_property (elem, "y", &index) == NULL ||
       vtkPLY::find_property (elem, "z", &index) == NULL ||
       (elem = vtkPLY::find_element (ply, "face")) == NULL ||
       vtkPLY::find_property (elem, "vertex_indices", &index) == NULL )
    {
    vtkErrorMacro(<<"Cannot read geometry");
    vtkPLY::ply_close (ply);
    }

  // Check for optional attribute data. We can handle intensity; and the
  // triplet red, green, blue.
  unsigned char intensityAvailable=false, RGBAvailable=false;
  vtkUnsignedCharArray *intensity=NULL;
  vtkUnsignedCharArray *RGB=NULL;
  if ( (elem = vtkPLY::find_element (ply, "face")) != NULL &&
       vtkPLY::find_property (elem, "intensity", &index) != NULL )
    {
    intensity = vtkUnsignedCharArray::New();
    intensity->SetName("intensity");
    intensityAvailable = true;
    output->GetCellData()->AddArray(intensity);
    output->GetCellData()->SetActiveScalars("intensity");
    intensity->Delete();
    }

  if ( (elem = vtkPLY::find_element (ply, "face")) != NULL &&
       vtkPLY::find_property (elem, "red", &index) != NULL &&
       vtkPLY::find_property (elem, "green", &index) != NULL &&
       vtkPLY::find_property (elem, "blue", &index) != NULL )
    {
    RGB = vtkUnsignedCharArray::New();
    RGB->SetName("RGB");
    RGBAvailable = true;
    output->GetCellData()->AddArray(RGB);
    output->GetCellData()->SetActiveScalars("RGB");
    RGB->Delete();
    }

  // Okay, now we can grab the data
  for (i = 0; i < nelems; i++)
    {
    //get the description of the first element */
    elemName = elist[i];
    vtkPLY::ply_get_element_description (ply, elemName, &numElems, &nprops);

    // if we're on vertex elements, read them in
    if ( elemName && !strcmp ("vertex", elemName) )
      {
      // Create a list of points
      numPts = numElems;
      vtkPoints *pts = vtkPoints::New();
      pts->SetDataTypeToFloat();
      pts->SetNumberOfPoints(numPts);
      float *ptsPtr = ((vtkFloatArray *)pts->GetData())->GetPointer(0);

      // Setup to read the PLY elements
      vtkPLY::ply_get_property (ply, elemName, &vertProps[0]);
      vtkPLY::ply_get_property (ply, elemName, &vertProps[1]);
      vtkPLY::ply_get_property (ply, elemName, &vertProps[2]);

      for (j=0; j < numPts; j++, ptsPtr+=3)
        {
        vtkPLY::ply_get_element (ply, (void *) ptsPtr);
        }
      output->SetPoints(pts);
      pts->Delete();
      }//if vertex

    else if ( elemName && !strcmp ("face", elemName) )
      {
      // Create a polygonal array
      numPolys = numElems;
      vtkCellArray *polys = vtkCellArray::New();
      polys->Allocate(polys->EstimateSize(numPolys,3),numPolys/2);
      plyFace face;
      int verts[256];
      vtkIdType vtkVerts[256];

      // Get the face properties
      vtkPLY::ply_get_property (ply, elemName, &faceProps[0]);
      if ( intensityAvailable )
        {
        vtkPLY::ply_get_property (ply, elemName, &faceProps[1]);
        RGB->SetNumberOfComponents(1);
        RGB->SetNumberOfTuples(numPolys);
        }
      if ( RGBAvailable )
        {
        vtkPLY::ply_get_property (ply, elemName, &faceProps[2]);
        vtkPLY::ply_get_property (ply, elemName, &faceProps[3]);
        vtkPLY::ply_get_property (ply, elemName, &faceProps[4]);
        RGB->SetNumberOfComponents(3);
        RGB->SetNumberOfTuples(numPolys);
        }

      // grab all the face elements
      for (j=0; j < numPolys; j++)
        {
        //grab and element from the file
        face.verts = verts;
        vtkPLY::ply_get_element (ply, (void *) &face);
        for (k=0; k<face.nverts; k++)
          {
          vtkVerts[k] = face.verts[k];
          }
        polys->InsertNextCell(face.nverts,vtkVerts);
        if ( intensityAvailable )
          {
          intensity->SetValue(j,face.intensity);
          }
        if ( RGBAvailable )
          {
          RGB->SetValue(3*j,face.red);
          RGB->SetValue(3*j+1,face.green);
          RGB->SetValue(3*j+2,face.blue);
          }
        }
      output->SetPolys(polys);
      polys->Delete();
      }//if face

    }//for all elements of the PLY file

  vtkDebugMacro( <<"Read: " << numPts << " points, "
                 << numPolys << " polygons");

  // close the PLY file
  vtkPLY::ply_close (ply);

}

void vtkPLYReader::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkPolyDataSource::PrintSelf(os,indent);

  os << indent << "File Name: "
     << (this->FileName ? this->FileName : "(none)") << "\n";

}
<commit_msg>ERR:Memory leak<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkPLYReader.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$
  Thanks:    Mike Dresser MD/PhD
             Director of Core Facility for Imaging
             Program in Molecular and Cell Biology
             Oklahoma Medical Research Foundation

Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

 * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
   of any contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

 * Modified source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=========================================================================*/
#include <ctype.h>
#include <string.h>
#include "vtkPLYReader.h"
#include "vtkPLY.h"
#include "vtkFloatArray.h"
#include "vtkObjectFactory.h"
#ifndef true
#define true 1
#endif
#ifndef false
#define false 0
#endif

//---------------------------------------------------------------------------
vtkPLYReader* vtkPLYReader::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkPLYReader");
  if(ret)
    {
    return (vtkPLYReader*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  return new vtkPLYReader;
}

// Construct object with merging set to true.
vtkPLYReader::vtkPLYReader()
{
  this->FileName = NULL;
}

vtkPLYReader::~vtkPLYReader()
{
  if (this->FileName)
    {
    delete [] this->FileName;
    }
}

typedef struct _plyVertex {
  float x[3];             // the usual 3-space position of a vertex
} plyVertex;

typedef struct _plyFace {
  unsigned char intensity; // optional face attributes
  unsigned char red;
  unsigned char green;
  unsigned char blue;
  unsigned char nverts;   // number of vertex indices in list
  int *verts;             // vertex index list
} plyFace;

void vtkPLYReader::Execute()
{
  PlyProperty vertProps[] = {
    {"x", PLY_FLOAT, PLY_FLOAT, offsetof(plyVertex,x[0]), 0, 0, 0, 0},
    {"y", PLY_FLOAT, PLY_FLOAT, offsetof(plyVertex,x[1]), 0, 0, 0, 0},
    {"z", PLY_FLOAT, PLY_FLOAT, offsetof(plyVertex,x[2]), 0, 0, 0, 0},
  };
  PlyProperty faceProps[] = {
    {"vertex_indices", PLY_INT, PLY_INT, offsetof(plyFace,verts),
     1, PLY_UCHAR, PLY_UCHAR, offsetof(plyFace,nverts)},
    {"intensity", PLY_UCHAR, PLY_UCHAR, offsetof(plyFace,intensity), 0, 0, 0, 0},
    {"red", PLY_UCHAR, PLY_UCHAR, offsetof(plyFace,red), 0, 0, 0, 0},
    {"green", PLY_UCHAR, PLY_UCHAR, offsetof(plyFace,green), 0, 0, 0, 0},
    {"blue", PLY_UCHAR, PLY_UCHAR, offsetof(plyFace,blue), 0, 0, 0, 0},
  };

  int i, j, k;
  int numPts, numPolys;
  vtkPolyData *output = (vtkPolyData *)this->GetOutput();

  if (!this->FileName)
    {
    vtkErrorMacro(<<"A File Name must be specified.");
    return;
    }

  // open a PLY file for reading
  PlyFile *ply;
  int nelems, fileType, numElems, nprops;
  char **elist, *elemName;
  float version;

  if ( !(ply = vtkPLY::ply_open_for_reading(this->FileName, &nelems, &elist,
                                            &fileType, &version)) )
    {
    vtkErrorMacro(<<"Could not open PLY file");
    return;
    }

  // Check to make sure that we can read geometry
  PlyElement *elem;
  int index;
  if ( (elem = vtkPLY::find_element (ply, "vertex")) == NULL ||
       vtkPLY::find_property (elem, "x", &index) == NULL ||
       vtkPLY::find_property (elem, "y", &index) == NULL ||
       vtkPLY::find_property (elem, "z", &index) == NULL ||
       (elem = vtkPLY::find_element (ply, "face")) == NULL ||
       vtkPLY::find_property (elem, "vertex_indices", &index) == NULL )
    {
    vtkErrorMacro(<<"Cannot read geometry");
    vtkPLY::ply_close (ply);
    }

  // Check for optional attribute data. We can handle intensity; and the
  // triplet red, green, blue.
  unsigned char intensityAvailable=false, RGBAvailable=false;
  vtkUnsignedCharArray *intensity=NULL;
  vtkUnsignedCharArray *RGB=NULL;
  if ( (elem = vtkPLY::find_element (ply, "face")) != NULL &&
       vtkPLY::find_property (elem, "intensity", &index) != NULL )
    {
    intensity = vtkUnsignedCharArray::New();
    intensity->SetName("intensity");
    intensityAvailable = true;
    output->GetCellData()->AddArray(intensity);
    output->GetCellData()->SetActiveScalars("intensity");
    intensity->Delete();
    }

  if ( (elem = vtkPLY::find_element (ply, "face")) != NULL &&
       vtkPLY::find_property (elem, "red", &index) != NULL &&
       vtkPLY::find_property (elem, "green", &index) != NULL &&
       vtkPLY::find_property (elem, "blue", &index) != NULL )
    {
    RGB = vtkUnsignedCharArray::New();
    RGB->SetName("RGB");
    RGBAvailable = true;
    output->GetCellData()->AddArray(RGB);
    output->GetCellData()->SetActiveScalars("RGB");
    RGB->Delete();
    }

  // Okay, now we can grab the data
  for (i = 0; i < nelems; i++)
    {
    //get the description of the first element */
    elemName = elist[i];
    vtkPLY::ply_get_element_description (ply, elemName, &numElems, &nprops);

    // if we're on vertex elements, read them in
    if ( elemName && !strcmp ("vertex", elemName) )
      {
      // Create a list of points
      numPts = numElems;
      vtkPoints *pts = vtkPoints::New();
      pts->SetDataTypeToFloat();
      pts->SetNumberOfPoints(numPts);
      float *ptsPtr = ((vtkFloatArray *)pts->GetData())->GetPointer(0);

      // Setup to read the PLY elements
      vtkPLY::ply_get_property (ply, elemName, &vertProps[0]);
      vtkPLY::ply_get_property (ply, elemName, &vertProps[1]);
      vtkPLY::ply_get_property (ply, elemName, &vertProps[2]);

      for (j=0; j < numPts; j++, ptsPtr+=3)
        {
        vtkPLY::ply_get_element (ply, (void *) ptsPtr);
        }
      output->SetPoints(pts);
      pts->Delete();
      }//if vertex

    else if ( elemName && !strcmp ("face", elemName) )
      {
      // Create a polygonal array
      numPolys = numElems;
      vtkCellArray *polys = vtkCellArray::New();
      polys->Allocate(polys->EstimateSize(numPolys,3),numPolys/2);
      plyFace face;
      int verts[256];
      vtkIdType vtkVerts[256];

      // Get the face properties
      vtkPLY::ply_get_property (ply, elemName, &faceProps[0]);
      if ( intensityAvailable )
        {
        vtkPLY::ply_get_property (ply, elemName, &faceProps[1]);
        RGB->SetNumberOfComponents(1);
        RGB->SetNumberOfTuples(numPolys);
        }
      if ( RGBAvailable )
        {
        vtkPLY::ply_get_property (ply, elemName, &faceProps[2]);
        vtkPLY::ply_get_property (ply, elemName, &faceProps[3]);
        vtkPLY::ply_get_property (ply, elemName, &faceProps[4]);
        RGB->SetNumberOfComponents(3);
        RGB->SetNumberOfTuples(numPolys);
        }

      // grab all the face elements
      for (j=0; j < numPolys; j++)
        {
        //grab and element from the file
        face.verts = verts;
        vtkPLY::ply_get_element (ply, (void *) &face);
        for (k=0; k<face.nverts; k++)
          {
          vtkVerts[k] = face.verts[k];
          }
        polys->InsertNextCell(face.nverts,vtkVerts);
        if ( intensityAvailable )
          {
          intensity->SetValue(j,face.intensity);
          }
        if ( RGBAvailable )
          {
          RGB->SetValue(3*j,face.red);
          RGB->SetValue(3*j+1,face.green);
          RGB->SetValue(3*j+2,face.blue);
          }
        }
      output->SetPolys(polys);
      polys->Delete();
      }//if face

    free(elist[i]); //allocated by ply_open_for_reading

    }//for all elements of the PLY file
  free(elist); //allocated by ply_open_for_reading

  vtkDebugMacro( <<"Read: " << numPts << " points, "
                 << numPolys << " polygons");

  // close the PLY file
  vtkPLY::ply_close (ply);

}

void vtkPLYReader::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkPolyDataSource::PrintSelf(os,indent);

  os << indent << "File Name: "
     << (this->FileName ? this->FileName : "(none)") << "\n";

}
<|endoftext|>


<commit_before>#include "config_manager.h"

using namespace std;
using namespace TOOLS;

ConfigDataKeeper::ConfigDataKeeper(const ConfigDataKeeper& obj)
  : storage(obj.storage), tinfo(obj.tinfo) { }

ConfigDataKeeper::ConfigDataKeeper(void* data, const string& tinfo)
  : storage(data), tinfo(tinfo) { }

ConfigDataKeeper::ConfigDataKeeper(const string& tinfo)
  : storage(nullptr), tinfo(tinfo) { }

// return verbose type string
string ConfigDataKeeper::verbose_type() const {
  if(tinfo == typeid(int).name())
    return "integer";
  else if(tinfo == typeid(double).name())
    return "float";
  else if(tinfo == typeid(string).name())
    return "string";
  else if(tinfo == typeid(tStringList).name())
    return "string list";
  else if(tinfo == typeid(tStringMap).name())
    return "string map";
  else if(tinfo == typeid(bool).name())
    return "boolean";
  return "unknown data type!!! ";
}

// return verbose data string representation
string ConfigDataKeeper::verbose_data(void* raw_data) const {
  string out;
  const ConfigDataKeeper* cdk;
  if(raw_data != nullptr)
    cdk = new ConfigDataKeeper(raw_data, tinfo);
  else
    cdk = this;

  if(tinfo == typeid(int).name())
    out = str(cdk->get<int>());
  else if(tinfo == typeid(double).name())
    out = str(cdk->get<double>());
  else if(tinfo == typeid(string).name())
    out = cdk->get<string>();
  else if(tinfo == typeid(tStringList).name())
    out = XString(",").join(cdk->get<tStringList>());
  else if(tinfo == typeid(tStringMap).name()) {
    tStringList tmp;
    for(auto& key_val : cdk->get<tStringMap>())
      tmp.push_back(key_val.first + ":" + key_val.second);
    out = XString(",").join(tmp);
  } else if(tinfo == typeid(bool).name())
    out = (cdk->get<bool>()) ? "true" : "false";
  else
    out = "unknown data";

  if(raw_data != nullptr)
    delete cdk;
  return out;
}

ConfigOption::ConfigOption(const std::string& id, const std::string& desc, \
  const std::string& tinfo, const std::string& scmd)
  : data(tinfo), default_data(tinfo), id(id), cmd_short(scmd), desc(desc),
    was_set(false), has_default(false), parent(NULL) { }

string ConfigOption::verbose_type() const {
  return data.verbose_type();
}

string ConfigOption::verbose_data() const {
  if(was_set)
    return data.verbose_data();
  else if(has_default)
    return verbose_default();
  else
    return "<no data>";
}

string ConfigOption::verbose_default() const {
  if(has_default)
    return default_data.verbose_data();
  return "<no default set>";
}

ConfigGroup::ConfigGroup(const std::string& name, ConfigManager* par)
  : name(name), parent(par)  {}

ConfigGroup::iterator ConfigGroup::begin() {
  return members.begin();
}

ConfigGroup::const_iterator ConfigGroup::begin() const {
  return members.begin();
}

ConfigGroup::iterator ConfigGroup::end() {
  return members.end();
}

ConfigGroup::const_iterator ConfigGroup::end() const {
  return members.end();
}

ConfigOption& ConfigGroup::get_option(const std::string& id) {
  tOptionIter it = members.find(id);
  if(it != members.end())
    return *it->second;
  throw OptionNotFound(id);
}

ConfigGroup& ConfigManager::new_group(const std::string& name) {
  groups[name] = new ConfigGroup(name, this);
  return *groups[name];
}

ConfigGroup& ConfigManager::get_group(const string& name) {
  tGroupIter it = groups.find(name);
  if(it == groups.end())
    throw GroupNotFound(name);
  return *it->second;
}

ConfigGroup& ConfigManager::get_group_from_option(const string& name) {
  return *(get_option(name).parent);
}

ConfigOption& ConfigManager::get_option(const std::string& id) {
  tOptionIter it = members.find(id);
  if(it == members.end())
    throw OptionNotFound(id);
  return *(it->second);
}

ConfigManager::iterator ConfigManager::begin() {
  return groups.begin();
}

ConfigManager::const_iterator ConfigManager::begin() const {
  return groups.begin();
}

ConfigManager::iterator ConfigManager::end() {
  return groups.end();
}

ConfigManager::const_iterator ConfigManager::end() const {
  return groups.end();
}

ConfigManager::ConfigManager(const std::string& start_command)
  : command(start_command) { }

void ConfigManager::parse(tStringList* args) {
  string cmd = args->at(0);

  if(cmdmap.find(cmd) == cmdmap.end())
    throw UnknownParameter(cmd);

  string id = cmdmap[cmd];
  ConfigDataKeeper* tmp = &members[id]->data;

  // catch boolean value as this doesn't need an arg
  if(tmp->same_data_types<bool>()) {
    // even if possible, a arg for bools may be passed
    if(args->size() > 1) {
      bool explicit_set = false;
      if(args->at(1) == "true") {
        explicit_set = true;
        set<bool>(id, true);
      } else if(args->at(1) == "false") {
        explicit_set = true;
        set<bool>(id, false);
      }
      if(explicit_set) {
        args->erase(args->begin(), args->begin()+2);
        return;
      }
    }

    // if not passed, just toggle or set to true
    if(members[id]->has_default)
      set<bool>(id, !get<bool>(id));
    else
      set<bool>(id, true);
    args->erase(args->begin());
    return;
  }

  if(args->size() < 2)
    throw MissingParameter(cmd + " - found no more args");

  string arg = args->at(1);

  // check for integer and double
  try {
    if(tmp->same_data_types<int>()) {
      set<int>(id, integer(arg));
      args->erase(args->begin(), args->begin()+2);
      return;
    } else if(tmp->same_data_types<double>()) {
      set<double>(id, real(arg));
      args->erase(args->begin(), args->begin()+2);
      return;
    }
  } catch(ConvertValueError e) {
    throw IncompatibleDataTypes("data: " + tmp->verbose_type() + " passed: " + arg);
  }

  // get string
  if(tmp->same_data_types<string>()) {
    set<string>(id, str(arg));
    args->erase(args->begin(), args->begin()+2);
    return;
  }

  // build tStringList from "," separated input
  if(tmp->same_data_types<tStringList>()) {
    set<tStringList>(id, XString(arg).split(","));
    args->erase(args->begin(), args->begin()+2);
    return;
    // build tStringMap from "," and ":" separated input
  }
  if(tmp->same_data_types<tStringMap>()) {
    tStringList tmp = XString(arg).split(",");
    tStringMap tmpmap;
    for(tStringIter i=tmp.begin(); i!=tmp.end(); ++i) {
      tStringList two = XString(*i).split(":");
      tmpmap[two[0]] = two[1];
    }
    set<tStringMap>(id, tmpmap);
    args->erase(args->begin(), args->begin()+2);
    return;
  }
  throw IncompatibleDataTypes("data: " + tmp->verbose_type() + " passed: " + arg);
}

void ConfigManager::parse_cmdline(int argc, char* argv[]) {
  tStringList args;
  for(int i=1; i<argc; ++i)
    args.push_back(argv[i]);

  while(args.size() > 0)
    parse(&args);
}

void ConfigManager::write_config_file(ostream& fd, bool shorter) {
  fd << endl;
  fd << "###" << endl;
  fd << "### config file for: " << command << endl;
  fd << "###" << endl;
  fd << endl;
  for(tGroupPair& grp : groups) {
    if(!shorter)
      fd << "####################################################" << endl;
    else
      fd << endl;
    fd << "# [ " << grp.first << " ]" << endl;
    for(tOptionPair& opt : *grp.second) {
      const ConfigOption* c = opt.second;
      const string& id = opt.first;

      // write desc/help text
      if(!shorter) {
        fd << "# " << c->desc << " [" << c->verbose_type() << "]";
        // write if ConfigOption has default
        if(c->has_default)
          fd << " default: " << c->verbose_default();
        fd << endl;
      }

      // ConfigOption was set, output its value
      if(c->was_set) {
        fd << id << " = " << c->verbose_data() << endl;
      // ConfigOption was _not_ set, output commented out line and default
      } else if(c->has_default) {
          fd << "# " << id << " = " << c->verbose_default() << endl;
      // ConfigOption was neither set nor has a default value
      } else {
        if(!shorter)
          fd << "# " << id << " = " << "<not set>" << endl;
      }
      if(!shorter)
        fd << endl;
    }
  }
}

void ConfigManager::parse_config_file(const string& fn) {
  ifstream fd(fn.c_str(), ios::in);
  XString line;
  tStringList tokens;
  while(fd.good()) {
    getline(fd, line);
    line.strip().strip("\n");
    if(line.length() == 0)
      continue;

    if(line.startswith("#"))
      continue;

    if(line.find("=") == string::npos) {
      tokens.push_back("--" + line);
      continue;
    }

    tStringList lr = line.split("=");
    XString left(lr[0]), right(lr[1]);
    left.strip();
    right.strip();

    tokens.push_back("--" + left);
    tokens.push_back(right);
  }
  fd.close();

  try {
    while(tokens.size() > 0)
      parse(&tokens);

  } catch(IncompatibleDataTypes& e) {
    e.message += " (inside configfile)";
    throw e;
  }
}

bool ConfigManager::is_group_active(const std::string& name) {
  tOptionMap& opts = groups[name]->members;
  for(tOptionIter i=opts.begin(); i!=opts.end(); ++i)
    if(i->second->was_set)
      return true;
  return false;
}

bool ConfigManager::is_option_set(const std::string& id) {
  return (get_option(id).was_set || get_option(id).has_default);
}

void ConfigManager::show_config(ostream& ss) {
  ss << "Showing all ConfigManager settings:" << endl << endl;
  for(tGroupPair& grp : groups) {
    ss << "[Group] -> " << grp.first << endl;
    for(tOptionPair& opt : grp.second->members) {
      ss << "[Option] " << opt.first << " = " << \
            opt.second->verbose_data() << endl;
    }
  }
}

void ConfigManager::usage(ostream& ss) {
  ss << "Usage: " << command << " <options>" << endl;
  ss << endl << "Options:" << endl;

  string::size_type id_len = 0, scmd_len = 0, desc_len = 0;
  for(tStringMapIter i=cmdmap.begin(); i!=cmdmap.end(); ++i) {
    ConfigOption* opt = members[i->second];
    if(i->first.find("--") != string::npos)
      id_len = max(opt->id.length(), id_len);
    else
      scmd_len = max(opt->cmd_short.length(), scmd_len);
    desc_len = max(opt->desc.length(), desc_len);
  }

  for(tGroupIter g=groups.begin(); g!=groups.end(); ++g) {
    ConfigGroup* grp = g->second;
    ss << endl << "--- Group: " << grp->name << endl;
    for(tOptionIter i=grp->members.begin(); i!=grp->members.end(); ++i) {
      ConfigOption* opt = grp->members[i->first];

      ss << right << setw(scmd_len+1) << ((opt->cmd_short.size() > 0) ? \
                                          ("-" + opt->cmd_short) : "") << " | " << flush;
      ss << left << setw(id_len+2) << ("--" + opt->id) << "   " << opt->desc;
      ss << " [" << opt->data.verbose_type() << "]";
      ss << endl;
    }
  }
  ss << endl;
}
<commit_msg>config manager now writes all config options in config-write-short-method<commit_after>#include "config_manager.h"

using namespace std;
using namespace TOOLS;

ConfigDataKeeper::ConfigDataKeeper(const ConfigDataKeeper& obj)
  : storage(obj.storage), tinfo(obj.tinfo) { }

ConfigDataKeeper::ConfigDataKeeper(void* data, const string& tinfo)
  : storage(data), tinfo(tinfo) { }

ConfigDataKeeper::ConfigDataKeeper(const string& tinfo)
  : storage(nullptr), tinfo(tinfo) { }

// return verbose type string
string ConfigDataKeeper::verbose_type() const {
  if(tinfo == typeid(int).name())
    return "integer";
  else if(tinfo == typeid(double).name())
    return "float";
  else if(tinfo == typeid(string).name())
    return "string";
  else if(tinfo == typeid(tStringList).name())
    return "string list";
  else if(tinfo == typeid(tStringMap).name())
    return "string map";
  else if(tinfo == typeid(bool).name())
    return "boolean";
  return "unknown data type!!! ";
}

// return verbose data string representation
string ConfigDataKeeper::verbose_data(void* raw_data) const {
  string out;
  const ConfigDataKeeper* cdk;
  if(raw_data != nullptr)
    cdk = new ConfigDataKeeper(raw_data, tinfo);
  else
    cdk = this;

  if(tinfo == typeid(int).name())
    out = str(cdk->get<int>());
  else if(tinfo == typeid(double).name())
    out = str(cdk->get<double>());
  else if(tinfo == typeid(string).name())
    out = cdk->get<string>();
  else if(tinfo == typeid(tStringList).name())
    out = XString(",").join(cdk->get<tStringList>());
  else if(tinfo == typeid(tStringMap).name()) {
    tStringList tmp;
    for(auto& key_val : cdk->get<tStringMap>())
      tmp.push_back(key_val.first + ":" + key_val.second);
    out = XString(",").join(tmp);
  } else if(tinfo == typeid(bool).name())
    out = (cdk->get<bool>()) ? "true" : "false";
  else
    out = "unknown data";

  if(raw_data != nullptr)
    delete cdk;
  return out;
}

ConfigOption::ConfigOption(const std::string& id, const std::string& desc, \
  const std::string& tinfo, const std::string& scmd)
  : data(tinfo), default_data(tinfo), id(id), cmd_short(scmd), desc(desc),
    was_set(false), has_default(false), parent(NULL) { }

string ConfigOption::verbose_type() const {
  return data.verbose_type();
}

string ConfigOption::verbose_data() const {
  if(was_set)
    return data.verbose_data();
  else if(has_default)
    return verbose_default();
  else
    return "<no data>";
}

string ConfigOption::verbose_default() const {
  if(has_default)
    return default_data.verbose_data();
  return "<no default set>";
}

ConfigGroup::ConfigGroup(const std::string& name, ConfigManager* par)
  : name(name), parent(par)  {}

ConfigGroup::iterator ConfigGroup::begin() {
  return members.begin();
}

ConfigGroup::const_iterator ConfigGroup::begin() const {
  return members.begin();
}

ConfigGroup::iterator ConfigGroup::end() {
  return members.end();
}

ConfigGroup::const_iterator ConfigGroup::end() const {
  return members.end();
}

ConfigOption& ConfigGroup::get_option(const std::string& id) {
  tOptionIter it = members.find(id);
  if(it != members.end())
    return *it->second;
  throw OptionNotFound(id);
}

ConfigGroup& ConfigManager::new_group(const std::string& name) {
  groups[name] = new ConfigGroup(name, this);
  return *groups[name];
}

ConfigGroup& ConfigManager::get_group(const string& name) {
  tGroupIter it = groups.find(name);
  if(it == groups.end())
    throw GroupNotFound(name);
  return *it->second;
}

ConfigGroup& ConfigManager::get_group_from_option(const string& name) {
  return *(get_option(name).parent);
}

ConfigOption& ConfigManager::get_option(const std::string& id) {
  tOptionIter it = members.find(id);
  if(it == members.end())
    throw OptionNotFound(id);
  return *(it->second);
}

ConfigManager::iterator ConfigManager::begin() {
  return groups.begin();
}

ConfigManager::const_iterator ConfigManager::begin() const {
  return groups.begin();
}

ConfigManager::iterator ConfigManager::end() {
  return groups.end();
}

ConfigManager::const_iterator ConfigManager::end() const {
  return groups.end();
}

ConfigManager::ConfigManager(const std::string& start_command)
  : command(start_command) { }

void ConfigManager::parse(tStringList* args) {
  string cmd = args->at(0);

  if(cmdmap.find(cmd) == cmdmap.end())
    throw UnknownParameter(cmd);

  string id = cmdmap[cmd];
  ConfigDataKeeper* tmp = &members[id]->data;

  // catch boolean value as this doesn't need an arg
  if(tmp->same_data_types<bool>()) {
    // even if possible, a arg for bools may be passed
    if(args->size() > 1) {
      bool explicit_set = false;
      if(args->at(1) == "true") {
        explicit_set = true;
        set<bool>(id, true);
      } else if(args->at(1) == "false") {
        explicit_set = true;
        set<bool>(id, false);
      }
      if(explicit_set) {
        args->erase(args->begin(), args->begin()+2);
        return;
      }
    }

    // if not passed, just toggle or set to true
    if(members[id]->has_default)
      set<bool>(id, !get<bool>(id));
    else
      set<bool>(id, true);
    args->erase(args->begin());
    return;
  }

  if(args->size() < 2)
    throw MissingParameter(cmd + " - found no more args");

  string arg = args->at(1);

  // check for integer and double
  try {
    if(tmp->same_data_types<int>()) {
      set<int>(id, integer(arg));
      args->erase(args->begin(), args->begin()+2);
      return;
    } else if(tmp->same_data_types<double>()) {
      set<double>(id, real(arg));
      args->erase(args->begin(), args->begin()+2);
      return;
    }
  } catch(ConvertValueError e) {
    throw IncompatibleDataTypes("data: " + tmp->verbose_type() + " passed: " + arg);
  }

  // get string
  if(tmp->same_data_types<string>()) {
    set<string>(id, str(arg));
    args->erase(args->begin(), args->begin()+2);
    return;
  }

  // build tStringList from "," separated input
  if(tmp->same_data_types<tStringList>()) {
    set<tStringList>(id, XString(arg).split(","));
    args->erase(args->begin(), args->begin()+2);
    return;
    // build tStringMap from "," and ":" separated input
  }
  if(tmp->same_data_types<tStringMap>()) {
    tStringList tmp = XString(arg).split(",");
    tStringMap tmpmap;
    for(tStringIter i=tmp.begin(); i!=tmp.end(); ++i) {
      tStringList two = XString(*i).split(":");
      tmpmap[two[0]] = two[1];
    }
    set<tStringMap>(id, tmpmap);
    args->erase(args->begin(), args->begin()+2);
    return;
  }
  throw IncompatibleDataTypes("data: " + tmp->verbose_type() + " passed: " + arg);
}

void ConfigManager::parse_cmdline(int argc, char* argv[]) {
  tStringList args;
  for(int i=1; i<argc; ++i)
    args.push_back(argv[i]);

  while(args.size() > 0)
    parse(&args);
}

void ConfigManager::write_config_file(ostream& fd, bool shorter) {
  fd << endl;
  fd << "###" << endl;
  fd << "### config file for: " << command << endl;
  fd << "###" << endl;
  fd << endl;
  for(tGroupPair& grp : groups) {
    if(!shorter)
      fd << "####################################################" << endl;
    else
      fd << endl;
    fd << "# [ " << grp.first << " ]" << endl;
    for(tOptionPair& opt : *grp.second) {
      const ConfigOption* c = opt.second;
      const string& id = opt.first;

      // write desc/help text
      if(!shorter) {
        fd << "# " << c->desc << " [" << c->verbose_type() << "]";
        // write if ConfigOption has default
        if(c->has_default)
          fd << " default: " << c->verbose_default();
        fd << endl;
      }

      // ConfigOption was set, output its value
      if(c->was_set) {
        fd << id << " = " << c->verbose_data() << endl;
      // ConfigOption was _not_ set, output commented out line and default
      } else if(c->has_default) {
          fd << "# " << id << " = " << c->verbose_default() << endl;
      // ConfigOption was neither set nor has a default value
      } else {
          fd << "# " << id << " = " << "<not set>" << endl;
      }
      if(!shorter)
        fd << endl;
    }
  }
}

void ConfigManager::parse_config_file(const string& fn) {
  ifstream fd(fn.c_str(), ios::in);
  XString line;
  tStringList tokens;
  while(fd.good()) {
    getline(fd, line);
    line.strip().strip("\n");
    if(line.length() == 0)
      continue;

    if(line.startswith("#"))
      continue;

    if(line.find("=") == string::npos) {
      tokens.push_back("--" + line);
      continue;
    }

    tStringList lr = line.split("=");
    XString left(lr[0]), right(lr[1]);
    left.strip();
    right.strip();

    tokens.push_back("--" + left);
    tokens.push_back(right);
  }
  fd.close();

  try {
    while(tokens.size() > 0)
      parse(&tokens);

  } catch(IncompatibleDataTypes& e) {
    e.message += " (inside configfile)";
    throw e;
  }
}

bool ConfigManager::is_group_active(const std::string& name) {
  tOptionMap& opts = groups[name]->members;
  for(tOptionIter i=opts.begin(); i!=opts.end(); ++i)
    if(i->second->was_set)
      return true;
  return false;
}

bool ConfigManager::is_option_set(const std::string& id) {
  return (get_option(id).was_set || get_option(id).has_default);
}

void ConfigManager::show_config(ostream& ss) {
  ss << "Showing all ConfigManager settings:" << endl << endl;
  for(tGroupPair& grp : groups) {
    ss << "[Group] -> " << grp.first << endl;
    for(tOptionPair& opt : grp.second->members) {
      ss << "[Option] " << opt.first << " = " << \
            opt.second->verbose_data() << endl;
    }
  }
}

void ConfigManager::usage(ostream& ss) {
  ss << "Usage: " << command << " <options>" << endl;
  ss << endl << "Options:" << endl;

  string::size_type id_len = 0, scmd_len = 0, desc_len = 0;
  for(tStringMapIter i=cmdmap.begin(); i!=cmdmap.end(); ++i) {
    ConfigOption* opt = members[i->second];
    if(i->first.find("--") != string::npos)
      id_len = max(opt->id.length(), id_len);
    else
      scmd_len = max(opt->cmd_short.length(), scmd_len);
    desc_len = max(opt->desc.length(), desc_len);
  }

  for(tGroupIter g=groups.begin(); g!=groups.end(); ++g) {
    ConfigGroup* grp = g->second;
    ss << endl << "--- Group: " << grp->name << endl;
    for(tOptionIter i=grp->members.begin(); i!=grp->members.end(); ++i) {
      ConfigOption* opt = grp->members[i->first];

      ss << right << setw(scmd_len+1) << ((opt->cmd_short.size() > 0) ? \
                                          ("-" + opt->cmd_short) : "") << " | " << flush;
      ss << left << setw(id_len+2) << ("--" + opt->id) << "   " << opt->desc;
      ss << " [" << opt->data.verbose_type() << "]";
      ss << endl;
    }
  }
  ss << endl;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: nranges.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2008-01-07 08:55:31 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/
#ifdef MACOSX
// We need an empty block in here. Otherwise, if the #ifndef _SFXNRANGES_HXX
// line is the first line, the Mac OS X version of the gcc preprocessor will
// incorrectly optimize the inclusion process and will never include this file
// a second time
#endif

#ifndef _SFXNRANGES_HXX

#ifndef NUMTYPE

#define NUMTYPE USHORT
#define SfxNumRanges SfxUShortRanges
#include <svtools/nranges.hxx>

#undef NUMTYPE
#define NUMTYPE ULONG
#define SfxNumRanges SfxULongRanges
#include <svtools/nranges.hxx>

#define _SFXNRANGES_HXX

#else

#ifndef _SOLAR_H
#include <tools/solar.h>
#endif

//========================================================================

#define NUMTYPE_ARG int

class SfxNumRanges
{
    NUMTYPE*                    _pRanges; // 0-terminated array of NUMTYPE-pairs

public:
                                SfxNumRanges() : _pRanges( 0 ) {}
                                SfxNumRanges( const SfxNumRanges &rOrig );
                                SfxNumRanges( NUMTYPE nWhich1, NUMTYPE nWhich2 );
                                SfxNumRanges( NUMTYPE_ARG nWh1, NUMTYPE_ARG nWh2, NUMTYPE_ARG nNull, ... );
                                SfxNumRanges( const NUMTYPE* nNumTable );
                                ~SfxNumRanges()
                                { delete [] _pRanges; }

    BOOL                        operator == ( const SfxNumRanges & ) const;
    BOOL                        operator != ( const SfxNumRanges & rRanges ) const
                                { return !( *this == rRanges ); }

    SfxNumRanges&               operator = ( const SfxNumRanges & );

    SfxNumRanges&               operator += ( const SfxNumRanges & );
    SfxNumRanges&               operator -= ( const SfxNumRanges & );
    SfxNumRanges&               operator /= ( const SfxNumRanges & );

    NUMTYPE                     Count() const;
    BOOL                        IsEmpty() const
                                { return !_pRanges || 0 == *_pRanges; }
    BOOL                        Contains( NUMTYPE n ) const;
    BOOL                        Intersects( const SfxNumRanges & ) const;

                                operator const NUMTYPE* () const
                                { return _pRanges; }
};

#undef NUMTYPE
#undef SfxNumRanges

#endif

#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.4.84); FILE MERGED 2008/04/01 15:44:33 thb 1.4.84.2: #i85898# Stripping all external header guards 2008/03/31 13:01:06 rt 1.4.84.1: #i87441# Change license header to LPGL v3.<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
 *
 * $RCSfile: nranges.hxx,v $
 * $Revision: 1.5 $
 *
 * 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.
 *
 ************************************************************************/
#ifdef MACOSX
// We need an empty block in here. Otherwise, if the #ifndef _SFXNRANGES_HXX
// line is the first line, the Mac OS X version of the gcc preprocessor will
// incorrectly optimize the inclusion process and will never include this file
// a second time
#endif

#ifndef _SFXNRANGES_HXX

#ifndef NUMTYPE

#define NUMTYPE USHORT
#define SfxNumRanges SfxUShortRanges
#include <svtools/nranges.hxx>

#undef NUMTYPE
#define NUMTYPE ULONG
#define SfxNumRanges SfxULongRanges
#include <svtools/nranges.hxx>

#define _SFXNRANGES_HXX

#else
#include <tools/solar.h>

//========================================================================

#define NUMTYPE_ARG int

class SfxNumRanges
{
    NUMTYPE*                    _pRanges; // 0-terminated array of NUMTYPE-pairs

public:
                                SfxNumRanges() : _pRanges( 0 ) {}
                                SfxNumRanges( const SfxNumRanges &rOrig );
                                SfxNumRanges( NUMTYPE nWhich1, NUMTYPE nWhich2 );
                                SfxNumRanges( NUMTYPE_ARG nWh1, NUMTYPE_ARG nWh2, NUMTYPE_ARG nNull, ... );
                                SfxNumRanges( const NUMTYPE* nNumTable );
                                ~SfxNumRanges()
                                { delete [] _pRanges; }

    BOOL                        operator == ( const SfxNumRanges & ) const;
    BOOL                        operator != ( const SfxNumRanges & rRanges ) const
                                { return !( *this == rRanges ); }

    SfxNumRanges&               operator = ( const SfxNumRanges & );

    SfxNumRanges&               operator += ( const SfxNumRanges & );
    SfxNumRanges&               operator -= ( const SfxNumRanges & );
    SfxNumRanges&               operator /= ( const SfxNumRanges & );

    NUMTYPE                     Count() const;
    BOOL                        IsEmpty() const
                                { return !_pRanges || 0 == *_pRanges; }
    BOOL                        Contains( NUMTYPE n ) const;
    BOOL                        Intersects( const SfxNumRanges & ) const;

                                operator const NUMTYPE* () const
                                { return _pRanges; }
};

#undef NUMTYPE
#undef SfxNumRanges

#endif

#endif
<|endoftext|>


<commit_before><commit_msg>[cppchecker] suppress unread Variable warnings<commit_after><|endoftext|>


<commit_before>/*
 * VocabMatch.cpp
 *
 *  Created on: Oct 11, 2013
 *      Author: andresf
 */

#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <sys/stat.h>

#include <boost/regex.hpp>

#include <opencv2/core/core.hpp>

#include <VocabTree.h>
#include <VocabDB.hpp>

#include <FileUtils.hpp>

#include <FunctionUtils.hpp>
#include <HtmlResultsWriter.hpp>

double mytime;

const static boost::regex DESCRIPTOR_REGEX("^(.+)(\\.)(yaml|xml)(\\.)(gz)$");

/**
 * Filters a set of features by keeping only those inside the region determined by query.
 *
 * @param query
 * @param descriptors
 *
 * @return number of filtered out features
 */
int filterFeaturesByRegion(FileUtils::Query& query, cv::Mat& descriptors);

int main(int argc, char **argv) {

	if (argc < 6 || argc > 12) {
		printf(
				"\nUsage:\n\t"
						"VocabMatch <in.vocab> <in.inverted.index> <in.db.desc.list> <in.queries.list>"
						" <out.ranked.files.folder> [in.num.neighbors:ALL] [in.norm:L2] [in.scoring:COS] [out.results:results.html]"
						" [in.use.regions:0] [in.nn.index:nn_index.bin]\n\n"
						"Norm:\n"
						"\tL1: L1-norm\n"
						"\tL2: L2-norm\n\n"
						"Distance:\n"
						"\tL1: Manhattan distance or Sum of absolute differences\n"
						"\tL2: Euclidean distance or Sum of squared differences\n"
						"\tCOS: Cosine distance or Euclidean dot product\n\n");
		return EXIT_FAILURE;
	}

	std::string in_vocab = argv[1];
	std::string in_inverted_index = argv[2];
	std::string in_db_desc_list = argv[3];
	std::string in_queries_desc_list = argv[4];
	std::string out_ranked_files_folder = argv[5];
	int in_num_nbrs = -1;
	std::string in_norm = "L2";
	std::string in_scoring = "COS";
	std::string out_html = "results.html";
	bool in_use_regions = false;
	std::string in_nn_index = "nn_index.bin";

	if (argc >= 7) {
		in_num_nbrs = atoi(argv[6]);
	}

	if (argc >= 8) {
		in_norm = argv[7];
	}

	if (argc >= 9) {
		in_scoring = argv[8];
	}

	if (argc >= 10) {
		out_html = argv[9];
	}

	if (argc >= 11) {
		in_use_regions = atoi(argv[10]);
	}

	if (argc >= 12) {
		in_nn_index = argv[11];
	}

	// Checking that database filename refers to a compressed YAML or XML file
	if (boost::regex_match(in_vocab, DESCRIPTOR_REGEX) == false) {
		fprintf(stderr,
				"Input vocabulary file must have the extension .yaml.gz or .xml.gz\n");
		return EXIT_FAILURE;
	}

	// Step 1/4: load vocabulary + inverted index
	cv::Ptr<vlr::VocabDB> db;

	std::string in_type = vlr::VocabBase::loadVocabType(in_vocab);

	if (in_type.compare("HKM") == 0) {
		// Instantiate a DB supported by a HKM vocabulary
		db = new vlr::HKMDB(false);
	} else if (in_type.compare("HKMAJ") == 0) {
		// Instantiate a DB supported by a HKMaj vocabulary
		db = new vlr::HKMDB(true);
	} else {
		// Instantiate a DB supported by a AKMaj vocabulary
		db = new vlr::AKMajDB();
	}

	printf("-- Loading vocabulary from [%s]\n", in_vocab.c_str());

	mytime = cv::getTickCount();
	db->loadBoFModel(in_vocab);
	mytime = ((double) cv::getTickCount() - mytime) / cv::getTickFrequency()
			* 1000;
	printf("   Vocabulary loaded in [%lf] ms, got [%lu] words \n", mytime,
			db->getNumOfWords());

	// Load nearest neighbor index when scoring using an AKMaj vocabulary
	if (in_type.compare("HKM") != 0 && in_type.compare("HKMAJ") != 0) {

		printf("-- Loading nearest neighbors index from [%s]\n",
				in_nn_index.c_str());

		mytime = cv::getTickCount();
		((cv::Ptr<vlr::AKMajDB>) db)->loadNNIndex(in_nn_index);
		mytime = ((double) cv::getTickCount() - mytime) / cv::getTickFrequency()
				* 1000;

		printf("   Loaded in [%lf] ms\n", mytime);
	}

	printf("-- Loading inverted index [%s]\n", in_inverted_index.c_str());

	mytime = cv::getTickCount();
	db->loadInvertedIndex(in_inverted_index);
	mytime = ((double) cv::getTickCount() - mytime) / cv::getTickFrequency()
			* 1000;

	printf("   Inverted index loaded in [%lf] ms\n", mytime);

	// Step 2/4: load names of database files
	printf("-- Loading names of database files\n");
	std::vector<std::string> db_desc_list;
	FileUtils::loadList(in_db_desc_list, db_desc_list);
	printf("   Loaded, got [%lu] entries\n", db_desc_list.size());

	// Step 3/4: load list of queries descriptors
	printf("-- Loading list of queries descriptors\n");
	std::vector<FileUtils::Query> query_filenames;
	FileUtils::loadQueriesList(in_queries_desc_list, query_filenames);
	printf("   Loaded, got [%lu] entries\n", query_filenames.size());

	// Step 4/4: score each query
	vlr::NormType norm = vlr::NORM_L1;

	if (in_norm.compare("L2") == 0) {
		norm = vlr::NORM_L2;
	}

	vlr::ScoringType distance = vlr::COS;

	if (in_scoring.compare("L1") == 0) {
		distance = vlr::L1;
	} else if (in_scoring.compare("L2") == 0) {
		distance = vlr::L2;
	}

	printf(
			"-- Scoring [%lu] query images against [%d] database images using [%s-norm] and [%s distance]\n",
			query_filenames.size(), db->getInvertedIndex()->m_numDbImages,
			norm == vlr::NORM_L1 ? "L1" :
			norm == vlr::NORM_L2 ? "L2" : "Unknown",
			distance == vlr::L1 ? "L1" : distance == vlr::L2 ? "L2" :
			distance == vlr::COS ? "Cosine" : "Unknown");

	cv::Mat imgDescriptors;
	cv::Mat scores;

	// Compute the number of candidates
	int top =
			in_num_nbrs != -1 ?
					in_num_nbrs : db->getInvertedIndex()->m_numDbImages;

	HtmlResultsWriter::getInstance().open(out_html, top);

	for (size_t i = 0; i < query_filenames.size(); ++i) {
		// Initialize descriptors
		imgDescriptors = cv::Mat();

		// Load query descriptors
		FileUtils::loadDescriptors(query_filenames[i].name, imgDescriptors);

		if (in_use_regions == true) {
			// Load key-points and use them to filter the features

			int numFilteredFeatures = filterFeaturesByRegion(query_filenames[i],
					imgDescriptors);

			printf("   Filtered out [%d] features\n", numFilteredFeatures);

		}

		if (imgDescriptors.empty() == true) {
			continue;
		}

		// Check type of descriptors
		bool is_binary = in_type.compare("HKM") != 0;
		if ((imgDescriptors.type() == CV_8U) != is_binary) {
			fprintf(stderr,
					"Descriptor type doesn't coincide, it is said to be [%s] while it is [%s]\n",
					is_binary == true ? "binary" : "non-binary",
					imgDescriptors.type() == CV_8U ? "binary" : "real");
			return EXIT_FAILURE;
		}

		// Score query BoF vector against database images BoF vectors
		mytime = cv::getTickCount();
		try {
			db->scoreQuery(imgDescriptors, scores, norm, distance);
		} catch (const std::runtime_error& error) {
			fprintf(stderr, "%s\n", error.what());
			return EXIT_FAILURE;
		}
		mytime = ((double) cv::getTickCount() - mytime) / cv::getTickFrequency()
				* 1000;
		imgDescriptors.release();

		// Print to standard output the matching scores between
		// the query BoF vector and the database images BoF vectors
		for (size_t j = 0; (int) j < scores.cols; ++j) {
			printf(
					"   Match score between [%lu] query image and [%lu] database image: %f\n",
					i, j, scores.at<float>(0, j));
		}

		// Obtain indices of ordered scores
		cv::Mat perm;
		// Note: recall that the index of the images in the inverted file corresponds
		// to the zero-based line number in the file used to build the database.
		cv::sortIdx(scores, perm, cv::SORT_EVERY_ROW + cv::SORT_DESCENDING);

		std::stringstream ranked_list_fname;
		printf("%lu) %s\n", i, query_filenames[i].name.c_str());
		ranked_list_fname << out_ranked_files_folder << "/query_" << i
				<< "_ranked.txt";

		std::ofstream f_ranked_list(ranked_list_fname.str().c_str(),
				std::fstream::out);
		if (f_ranked_list.good() == false) {
			fprintf(stderr, "Error opening file [%s] for writing\n",
					ranked_list_fname.str().c_str());
			return EXIT_FAILURE;
		}
		for (int j = 0; j < top; ++j) {
			// Get base filename: remove extension and folder path
			std::string d_base = FunctionUtils::basify(
					db_desc_list[perm.at<int>(0, j)]);
			f_ranked_list << d_base + "\n";
		}
		f_ranked_list.close();

		// Print to a file the ranked list of candidates ordered by score in HTML format
		HtmlResultsWriter::getInstance().writeRow(query_filenames[i].name,
				scores, perm, top, db_desc_list);
		scores.release();
		perm.release();
	}

	HtmlResultsWriter::getInstance().close();

	return EXIT_SUCCESS;
}

int filterFeaturesByRegion(FileUtils::Query& q, cv::Mat& descriptors) {

	cv::Mat filteredDescriptors;
	std::vector<cv::KeyPoint> keypoints, filteredKeypoints;
	std::string queries_keys_folder = "queries", queryBase;

	queryBase = q.name.substr(8, q.name.length() - 16);

	FileUtils::loadKeypoints(
			queries_keys_folder + "/" + queryBase + "_kpt.yaml.gz", keypoints);

	for (int i = 0; i < descriptors.rows; ++i) {
		if (keypoints[i].pt.x > q.x1 && keypoints[i].pt.x < q.x2
				&& keypoints[i].pt.y > q.y1 && keypoints[i].pt.y < q.y2) {
			filteredKeypoints.push_back(keypoints[i]);
			filteredDescriptors.push_back(descriptors.row(i));
		}
	}

	int numFilteredFeatures = descriptors.rows - filteredDescriptors.rows;

	keypoints.clear();
	keypoints = filteredKeypoints;

	descriptors.release();
	descriptors = filteredDescriptors;

	CV_Assert(descriptors.rows == int(keypoints.size()));

	return numFilteredFeatures;

}
<commit_msg>Removed "_kpt" suffix.<commit_after>/*
 * VocabMatch.cpp
 *
 *  Created on: Oct 11, 2013
 *      Author: andresf
 */

#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <sys/stat.h>

#include <boost/regex.hpp>

#include <opencv2/core/core.hpp>

#include <VocabTree.h>
#include <VocabDB.hpp>

#include <FileUtils.hpp>

#include <FunctionUtils.hpp>
#include <HtmlResultsWriter.hpp>

double mytime;

const static boost::regex DESCRIPTOR_REGEX("^(.+)(\\.)(yaml|xml)(\\.)(gz)$");

/**
 * Filters a set of features by keeping only those inside the region determined by query.
 *
 * @param query
 * @param descriptors
 *
 * @return number of filtered out features
 */
int filterFeaturesByRegion(FileUtils::Query& query, cv::Mat& descriptors);

int main(int argc, char **argv) {

	if (argc < 6 || argc > 12) {
		printf(
				"\nUsage:\n\t"
						"VocabMatch <in.vocab> <in.inverted.index> <in.db.desc.list> <in.queries.list>"
						" <out.ranked.files.folder> [in.num.neighbors:ALL] [in.norm:L2] [in.scoring:COS] [out.results:results.html]"
						" [in.use.regions:0] [in.nn.index:nn_index.bin]\n\n"
						"Norm:\n"
						"\tL1: L1-norm\n"
						"\tL2: L2-norm\n\n"
						"Distance:\n"
						"\tL1: Manhattan distance or Sum of absolute differences\n"
						"\tL2: Euclidean distance or Sum of squared differences\n"
						"\tCOS: Cosine distance or Euclidean dot product\n\n");
		return EXIT_FAILURE;
	}

	std::string in_vocab = argv[1];
	std::string in_inverted_index = argv[2];
	std::string in_db_desc_list = argv[3];
	std::string in_queries_desc_list = argv[4];
	std::string out_ranked_files_folder = argv[5];
	int in_num_nbrs = -1;
	std::string in_norm = "L2";
	std::string in_scoring = "COS";
	std::string out_html = "results.html";
	bool in_use_regions = false;
	std::string in_nn_index = "nn_index.bin";

	if (argc >= 7) {
		in_num_nbrs = atoi(argv[6]);
	}

	if (argc >= 8) {
		in_norm = argv[7];
	}

	if (argc >= 9) {
		in_scoring = argv[8];
	}

	if (argc >= 10) {
		out_html = argv[9];
	}

	if (argc >= 11) {
		in_use_regions = atoi(argv[10]);
	}

	if (argc >= 12) {
		in_nn_index = argv[11];
	}

	// Checking that database filename refers to a compressed YAML or XML file
	if (boost::regex_match(in_vocab, DESCRIPTOR_REGEX) == false) {
		fprintf(stderr,
				"Input vocabulary file must have the extension .yaml.gz or .xml.gz\n");
		return EXIT_FAILURE;
	}

	// Step 1/4: load vocabulary + inverted index
	cv::Ptr<vlr::VocabDB> db;

	std::string in_type = vlr::VocabBase::loadVocabType(in_vocab);

	if (in_type.compare("HKM") == 0) {
		// Instantiate a DB supported by a HKM vocabulary
		db = new vlr::HKMDB(false);
	} else if (in_type.compare("HKMAJ") == 0) {
		// Instantiate a DB supported by a HKMaj vocabulary
		db = new vlr::HKMDB(true);
	} else {
		// Instantiate a DB supported by a AKMaj vocabulary
		db = new vlr::AKMajDB();
	}

	printf("-- Loading vocabulary from [%s]\n", in_vocab.c_str());

	mytime = cv::getTickCount();
	db->loadBoFModel(in_vocab);
	mytime = ((double) cv::getTickCount() - mytime) / cv::getTickFrequency()
			* 1000;
	printf("   Vocabulary loaded in [%lf] ms, got [%lu] words \n", mytime,
			db->getNumOfWords());

	// Load nearest neighbor index when scoring using an AKMaj vocabulary
	if (in_type.compare("HKM") != 0 && in_type.compare("HKMAJ") != 0) {

		printf("-- Loading nearest neighbors index from [%s]\n",
				in_nn_index.c_str());

		mytime = cv::getTickCount();
		((cv::Ptr<vlr::AKMajDB>) db)->loadNNIndex(in_nn_index);
		mytime = ((double) cv::getTickCount() - mytime) / cv::getTickFrequency()
				* 1000;

		printf("   Loaded in [%lf] ms\n", mytime);
	}

	printf("-- Loading inverted index [%s]\n", in_inverted_index.c_str());

	mytime = cv::getTickCount();
	db->loadInvertedIndex(in_inverted_index);
	mytime = ((double) cv::getTickCount() - mytime) / cv::getTickFrequency()
			* 1000;

	printf("   Inverted index loaded in [%lf] ms\n", mytime);

	// Step 2/4: load names of database files
	printf("-- Loading names of database files\n");
	std::vector<std::string> db_desc_list;
	FileUtils::loadList(in_db_desc_list, db_desc_list);
	printf("   Loaded, got [%lu] entries\n", db_desc_list.size());

	// Step 3/4: load list of queries descriptors
	printf("-- Loading list of queries descriptors\n");
	std::vector<FileUtils::Query> query_filenames;
	FileUtils::loadQueriesList(in_queries_desc_list, query_filenames);
	printf("   Loaded, got [%lu] entries\n", query_filenames.size());

	// Step 4/4: score each query
	vlr::NormType norm = vlr::NORM_L1;

	if (in_norm.compare("L2") == 0) {
		norm = vlr::NORM_L2;
	}

	vlr::ScoringType distance = vlr::COS;

	if (in_scoring.compare("L1") == 0) {
		distance = vlr::L1;
	} else if (in_scoring.compare("L2") == 0) {
		distance = vlr::L2;
	}

	printf(
			"-- Scoring [%lu] query images against [%d] database images using [%s-norm] and [%s distance]\n",
			query_filenames.size(), db->getInvertedIndex()->m_numDbImages,
			norm == vlr::NORM_L1 ? "L1" :
			norm == vlr::NORM_L2 ? "L2" : "Unknown",
			distance == vlr::L1 ? "L1" : distance == vlr::L2 ? "L2" :
			distance == vlr::COS ? "Cosine" : "Unknown");

	cv::Mat imgDescriptors;
	cv::Mat scores;

	// Compute the number of candidates
	int top =
			in_num_nbrs != -1 ?
					in_num_nbrs : db->getInvertedIndex()->m_numDbImages;

	HtmlResultsWriter::getInstance().open(out_html, top);

	for (size_t i = 0; i < query_filenames.size(); ++i) {
		// Initialize descriptors
		imgDescriptors = cv::Mat();

		// Load query descriptors
		FileUtils::loadDescriptors(query_filenames[i].name, imgDescriptors);

		if (in_use_regions == true) {
			// Load key-points and use them to filter the features

			int numFilteredFeatures = filterFeaturesByRegion(query_filenames[i],
					imgDescriptors);

			printf("   Filtered out [%d] features\n", numFilteredFeatures);

		}

		if (imgDescriptors.empty() == true) {
			continue;
		}

		// Check type of descriptors
		bool is_binary = in_type.compare("HKM") != 0;
		if ((imgDescriptors.type() == CV_8U) != is_binary) {
			fprintf(stderr,
					"Descriptor type doesn't coincide, it is said to be [%s] while it is [%s]\n",
					is_binary == true ? "binary" : "non-binary",
					imgDescriptors.type() == CV_8U ? "binary" : "real");
			return EXIT_FAILURE;
		}

		// Score query BoF vector against database images BoF vectors
		mytime = cv::getTickCount();
		try {
			db->scoreQuery(imgDescriptors, scores, norm, distance);
		} catch (const std::runtime_error& error) {
			fprintf(stderr, "%s\n", error.what());
			return EXIT_FAILURE;
		}
		mytime = ((double) cv::getTickCount() - mytime) / cv::getTickFrequency()
				* 1000;
		imgDescriptors.release();

		// Print to standard output the matching scores between
		// the query BoF vector and the database images BoF vectors
		for (size_t j = 0; (int) j < scores.cols; ++j) {
			printf(
					"   Match score between [%lu] query image and [%lu] database image: %f\n",
					i, j, scores.at<float>(0, j));
		}

		// Obtain indices of ordered scores
		cv::Mat perm;
		// Note: recall that the index of the images in the inverted file corresponds
		// to the zero-based line number in the file used to build the database.
		cv::sortIdx(scores, perm, cv::SORT_EVERY_ROW + cv::SORT_DESCENDING);

		std::stringstream ranked_list_fname;
		printf("%lu) %s\n", i, query_filenames[i].name.c_str());
		ranked_list_fname << out_ranked_files_folder << "/query_" << i
				<< "_ranked.txt";

		std::ofstream f_ranked_list(ranked_list_fname.str().c_str(),
				std::fstream::out);
		if (f_ranked_list.good() == false) {
			fprintf(stderr, "Error opening file [%s] for writing\n",
					ranked_list_fname.str().c_str());
			return EXIT_FAILURE;
		}
		for (int j = 0; j < top; ++j) {
			// Get base filename: remove extension and folder path
			std::string d_base = FunctionUtils::basify(
					db_desc_list[perm.at<int>(0, j)]);
			f_ranked_list << d_base + "\n";
		}
		f_ranked_list.close();

		// Print to a file the ranked list of candidates ordered by score in HTML format
		HtmlResultsWriter::getInstance().writeRow(query_filenames[i].name,
				scores, perm, top, db_desc_list);
		scores.release();
		perm.release();
	}

	HtmlResultsWriter::getInstance().close();

	return EXIT_SUCCESS;
}

int filterFeaturesByRegion(FileUtils::Query& q, cv::Mat& descriptors) {

	cv::Mat filteredDescriptors;
	std::vector<cv::KeyPoint> keypoints, filteredKeypoints;
	std::string queries_keys_folder = "queries", queryBase;

	queryBase = q.name.substr(8, q.name.length() - 12);

	FileUtils::loadKeypoints(queries_keys_folder + "/" + queryBase + ".yaml.gz",
			keypoints);

	for (int i = 0; i < descriptors.rows; ++i) {
		if (keypoints[i].pt.x > q.x1 && keypoints[i].pt.x < q.x2
				&& keypoints[i].pt.y > q.y1 && keypoints[i].pt.y < q.y2) {
			filteredKeypoints.push_back(keypoints[i]);
			filteredDescriptors.push_back(descriptors.row(i));
		}
	}

	int numFilteredFeatures = descriptors.rows - filteredDescriptors.rows;

	keypoints.clear();
	keypoints = filteredKeypoints;

	descriptors.release();
	descriptors = filteredDescriptors;

	CV_Assert(descriptors.rows == int(keypoints.size()));

	return numFilteredFeatures;

}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkPNGReader.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

 * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
   of any contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

 * Modified source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=========================================================================*/
#include "vtkPNGReader.h"
#include "vtkObjectFactory.h"

#include <png.h>

//-------------------------------------------------------------------------
vtkPNGReader* vtkPNGReader::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkPNGReader");
  if(ret)
    {
    return (vtkPNGReader*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  return new vtkPNGReader;
}

void vtkPNGReader::ExecuteInformation()
{
  this->ComputeInternalFileName(this->DataExtent[4]);
  if (this->InternalFileName == NULL)
    {
    return;
    }

  FILE *fp = fopen(this->InternalFileName, "rb");
  if (!fp)
    {
    vtkErrorMacro("Unable to open file " << this->InternalFileName);
    return;
    }
  unsigned char header[8];
  fread(header, 1, 8, fp);
  int is_png = !png_sig_cmp(header, 0, 8);
  if (!is_png)
    {
    vtkErrorMacro(<<"Unknown file type! Not a PNG file!");
    fclose(fp);
    return;
    }

  png_structp png_ptr = png_create_read_struct
    (PNG_LIBPNG_VER_STRING, (png_voidp)NULL,
     NULL, NULL);
  if (!png_ptr)
    {
    vtkErrorMacro(<<"Unable to read PNG file!");
    fclose(fp);
    return;
    }

  png_infop info_ptr = png_create_info_struct(png_ptr);
  if (!info_ptr)
    {
    png_destroy_read_struct(&png_ptr,
                            (png_infopp)NULL, (png_infopp)NULL);
    vtkErrorMacro(<<"Unable to read PNG file!");
    fclose(fp);
    return;
    }

  png_infop end_info = png_create_info_struct(png_ptr);
  if (!end_info)
    {
    png_destroy_read_struct(&png_ptr, &info_ptr,
                            (png_infopp)NULL);
    vtkErrorMacro(<<"Unable to read PNG file!");
    fclose(fp);
    return;
    }

  png_init_io(png_ptr, fp);
  png_set_sig_bytes(png_ptr, 8);

  png_read_info(png_ptr, info_ptr);

  png_uint_32 width, height;
  int bit_depth, color_type, interlace_type;
  int compression_type, filter_method;
  png_get_IHDR(png_ptr, info_ptr,
               &width, &height,
               &bit_depth, &color_type, &interlace_type,
               &compression_type, &filter_method);

  // convert palettes to RGB
  if (color_type == PNG_COLOR_TYPE_PALETTE)
    {
    png_set_palette_to_rgb(png_ptr);
    }

  // minimum of a byte per pixel
  if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
    {
    png_set_gray_1_2_4_to_8(png_ptr);
    }

  // add alpha if any alpha found
  if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))
    {
    png_set_tRNS_to_alpha(png_ptr);
    }

  // update the info now that we have defined the filters
  png_read_update_info(png_ptr, info_ptr);

  this->DataExtent[0] = 0;
  this->DataExtent[1] = width - 1;
  this->DataExtent[2] = 0;
  this->DataExtent[3] = height - 1;

  if (bit_depth <= 8)
    {
    this->SetDataScalarTypeToUnsignedChar();
    }
  else
    {
    this->SetDataScalarTypeToUnsignedShort();
    }
  this->SetNumberOfScalarComponents(
    png_get_channels(png_ptr, info_ptr));
  this->vtkImageReader2::ExecuteInformation();

  // close the file
  png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
  fclose(fp);
}

template <class OT>
static void vtkPNGReaderUpdate2(vtkPNGReader *self, OT *outPtr,
                                int *outExt, int *outInc, long pixSize)
{
  unsigned int ui;
  int i;
  FILE *fp = fopen(self->GetInternalFileName(), "rb");
  if (!fp)
    {
    return;
    }
  unsigned char header[8];
  fread(header, 1, 8, fp);
  int is_png = !png_sig_cmp(header, 0, 8);
  if (!is_png)
    {
    fclose(fp);
    return;
    }

  png_structp png_ptr = png_create_read_struct
    (PNG_LIBPNG_VER_STRING, (png_voidp)NULL, NULL, NULL);
  if (!png_ptr)
    {
    return;
    }

  png_infop info_ptr = png_create_info_struct(png_ptr);
  if (!info_ptr)
    {
    png_destroy_read_struct(&png_ptr,
                            (png_infopp)NULL, (png_infopp)NULL);
    return;
    }

  png_infop end_info = png_create_info_struct(png_ptr);
  if (!end_info)
    {
    png_destroy_read_struct(&png_ptr, &info_ptr,
                            (png_infopp)NULL);
    return;
    }

  png_init_io(png_ptr, fp);
  png_set_sig_bytes(png_ptr, 8);
  png_read_info(png_ptr, info_ptr);

  png_uint_32 width, height;
  int bit_depth, color_type, interlace_type;
  int compression_type, filter_method;
  png_get_IHDR(png_ptr, info_ptr,
               &width, &height,
               &bit_depth, &color_type, &interlace_type,
               &compression_type, &filter_method);

  // convert palettes to RGB
  if (color_type == PNG_COLOR_TYPE_PALETTE)
    {
    png_set_palette_to_rgb(png_ptr);
    }

  // minimum of a byte per pixel
  if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
    {
    png_set_gray_1_2_4_to_8(png_ptr);
    }

  // add alpha if any alpha found
  if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))
    {
    png_set_tRNS_to_alpha(png_ptr);
    }

  if (bit_depth > 8)
    {
#ifndef VTK_WORDS_BIGENDIAN
    png_set_swap(png_ptr);
#endif
    }

  // have libpng handle interlacing
  //int number_of_passes = png_set_interlace_handling(png_ptr);
  // update the info now that we have defined the filters
  png_read_update_info(png_ptr, info_ptr);

  int rowbytes = png_get_rowbytes(png_ptr, info_ptr);
  unsigned char *tempImage = new unsigned char [rowbytes*height];
  png_bytep *row_pointers = new png_bytep [height];
  for (ui = 0; ui < height; ++ui)
    {
    row_pointers[ui] = tempImage + rowbytes*ui;
    }
  png_read_image(png_ptr, row_pointers);
  delete [] tempImage;

  // copy the data into the outPtr
  OT *outPtr2;
  outPtr2 = outPtr;
  long outSize = pixSize*(outExt[1] - outExt[0] + 1);
  for (i = outExt[2]; i <= outExt[3]; ++i)
    {
    memcpy(outPtr2,row_pointers[height - i - 1] + outExt[0]*pixSize,outSize);
    outPtr2 += outInc[1];
    }
  delete [] row_pointers;

  // close the file
  png_read_end(png_ptr, NULL);
  png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
  fclose(fp);
}

//----------------------------------------------------------------------------
// This function reads in one data of data.
// templated to handle different data types.
template <class OT>
static void vtkPNGReaderUpdate(vtkPNGReader *self, vtkImageData *data,
                               OT *outPtr)
{
  int outIncr[3];
  int outExtent[6];
  OT *outPtr2;

  data->GetExtent(outExtent);
  data->GetIncrements(outIncr);

  long pixSize = data->GetNumberOfScalarComponents()*sizeof(OT);

  outPtr2 = outPtr;
  int idx2;
  for (idx2 = outExtent[4]; idx2 <= outExtent[5]; ++idx2)
    {
    self->ComputeInternalFileName(idx2);
    // read in a PNG file
    vtkPNGReaderUpdate2(self, outPtr2, outExtent, outIncr, pixSize);
    self->UpdateProgress((idx2 - outExtent[4])/
                         (outExtent[5] - outExtent[4] + 1.0));
    outPtr2 += outIncr[2];
    }
}

//----------------------------------------------------------------------------
// This function reads a data from a file.  The datas extent/axes
// are assumed to be the same as the file extent/order.
void vtkPNGReader::ExecuteData(vtkDataObject *output)
{
  vtkImageData *data = this->AllocateOutputData(output);

  if (this->InternalFileName == NULL)
    {
    vtkErrorMacro(<< "Either a FileName or FilePrefix must be specified.");
    return;
    }

  this->ComputeDataIncrements();

  // Call the correct templated function for the output
  void *outPtr;

  // Call the correct templated function for the input
  outPtr = data->GetScalarPointer();
  switch (data->GetScalarType())
    {
    vtkTemplateMacro3(vtkPNGReaderUpdate, this, data, (VTK_TT *)(outPtr));
    default:
      vtkErrorMacro(<< "UpdateFromFile: Unknown data type");
    }
}

<commit_msg>fixed kens stupid mistakes again<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkPNGReader.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

 * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
   of any contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

 * Modified source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=========================================================================*/
#include "vtkPNGReader.h"
#include "vtkObjectFactory.h"

#include <png.h>

//-------------------------------------------------------------------------
vtkPNGReader* vtkPNGReader::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkPNGReader");
  if(ret)
    {
    return (vtkPNGReader*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  return new vtkPNGReader;
}

void vtkPNGReader::ExecuteInformation()
{
  this->ComputeInternalFileName(this->DataExtent[4]);
  if (this->InternalFileName == NULL)
    {
    return;
    }

  FILE *fp = fopen(this->InternalFileName, "rb");
  if (!fp)
    {
    vtkErrorMacro("Unable to open file " << this->InternalFileName);
    return;
    }
  unsigned char header[8];
  fread(header, 1, 8, fp);
  int is_png = !png_sig_cmp(header, 0, 8);
  if (!is_png)
    {
    vtkErrorMacro(<<"Unknown file type! Not a PNG file!");
    fclose(fp);
    return;
    }

  png_structp png_ptr = png_create_read_struct
    (PNG_LIBPNG_VER_STRING, (png_voidp)NULL,
     NULL, NULL);
  if (!png_ptr)
    {
    vtkErrorMacro(<<"Unable to read PNG file!");
    fclose(fp);
    return;
    }

  png_infop info_ptr = png_create_info_struct(png_ptr);
  if (!info_ptr)
    {
    png_destroy_read_struct(&png_ptr,
                            (png_infopp)NULL, (png_infopp)NULL);
    vtkErrorMacro(<<"Unable to read PNG file!");
    fclose(fp);
    return;
    }

  png_infop end_info = png_create_info_struct(png_ptr);
  if (!end_info)
    {
    png_destroy_read_struct(&png_ptr, &info_ptr,
                            (png_infopp)NULL);
    vtkErrorMacro(<<"Unable to read PNG file!");
    fclose(fp);
    return;
    }

  png_init_io(png_ptr, fp);
  png_set_sig_bytes(png_ptr, 8);

  png_read_info(png_ptr, info_ptr);

  png_uint_32 width, height;
  int bit_depth, color_type, interlace_type;
  int compression_type, filter_method;
  png_get_IHDR(png_ptr, info_ptr,
               &width, &height,
               &bit_depth, &color_type, &interlace_type,
               &compression_type, &filter_method);

  // convert palettes to RGB
  if (color_type == PNG_COLOR_TYPE_PALETTE)
    {
    png_set_palette_to_rgb(png_ptr);
    }

  // minimum of a byte per pixel
  if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
    {
    png_set_gray_1_2_4_to_8(png_ptr);
    }

  // add alpha if any alpha found
  if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))
    {
    png_set_tRNS_to_alpha(png_ptr);
    }

  // update the info now that we have defined the filters
  png_read_update_info(png_ptr, info_ptr);

  this->DataExtent[0] = 0;
  this->DataExtent[1] = width - 1;
  this->DataExtent[2] = 0;
  this->DataExtent[3] = height - 1;

  if (bit_depth <= 8)
    {
    this->SetDataScalarTypeToUnsignedChar();
    }
  else
    {
    this->SetDataScalarTypeToUnsignedShort();
    }
  this->SetNumberOfScalarComponents(
    png_get_channels(png_ptr, info_ptr));
  this->vtkImageReader2::ExecuteInformation();

  // close the file
  png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
  fclose(fp);
}

template <class OT>
static void vtkPNGReaderUpdate2(vtkPNGReader *self, OT *outPtr,
                                int *outExt, int *outInc, long pixSize)
{
  unsigned int ui;
  int i;
  FILE *fp = fopen(self->GetInternalFileName(), "rb");
  if (!fp)
    {
    return;
    }
  unsigned char header[8];
  fread(header, 1, 8, fp);
  int is_png = !png_sig_cmp(header, 0, 8);
  if (!is_png)
    {
    fclose(fp);
    return;
    }

  png_structp png_ptr = png_create_read_struct
    (PNG_LIBPNG_VER_STRING, (png_voidp)NULL, NULL, NULL);
  if (!png_ptr)
    {
    return;
    }

  png_infop info_ptr = png_create_info_struct(png_ptr);
  if (!info_ptr)
    {
    png_destroy_read_struct(&png_ptr,
                            (png_infopp)NULL, (png_infopp)NULL);
    return;
    }

  png_infop end_info = png_create_info_struct(png_ptr);
  if (!end_info)
    {
    png_destroy_read_struct(&png_ptr, &info_ptr,
                            (png_infopp)NULL);
    return;
    }

  png_init_io(png_ptr, fp);
  png_set_sig_bytes(png_ptr, 8);
  png_read_info(png_ptr, info_ptr);

  png_uint_32 width, height;
  int bit_depth, color_type, interlace_type;
  int compression_type, filter_method;
  png_get_IHDR(png_ptr, info_ptr,
               &width, &height,
               &bit_depth, &color_type, &interlace_type,
               &compression_type, &filter_method);

  // convert palettes to RGB
  if (color_type == PNG_COLOR_TYPE_PALETTE)
    {
    png_set_palette_to_rgb(png_ptr);
    }

  // minimum of a byte per pixel
  if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
    {
    png_set_gray_1_2_4_to_8(png_ptr);
    }

  // add alpha if any alpha found
  if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))
    {
    png_set_tRNS_to_alpha(png_ptr);
    }

  if (bit_depth > 8)
    {
#ifndef VTK_WORDS_BIGENDIAN
    png_set_swap(png_ptr);
#endif
    }

  // have libpng handle interlacing
  //int number_of_passes = png_set_interlace_handling(png_ptr);
  // update the info now that we have defined the filters
  png_read_update_info(png_ptr, info_ptr);

  int rowbytes = png_get_rowbytes(png_ptr, info_ptr);
  unsigned char *tempImage = new unsigned char [rowbytes*height];
  png_bytep *row_pointers = new png_bytep [height];
  for (ui = 0; ui < height; ++ui)
    {
    row_pointers[ui] = tempImage + rowbytes*ui;
    }
  png_read_image(png_ptr, row_pointers);

  // copy the data into the outPtr
  OT *outPtr2;
  outPtr2 = outPtr;
  long outSize = pixSize*(outExt[1] - outExt[0] + 1);
  for (i = outExt[2]; i <= outExt[3]; ++i)
    {
    memcpy(outPtr2,row_pointers[height - i - 1] + outExt[0]*pixSize,outSize);
    outPtr2 += outInc[1];
    }
  delete [] tempImage;
  delete [] row_pointers;

  // close the file
  png_read_end(png_ptr, NULL);
  png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
  fclose(fp);
}

//----------------------------------------------------------------------------
// This function reads in one data of data.
// templated to handle different data types.
template <class OT>
static void vtkPNGReaderUpdate(vtkPNGReader *self, vtkImageData *data,
                               OT *outPtr)
{
  int outIncr[3];
  int outExtent[6];
  OT *outPtr2;

  data->GetExtent(outExtent);
  data->GetIncrements(outIncr);

  long pixSize = data->GetNumberOfScalarComponents()*sizeof(OT);

  outPtr2 = outPtr;
  int idx2;
  for (idx2 = outExtent[4]; idx2 <= outExtent[5]; ++idx2)
    {
    self->ComputeInternalFileName(idx2);
    // read in a PNG file
    vtkPNGReaderUpdate2(self, outPtr2, outExtent, outIncr, pixSize);
    self->UpdateProgress((idx2 - outExtent[4])/
                         (outExtent[5] - outExtent[4] + 1.0));
    outPtr2 += outIncr[2];
    }
}

//----------------------------------------------------------------------------
// This function reads a data from a file.  The datas extent/axes
// are assumed to be the same as the file extent/order.
void vtkPNGReader::ExecuteData(vtkDataObject *output)
{
  vtkImageData *data = this->AllocateOutputData(output);

  if (this->InternalFileName == NULL)
    {
    vtkErrorMacro(<< "Either a FileName or FilePrefix must be specified.");
    return;
    }

  this->ComputeDataIncrements();

  // Call the correct templated function for the output
  void *outPtr;

  // Call the correct templated function for the input
  outPtr = data->GetScalarPointer();
  switch (data->GetScalarType())
    {
    vtkTemplateMacro3(vtkPNGReaderUpdate, this, data, (VTK_TT *)(outPtr));
    default:
      vtkErrorMacro(<< "UpdateFromFile: Unknown data type");
    }
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ptitem.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 21:40:13 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"

#include <svtools/ptitem.hxx>

#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif

#ifndef _COM_SUN_STAR_AWT_POINT_HPP_
#include <com/sun/star/awt/Point.hpp>
#endif

#ifndef _STREAM_HXX //autogen
#include <tools/stream.hxx>
#endif

#include <svtools/poolitem.hxx>
#include "memberid.hrc"

using namespace ::com::sun::star;
// STATIC DATA -----------------------------------------------------------

DBG_NAME(SfxPointItem)

#define TWIP_TO_MM100(TWIP)     ((TWIP) >= 0 ? (((TWIP)*127L+36L)/72L) : (((TWIP)*127L-36L)/72L))
#define MM100_TO_TWIP(MM100)    ((MM100) >= 0 ? (((MM100)*72L+63L)/127L) : (((MM100)*72L-63L)/127L))

// -----------------------------------------------------------------------

TYPEINIT1_AUTOFACTORY(SfxPointItem, SfxPoolItem);

// -----------------------------------------------------------------------

SfxPointItem::SfxPointItem()
{
    DBG_CTOR(SfxPointItem, 0);
}

// -----------------------------------------------------------------------

SfxPointItem::SfxPointItem( USHORT nW, const Point& rVal ) :
    SfxPoolItem( nW ),
    aVal( rVal )
{
    DBG_CTOR(SfxPointItem, 0);
}

// -----------------------------------------------------------------------

SfxPointItem::SfxPointItem( USHORT nW, SvStream &rStream ) :
    SfxPoolItem( nW )
{
    DBG_CTOR(SfxPointItem, 0);
    rStream >> aVal;
}

// -----------------------------------------------------------------------

SfxPointItem::SfxPointItem( const SfxPointItem& rItem ) :
    SfxPoolItem( rItem ),
    aVal( rItem.aVal )
{
    DBG_CTOR(SfxPointItem, 0);
}

// -----------------------------------------------------------------------

SfxItemPresentation SfxPointItem::GetPresentation
(
    SfxItemPresentation     /*ePresentation*/,
    SfxMapUnit              /*eCoreMetric*/,
    SfxMapUnit              /*ePresentationMetric*/,
    XubString&              rText,
    const IntlWrapper *
)   const
{
    DBG_CHKTHIS(SfxPointItem, 0);
    rText = UniString::CreateFromInt32(aVal.X());
    rText.AppendAscii(RTL_CONSTASCII_STRINGPARAM(", "));
    rText += UniString::CreateFromInt32(aVal.Y());
    rText.AppendAscii(RTL_CONSTASCII_STRINGPARAM(", "));
    return SFX_ITEM_PRESENTATION_NAMELESS;
}

// -----------------------------------------------------------------------

int SfxPointItem::operator==( const SfxPoolItem& rItem ) const
{
    DBG_CHKTHIS(SfxPointItem, 0);
    DBG_ASSERT( SfxPoolItem::operator==( rItem ), "unequal type" );
    return ((SfxPointItem&)rItem).aVal == aVal;
}

// -----------------------------------------------------------------------

SfxPoolItem* SfxPointItem::Clone(SfxItemPool *) const
{
    DBG_CHKTHIS(SfxPointItem, 0);
    return new SfxPointItem( *this );
}

// -----------------------------------------------------------------------

SfxPoolItem* SfxPointItem::Create(SvStream &rStream, USHORT ) const
{
    DBG_CHKTHIS(SfxPointItem, 0);
    Point aStr;
    rStream >> aStr;
    return new SfxPointItem(Which(), aStr);
}

// -----------------------------------------------------------------------

SvStream& SfxPointItem::Store(SvStream &rStream, USHORT ) const
{
    DBG_CHKTHIS(SfxPointItem, 0);
    rStream << aVal;
    return rStream;
}

// -----------------------------------------------------------------------

BOOL SfxPointItem::QueryValue( uno::Any& rVal,
                               BYTE nMemberId ) const
{
    sal_Bool bConvert = 0!=(nMemberId&CONVERT_TWIPS);
    awt::Point aTmp(aVal.X(), aVal.Y());
    if( bConvert )
    {
        aTmp.X = TWIP_TO_MM100(aTmp.X);
        aTmp.Y = TWIP_TO_MM100(aTmp.Y);
    }
    nMemberId &= ~CONVERT_TWIPS;
    switch ( nMemberId )
    {
        case 0: rVal <<= aTmp; break;
        case MID_X: rVal <<= aTmp.X; break;
        case MID_Y: rVal <<= aTmp.Y; break;
        default: DBG_ERROR("Wrong MemberId!"); return FALSE;
    }

    return TRUE;
}

// -----------------------------------------------------------------------

BOOL SfxPointItem::PutValue( const uno::Any& rVal,
                             BYTE nMemberId )
{
    sal_Bool bConvert = 0!=(nMemberId&CONVERT_TWIPS);
    nMemberId &= ~CONVERT_TWIPS;
    BOOL bRet = FALSE;
    awt::Point aValue;
    sal_Int32 nVal = 0;
    if ( !nMemberId )
    {
        bRet = ( rVal >>= aValue );
        if( bConvert )
        {
            aValue.X = MM100_TO_TWIP(aValue.X);
            aValue.Y = MM100_TO_TWIP(aValue.Y);
        }
    }
    else
    {
        bRet = ( rVal >>= nVal );
        if( bConvert )
            nVal = MM100_TO_TWIP( nVal );
    }

    if ( bRet )
    {
        switch ( nMemberId )
        {
            case 0: aVal.setX( aValue.X ); aVal.setY( aValue.Y ); break;
            case MID_X: aVal.setX( nVal ); break;
            case MID_Y: aVal.setY( nVal ); break;
            default: DBG_ERROR("Wrong MemberId!"); return FALSE;
        }
    }

    return bRet;
}

<commit_msg>INTEGRATION: CWS changefileheader (1.11.246); FILE MERGED 2008/04/01 15:45:11 thb 1.11.246.3: #i85898# Stripping all external header guards 2008/04/01 12:43:39 thb 1.11.246.2: #i85898# Stripping all external header guards 2008/03/31 13:02:07 rt 1.11.246.1: #i87441# Change license header to LPGL v3.<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
 *
 * $RCSfile: ptitem.cxx,v $
 * $Revision: 1.12 $
 *
 * 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.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"

#include <svtools/ptitem.hxx>
#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/awt/Point.hpp>
#include <tools/stream.hxx>

#include <svtools/poolitem.hxx>
#include "memberid.hrc"

using namespace ::com::sun::star;
// STATIC DATA -----------------------------------------------------------

DBG_NAME(SfxPointItem)

#define TWIP_TO_MM100(TWIP)     ((TWIP) >= 0 ? (((TWIP)*127L+36L)/72L) : (((TWIP)*127L-36L)/72L))
#define MM100_TO_TWIP(MM100)    ((MM100) >= 0 ? (((MM100)*72L+63L)/127L) : (((MM100)*72L-63L)/127L))

// -----------------------------------------------------------------------

TYPEINIT1_AUTOFACTORY(SfxPointItem, SfxPoolItem);

// -----------------------------------------------------------------------

SfxPointItem::SfxPointItem()
{
    DBG_CTOR(SfxPointItem, 0);
}

// -----------------------------------------------------------------------

SfxPointItem::SfxPointItem( USHORT nW, const Point& rVal ) :
    SfxPoolItem( nW ),
    aVal( rVal )
{
    DBG_CTOR(SfxPointItem, 0);
}

// -----------------------------------------------------------------------

SfxPointItem::SfxPointItem( USHORT nW, SvStream &rStream ) :
    SfxPoolItem( nW )
{
    DBG_CTOR(SfxPointItem, 0);
    rStream >> aVal;
}

// -----------------------------------------------------------------------

SfxPointItem::SfxPointItem( const SfxPointItem& rItem ) :
    SfxPoolItem( rItem ),
    aVal( rItem.aVal )
{
    DBG_CTOR(SfxPointItem, 0);
}

// -----------------------------------------------------------------------

SfxItemPresentation SfxPointItem::GetPresentation
(
    SfxItemPresentation     /*ePresentation*/,
    SfxMapUnit              /*eCoreMetric*/,
    SfxMapUnit              /*ePresentationMetric*/,
    XubString&              rText,
    const IntlWrapper *
)   const
{
    DBG_CHKTHIS(SfxPointItem, 0);
    rText = UniString::CreateFromInt32(aVal.X());
    rText.AppendAscii(RTL_CONSTASCII_STRINGPARAM(", "));
    rText += UniString::CreateFromInt32(aVal.Y());
    rText.AppendAscii(RTL_CONSTASCII_STRINGPARAM(", "));
    return SFX_ITEM_PRESENTATION_NAMELESS;
}

// -----------------------------------------------------------------------

int SfxPointItem::operator==( const SfxPoolItem& rItem ) const
{
    DBG_CHKTHIS(SfxPointItem, 0);
    DBG_ASSERT( SfxPoolItem::operator==( rItem ), "unequal type" );
    return ((SfxPointItem&)rItem).aVal == aVal;
}

// -----------------------------------------------------------------------

SfxPoolItem* SfxPointItem::Clone(SfxItemPool *) const
{
    DBG_CHKTHIS(SfxPointItem, 0);
    return new SfxPointItem( *this );
}

// -----------------------------------------------------------------------

SfxPoolItem* SfxPointItem::Create(SvStream &rStream, USHORT ) const
{
    DBG_CHKTHIS(SfxPointItem, 0);
    Point aStr;
    rStream >> aStr;
    return new SfxPointItem(Which(), aStr);
}

// -----------------------------------------------------------------------

SvStream& SfxPointItem::Store(SvStream &rStream, USHORT ) const
{
    DBG_CHKTHIS(SfxPointItem, 0);
    rStream << aVal;
    return rStream;
}

// -----------------------------------------------------------------------

BOOL SfxPointItem::QueryValue( uno::Any& rVal,
                               BYTE nMemberId ) const
{
    sal_Bool bConvert = 0!=(nMemberId&CONVERT_TWIPS);
    awt::Point aTmp(aVal.X(), aVal.Y());
    if( bConvert )
    {
        aTmp.X = TWIP_TO_MM100(aTmp.X);
        aTmp.Y = TWIP_TO_MM100(aTmp.Y);
    }
    nMemberId &= ~CONVERT_TWIPS;
    switch ( nMemberId )
    {
        case 0: rVal <<= aTmp; break;
        case MID_X: rVal <<= aTmp.X; break;
        case MID_Y: rVal <<= aTmp.Y; break;
        default: DBG_ERROR("Wrong MemberId!"); return FALSE;
    }

    return TRUE;
}

// -----------------------------------------------------------------------

BOOL SfxPointItem::PutValue( const uno::Any& rVal,
                             BYTE nMemberId )
{
    sal_Bool bConvert = 0!=(nMemberId&CONVERT_TWIPS);
    nMemberId &= ~CONVERT_TWIPS;
    BOOL bRet = FALSE;
    awt::Point aValue;
    sal_Int32 nVal = 0;
    if ( !nMemberId )
    {
        bRet = ( rVal >>= aValue );
        if( bConvert )
        {
            aValue.X = MM100_TO_TWIP(aValue.X);
            aValue.Y = MM100_TO_TWIP(aValue.Y);
        }
    }
    else
    {
        bRet = ( rVal >>= nVal );
        if( bConvert )
            nVal = MM100_TO_TWIP( nVal );
    }

    if ( bRet )
    {
        switch ( nMemberId )
        {
            case 0: aVal.setX( aValue.X ); aVal.setY( aValue.Y ); break;
            case MID_X: aVal.setX( nVal ); break;
            case MID_Y: aVal.setY( nVal ); break;
            default: DBG_ERROR("Wrong MemberId!"); return FALSE;
        }
    }

    return bRet;
}

<|endoftext|>