<commit_before>/*
 * Copyright (C) 2017 National Research Institute of Science and
 * Technology for Environment and Agriculture (IRSTEA)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "itkFixedArray.h"
#include "itkObjectFactory.h"

// Elevation handler
#include "otbWrapperElevationParametersHandler.h"
#include "otbWrapperApplicationFactory.h"

// Application engine
#include "otbStandardFilterWatcher.h"

// Process objects
#include "otbVectorDataToLabelImageFilter.h"
#include "otbVectorDataIntoImageProjectionFilter.h"
#include "otbStreamingStatisticsMapFromLabelImageFilter.h"
#include "otbStatisticsXMLFileWriter.h"

namespace otb
{

namespace Wrapper
{

class ZonalStatistics : public Application
{
public:
  /** Standard class typedefs. */
  typedef ZonalStatistics               Self;
  typedef Application                   Superclass;
  typedef itk::SmartPointer<Self>       Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

  /* Typedefs */
  typedef Int32ImageType                LabelImageType;
  typedef LabelImageType::ValueType     LabelValueType;
  typedef otb::VectorData<double, 2>    VectorDataType;
  typedef otb::VectorDataIntoImageProjectionFilter<VectorDataType,
      FloatVectorImageType>             VectorDataReprojFilterType;
  typedef otb::VectorDataToLabelImageFilter<VectorDataType,
      LabelImageType>                   RasterizeFilterType;
  typedef VectorDataType::DataTreeType  DataTreeType;
  typedef itk::PreOrderTreeIterator<DataTreeType>
                                        TreeIteratorType;
  typedef VectorDataType::DataNodeType  DataNodeType;
  typedef DataNodeType::PolygonListPointerType
                                        PolygonListPointerType;
  typedef otb::StreamingStatisticsMapFromLabelImageFilter<FloatVectorImageType,
      LabelImageType>                   StatsFilterType;
  typedef otb::StatisticsXMLFileWriter<FloatVectorImageType::PixelType>
                                        StatsWriterType;

  /** Standard macro */
  itkNewMacro(Self);
  itkTypeMacro(ZonalStatistics, Application);

  void DoInit()
  {

    SetName("ZonalStatistics");
    SetDescription("This application computes zonal statistics");

    // Documentation
    SetDocName("ZonalStatistics");
    SetDocLongDescription("This application computes zonal statistics from label image, or vector data. "
        "The application inputs one input multiband image, and a label input. "
        "If the label input is a raster, the output statistics are exported in a XML file. If the label "
        "input is a vector data, the output statistics are exported in a new vector data with statistics "
        "in the attribute table. The computed statistics are mean, min, max, and standard deviation.");
    SetDocLimitations("The shapefile must fit in memory");
    SetDocAuthors("Remi Cresson");

    AddDocTag(Tags::Manip);
    AddDocTag(Tags::Analysis);

    // Input image
    AddParameter(ParameterType_InputImage, "in",   "Input Image");
    AddParameter(ParameterType_Float,      "inbv", "Background value to ignore in statistics computation");

    // Input zone mode
    AddParameter(ParameterType_Choice, "inzone", "Type of input for the zone definitions");
    AddChoice("inzone.vector",     "Input objects from vector data");
    AddChoice("inzone.labelimage", "Input objects from label image");

    // Input for vector mode
    AddParameter(ParameterType_InputVectorData,  "inzone.vector.in",        "Input vector data");
    AddParameter(ParameterType_Bool,             "inzone.vector.reproject", "Reproject the input vector");

    // Input for label image mode
    AddParameter(ParameterType_InputImage, "inzone.labelimage.in",     "Input label image");
    AddParameter(ParameterType_Int,        "inzone.labelimage.nodata", "No-data value for the input label image");
    MandatoryOff                          ("inzone.labelimage.nodata");

    // Output stats mode
    AddParameter(ParameterType_Choice, "out", "Format of the output stats");
    AddChoice("out.vector", "Output vector data");
    AddParameter(ParameterType_OutputVectorData, "out.vector.filename", "Filename for the output vector data");
    AddChoice("out.xml", "Output XML file");
    AddParameter(ParameterType_String, "out.xml.filename", "");
    AddChoice("out.raster", "Output raster image");
    AddParameter(ParameterType_OutputImage, "out.raster.filename", "");

    AddRAMParameter();

    // Doc example parameter settings
    SetDocExampleParameterValue("in", "input.tif");
    SetDocExampleParameterValue("inzone.vector.in", "myvector.shp");
    SetDocExampleParameterValue("out.vector.filename", "myvector_with_stats.shp");

  }

  void DoUpdateParameters()
  {
    // Nothing to do here : all parameters are independent
  }

  // Returns a string of the kind "prefix_i"
  const std::string CreateFieldName(const std::string & prefix, const unsigned int i)
  {
    std::stringstream ss;
    ss << prefix << "_" << i;
    return ss.str();
  }

  // Returns a null pixel which has the same number of components per pixels as img
  FloatVectorImageType::PixelType NullPixel(FloatVectorImageType::Pointer & img)
  {
    const unsigned int nBands = img->GetNumberOfComponentsPerPixel();
    FloatVectorImageType::PixelType pix;
    pix.SetSize(nBands);
    pix.Fill(0);
    return pix;
  }

  void DoExecute()
  {

    // Get input image
    FloatVectorImageType::Pointer img = GetParameterImage("in");

    // Statistics filter
    m_StatsFilter = StatsFilterType::New();
    m_StatsFilter->SetInput(img);
    m_StatsFilter->GetStreamer()->SetAutomaticAdaptativeStreaming(GetParameterInt("ram"));
    AddProcess(m_StatsFilter->GetStreamer(), "Computing statistics");

    // Internal no-data value
    LabelValueType intNoData = itk::NumericTraits<LabelValueType>::max();

    // Select zone definition mode
    if (GetParameterAsString("inzone") == "labelimage")
      {
      otbAppLogINFO("Zone definition: label image");

      // Computing stats
      m_StatsFilter->SetInputLabelImage(GetParameterInt32Image("inzone.labelimage.in"));
      m_StatsFilter->SetUseNoDataValue(HasUserValue("inbv"));
      m_StatsFilter->SetNoDataValue(GetParameterFloat("inbv"));
      m_StatsFilter->Update();

      // In this zone definition mode, the user can provide a no-data value for the labels
      if (HasUserValue("inzone.labelimage.nodata"))
        intNoData = GetParameterInt("inzone.labelimage.nodata");

      otbAppLogINFO("Using no-data value for the label image: " << intNoData);

      }
    else if (GetParameterAsString("inzone") == "vector")
      {
      otbAppLogINFO("Zone definition: vector");

      otbAppLogINFO("Loading vector data...");
      VectorDataType* shp = GetParameterVectorData("inzone.vector.in");

      // Reproject vector data
      if (GetParameterInt("inzone.vector.reproject") != 0)
        {
        otbAppLogINFO("Vector data reprojection enabled");
        m_VectorDataReprojectionFilter = VectorDataReprojFilterType::New();
        m_VectorDataReprojectionFilter->SetInputVectorData(shp);
        m_VectorDataReprojectionFilter->SetInputImage(img);
        AddProcess(m_VectorDataReprojectionFilter, "Reproject vector data");
        m_VectorDataReprojectionFilter->Update();
        m_VectorDataSrc = m_VectorDataReprojectionFilter->GetOutput();
        }
      else
        {
        m_VectorDataSrc = shp;
        }

      // Rasterize vector data
      m_RasterizeFilter = RasterizeFilterType::New();
      m_RasterizeFilter->AddVectorData(m_VectorDataSrc);
      m_RasterizeFilter->SetOutputOrigin(img->GetOrigin());
      m_RasterizeFilter->SetOutputSpacing(img->GetSignedSpacing());
      m_RasterizeFilter->SetOutputSize(img->GetLargestPossibleRegion().GetSize());
      m_RasterizeFilter->SetOutputProjectionRef(img->GetProjectionRef());
      m_RasterizeFilter->SetBurnAttribute("________");
      m_RasterizeFilter->SetDefaultBurnValue(0);
      m_RasterizeFilter->SetGlobalWarningDisplay(false);
      m_RasterizeFilter->SetBackgroundValue(intNoData);

      // Computing stats
      m_StatsFilter->SetInputLabelImage(m_RasterizeFilter->GetOutput());
      m_StatsFilter->Update();
      }
    else
      {
      otbAppLogFATAL("Unknown zone definition mode");
      }

    // Remove the no-data entry
    StatsFilterType::LabelPopulationMapType countMap = m_StatsFilter->GetLabelPopulationMap();
    StatsFilterType::PixelValueMapType meanMap = m_StatsFilter->GetMeanValueMap();
    StatsFilterType::PixelValueMapType stdMap = m_StatsFilter->GetStandardDeviationValueMap();
    StatsFilterType::PixelValueMapType minMap = m_StatsFilter->GetMinValueMap();
    StatsFilterType::PixelValueMapType maxMap = m_StatsFilter->GetMaxValueMap();
    if (( GetParameterAsString("inzone") == "labelimage" && HasUserValue("inzone.labelimage.nodata"))
        || (GetParameterAsString("inzone") == "vector")      )
      {
      countMap.erase(intNoData);
      meanMap.erase(intNoData);
      stdMap.erase(intNoData);
      minMap.erase(intNoData);
      maxMap.erase(intNoData);
      }

    if (GetParameterAsString("out") == "vector")
      {
      if (GetParameterAsString("inzone") == "vector")
        {
        // Add a statistics fields
        otbAppLogINFO("Writing output vector data");
      LabelValueType internalFID = 0;
      m_NewVectorData = VectorDataType::New();
      DataNodeType::Pointer root = m_NewVectorData->GetDataTree()->GetRoot()->Get();
      DataNodeType::Pointer document = DataNodeType::New();
      document->SetNodeType(otb::DOCUMENT);
      m_NewVectorData->GetDataTree()->Add(document, root);
      DataNodeType::Pointer folder = DataNodeType::New();
      folder->SetNodeType(otb::FOLDER);
      m_NewVectorData->GetDataTree()->Add(folder, document);
      m_NewVectorData->SetProjectionRef(m_VectorDataSrc->GetProjectionRef());
      TreeIteratorType itVector(m_VectorDataSrc->GetDataTree());
      itVector.GoToBegin();

      while (!itVector.IsAtEnd())
        {
        if (!itVector.Get()->IsRoot() && !itVector.Get()->IsDocument() && !itVector.Get()->IsFolder())
          {

          DataNodeType::Pointer currentGeometry = itVector.Get();

          // Add the geometry with the new fields
          if (countMap.count(internalFID) > 0)
            {
            currentGeometry->SetFieldAsDouble("count", countMap[internalFID] );
            for (unsigned int band = 0 ; band < img->GetNumberOfComponentsPerPixel() ; band++)
              {
              currentGeometry->SetFieldAsDouble(CreateFieldName("mean",  band), meanMap[internalFID][band] );
              currentGeometry->SetFieldAsDouble(CreateFieldName("stdev", band), stdMap [internalFID][band] );
              currentGeometry->SetFieldAsDouble(CreateFieldName("min",   band), minMap [internalFID][band] );
              currentGeometry->SetFieldAsDouble(CreateFieldName("max",   band), maxMap [internalFID][band] );
              }
            m_NewVectorData->GetDataTree()->Add(currentGeometry, folder);
            }

          internalFID++;
          }
        ++itVector;
        } // next feature

      SetParameterOutputVectorData("out.vector.filename", m_NewVectorData);
        }
      else if (GetParameterAsString("inzone") == "labelimage")
        {
          //vectorize the image
        otbAppLogFATAL("Vector output from labelimage input not implemented yet");
        }
      }
    else if (GetParameterAsString("out") == "xml")
      {
      // Write stats
      const std::string outXMLFile = this->GetParameterString("out.xml.filename");
      otbAppLogINFO("Writing " + outXMLFile)
      StatsWriterType::Pointer statWriter = StatsWriterType::New();
      statWriter->SetFileName(outXMLFile);
      statWriter->AddInputMap<StatsFilterType::LabelPopulationMapType>("count",countMap);
      statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("mean",meanMap);
      statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("std",stdMap);
      statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("min",minMap);
      statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("max",maxMap);
      statWriter->Update();

      }
    else
      {
      otbAppLogFATAL("Unknown output mode");
      }

  }

  VectorDataType::Pointer m_VectorDataSrc;
  VectorDataType::Pointer m_NewVectorData;
  VectorDataReprojFilterType::Pointer m_VectorDataReprojectionFilter;
  RasterizeFilterType::Pointer m_RasterizeFilter;
  StatsFilterType::Pointer m_StatsFilter;

};
}
}

OTB_APPLICATION_EXPORT( otb::Wrapper::ZonalStatistics )
<commit_msg>FIX: use inbv for background value for all input modes<commit_after>/*
 * Copyright (C) 2017 National Research Institute of Science and
 * Technology for Environment and Agriculture (IRSTEA)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "itkFixedArray.h"
#include "itkObjectFactory.h"

// Elevation handler
#include "otbWrapperElevationParametersHandler.h"
#include "otbWrapperApplicationFactory.h"

// Application engine
#include "otbStandardFilterWatcher.h"

// Process objects
#include "otbVectorDataToLabelImageFilter.h"
#include "otbVectorDataIntoImageProjectionFilter.h"
#include "otbStreamingStatisticsMapFromLabelImageFilter.h"
#include "otbStatisticsXMLFileWriter.h"

namespace otb
{

namespace Wrapper
{

class ZonalStatistics : public Application
{
public:
  /** Standard class typedefs. */
  typedef ZonalStatistics               Self;
  typedef Application                   Superclass;
  typedef itk::SmartPointer<Self>       Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

  /* Typedefs */
  typedef Int32ImageType                LabelImageType;
  typedef LabelImageType::ValueType     LabelValueType;
  typedef otb::VectorData<double, 2>    VectorDataType;
  typedef otb::VectorDataIntoImageProjectionFilter<VectorDataType,
      FloatVectorImageType>             VectorDataReprojFilterType;
  typedef otb::VectorDataToLabelImageFilter<VectorDataType,
      LabelImageType>                   RasterizeFilterType;
  typedef VectorDataType::DataTreeType  DataTreeType;
  typedef itk::PreOrderTreeIterator<DataTreeType>
                                        TreeIteratorType;
  typedef VectorDataType::DataNodeType  DataNodeType;
  typedef DataNodeType::PolygonListPointerType
                                        PolygonListPointerType;
  typedef otb::StreamingStatisticsMapFromLabelImageFilter<FloatVectorImageType,
      LabelImageType>                   StatsFilterType;
  typedef otb::StatisticsXMLFileWriter<FloatVectorImageType::PixelType>
                                        StatsWriterType;

  /** Standard macro */
  itkNewMacro(Self);
  itkTypeMacro(ZonalStatistics, Application);

  void DoInit()
  {

    SetName("ZonalStatistics");
    SetDescription("This application computes zonal statistics");

    // Documentation
    SetDocName("ZonalStatistics");
    SetDocLongDescription("This application computes zonal statistics from label image, or vector data. "
        "The application inputs one input multiband image, and a label input. "
        "If the label input is a raster, the output statistics are exported in a XML file. If the label "
        "input is a vector data, the output statistics are exported in a new vector data with statistics "
        "in the attribute table. The computed statistics are mean, min, max, and standard deviation.");
    SetDocLimitations("The shapefile must fit in memory");
    SetDocAuthors("Remi Cresson");

    AddDocTag(Tags::Manip);
    AddDocTag(Tags::Analysis);

    // Input image
    AddParameter(ParameterType_InputImage, "in",   "Input Image");
    AddParameter(ParameterType_Float,      "inbv", "Background value to ignore in statistics computation");

    // Input zone mode
    AddParameter(ParameterType_Choice, "inzone", "Type of input for the zone definitions");
    AddChoice("inzone.vector",     "Input objects from vector data");
    AddChoice("inzone.labelimage", "Input objects from label image");

    // Input for vector mode
    AddParameter(ParameterType_InputVectorData,  "inzone.vector.in",        "Input vector data");
    AddParameter(ParameterType_Bool,             "inzone.vector.reproject", "Reproject the input vector");

    // Input for label image mode
    AddParameter(ParameterType_InputImage, "inzone.labelimage.in",     "Input label image");
    AddParameter(ParameterType_Int,        "inzone.labelimage.nodata", "No-data value for the input label image");
    MandatoryOff                          ("inzone.labelimage.nodata");

    // Output stats mode
    AddParameter(ParameterType_Choice, "out", "Format of the output stats");
    AddChoice("out.vector", "Output vector data");
    AddParameter(ParameterType_OutputVectorData, "out.vector.filename", "Filename for the output vector data");
    AddChoice("out.xml", "Output XML file");
    AddParameter(ParameterType_String, "out.xml.filename", "");
    AddChoice("out.raster", "Output raster image");
    AddParameter(ParameterType_OutputImage, "out.raster.filename", "");

    AddRAMParameter();

    // Doc example parameter settings
    SetDocExampleParameterValue("in", "input.tif");
    SetDocExampleParameterValue("inzone.vector.in", "myvector.shp");
    SetDocExampleParameterValue("out.vector.filename", "myvector_with_stats.shp");

  }

  void DoUpdateParameters()
  {
    // Nothing to do here : all parameters are independent
  }

  // Returns a string of the kind "prefix_i"
  const std::string CreateFieldName(const std::string & prefix, const unsigned int i)
  {
    std::stringstream ss;
    ss << prefix << "_" << i;
    return ss.str();
  }

  // Returns a null pixel which has the same number of components per pixels as img
  FloatVectorImageType::PixelType NullPixel(FloatVectorImageType::Pointer & img)
  {
    const unsigned int nBands = img->GetNumberOfComponentsPerPixel();
    FloatVectorImageType::PixelType pix;
    pix.SetSize(nBands);
    pix.Fill(0);
    return pix;
  }

  void DoExecute()
  {

    // Get input image
    FloatVectorImageType::Pointer img = GetParameterImage("in");

    // Statistics filter
    m_StatsFilter = StatsFilterType::New();
    m_StatsFilter->SetInput(img);
    m_StatsFilter->SetUseNoDataValue(HasUserValue("inbv"));
    m_StatsFilter->SetNoDataValue(GetParameterFloat("inbv"));
    m_StatsFilter->GetStreamer()->SetAutomaticAdaptativeStreaming(GetParameterInt("ram"));
    AddProcess(m_StatsFilter->GetStreamer(), "Computing statistics");

    // Internal no-data value
    LabelValueType intNoData = itk::NumericTraits<LabelValueType>::max();

    // Select zone definition mode
    if (GetParameterAsString("inzone") == "labelimage")
      {
      otbAppLogINFO("Zone definition: label image");

      // Computing stats
      m_StatsFilter->SetInputLabelImage(GetParameterInt32Image("inzone.labelimage.in"));
      m_StatsFilter->Update();

      // In this zone definition mode, the user can provide a no-data value for the labels
      if (HasUserValue("inzone.labelimage.nodata"))
        intNoData = GetParameterInt("inzone.labelimage.nodata");

      otbAppLogINFO("Using no-data value for the label image: " << intNoData);

      }
    else if (GetParameterAsString("inzone") == "vector")
      {
      otbAppLogINFO("Zone definition: vector");

      otbAppLogINFO("Loading vector data...");
      VectorDataType* shp = GetParameterVectorData("inzone.vector.in");

      // Reproject vector data
      if (GetParameterInt("inzone.vector.reproject") != 0)
        {
        otbAppLogINFO("Vector data reprojection enabled");
        m_VectorDataReprojectionFilter = VectorDataReprojFilterType::New();
        m_VectorDataReprojectionFilter->SetInputVectorData(shp);
        m_VectorDataReprojectionFilter->SetInputImage(img);
        AddProcess(m_VectorDataReprojectionFilter, "Reproject vector data");
        m_VectorDataReprojectionFilter->Update();
        m_VectorDataSrc = m_VectorDataReprojectionFilter->GetOutput();
        }
      else
        {
        m_VectorDataSrc = shp;
        }

      // Rasterize vector data
      m_RasterizeFilter = RasterizeFilterType::New();
      m_RasterizeFilter->AddVectorData(m_VectorDataSrc);
      m_RasterizeFilter->SetOutputOrigin(img->GetOrigin());
      m_RasterizeFilter->SetOutputSpacing(img->GetSignedSpacing());
      m_RasterizeFilter->SetOutputSize(img->GetLargestPossibleRegion().GetSize());
      m_RasterizeFilter->SetOutputProjectionRef(img->GetProjectionRef());
      m_RasterizeFilter->SetBurnAttribute("________");
      m_RasterizeFilter->SetDefaultBurnValue(0);
      m_RasterizeFilter->SetGlobalWarningDisplay(false);
      m_RasterizeFilter->SetBackgroundValue(intNoData);

      // Computing stats
      m_StatsFilter->SetInputLabelImage(m_RasterizeFilter->GetOutput());
      m_StatsFilter->Update();
      }
    else
      {
      otbAppLogFATAL("Unknown zone definition mode");
      }

    // Remove the no-data entry
    StatsFilterType::LabelPopulationMapType countMap = m_StatsFilter->GetLabelPopulationMap();
    StatsFilterType::PixelValueMapType meanMap = m_StatsFilter->GetMeanValueMap();
    StatsFilterType::PixelValueMapType stdMap = m_StatsFilter->GetStandardDeviationValueMap();
    StatsFilterType::PixelValueMapType minMap = m_StatsFilter->GetMinValueMap();
    StatsFilterType::PixelValueMapType maxMap = m_StatsFilter->GetMaxValueMap();
    if (( GetParameterAsString("inzone") == "labelimage" && HasUserValue("inzone.labelimage.nodata"))
        || (GetParameterAsString("inzone") == "vector")      )
      {
      countMap.erase(intNoData);
      meanMap.erase(intNoData);
      stdMap.erase(intNoData);
      minMap.erase(intNoData);
      maxMap.erase(intNoData);
      }

    if (GetParameterAsString("out") == "vector")
      {
      if (GetParameterAsString("inzone") == "vector")
        {
        // Add a statistics fields
        otbAppLogINFO("Writing output vector data");
      LabelValueType internalFID = 0;
      m_NewVectorData = VectorDataType::New();
      DataNodeType::Pointer root = m_NewVectorData->GetDataTree()->GetRoot()->Get();
      DataNodeType::Pointer document = DataNodeType::New();
      document->SetNodeType(otb::DOCUMENT);
      m_NewVectorData->GetDataTree()->Add(document, root);
      DataNodeType::Pointer folder = DataNodeType::New();
      folder->SetNodeType(otb::FOLDER);
      m_NewVectorData->GetDataTree()->Add(folder, document);
      m_NewVectorData->SetProjectionRef(m_VectorDataSrc->GetProjectionRef());
      TreeIteratorType itVector(m_VectorDataSrc->GetDataTree());
      itVector.GoToBegin();

      while (!itVector.IsAtEnd())
        {
        if (!itVector.Get()->IsRoot() && !itVector.Get()->IsDocument() && !itVector.Get()->IsFolder())
          {

          DataNodeType::Pointer currentGeometry = itVector.Get();

          // Add the geometry with the new fields
          if (countMap.count(internalFID) > 0)
            {
            currentGeometry->SetFieldAsDouble("count", countMap[internalFID] );
            for (unsigned int band = 0 ; band < img->GetNumberOfComponentsPerPixel() ; band++)
              {
              currentGeometry->SetFieldAsDouble(CreateFieldName("mean",  band), meanMap[internalFID][band] );
              currentGeometry->SetFieldAsDouble(CreateFieldName("stdev", band), stdMap [internalFID][band] );
              currentGeometry->SetFieldAsDouble(CreateFieldName("min",   band), minMap [internalFID][band] );
              currentGeometry->SetFieldAsDouble(CreateFieldName("max",   band), maxMap [internalFID][band] );
              }
            m_NewVectorData->GetDataTree()->Add(currentGeometry, folder);
            }

          internalFID++;
          }
        ++itVector;
        } // next feature

      SetParameterOutputVectorData("out.vector.filename", m_NewVectorData);
        }
      else if (GetParameterAsString("inzone") == "labelimage")
        {
          //vectorize the image
        otbAppLogFATAL("Vector output from labelimage input not implemented yet");
        }
      }
    else if (GetParameterAsString("out") == "xml")
      {
      // Write stats
      const std::string outXMLFile = this->GetParameterString("out.xml.filename");
      otbAppLogINFO("Writing " + outXMLFile)
      StatsWriterType::Pointer statWriter = StatsWriterType::New();
      statWriter->SetFileName(outXMLFile);
      statWriter->AddInputMap<StatsFilterType::LabelPopulationMapType>("count",countMap);
      statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("mean",meanMap);
      statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("std",stdMap);
      statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("min",minMap);
      statWriter->AddInputMap<StatsFilterType::PixelValueMapType>("max",maxMap);
      statWriter->Update();

      }
    else
      {
      otbAppLogFATAL("Unknown output mode");
      }

  }

  VectorDataType::Pointer m_VectorDataSrc;
  VectorDataType::Pointer m_NewVectorData;
  VectorDataReprojFilterType::Pointer m_VectorDataReprojectionFilter;
  RasterizeFilterType::Pointer m_RasterizeFilter;
  StatsFilterType::Pointer m_StatsFilter;

};
}
}

OTB_APPLICATION_EXPORT( otb::Wrapper::ZonalStatistics )
<|endoftext|>


<commit_before>//
// luna
//
// Copyright © 2016 D.E. Goodman-Wilson
//

#include <gtest/gtest.h>
#include <luna/luna.h>
#include <cpr/cpr.h>
#include "server_impl.h"

TEST(server_options, set_mime_type)
{
    luna::server server{luna::server::mime_type{"howdyho"}
    };
    server.handle_request(luna::request_method::GET,
                          "/test",
                          [](auto matches, auto params) -> luna::response
                              {
                                  return {"hello"};
                              });

    auto res = cpr::Get(cpr::Url{"http://localhost:8080/test"}, cpr::Parameters{{"key", "value"}});

    ASSERT_EQ(200, res.status_code);
    ASSERT_EQ("hello", res.text);
    ASSERT_EQ("howdyho", res.header["Content-Type"]);
}

TEST(server_options, set_error_handler_cb)
{
    luna::server server{luna::server::error_handler_cb
                                {
                                        [](luna::response &response, //a hook for modifying in place to insert default content
                                           luna::request_method method,
                                           const std::string &path)
                                            {
                                                ASSERT_EQ(404, response.status_code);
                                                ASSERT_EQ("/test", path);
                                                ASSERT_EQ(luna::request_method::GET, method);
                                            }
                                }
    };

    auto res = cpr::Get(cpr::Url{"http://localhost:8080/test"}, cpr::Parameters{{"key", "value"}});
}

TEST(server_options, set_accept_policy_cb)
{
    luna::server server{luna::server::accept_policy_cb
        {
            [](const struct sockaddr *add, socklen_t len) -> bool
            {
                //we can't really know what address will get passed in so just assert that
                // returning "false" does the right thing, and that we got called.
                EXPECT_NE(nullptr, add);
                return false;
            }
        }
    };
    server.handle_request(luna::request_method::POST,
                          "/test",
                          [](auto matches, auto params) -> luna::response
                              {
                                  return {"hello"};
                              });

    auto res = cpr::Get(cpr::Url{"http://localhost:8080/test"});
    ASSERT_EQ("", res.text);
}

TEST(server_options, set_unescaper_cb)
{
    luna::server server{luna::server::unescaper_cb
        {
            [](const std::string &text) -> std::string
            {
                    if(text == "value") return "ugh";
                    return text;
            }
        }
    };

    server.handle_request(luna::request_method::GET,
                          "/test",
                          [](auto matches, auto params) -> luna::response
                          {
                              EXPECT_EQ("ugh", params["key"]);
                              return {params["key"]};
                          });

    auto res = cpr::Get(cpr::Url{"http://localhost:8080/test"}, cpr::Parameters{{"key", "value"}});
    ASSERT_EQ("ugh", res.text);
}<commit_msg>Autoformatting<commit_after>//
// luna
//
// Copyright © 2016 D.E. Goodman-Wilson
//

#include <gtest/gtest.h>
#include <luna/luna.h>
#include <cpr/cpr.h>
#include "server_impl.h"

TEST(server_options, set_mime_type)
{
    luna::server server{luna::server::mime_type{"howdyho"}
    };
    server.handle_request(luna::request_method::GET,
                          "/test",
                          [](auto matches, auto params) -> luna::response
                              {
                                  return {"hello"};
                              });

    auto res = cpr::Get(cpr::Url{"http://localhost:8080/test"}, cpr::Parameters{{"key", "value"}});

    ASSERT_EQ(200, res.status_code);
    ASSERT_EQ("hello", res.text);
    ASSERT_EQ("howdyho", res.header["Content-Type"]);
}

TEST(server_options, set_error_handler_cb)
{
    luna::server server{luna::server::error_handler_cb
                                {
                                        [](luna::response &response, //a hook for modifying in place to insert default content
                                           luna::request_method method,
                                           const std::string &path)
                                            {
                                                ASSERT_EQ(404, response.status_code);
                                                ASSERT_EQ("/test", path);
                                                ASSERT_EQ(luna::request_method::GET, method);
                                            }
                                }
    };

    auto res = cpr::Get(cpr::Url{"http://localhost:8080/test"}, cpr::Parameters{{"key", "value"}});
}

TEST(server_options, set_accept_policy_cb)
{
    luna::server server{luna::server::accept_policy_cb
                                {
                                        [](const struct sockaddr *add, socklen_t len) -> bool
                                            {
                                                //we can't really know what address will get passed in so just assert that
                                                // returning "false" does the right thing, and that we got called.
                                                EXPECT_NE(nullptr, add);
                                                return false;
                                            }
                                }
    };
    server.handle_request(luna::request_method::POST,
                          "/test",
                          [](auto matches, auto params) -> luna::response
                              {
                                  return {"hello"};
                              });

    auto res = cpr::Get(cpr::Url{"http://localhost:8080/test"});
    ASSERT_EQ("", res.text);
}

TEST(server_options, set_unescaper_cb)
{
    luna::server server{luna::server::unescaper_cb
                                {
                                        [](const std::string &text) -> std::string
                                            {
                                                if (text == "value") return "ugh";
                                                return text;
                                            }
                                }
    };

    server.handle_request(luna::request_method::GET,
                          "/test",
                          [](auto matches, auto params) -> luna::response
                              {
                                  EXPECT_EQ("ugh", params["key"]);
                                  return {params["key"]};
                              });

    auto res = cpr::Get(cpr::Url{"http://localhost:8080/test"}, cpr::Parameters{{"key", "value"}});
    ASSERT_EQ("ugh", res.text);
}<|endoftext|>


<commit_before>/**
 * Copyright (C) 2013 Regents of the University of California.
 * @author: Jeff Thompson <jefft0@remap.ucla.edu>
 * See COPYING for copyright and distribution information.
 */

#include <cstdlib>
#include <sstream>
#include <iostream>
#include "../ndn-cpp/face.hpp"

using namespace std;
using namespace ndn;
using namespace ptr_lib;
using namespace func_lib;
#if HAVE_STD_FUNCTION
// In the std library, the placeholders are in a different namespace than boost.
using namespace func_lib::placeholders;
#endif

class Counter
{
public:
  Counter() {
    callbackCount_ = 0;
  }

  void onData(const shared_ptr<const Interest>& interest, const shared_ptr<Data>& data)
  {
    ++callbackCount_;
    cout << "Got data packet with name " << data->getName().to_uri() << endl;
    for (size_t i = 0; i < data->getContent().size(); ++i)
      cout << (*data->getContent())[i];
    cout << endl;
  }

  void onTimeout(const shared_ptr<const Interest>& interest)
  {
    ++callbackCount_;
    cout << "Time out for interest " << interest->getName().toUri() << endl;
  }

  int callbackCount_;
};

int main(int argc, char** argv)
{
  try {
    // Connect to port 9695 until the testbed hubs use NDNx.
    Face face("E.hub.ndn.ucla.edu", 9695);

    // Counter holds data used by the callbacks.
    Counter counter;

    Name name1("/ndn/ucla.edu/apps/ndn-js-test/hello.txt/level2/%FD%05%0B%16%7D%95%0E");
    cout << "Express name  " << name1.toUri() << endl;
    // Use bind to pass the counter object to the callbacks.
    face.expressInterest(name1, bind(&Counter::onData, &counter, _1, _2), bind(&Counter::onTimeout, &counter, _1));

    Name name2("/ndn/ucla.edu/apps/lwndn-test/howdy.txt/%FD%05%05%E8%0C%CE%1D");
    cout << "Express name  " << name2.toUri() << endl;
    face.expressInterest(name2, bind(&Counter::onData, &counter, _1, _2), bind(&Counter::onTimeout, &counter, _1));

    Name name3("/test/timeout");
    cout << "Express name  " << name3.toUri() << endl;
    face.expressInterest(name3, bind(&Counter::onData, &counter, _1, _2), bind(&Counter::onTimeout, &counter, _1));

    // The main event loop.
    while (counter.callbackCount_ < 3) {
      face.processEvents();
      // We need to sleep for a few milliseconds so we don't use 100% of the CPU.
      usleep(10000);
    }
  } catch (std::exception& e) {
    cout << "exception: " << e.what() << endl;
  }
  return 0;
}
<commit_msg>tests: Change test-get-async to use A.hub.ndn.ucla.edu.<commit_after>/**
 * Copyright (C) 2013 Regents of the University of California.
 * @author: Jeff Thompson <jefft0@remap.ucla.edu>
 * See COPYING for copyright and distribution information.
 */

#include <cstdlib>
#include <sstream>
#include <iostream>
#include "../ndn-cpp/face.hpp"

using namespace std;
using namespace ndn;
using namespace ptr_lib;
using namespace func_lib;
#if HAVE_STD_FUNCTION
// In the std library, the placeholders are in a different namespace than boost.
using namespace func_lib::placeholders;
#endif

class Counter
{
public:
  Counter() {
    callbackCount_ = 0;
  }

  void onData(const shared_ptr<const Interest>& interest, const shared_ptr<Data>& data)
  {
    ++callbackCount_;
    cout << "Got data packet with name " << data->getName().to_uri() << endl;
    for (size_t i = 0; i < data->getContent().size(); ++i)
      cout << (*data->getContent())[i];
    cout << endl;
  }

  void onTimeout(const shared_ptr<const Interest>& interest)
  {
    ++callbackCount_;
    cout << "Time out for interest " << interest->getName().toUri() << endl;
  }

  int callbackCount_;
};

int main(int argc, char** argv)
{
  try {
    // Connect to port 9695 until the testbed hubs use NDNx.
    Face face("A.hub.ndn.ucla.edu", 9695);

    // Counter holds data used by the callbacks.
    Counter counter;

    Name name1("/ndn/ucla.edu/apps/ndn-js-test/hello.txt/level2/%FD%05%0B%16%7D%95%0E");
    cout << "Express name  " << name1.toUri() << endl;
    // Use bind to pass the counter object to the callbacks.
    face.expressInterest(name1, bind(&Counter::onData, &counter, _1, _2), bind(&Counter::onTimeout, &counter, _1));

    Name name2("/ndn/ucla.edu/apps/lwndn-test/howdy.txt/%FD%05%05%E8%0C%CE%1D");
    cout << "Express name  " << name2.toUri() << endl;
    face.expressInterest(name2, bind(&Counter::onData, &counter, _1, _2), bind(&Counter::onTimeout, &counter, _1));

    Name name3("/test/timeout");
    cout << "Express name  " << name3.toUri() << endl;
    face.expressInterest(name3, bind(&Counter::onData, &counter, _1, _2), bind(&Counter::onTimeout, &counter, _1));

    // The main event loop.
    while (counter.callbackCount_ < 3) {
      face.processEvents();
      // We need to sleep for a few milliseconds so we don't use 100% of the CPU.
      usleep(10000);
    }
  } catch (std::exception& e) {
    cout << "exception: " << e.what() << endl;
  }
  return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: opengrf.cxx,v $
 *
 *  $Revision: 1.20 $
 *
 *  last change: $Author: ihi $ $Date: 2007-06-05 14:34:02 $
 *
 *  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_svx.hxx"
#include <tools/urlobj.hxx>

#ifndef  _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif

#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif

#ifndef  _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif

#ifndef  _COM_SUN_STAR_UI_DIALOGS_COMMONFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/CommonFilePickerElementIds.hpp>
#endif
#ifndef  _COM_SUN_STAR_UI_DIALOGS_EXECUTABLEDIALOGRESULTS_HPP_
#include <com/sun/star/ui/dialogs/ExecutableDialogResults.hpp>
#endif
#ifndef  _COM_SUN_STAR_UI_DIALOGS_EXTENDEDFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp>
#endif
#ifndef  _COM_SUN_STAR_UI_DIALOGS_FILEPREVIEWIMAGEFORMATS_HPP_
#include <com/sun/star/ui/dialogs/FilePreviewImageFormats.hpp>
#endif
#ifndef  _COM_SUN_STAR_UI_DIALOGS_LISTBOXCONTROLACTIONS_HPP_
#include <com/sun/star/ui/dialogs/ListboxControlActions.hpp>
#endif
#ifndef  _COM_SUN_STAR_UI_DIALOGS_TEMPLATEDESCRIPTION_HPP_
#include <com/sun/star/ui/dialogs/TemplateDescription.hpp>
#endif
#ifndef  _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERCONTROLACCESS_HPP_
#include <com/sun/star/ui/dialogs/XFilePickerControlAccess.hpp>
#endif
#ifndef  _COM_SUN_STAR_UI_DIALOGS_XFILEPICKER_HPP_
#include <com/sun/star/ui/dialogs/XFilePicker.hpp>
#endif
#ifndef  _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERLISTENER_HPP_
#include <com/sun/star/ui/dialogs/XFilePickerListener.hpp>
#endif
#ifndef  _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERNOTIFIER_HPP_
#include <com/sun/star/ui/dialogs/XFilePickerNotifier.hpp>
#endif
#ifndef  _COM_SUN_STAR_UI_DIALOGS_XFILEPREVIEW_HPP_
#include <com/sun/star/ui/dialogs/XFilePreview.hpp>
#endif
#ifndef  _COM_SUN_STAR_UI_DIALOGS_XFILTERMANAGER_HPP_
#include <com/sun/star/ui/dialogs/XFilterManager.hpp>
#endif
#ifndef SVTOOLS_URIHELPER_HXX
#include <svtools/urihelper.hxx>
#endif
#ifndef _UNOTOOLS_UCBSTREAMHELPER_HXX
#include <unotools/ucbstreamhelper.hxx>
#endif
#ifndef _TRANSFER_HXX //autogen
#include <svtools/transfer.hxx>
#endif
#ifndef _SVDOGRAF_HXX //autogen
#include "svdograf.hxx"
#endif
#ifndef _SOT_FORMATS_HXX //autogen
#include <sot/formats.hxx>
#endif
#ifndef _MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _FILEDLGHELPER_HXX
#include <sfx2/filedlghelper.hxx>
#endif
#ifndef _SFXDOCFILE_HXX
#include <sfx2/docfile.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX
#include <svtools/pathoptions.hxx>
#endif
#ifndef _SVX_DIALMGR_HXX
#include "dialmgr.hxx"
#endif

#ifndef _SVX_OPENGRF_HXX
#include "opengrf.hxx"
#endif

#include "dialogs.hrc"
#include "impgrf.hrc"

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

using namespace ::com::sun::star;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::ui::dialogs;
using namespace ::com::sun::star::uno;
using namespace ::rtl;
using namespace ::cppu;

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

USHORT  SvxOpenGrfErr2ResId(    short   err     )
{
    switch( err )
    {
        case GRFILTER_OPENERROR:
            return RID_SVXSTR_GRFILTER_OPENERROR;
        case GRFILTER_IOERROR:
            return RID_SVXSTR_GRFILTER_IOERROR;
        case GRFILTER_VERSIONERROR:
            return RID_SVXSTR_GRFILTER_VERSIONERROR;
        case GRFILTER_FILTERERROR:
            return RID_SVXSTR_GRFILTER_FILTERERROR;
        case GRFILTER_FORMATERROR:
        default:
            return RID_SVXSTR_GRFILTER_FORMATERROR;
    }
}

struct SvxOpenGrf_Impl
{
    SvxOpenGrf_Impl         ();

    sfx2::FileDialogHelper                  aFileDlg;
    uno::Reference < XFilePickerControlAccess > xCtrlAcc;
};

SvxOpenGrf_Impl::SvxOpenGrf_Impl() :
    aFileDlg(SFXWB_GRAPHIC)
{
    uno::Reference < XFilePicker > xFP = aFileDlg.GetFilePicker();
    xCtrlAcc = uno::Reference < XFilePickerControlAccess >(xFP, UNO_QUERY);
}

SvxOpenGraphicDialog::SvxOpenGraphicDialog( const String& rTitle ) :
    mpImpl( new SvxOpenGrf_Impl )
{
    mpImpl->aFileDlg.SetTitle(rTitle);
}

SvxOpenGraphicDialog::~SvxOpenGraphicDialog()
{
}

GraphicFilter* GetGrfFilter();

short SvxOpenGraphicDialog::Execute()
{
    USHORT  nImpRet;
    BOOL    bQuitLoop(FALSE);

    while( bQuitLoop == FALSE &&
           mpImpl->aFileDlg.Execute() == ERRCODE_NONE )
    {
        if( GetPath().Len() )
        {
            GraphicFilter*  pFilter = GetGrfFilter();
            INetURLObject aObj( GetPath() );

            // check whether we can load the graphic
            String  aCurFilter( GetCurrentFilter() );
            USHORT  nFormatNum = pFilter->GetImportFormatNumber( aCurFilter );
            USHORT  nRetFormat = 0;
            USHORT  nFound = USHRT_MAX;

            // non-local?
            if ( INET_PROT_FILE != aObj.GetProtocol() )
            {
                SfxMedium aMed( aObj.GetMainURL( INetURLObject::NO_DECODE ), STREAM_READ, TRUE );
                aMed.DownLoad();
                SvStream* pStream = aMed.GetInStream();

                if( pStream )
                    nImpRet = pFilter->CanImportGraphic( aObj.GetMainURL( INetURLObject::NO_DECODE ), *pStream, nFormatNum, &nRetFormat );
                else
                    nImpRet = pFilter->CanImportGraphic( aObj, nFormatNum, &nRetFormat );

                if ( GRFILTER_OK != nImpRet )
                {
                    if ( !pStream )
                        nImpRet = pFilter->CanImportGraphic( aObj, GRFILTER_FORMAT_DONTKNOW, &nRetFormat );
                    else
                        nImpRet = pFilter->CanImportGraphic( aObj.GetMainURL( INetURLObject::NO_DECODE ), *pStream,
                                                             GRFILTER_FORMAT_DONTKNOW, &nRetFormat );
                }
            }
            else
            {
                if( (nImpRet=pFilter->CanImportGraphic( aObj, nFormatNum, &nRetFormat )) != GRFILTER_OK )
                    nImpRet = pFilter->CanImportGraphic( aObj, GRFILTER_FORMAT_DONTKNOW, &nRetFormat );
            }

            if ( GRFILTER_OK == nImpRet )
                nFound = nRetFormat;

            // could not load?
            if ( nFound == USHRT_MAX )
            {
                WarningBox aWarningBox( NULL, WB_3DLOOK | WB_RETRY_CANCEL, SVX_RESSTR( SvxOpenGrfErr2ResId(nImpRet) ) );
                bQuitLoop = aWarningBox.Execute()==RET_RETRY ? FALSE : TRUE;
            }
            else
            {
                // setup appropriate filter (so next time, it will work)
                if( pFilter->GetImportFormatCount() )
                {
                    String  aFormatName(pFilter->GetImportFormatName(nFound));
                    SetCurrentFilter(aFormatName);
                }

                return nImpRet;
            }
        }
    }

    // cancel
    return -1;
}

void SvxOpenGraphicDialog::SetPath( const String& rPath )
{
    mpImpl->aFileDlg.SetDisplayDirectory(rPath);
}

void SvxOpenGraphicDialog::SetPath( const String& rPath, sal_Bool bLinkState )
{
    SetPath(rPath);
    AsLink(bLinkState);
}

void SvxOpenGraphicDialog::EnableLink( sal_Bool  state  )
{
    if( mpImpl->xCtrlAcc.is() )
    {
        try
        {
            mpImpl->xCtrlAcc->enableControl( ExtendedFilePickerElementIds::CHECKBOX_LINK, state );
        }
        catch(IllegalArgumentException)
        {
#ifdef DBG_UTIL
            DBG_ERROR( "Cannot enable \"link\" checkbox" );
#endif
        }
    }
}

void SvxOpenGraphicDialog::AsLink(sal_Bool  bState)
{
    if( mpImpl->xCtrlAcc.is() )
    {
        try
        {
            Any aAny; aAny <<= bState;
            mpImpl->xCtrlAcc->setValue( ExtendedFilePickerElementIds::CHECKBOX_LINK, 0, aAny );
        }
        catch(IllegalArgumentException)
        {
#ifdef DBG_UTIL
            DBG_ERROR( "Cannot check \"link\" checkbox" );
#endif
        }
    }
}

sal_Bool SvxOpenGraphicDialog::IsAsLink() const
{
    try
    {
        if( mpImpl->xCtrlAcc.is() )
        {
            Any aVal = mpImpl->xCtrlAcc->getValue( ExtendedFilePickerElementIds::CHECKBOX_LINK, 0 );
            DBG_ASSERT(aVal.hasValue(), "Value CBX_INSERT_AS_LINK not found")
            return aVal.hasValue() ? *(sal_Bool*) aVal.getValue() : sal_False;
        }
    }
    catch(IllegalArgumentException)
    {
#ifdef DBG_UTIL
        DBG_ERROR( "Cannot access \"link\" checkbox" );
#endif
    }

    return sal_False;
}

int SvxOpenGraphicDialog::GetGraphic(Graphic& rGraphic) const
{
    return mpImpl->aFileDlg.GetGraphic(rGraphic);
}

String SvxOpenGraphicDialog::GetPath() const
{
    return mpImpl->aFileDlg.GetPath();
}

String SvxOpenGraphicDialog::GetCurrentFilter() const
{
    return mpImpl->aFileDlg.GetCurrentFilter();
}

void SvxOpenGraphicDialog::SetCurrentFilter(const String&   rStr)
{
    mpImpl->aFileDlg.SetCurrentFilter(rStr);
}

void SvxOpenGraphicDialog::SetControlHelpIds( const INT16* _pControlId, const INT32* _pHelpId )
{
    mpImpl->aFileDlg.SetControlHelpIds( _pControlId, _pHelpId );
}

void SvxOpenGraphicDialog::SetDialogHelpId( const INT32 _nHelpId )
{
    mpImpl->aFileDlg.SetDialogHelpId( _nHelpId );
}
<commit_msg>INTEGRATION: CWS vgbugs07 (1.19.354); FILE MERGED 2007/06/04 13:26:22 vg 1.19.354.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: opengrf.cxx,v $
 *
 *  $Revision: 1.21 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 17:23:46 $
 *
 *  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_svx.hxx"
#include <tools/urlobj.hxx>

#ifndef  _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif

#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif

#ifndef  _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif

#ifndef  _COM_SUN_STAR_UI_DIALOGS_COMMONFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/CommonFilePickerElementIds.hpp>
#endif
#ifndef  _COM_SUN_STAR_UI_DIALOGS_EXECUTABLEDIALOGRESULTS_HPP_
#include <com/sun/star/ui/dialogs/ExecutableDialogResults.hpp>
#endif
#ifndef  _COM_SUN_STAR_UI_DIALOGS_EXTENDEDFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp>
#endif
#ifndef  _COM_SUN_STAR_UI_DIALOGS_FILEPREVIEWIMAGEFORMATS_HPP_
#include <com/sun/star/ui/dialogs/FilePreviewImageFormats.hpp>
#endif
#ifndef  _COM_SUN_STAR_UI_DIALOGS_LISTBOXCONTROLACTIONS_HPP_
#include <com/sun/star/ui/dialogs/ListboxControlActions.hpp>
#endif
#ifndef  _COM_SUN_STAR_UI_DIALOGS_TEMPLATEDESCRIPTION_HPP_
#include <com/sun/star/ui/dialogs/TemplateDescription.hpp>
#endif
#ifndef  _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERCONTROLACCESS_HPP_
#include <com/sun/star/ui/dialogs/XFilePickerControlAccess.hpp>
#endif
#ifndef  _COM_SUN_STAR_UI_DIALOGS_XFILEPICKER_HPP_
#include <com/sun/star/ui/dialogs/XFilePicker.hpp>
#endif
#ifndef  _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERLISTENER_HPP_
#include <com/sun/star/ui/dialogs/XFilePickerListener.hpp>
#endif
#ifndef  _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERNOTIFIER_HPP_
#include <com/sun/star/ui/dialogs/XFilePickerNotifier.hpp>
#endif
#ifndef  _COM_SUN_STAR_UI_DIALOGS_XFILEPREVIEW_HPP_
#include <com/sun/star/ui/dialogs/XFilePreview.hpp>
#endif
#ifndef  _COM_SUN_STAR_UI_DIALOGS_XFILTERMANAGER_HPP_
#include <com/sun/star/ui/dialogs/XFilterManager.hpp>
#endif
#ifndef SVTOOLS_URIHELPER_HXX
#include <svtools/urihelper.hxx>
#endif
#ifndef _UNOTOOLS_UCBSTREAMHELPER_HXX
#include <unotools/ucbstreamhelper.hxx>
#endif
#ifndef _TRANSFER_HXX //autogen
#include <svtools/transfer.hxx>
#endif
#ifndef _SVDOGRAF_HXX //autogen
#include <svx/svdograf.hxx>
#endif
#ifndef _SOT_FORMATS_HXX //autogen
#include <sot/formats.hxx>
#endif
#ifndef _MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _FILEDLGHELPER_HXX
#include <sfx2/filedlghelper.hxx>
#endif
#ifndef _SFXDOCFILE_HXX
#include <sfx2/docfile.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX
#include <svtools/pathoptions.hxx>
#endif
#ifndef _SVX_DIALMGR_HXX
#include <svx/dialmgr.hxx>
#endif

#ifndef _SVX_OPENGRF_HXX
#include "opengrf.hxx"
#endif

#include <svx/dialogs.hrc>
#include "impgrf.hrc"

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

using namespace ::com::sun::star;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::ui::dialogs;
using namespace ::com::sun::star::uno;
using namespace ::rtl;
using namespace ::cppu;

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

USHORT  SvxOpenGrfErr2ResId(    short   err     )
{
    switch( err )
    {
        case GRFILTER_OPENERROR:
            return RID_SVXSTR_GRFILTER_OPENERROR;
        case GRFILTER_IOERROR:
            return RID_SVXSTR_GRFILTER_IOERROR;
        case GRFILTER_VERSIONERROR:
            return RID_SVXSTR_GRFILTER_VERSIONERROR;
        case GRFILTER_FILTERERROR:
            return RID_SVXSTR_GRFILTER_FILTERERROR;
        case GRFILTER_FORMATERROR:
        default:
            return RID_SVXSTR_GRFILTER_FORMATERROR;
    }
}

struct SvxOpenGrf_Impl
{
    SvxOpenGrf_Impl         ();

    sfx2::FileDialogHelper                  aFileDlg;
    uno::Reference < XFilePickerControlAccess > xCtrlAcc;
};

SvxOpenGrf_Impl::SvxOpenGrf_Impl() :
    aFileDlg(SFXWB_GRAPHIC)
{
    uno::Reference < XFilePicker > xFP = aFileDlg.GetFilePicker();
    xCtrlAcc = uno::Reference < XFilePickerControlAccess >(xFP, UNO_QUERY);
}

SvxOpenGraphicDialog::SvxOpenGraphicDialog( const String& rTitle ) :
    mpImpl( new SvxOpenGrf_Impl )
{
    mpImpl->aFileDlg.SetTitle(rTitle);
}

SvxOpenGraphicDialog::~SvxOpenGraphicDialog()
{
}

GraphicFilter* GetGrfFilter();

short SvxOpenGraphicDialog::Execute()
{
    USHORT  nImpRet;
    BOOL    bQuitLoop(FALSE);

    while( bQuitLoop == FALSE &&
           mpImpl->aFileDlg.Execute() == ERRCODE_NONE )
    {
        if( GetPath().Len() )
        {
            GraphicFilter*  pFilter = GetGrfFilter();
            INetURLObject aObj( GetPath() );

            // check whether we can load the graphic
            String  aCurFilter( GetCurrentFilter() );
            USHORT  nFormatNum = pFilter->GetImportFormatNumber( aCurFilter );
            USHORT  nRetFormat = 0;
            USHORT  nFound = USHRT_MAX;

            // non-local?
            if ( INET_PROT_FILE != aObj.GetProtocol() )
            {
                SfxMedium aMed( aObj.GetMainURL( INetURLObject::NO_DECODE ), STREAM_READ, TRUE );
                aMed.DownLoad();
                SvStream* pStream = aMed.GetInStream();

                if( pStream )
                    nImpRet = pFilter->CanImportGraphic( aObj.GetMainURL( INetURLObject::NO_DECODE ), *pStream, nFormatNum, &nRetFormat );
                else
                    nImpRet = pFilter->CanImportGraphic( aObj, nFormatNum, &nRetFormat );

                if ( GRFILTER_OK != nImpRet )
                {
                    if ( !pStream )
                        nImpRet = pFilter->CanImportGraphic( aObj, GRFILTER_FORMAT_DONTKNOW, &nRetFormat );
                    else
                        nImpRet = pFilter->CanImportGraphic( aObj.GetMainURL( INetURLObject::NO_DECODE ), *pStream,
                                                             GRFILTER_FORMAT_DONTKNOW, &nRetFormat );
                }
            }
            else
            {
                if( (nImpRet=pFilter->CanImportGraphic( aObj, nFormatNum, &nRetFormat )) != GRFILTER_OK )
                    nImpRet = pFilter->CanImportGraphic( aObj, GRFILTER_FORMAT_DONTKNOW, &nRetFormat );
            }

            if ( GRFILTER_OK == nImpRet )
                nFound = nRetFormat;

            // could not load?
            if ( nFound == USHRT_MAX )
            {
                WarningBox aWarningBox( NULL, WB_3DLOOK | WB_RETRY_CANCEL, SVX_RESSTR( SvxOpenGrfErr2ResId(nImpRet) ) );
                bQuitLoop = aWarningBox.Execute()==RET_RETRY ? FALSE : TRUE;
            }
            else
            {
                // setup appropriate filter (so next time, it will work)
                if( pFilter->GetImportFormatCount() )
                {
                    String  aFormatName(pFilter->GetImportFormatName(nFound));
                    SetCurrentFilter(aFormatName);
                }

                return nImpRet;
            }
        }
    }

    // cancel
    return -1;
}

void SvxOpenGraphicDialog::SetPath( const String& rPath )
{
    mpImpl->aFileDlg.SetDisplayDirectory(rPath);
}

void SvxOpenGraphicDialog::SetPath( const String& rPath, sal_Bool bLinkState )
{
    SetPath(rPath);
    AsLink(bLinkState);
}

void SvxOpenGraphicDialog::EnableLink( sal_Bool  state  )
{
    if( mpImpl->xCtrlAcc.is() )
    {
        try
        {
            mpImpl->xCtrlAcc->enableControl( ExtendedFilePickerElementIds::CHECKBOX_LINK, state );
        }
        catch(IllegalArgumentException)
        {
#ifdef DBG_UTIL
            DBG_ERROR( "Cannot enable \"link\" checkbox" );
#endif
        }
    }
}

void SvxOpenGraphicDialog::AsLink(sal_Bool  bState)
{
    if( mpImpl->xCtrlAcc.is() )
    {
        try
        {
            Any aAny; aAny <<= bState;
            mpImpl->xCtrlAcc->setValue( ExtendedFilePickerElementIds::CHECKBOX_LINK, 0, aAny );
        }
        catch(IllegalArgumentException)
        {
#ifdef DBG_UTIL
            DBG_ERROR( "Cannot check \"link\" checkbox" );
#endif
        }
    }
}

sal_Bool SvxOpenGraphicDialog::IsAsLink() const
{
    try
    {
        if( mpImpl->xCtrlAcc.is() )
        {
            Any aVal = mpImpl->xCtrlAcc->getValue( ExtendedFilePickerElementIds::CHECKBOX_LINK, 0 );
            DBG_ASSERT(aVal.hasValue(), "Value CBX_INSERT_AS_LINK not found")
            return aVal.hasValue() ? *(sal_Bool*) aVal.getValue() : sal_False;
        }
    }
    catch(IllegalArgumentException)
    {
#ifdef DBG_UTIL
        DBG_ERROR( "Cannot access \"link\" checkbox" );
#endif
    }

    return sal_False;
}

int SvxOpenGraphicDialog::GetGraphic(Graphic& rGraphic) const
{
    return mpImpl->aFileDlg.GetGraphic(rGraphic);
}

String SvxOpenGraphicDialog::GetPath() const
{
    return mpImpl->aFileDlg.GetPath();
}

String SvxOpenGraphicDialog::GetCurrentFilter() const
{
    return mpImpl->aFileDlg.GetCurrentFilter();
}

void SvxOpenGraphicDialog::SetCurrentFilter(const String&   rStr)
{
    mpImpl->aFileDlg.SetCurrentFilter(rStr);
}

void SvxOpenGraphicDialog::SetControlHelpIds( const INT16* _pControlId, const INT32* _pHelpId )
{
    mpImpl->aFileDlg.SetControlHelpIds( _pControlId, _pHelpId );
}

void SvxOpenGraphicDialog::SetDialogHelpId( const INT32 _nHelpId )
{
    mpImpl->aFileDlg.SetDialogHelpId( _nHelpId );
}
<|endoftext|>


<commit_before><commit_msg>SdrMarkView tiled rendering: fix unexpected empty graphic selection events<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: anchoreddrawobject.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 01:32:25 $
 *
 *  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
 *
 ************************************************************************/
#ifndef _ANCHOREDDRAWOBJECT_HXX
#define _ANCHOREDDRAWOBJECT_HXX

#ifndef _ANCHOREDOBJECT_HXX
#include <anchoredobject.hxx>
#endif
#ifndef _GEN_HXX
#include <tools/gen.hxx>
#endif

/** class for the positioning of drawing objects

    OD 2004-03-25 #i26791#

    @author OD
*/
class SwAnchoredDrawObject : public SwAnchoredObject
{
    private:
        // boolean, indicating that the object position has been invalidated
        // and that a positioning has to be performed.
        bool mbValidPos;

        // rectangle, keeping the last object rectangle after the postioning
        // --> OD 2004-09-29 #i34748# - change <maLastObjRect> to a pointer
        Rectangle* mpLastObjRect;

        // boolean, indicating that anchored drawing object hasn't been attached
        // to a anchor frame yet. Once, it is attached to a anchor frame the
        // boolean changes its state.
        bool mbNotYetAttachedToAnchorFrame;

        // --> OD 2004-08-09 #i28749# - boolean, indicating that anchored
        // drawing object hasn't been positioned yet. Once, it's positioned the
        // boolean changes its state.
        bool mbNotYetPositioned;

        /** method for the intrinsic positioning of a at-paragraph|at-character
            anchored drawing object

            OD 2004-08-12 #i32795# - helper method for method <MakeObjPos>

            @author OD
        */
        void _MakeObjPosAnchoredAtPara();

        /** method for the intrinsic positioning of a at-page|at-frame anchored
            drawing object

            OD 2004-08-12 #i32795# - helper method for method <MakeObjPos>

            @author OD
        */
        void _MakeObjPosAnchoredAtLayout();

            /** method to set positioning attributes (not for as-character anchored)

            OD 2004-10-20 #i35798#
            During load the positioning attributes aren't set.
            Thus, the positioning attributes are set by the current object geometry.
            This method is also used for the conversion for drawing objects
            (not anchored as-character) imported from OpenOffice.org file format
            once and directly before the first positioning.

            @author OD
        */
        void _SetPositioningAttr();

        /** method to set internal anchor position of <SdrObject> instance
            of the drawing object

            For drawing objects the internal anchor position of the <SdrObject>
            instance has to be set.
            Note: This adjustment is not be done for as-character anchored
            drawing object - the positioning code takes care of this.
            OD 2004-07-29 #i31698# - API for drawing objects in Writer has
            been adjusted. Thus, this method will only set the internal anchor
            position of the <SdrObject> instance to the anchor position given
            by its anchor frame.

            @author OD
        */
        void _SetDrawObjAnchor();

        /** method to invalidate the given page frame

            OD 2004-07-02 #i28701#

            @author OD
        */
        void _InvalidatePage( SwPageFrm* _pPageFrm );

    protected:
        virtual void ObjectAttachedToAnchorFrame();

        /** method to assure that anchored object is registered at the correct
            page frame

            OD 2004-07-02 #i28701#

            @author OD
        */
        virtual void RegisterAtCorrectPage();

    public:
        TYPEINFO();

        SwAnchoredDrawObject();
        virtual ~SwAnchoredDrawObject();

        // declaration of pure virtual methods of base class <SwAnchoredObject>
        virtual void MakeObjPos();
        virtual void InvalidateObjPos();
        inline bool IsValidPos() const
        {
            return mbValidPos;
        }

        // accessors to the format
        virtual SwFrmFmt& GetFrmFmt();
        virtual const SwFrmFmt& GetFrmFmt() const;

        // accessors to the object area and its position
        virtual const SwRect GetObjRect() const;
        virtual void SetObjTop( const SwTwips _nTop);
        virtual void SetObjLeft( const SwTwips _nLeft);
        // --> OD 2004-09-29 #i34748# - change return type to a pointer.
        // Return value can be NULL.
        const Rectangle* GetLastObjRect() const;
        // <--
        // --> OD 2004-09-29 #i34748# - change method
        void SetLastObjRect( const Rectangle& _rNewObjRect );
        // <--

        /** adjust positioning and alignment attributes for new anchor frame

            OD 2004-04-21
            Set horizontal and vertical position/alignment to manual position
            relative to anchor frame area using the anchor position of the
            new anchor frame and the current absolute drawing object position.
            Note: For correct Undo/Redo method should only be called inside a
            Undo-/Redo-action.
            OD 2004-08-24 #i33313# - add second optional parameter <_pNewObjRect>

            @author OD

            @param <_pNewAnchorFrm>
            input parameter - new anchor frame for the anchored object.

            @param <_pNewObjRect>
            optional input parameter - proposed new object rectangle. If not
            provided the current object rectangle is taken.
        */
        void AdjustPositioningAttr( const SwFrm* _pNewAnchorFrm,
                                    const SwRect* _pNewObjRect = 0L );

        /** anchored drawing object not yet attached to a anchor frame

            OD 2004-08-04 #i31698#

            @author OD
        */
        inline bool NotYetAttachedToAnchorFrm() const
        {
            return mbNotYetAttachedToAnchorFrame;
        }

        /** method to notify background of drawing object

            OD 2004-06-30 #i28701#

            @author OD
        */
        virtual void NotifyBackground( SwPageFrm* _pPageFrm,
                                       const SwRect& _rRect,
                                       PrepareHint _eHint );
};

#endif
<commit_msg>INTEGRATION: CWS dbwizardpp1 (1.7.212); FILE MERGED 2005/12/05 12:54:25 bc 1.7.212.2: RESYNC: (1.7-1.8); FILE MERGED 2005/08/16 12:27:54 od 1.7.212.1: #i53320# class <SwAnchoredDrawObject> 	 - remove method <NotYetAttachedToAnchorFrm()> 	 - add method <NotYetPositioned()><commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: anchoreddrawobject.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: hr $ $Date: 2005-12-28 17:11:07 $
 *
 *  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
 *
 ************************************************************************/
#ifndef _ANCHOREDDRAWOBJECT_HXX
#define _ANCHOREDDRAWOBJECT_HXX

#ifndef _ANCHOREDOBJECT_HXX
#include <anchoredobject.hxx>
#endif
#ifndef _GEN_HXX
#include <tools/gen.hxx>
#endif

/** class for the positioning of drawing objects

    OD 2004-03-25 #i26791#

    @author OD
*/
class SwAnchoredDrawObject : public SwAnchoredObject
{
    private:
        // boolean, indicating that the object position has been invalidated
        // and that a positioning has to be performed.
        bool mbValidPos;

        // rectangle, keeping the last object rectangle after the postioning
        // --> OD 2004-09-29 #i34748# - change <maLastObjRect> to a pointer
        Rectangle* mpLastObjRect;

        // boolean, indicating that anchored drawing object hasn't been attached
        // to a anchor frame yet. Once, it is attached to a anchor frame the
        // boolean changes its state.
        bool mbNotYetAttachedToAnchorFrame;

        // --> OD 2004-08-09 #i28749# - boolean, indicating that anchored
        // drawing object hasn't been positioned yet. Once, it's positioned the
        // boolean changes its state.
        bool mbNotYetPositioned;

        /** method for the intrinsic positioning of a at-paragraph|at-character
            anchored drawing object

            OD 2004-08-12 #i32795# - helper method for method <MakeObjPos>

            @author OD
        */
        void _MakeObjPosAnchoredAtPara();

        /** method for the intrinsic positioning of a at-page|at-frame anchored
            drawing object

            OD 2004-08-12 #i32795# - helper method for method <MakeObjPos>

            @author OD
        */
        void _MakeObjPosAnchoredAtLayout();

            /** method to set positioning attributes (not for as-character anchored)

            OD 2004-10-20 #i35798#
            During load the positioning attributes aren't set.
            Thus, the positioning attributes are set by the current object geometry.
            This method is also used for the conversion for drawing objects
            (not anchored as-character) imported from OpenOffice.org file format
            once and directly before the first positioning.

            @author OD
        */
        void _SetPositioningAttr();

        /** method to set internal anchor position of <SdrObject> instance
            of the drawing object

            For drawing objects the internal anchor position of the <SdrObject>
            instance has to be set.
            Note: This adjustment is not be done for as-character anchored
            drawing object - the positioning code takes care of this.
            OD 2004-07-29 #i31698# - API for drawing objects in Writer has
            been adjusted. Thus, this method will only set the internal anchor
            position of the <SdrObject> instance to the anchor position given
            by its anchor frame.

            @author OD
        */
        void _SetDrawObjAnchor();

        /** method to invalidate the given page frame

            OD 2004-07-02 #i28701#

            @author OD
        */
        void _InvalidatePage( SwPageFrm* _pPageFrm );

    protected:
        virtual void ObjectAttachedToAnchorFrame();

        /** method to assure that anchored object is registered at the correct
            page frame

            OD 2004-07-02 #i28701#

            @author OD
        */
        virtual void RegisterAtCorrectPage();

    public:
        TYPEINFO();

        SwAnchoredDrawObject();
        virtual ~SwAnchoredDrawObject();

        // declaration of pure virtual methods of base class <SwAnchoredObject>
        virtual void MakeObjPos();
        virtual void InvalidateObjPos();
        inline bool IsValidPos() const
        {
            return mbValidPos;
        }

        // accessors to the format
        virtual SwFrmFmt& GetFrmFmt();
        virtual const SwFrmFmt& GetFrmFmt() const;

        // accessors to the object area and its position
        virtual const SwRect GetObjRect() const;
        virtual void SetObjTop( const SwTwips _nTop);
        virtual void SetObjLeft( const SwTwips _nLeft);
        // --> OD 2004-09-29 #i34748# - change return type to a pointer.
        // Return value can be NULL.
        const Rectangle* GetLastObjRect() const;
        // <--
        // --> OD 2004-09-29 #i34748# - change method
        void SetLastObjRect( const Rectangle& _rNewObjRect );
        // <--

        /** adjust positioning and alignment attributes for new anchor frame

            OD 2004-04-21
            Set horizontal and vertical position/alignment to manual position
            relative to anchor frame area using the anchor position of the
            new anchor frame and the current absolute drawing object position.
            Note: For correct Undo/Redo method should only be called inside a
            Undo-/Redo-action.
            OD 2004-08-24 #i33313# - add second optional parameter <_pNewObjRect>

            @author OD

            @param <_pNewAnchorFrm>
            input parameter - new anchor frame for the anchored object.

            @param <_pNewObjRect>
            optional input parameter - proposed new object rectangle. If not
            provided the current object rectangle is taken.
        */
        void AdjustPositioningAttr( const SwFrm* _pNewAnchorFrm,
                                    const SwRect* _pNewObjRect = 0L );

        /** method to notify background of drawing object

            OD 2004-06-30 #i28701#

            @author OD
        */
        virtual void NotifyBackground( SwPageFrm* _pPageFrm,
                                       const SwRect& _rRect,
                                       PrepareHint _eHint );

    // --> OD 2005-08-16 #i53320#
        inline bool NotYetPositioned() const
        {
            return mbNotYetPositioned;
        }
        // <--
};

#endif
<|endoftext|>


<commit_before>/* -*- mode: C++; c-file-style: "gnu" -*-
 * kmail: KDE mail client
 * Copyright (c) 1996-1998 Stefan Taferner <taferner@kde.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 */

#include <kontactinterface/pimuniqueapplication.h>
#include <kglobal.h>
#include "kmkernel.h" //control center
#include "kmmainwidget.h"
#include "kmail_options.h"

#include <kdebug.h>

#include <akonadi/control.h>

#undef Status // stupid X headers

#include "aboutdata.h"

#include "kmstartup.h"

#ifdef Q_WS_WIN
#include <unistd.h>
#include <windows.h>
#endif

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

class KMailApplication : public KontactInterface::PimUniqueApplication
{
public:
  KMailApplication() : KontactInterface::PimUniqueApplication(),
                       mDelayedInstanceCreation( false ),
                       mEventLoopReached( false ) { }
  virtual int newInstance();
  void commitData(QSessionManager& sm);
  void setEventLoopReached();
  void delayedInstanceCreation();
protected:
  bool mDelayedInstanceCreation;
  bool mEventLoopReached;

};

void KMailApplication::commitData(QSessionManager& sm) {
  kmkernel->dumpDeadLetters();
  kmkernel->setShuttingDown( true ); // Prevent further dumpDeadLetters calls
  KApplication::commitData( sm );
}

void KMailApplication::setEventLoopReached() {
  mEventLoopReached = true;
}

int KMailApplication::newInstance()
{
  kDebug();

  // If the event loop hasn't been reached yet, the kernel is probably not
  // fully initialized. Creating an instance would therefore fail, this is why
  // that is delayed until delayedInstanceCreation() is called.
  if ( !mEventLoopReached ) {
    kDebug() << "Delaying instance creation.";
    mDelayedInstanceCreation = true;
    return 0;
  }

  if (!kmkernel)
     return 0;

  if (!kmkernel->firstInstance() || !kapp->isSessionRestored())
    kmkernel->handleCommandLine( true );
  kmkernel->setFirstInstance(false);
  return 0;
}

void KMailApplication::delayedInstanceCreation() {
  if ( mDelayedInstanceCreation )
    newInstance();
}

int main(int argc, char *argv[])
{
  // WABA: KMail is a KUniqueApplication. Unfortunately this makes debugging
  // a bit harder: You should pass --nofork as commandline argument when using
  // a debugger. In gdb you can do this by typing "set args --nofork" before
  // typing "run".
#if 0 // for testing KUniqueAppliaction on Windows
  MessageBoxA(NULL,
             QString("main() %1 pid=%2").arg(argv[0]).arg(getpid()).toLatin1(),
             QString("main() \"%1\"").arg(argv[0]).toLatin1(), MB_OK|MB_ICONINFORMATION|MB_TASKMODAL);
#endif
  KMail::AboutData about;

  KCmdLineArgs::init(argc, argv, &about);
  KCmdLineArgs::addCmdLineOptions( kmail_options() ); // Add kmail options
  if (!KMailApplication::start())
     return 0;

  KMailApplication app;

  // Qt doesn't treat the system tray as a window, and therefore Qt would quit
  // the event loop when an error message is clicked away while KMail is in the
  // tray.
  // Rely on KGlobal::ref() and KGlobal::deref() instead, like we did in KDE3.
  // See http://bugs.kde.org/show_bug.cgi?id=163479
  QApplication::setQuitOnLastWindowClosed( false );

  // import i18n data and icons from libraries:
  KMail::insertLibraryCataloguesAndIcons();

  KMail::lockOrDie();

  //local, do the init
  KMKernel kmailKernel;
  kmailKernel.init();

  // and session management
  kmailKernel.doSessionManagement();

  // any dead letters?
  kmailKernel.recoverDeadLetters();

  kmsetSignalHandler(kmsignalHandler);

  kmkernel->setupDBus(); // Ok. We are ready for D-Bus requests.
  kmkernel->setStartingUp( false ); // Starting up is finished

  //If the instance hasn't been created yet, do that now
  app.setEventLoopReached();
  app.delayedInstanceCreation();

  // Start Akonadi
  if ( !Akonadi::Control::start( kmkernel->getKMMainWidget() ) ) {
    //TODO: add message box after string freeze
    kWarning() << "Unable to start Akonadi server, exit application";
    return 1;
  }

  // Go!
  int ret = qApp->exec();
  // clean up
  kmailKernel.cleanup();

  KMail::cleanup(); // pid file (see kmstartup.cpp)
  return ret;
}
<commit_msg>Revert "Abort application if Akonadi couldn't be started"<commit_after>/* -*- mode: C++; c-file-style: "gnu" -*-
 * kmail: KDE mail client
 * Copyright (c) 1996-1998 Stefan Taferner <taferner@kde.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 */

#include <kontactinterface/pimuniqueapplication.h>
#include <kglobal.h>
#include "kmkernel.h" //control center
#include "kmmainwidget.h"
#include "kmail_options.h"

#include <kdebug.h>

#include <akonadi/control.h>

#undef Status // stupid X headers

#include "aboutdata.h"

#include "kmstartup.h"

#ifdef Q_WS_WIN
#include <unistd.h>
#include <windows.h>
#endif

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

class KMailApplication : public KontactInterface::PimUniqueApplication
{
public:
  KMailApplication() : KontactInterface::PimUniqueApplication(),
                       mDelayedInstanceCreation( false ),
                       mEventLoopReached( false ) { }
  virtual int newInstance();
  void commitData(QSessionManager& sm);
  void setEventLoopReached();
  void delayedInstanceCreation();
protected:
  bool mDelayedInstanceCreation;
  bool mEventLoopReached;

};

void KMailApplication::commitData(QSessionManager& sm) {
  kmkernel->dumpDeadLetters();
  kmkernel->setShuttingDown( true ); // Prevent further dumpDeadLetters calls
  KApplication::commitData( sm );
}

void KMailApplication::setEventLoopReached() {
  mEventLoopReached = true;
}

int KMailApplication::newInstance()
{
  kDebug();

  // If the event loop hasn't been reached yet, the kernel is probably not
  // fully initialized. Creating an instance would therefore fail, this is why
  // that is delayed until delayedInstanceCreation() is called.
  if ( !mEventLoopReached ) {
    kDebug() << "Delaying instance creation.";
    mDelayedInstanceCreation = true;
    return 0;
  }

  if (!kmkernel)
     return 0;

  if (!kmkernel->firstInstance() || !kapp->isSessionRestored())
    kmkernel->handleCommandLine( true );
  kmkernel->setFirstInstance(false);
  return 0;
}

void KMailApplication::delayedInstanceCreation() {
  if ( mDelayedInstanceCreation )
    newInstance();
}

int main(int argc, char *argv[])
{
  // WABA: KMail is a KUniqueApplication. Unfortunately this makes debugging
  // a bit harder: You should pass --nofork as commandline argument when using
  // a debugger. In gdb you can do this by typing "set args --nofork" before
  // typing "run".
#if 0 // for testing KUniqueAppliaction on Windows
  MessageBoxA(NULL,
             QString("main() %1 pid=%2").arg(argv[0]).arg(getpid()).toLatin1(),
             QString("main() \"%1\"").arg(argv[0]).toLatin1(), MB_OK|MB_ICONINFORMATION|MB_TASKMODAL);
#endif
  KMail::AboutData about;

  KCmdLineArgs::init(argc, argv, &about);
  KCmdLineArgs::addCmdLineOptions( kmail_options() ); // Add kmail options
  if (!KMailApplication::start())
     return 0;

  KMailApplication app;

  // Qt doesn't treat the system tray as a window, and therefore Qt would quit
  // the event loop when an error message is clicked away while KMail is in the
  // tray.
  // Rely on KGlobal::ref() and KGlobal::deref() instead, like we did in KDE3.
  // See http://bugs.kde.org/show_bug.cgi?id=163479
  QApplication::setQuitOnLastWindowClosed( false );

  // import i18n data and icons from libraries:
  KMail::insertLibraryCataloguesAndIcons();

  KMail::lockOrDie();

  //local, do the init
  KMKernel kmailKernel;
  kmailKernel.init();

  // and session management
  kmailKernel.doSessionManagement();

  // any dead letters?
  kmailKernel.recoverDeadLetters();

  kmsetSignalHandler(kmsignalHandler);

  kmkernel->setupDBus(); // Ok. We are ready for D-Bus requests.
  kmkernel->setStartingUp( false ); // Starting up is finished

  //If the instance hasn't been created yet, do that now
  app.setEventLoopReached();
  app.delayedInstanceCreation();

  // Start Akonadi
  Akonadi::Control::start( kmkernel->getKMMainWidget() );

  // Go!
  int ret = qApp->exec();
  // clean up
  kmailKernel.cleanup();

  KMail::cleanup(); // pid file (see kmstartup.cpp)
  return ret;
}
<|endoftext|>