<commit_before>/*
 * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
 *
 * 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 "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbOGRDataSourceWrapper.h"
#include "otbOGRFeatureWrapper.h"
#include "itkVariableLengthVector.h"
#include "otbStatisticsXMLFileReader.h"
#include "itkListSample.h"
#include "otbShiftScaleSampleListFilter.h"
#include "otbDimensionalityReductionModelFactory.h"
#include <time.h>

namespace otb
{
namespace Wrapper
{

/** Utility function to negate std::isalnum */
bool IsNotAlphaNum(char c)
{
return !std::isalnum(c);
}

/**
 * \class VectorDimensionalityReduction
 *
 * Apply a dimensionality reduction model on a vector file
 */
class VectorDimensionalityReduction : public Application
{
public:
    /** Standard class typedefs. */
  typedef VectorDimensionalityReduction Self;
  typedef Application Superclass;
  typedef itk::SmartPointer<Self> Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

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

  /** Filters typedef */
  typedef float                                           ValueType;
  typedef itk::VariableLengthVector<ValueType>            InputSampleType;
  typedef itk::Statistics::ListSample<InputSampleType>    ListSampleType;
  typedef MachineLearningModel<
    itk::VariableLengthVector<ValueType>,
    itk::VariableLengthVector<ValueType> >                DimensionalityReductionModelType;
  typedef DimensionalityReductionModelFactory<
    ValueType,ValueType>                                  DimensionalityReductionModelFactoryType;
  typedef DimensionalityReductionModelType::Pointer       ModelPointerType;

  /** Statistics Filters typedef */
  typedef itk::VariableLengthVector<ValueType>            MeasurementType;
  typedef otb::StatisticsXMLFileReader<MeasurementType>   StatisticsReader;
  typedef otb::Statistics::ShiftScaleSampleListFilter<
    ListSampleType, ListSampleType>                       ShiftScaleFilterType;

protected:
  ~VectorDimensionalityReduction() ITK_OVERRIDE
    {
    DimensionalityReductionModelFactoryType::CleanFactories();
    }

private:
  void DoInit() ITK_OVERRIDE
    {
    SetName("VectorDimensionalityReduction");
    SetDescription("Performs dimensionality reduction of the input vector data "
      "according to a model file.");
    SetDocName("Vector Dimensionality Reduction");
    SetDocAuthors("OTB-Team");
    SetDocLongDescription("This application performs a vector data "
      "dimensionality reduction based on a model file produced by the "
      "TrainDimensionalityReduction application.");
    SetDocSeeAlso("TrainDimensionalityReduction");
    SetDocLimitations("None");
    AddDocTag(Tags::Learning);

    AddParameter(ParameterType_InputVectorData, "in", "Name of the input vector data");
    SetParameterDescription("in","The input vector data to reduce.");

    AddParameter(ParameterType_InputFilename, "instat", "Statistics file");
    SetParameterDescription("instat", "A XML file containing mean and standard "
      "deviation to center and reduce samples before dimensionality reduction "
      "(produced by ComputeImagesStatistics application).");
    MandatoryOff("instat");

    AddParameter(ParameterType_InputFilename, "model", "Model file");
    SetParameterDescription("model", "A model file (produced by the "
      "TrainDimensionalityReduction application,");

    AddParameter(ParameterType_ListView, "feat", "Input features to use for reduction."); //
    SetParameterDescription("feat","List of field names in the input vector "
      "data used as features for reduction."); //

    AddParameter(ParameterType_StringList, "featout", "Names of the new output features."); //
    SetParameterDescription("featout","List of field names for the output "
      "features which result from the reduction."); //

    AddParameter(ParameterType_OutputFilename, "out", "Output vector data file "
      "containing the reduced vector");
    SetParameterDescription("out","Output vector data file storing sample "
      "values (OGR format). If not given, the input vector data file is used. "
      "In overwrite mode, the original features will be lost.");
    MandatoryOff("out");

    AddParameter(ParameterType_Int, "indim", "Dimension of the input vector");
    SetParameterDescription("indim","Dimension of the whole input vector, this "
      "value is required if only a part of the bands contained in the vector "
      "are used. If not given, the dimension is deduced from the length of the "
      "'feat' parameter");
    MandatoryOff("indim");

    AddParameter(ParameterType_Int, "pcadim", "Principal component"); //
    SetParameterDescription("pcadim","This optional parameter can be set to "
      "reduce the number of eignevectors used in the PCA model file."); //
    MandatoryOff("pcadim");

    AddParameter(ParameterType_String, "mode", "Writting mode"); //
    SetParameterString("mode","overwrite", false);
    SetParameterDescription("mode","This parameter determines if the output "
      "file is overwritten or updated [overwrite/update]. If an output file "
      "name is given, the original file is copied before creating the new features."); //

    // Doc example parameter settings
    SetDocExampleParameterValue("in", "vectorData.shp");
    SetDocExampleParameterValue("instat", "meanVar.xml");
    SetDocExampleParameterValue("model", "model.txt");
    SetDocExampleParameterValue("out", "vectorDataOut.shp");
    SetDocExampleParameterValue("feat", "perimeter area width");
    SetDocExampleParameterValue("featout", "perimeter area width");
    //SetOfficialDocLink();
    }

  void DoUpdateParameters() ITK_OVERRIDE
    {
    if ( HasValue("in") )
      {
      std::string shapefile = GetParameterString("in");
      otb::ogr::DataSource::Pointer ogrDS;
      OGRSpatialReference oSRS("");
      std::vector<std::string> options;
      ogrDS = otb::ogr::DataSource::New(shapefile, otb::ogr::DataSource::Modes::Read);
      otb::ogr::Layer layer = ogrDS->GetLayer(0);
      OGRFeatureDefn &layerDefn = layer.GetLayerDefn();
      ClearChoices("feat");

      for(int iField=0; iField< layerDefn.GetFieldCount(); iField++)
        {
        std::string item = layerDefn.GetFieldDefn(iField)->GetNameRef();
        std::string key(item);
        std::string::iterator end = std::remove_if( key.begin(), key.end(), IsNotAlphaNum );
        std::transform( key.begin(), end, key.begin(), tolower );
        std::string tmpKey = "feat." + key.substr( 0, static_cast<unsigned long>( end - key.begin() ) );
        AddChoice(tmpKey,item);
        }
      }
    }

  void DoExecute() ITK_OVERRIDE
    {
    clock_t tic = clock();

    std::string shapefile = GetParameterString("in");
    otb::ogr::DataSource::Pointer source = otb::ogr::DataSource::New(
      shapefile, otb::ogr::DataSource::Modes::Read);
    otb::ogr::Layer layer = source->GetLayer(0);
    ListSampleType::Pointer input = ListSampleType::New();
    int nbFeatures = GetSelectedItems("feat").size();

    input->SetMeasurementVectorSize(nbFeatures);
    otb::ogr::Layer::const_iterator it = layer.cbegin();
    otb::ogr::Layer::const_iterator itEnd = layer.cend();

    for( ; it!=itEnd ; ++it)
      {
      MeasurementType mv;
      mv.SetSize(nbFeatures);

      for(int idx=0; idx < nbFeatures; ++idx)
        {
        mv[idx] = static_cast<float>( (*it)[GetSelectedItems("feat")[idx]].GetValue<double>() );
        }
      input->PushBack(mv);
      }

    /** Statistics for shift/scale */
    MeasurementType meanMeasurementVector;
    MeasurementType stddevMeasurementVector;

    if (HasValue("instat") && IsParameterEnabled("instat"))
      {
      StatisticsReader::Pointer statisticsReader = StatisticsReader::New();
      std::string XMLfile = GetParameterString("instat");
      statisticsReader->SetFileName(XMLfile);
      meanMeasurementVector = statisticsReader->GetStatisticVectorByName("mean");
      stddevMeasurementVector = statisticsReader->GetStatisticVectorByName("stddev");
      }
    else
      {
      meanMeasurementVector.SetSize(nbFeatures);
      meanMeasurementVector.Fill(0.);
      stddevMeasurementVector.SetSize(nbFeatures);
      stddevMeasurementVector.Fill(1.);
      }

    ShiftScaleFilterType::Pointer trainingShiftScaleFilter = ShiftScaleFilterType::New();
    trainingShiftScaleFilter->SetInput(input);
    trainingShiftScaleFilter->SetShifts(meanMeasurementVector);
    trainingShiftScaleFilter->SetScales(stddevMeasurementVector);
    trainingShiftScaleFilter->Update();
    otbAppLogINFO("mean used: " << meanMeasurementVector);
    otbAppLogINFO("standard deviation used: " << stddevMeasurementVector);
    otbAppLogINFO("Loading model");

    /** Read the model */
    m_Model = DimensionalityReductionModelFactoryType::CreateDimensionalityReductionModel(
      GetParameterString("model"),
      DimensionalityReductionModelFactoryType::ReadMode);
    if (m_Model.IsNull())
      {
      otbAppLogFATAL(<< "Error when loading model " << GetParameterString("model")
        << " : unsupported model type");
      }
    if (HasValue("pcadim") && IsParameterEnabled("pcadim"))
      {
      int dimension = GetParameterInt("pcadim");
      m_Model->SetDimension(dimension );
      }

    m_Model->Load(GetParameterString("model"));
    otbAppLogINFO("Model loaded");

    /** Perform Dimensionality Reduction */
    ListSampleType::Pointer listSample = trainingShiftScaleFilter->GetOutput();
    ListSampleType::Pointer target = m_Model->PredictBatch(listSample);

    /** Create/Update Output Shape file */
    ogr::DataSource::Pointer output;
    ogr::DataSource::Pointer buffer = ogr::DataSource::New();
    bool updateMode = false;

    int nbBands = nbFeatures;
    if (HasValue("indim") && IsParameterEnabled("indim"))
      {
      nbBands = GetParameterInt("indim");
      }

    if (IsParameterEnabled("out") && HasValue("out"))
      {
      // Create new OGRDataSource
      if (GetParameterString("mode")=="overwrite")
        {
        output = ogr::DataSource::New(GetParameterString("out"), ogr::DataSource::Modes::Overwrite);
        otb::ogr::Layer newLayer = output->CreateLayer(
          GetParameterString("out"),
          const_cast<OGRSpatialReference*>(layer.GetSpatialRef()),
          layer.GetGeomType());
        // Copy existing fields
        OGRFeatureDefn &inLayerDefn = layer.GetLayerDefn();
        for (int k=0 ; k<inLayerDefn.GetFieldCount()-nbBands ; k++) // we don't copy the original bands
          {
          OGRFieldDefn fieldDefn(inLayerDefn.GetFieldDefn(k));
          newLayer.CreateField(fieldDefn);
          }
        }
      else if (GetParameterString("mode")=="update")
        {
        //output = ogr::DataSource::New(GetParameterString("out"), ogr::DataSource::Modes::Update_LayerCreateOnly);
        // Update mode
        otb::ogr::DataSource::Pointer source_output =
          otb::ogr::DataSource::New(GetParameterString("out"), otb::ogr::DataSource::Modes::Read);
        layer = source_output->GetLayer(0);
        updateMode = true;
        otbAppLogINFO("Update input vector data.");

        // fill temporary buffer for the transfer
        otb::ogr::Layer inputLayer = layer;
        layer = buffer->CopyLayer(inputLayer, std::string("Buffer"));
        // close input data source
        source_output->Clear();
        // Re-open input data source in update mode
        output = otb::ogr::DataSource::New(
          GetParameterString("out"),
          otb::ogr::DataSource::Modes::Update_LayerUpdate);
        }
      else
        {
        otbAppLogFATAL(<< "Error when creating the output file" <<
          GetParameterString("mode") << " : unsupported writting mode type");
        }
      }

    otb::ogr::Layer outLayer = output->GetLayer(0);
    OGRErr errStart = outLayer.ogr().StartTransaction();

    if (errStart != OGRERR_NONE)
      {
      itkExceptionMacro(<< "Unable to start transaction for OGR layer " << outLayer.ogr().GetName() << ".");
      }

    // Add the field of prediction in the output layer if field not exist
    for (unsigned int i=0; i<GetParameterStringList("featout").size() ;i++)
      {
      OGRFeatureDefn &layerDefn = outLayer.GetLayerDefn();
      int idx = layerDefn.GetFieldIndex(GetParameterStringList("featout")[i].c_str());

      if (idx >= 0)
        {
        if (layerDefn.GetFieldDefn(idx)->GetType() != OFTReal)
        itkExceptionMacro("Field name "<< GetParameterStringList("featout")[i]
          << " already exists with a different type!");
        }
      else
        {
        OGRFieldDefn predictedField(GetParameterStringList("featout")[i].c_str(), OFTReal);
        ogr::FieldDefn predictedFieldDef(predictedField);
        outLayer.CreateField(predictedFieldDef);
        }
      }

    // Fill output layer
    unsigned int count=0;
    auto classfieldname = GetParameterStringList("featout");
    it = layer.cbegin();
    itEnd = layer.cend();

    for( ; it!=itEnd ; ++it, ++count)
      {
      ogr::Feature dstFeature(outLayer.GetLayerDefn());

      dstFeature.SetFrom( *it , TRUE);
      dstFeature.SetFID(it->GetFID());

      for (std::size_t i=0; i<classfieldname.size(); ++i)
        {
        dstFeature[classfieldname[i]].SetValue<double>(target->GetMeasurementVector(count)[i]);
        }
      if (updateMode)
        {
        outLayer.SetFeature(dstFeature);
        }
      else
        {
        outLayer.CreateFeature(dstFeature);
        }
      }

    if(outLayer.ogr().TestCapability("Transactions"))
      {
      const OGRErr errCommitX = outLayer.ogr().CommitTransaction();
      if (errCommitX != OGRERR_NONE)
        {
        itkExceptionMacro(<< "Unable to commit transaction for OGR layer " <<
          outLayer.ogr().GetName() << ".");
        }
      }
    output->SyncToDisk();
    clock_t toc = clock();
    otbAppLogINFO( "Elapsed: "<< ((double)(toc - tic) / CLOCKS_PER_SEC)<<" seconds.");
    }

  ModelPointerType m_Model;
};

} // end of namespace Wrapper
} // end of namespace otb

OTB_APPLICATION_EXPORT(otb::Wrapper::VectorDimensionalityReduction)
<commit_msg>ENH: rework some parameters for simpler interface<commit_after>/*
 * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
 *
 * 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 "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbOGRDataSourceWrapper.h"
#include "otbOGRFeatureWrapper.h"
#include "itkVariableLengthVector.h"
#include "otbStatisticsXMLFileReader.h"
#include "itkListSample.h"
#include "otbShiftScaleSampleListFilter.h"
#include "otbDimensionalityReductionModelFactory.h"
#include <time.h>

namespace otb
{
namespace Wrapper
{

/** Utility function to negate std::isalnum */
bool IsNotAlphaNum(char c)
{
return !std::isalnum(c);
}

/**
 * \class VectorDimensionalityReduction
 *
 * Apply a dimensionality reduction model on a vector file
 */
class VectorDimensionalityReduction : public Application
{
public:
    /** Standard class typedefs. */
  typedef VectorDimensionalityReduction Self;
  typedef Application Superclass;
  typedef itk::SmartPointer<Self> Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

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

  /** Filters typedef */
  typedef float                                           ValueType;
  typedef itk::VariableLengthVector<ValueType>            InputSampleType;
  typedef itk::Statistics::ListSample<InputSampleType>    ListSampleType;
  typedef MachineLearningModel<
    itk::VariableLengthVector<ValueType>,
    itk::VariableLengthVector<ValueType> >                DimensionalityReductionModelType;
  typedef DimensionalityReductionModelFactory<
    ValueType,ValueType>                                  DimensionalityReductionModelFactoryType;
  typedef DimensionalityReductionModelType::Pointer       ModelPointerType;

  /** Statistics Filters typedef */
  typedef itk::VariableLengthVector<ValueType>            MeasurementType;
  typedef otb::StatisticsXMLFileReader<MeasurementType>   StatisticsReader;
  typedef otb::Statistics::ShiftScaleSampleListFilter<
    ListSampleType, ListSampleType>                       ShiftScaleFilterType;

protected:
  ~VectorDimensionalityReduction() ITK_OVERRIDE
    {
    DimensionalityReductionModelFactoryType::CleanFactories();
    }

private:
  void DoInit() ITK_OVERRIDE
    {
    SetName("VectorDimensionalityReduction");
    SetDescription("Performs dimensionality reduction of the input vector data "
      "according to a model file.");
    SetDocName("Vector Dimensionality Reduction");
    SetDocAuthors("OTB-Team");
    SetDocLongDescription("This application performs a vector data "
      "dimensionality reduction based on a model file produced by the "
      "TrainDimensionalityReduction application.");
    SetDocSeeAlso("TrainDimensionalityReduction");
    SetDocLimitations("None");
    AddDocTag(Tags::Learning);

    AddParameter(ParameterType_InputVectorData, "in", "Name of the input vector data");
    SetParameterDescription("in","The input vector data to reduce.");

    AddParameter(ParameterType_InputFilename, "instat", "Statistics file");
    SetParameterDescription("instat", "A XML file containing mean and standard "
      "deviation to center and reduce samples before dimensionality reduction "
      "(produced by ComputeImagesStatistics application).");
    MandatoryOff("instat");

    AddParameter(ParameterType_InputFilename, "model", "Model file");
    SetParameterDescription("model", "A model file (produced by the "
      "TrainDimensionalityReduction application,");

    AddParameter(ParameterType_OutputFilename, "out", "Output vector data file "
      "containing the reduced vector");
    SetParameterDescription("out","Output vector data file storing sample "
      "values (OGR format). If not given, the input vector data file is used. "
      "In overwrite mode, the original features will be lost.");
    MandatoryOff("out");

    AddParameter(ParameterType_ListView, "feat", "Input features to use for reduction."); //
    SetParameterDescription("feat","List of field names in the input vector "
      "data used as features for reduction."); //

    AddParameter(ParameterType_Choice, "featout", "Output feature"); //
    SetParameterDescription("featout", "Naming of output features");

    AddChoice("featout.prefix", "Prefix");
    SetParameterDescription("featout.prefix", "Use a name prefix");

    AddParameter(ParameterType_String, "featout.prefix.name", "Feature name prefix");
    SetParameterDescription("featout.prefix.name","Name prefix for output "
      "features. This prefix is followed by the numeric index of each output feature.");
    SetParameterString("featout.prefix.name","reduced_", false);

    AddChoice("featout.list","List");
    SetParameterDescription("featout.list", "Use a list with all names");

    AddParameter(ParameterType_StringList, "featout.list.names", "Feature name list");
    SetParameterDescription("featout.list.names","List of field names for the output "
      "features which result from the reduction."); //

    AddParameter(ParameterType_Int, "pcadim", "Principal component dimension"); //
    SetParameterDescription("pcadim","This optional parameter can be set to "
      "reduce the number of eignevectors used in the PCA model file. This "
      "parameter can't be used for other models"); //
    MandatoryOff("pcadim");

    AddParameter(ParameterType_Choice, "mode", "Writting mode"); //
    SetParameterDescription("mode", "This parameter determines if the output "
      "file is overwritten or updated [overwrite/update]. If an output file "
      "name is given, the original file is copied before creating the new features.");

    AddChoice("mode.overwrite", "Overwrite");
    SetParameterDescription("mode.overwrite","Overwrite mode"); //

    AddChoice("mode.update", "Update");
    SetParameterDescription("mode.update", "Update mode");

    // Doc example parameter settings
    SetDocExampleParameterValue("in", "vectorData.shp");
    SetDocExampleParameterValue("instat", "meanVar.xml");
    SetDocExampleParameterValue("model", "model.txt");
    SetDocExampleParameterValue("out", "vectorDataOut.shp");
    SetDocExampleParameterValue("feat", "perimeter area width");
    //SetOfficialDocLink();
    }

  void DoUpdateParameters() ITK_OVERRIDE
    {
    if ( HasValue("in") )
      {
      std::string shapefile = GetParameterString("in");
      otb::ogr::DataSource::Pointer ogrDS;
      OGRSpatialReference oSRS("");
      std::vector<std::string> options;
      ogrDS = otb::ogr::DataSource::New(shapefile, otb::ogr::DataSource::Modes::Read);
      otb::ogr::Layer layer = ogrDS->GetLayer(0);
      OGRFeatureDefn &layerDefn = layer.GetLayerDefn();
      ClearChoices("feat");

      for(int iField=0; iField< layerDefn.GetFieldCount(); iField++)
        {
        std::string item = layerDefn.GetFieldDefn(iField)->GetNameRef();
        std::string key(item);
        std::string::iterator end = std::remove_if( key.begin(), key.end(), IsNotAlphaNum );
        std::transform( key.begin(), end, key.begin(), tolower );
        std::string tmpKey = "feat." + key.substr( 0, static_cast<unsigned long>( end - key.begin() ) );
        AddChoice(tmpKey,item);
        }
      }
    }

  void DoExecute() ITK_OVERRIDE
    {
    clock_t tic = clock();

    std::string shapefile = GetParameterString("in");
    otb::ogr::DataSource::Pointer source = otb::ogr::DataSource::New(
      shapefile, otb::ogr::DataSource::Modes::Read);
    otb::ogr::Layer layer = source->GetLayer(0);
    ListSampleType::Pointer input = ListSampleType::New();
    std::vector<int> inputIndexes = GetSelectedItems("feat");
    int nbFeatures = inputIndexes.size();

    input->SetMeasurementVectorSize(nbFeatures);
    otb::ogr::Layer::const_iterator it = layer.cbegin();
    otb::ogr::Layer::const_iterator itEnd = layer.cend();

    // Get the list of non-selected field indexes
    // /!\ The 'feat' is assumed to expose all available fields, hence the
    // mapping between GetSelectedItems() and OGR field indexes
    OGRFeatureDefn &inLayerDefn = layer.GetLayerDefn();
    std::set<int> otherInputFields;
    for (int i=0 ; i < inLayerDefn.GetFieldCount() ; i++)
      otherInputFields.insert(i);
    for (int k=0 ; k < nbFeatures ; k++)
      otherInputFields.erase(inputIndexes[k]);

    for( ; it!=itEnd ; ++it)
      {
      MeasurementType mv;
      mv.SetSize(nbFeatures);

      for(int idx=0; idx < nbFeatures; ++idx)
        {
        mv[idx] = static_cast<float>( (*it)[inputIndexes[idx]].GetValue<double>() );
        }
      input->PushBack(mv);
      }

    /** Statistics for shift/scale */
    MeasurementType meanMeasurementVector;
    MeasurementType stddevMeasurementVector;

    if (HasValue("instat") && IsParameterEnabled("instat"))
      {
      StatisticsReader::Pointer statisticsReader = StatisticsReader::New();
      std::string XMLfile = GetParameterString("instat");
      statisticsReader->SetFileName(XMLfile);
      meanMeasurementVector = statisticsReader->GetStatisticVectorByName("mean");
      stddevMeasurementVector = statisticsReader->GetStatisticVectorByName("stddev");
      otbAppLogINFO("Mean used: " << meanMeasurementVector);
      otbAppLogINFO("Standard deviation used: " << stddevMeasurementVector);
      }
    else
      {
      meanMeasurementVector.SetSize(nbFeatures);
      meanMeasurementVector.Fill(0.);
      stddevMeasurementVector.SetSize(nbFeatures);
      stddevMeasurementVector.Fill(1.);
      }

    ShiftScaleFilterType::Pointer trainingShiftScaleFilter = ShiftScaleFilterType::New();
    trainingShiftScaleFilter->SetInput(input);
    trainingShiftScaleFilter->SetShifts(meanMeasurementVector);
    trainingShiftScaleFilter->SetScales(stddevMeasurementVector);
    trainingShiftScaleFilter->Update();

    otbAppLogINFO("Loading model");
    /** Read the model */
    m_Model = DimensionalityReductionModelFactoryType::CreateDimensionalityReductionModel(
      GetParameterString("model"),
      DimensionalityReductionModelFactoryType::ReadMode);
    if (m_Model.IsNull())
      {
      otbAppLogFATAL(<< "Error when loading model " << GetParameterString("model")
        << " : unsupported model type");
      }
    m_Model->Load(GetParameterString("model"));
    if (HasValue("pcadim") && IsParameterEnabled("pcadim"))
      {
      std::string modelName(m_Model->GetNameOfClass());
      if (modelName != "PCAModel")
        {
        otbAppLogFATAL(<< "Can't set 'pcadim' on a model : "<< modelName);
        }
      m_Model->SetDimension( GetParameterInt("pcadim") );
      }
    otbAppLogINFO("Model loaded, dimension : "<< m_Model->GetDimension());

    /** Perform Dimensionality Reduction */
    ListSampleType::Pointer listSample = trainingShiftScaleFilter->GetOutput();
    ListSampleType::Pointer target = m_Model->PredictBatch(listSample);

    /** Create/Update Output Shape file */
    ogr::DataSource::Pointer output;
    ogr::DataSource::Pointer buffer = ogr::DataSource::New();
    bool updateMode = false;

    if (IsParameterEnabled("out") && HasValue("out"))
      {
      // Create new OGRDataSource
      if (GetParameterString("mode")=="overwrite")
        {
        output = ogr::DataSource::New(GetParameterString("out"), ogr::DataSource::Modes::Overwrite);
        otb::ogr::Layer newLayer = output->CreateLayer(
          GetParameterString("out"),
          const_cast<OGRSpatialReference*>(layer.GetSpatialRef()),
          layer.GetGeomType());
        // Copy existing fields except the ones selected for reduction
        for (const int& k : otherInputFields)
          {
          OGRFieldDefn fieldDefn(inLayerDefn.GetFieldDefn(k));
          newLayer.CreateField(fieldDefn);
          }
        }
      else if (GetParameterString("mode")=="update")
        {
        //output = ogr::DataSource::New(GetParameterString("out"), ogr::DataSource::Modes::Update_LayerCreateOnly);
        // Update mode
        otb::ogr::DataSource::Pointer source_output =
          otb::ogr::DataSource::New(GetParameterString("out"), otb::ogr::DataSource::Modes::Read);
        layer = source_output->GetLayer(0);
        updateMode = true;
        otbAppLogINFO("Update input vector data.");

        // fill temporary buffer for the transfer
        otb::ogr::Layer inputLayer = layer;
        layer = buffer->CopyLayer(inputLayer, std::string("Buffer"));
        // close input data source
        source_output->Clear();
        // Re-open input data source in update mode
        output = otb::ogr::DataSource::New(
          GetParameterString("out"),
          otb::ogr::DataSource::Modes::Update_LayerUpdate);
        }
      else
        {
        otbAppLogFATAL(<< "Error when creating the output file" <<
          GetParameterString("mode") << " : unsupported writting mode type");
        }
      }

    otb::ogr::Layer outLayer = output->GetLayer(0);
    OGRErr errStart = outLayer.ogr().StartTransaction();

    if (errStart != OGRERR_NONE)
      {
      otbAppLogFATAL(<< "Unable to start transaction for OGR layer " << outLayer.ogr().GetName() << ".");
      }

    // Build the list of output fields
    std::vector<std::string> outFields;
    if(GetParameterString("featout") == "prefix")
      {
      std::string prefix = GetParameterString("featout.prefix.name");
      std::ostringstream oss;
      for (unsigned int i=0 ; i < m_Model->GetDimension() ; i++)
        {
        oss.str(prefix);
        oss.seekp(0,std::ios_base::end);
        oss << i;
        outFields.push_back(oss.str());
        }
      }
    else if(GetParameterString("featout") == "list")
      {
      outFields = GetParameterStringList("featout.list.names");
      if (outFields.size() != m_Model->GetDimension())
        {
        otbAppLogFATAL( << "Wrong number of output field names, expected "
          << m_Model->GetDimension() << " , got "<< outFields.size());
        }
      }
    else
      {
      otbAppLogFATAL( << "Unsupported output feature mode : "
        << GetParameterString("featout"));
      }

    // Add the field of prediction in the output layer if field not exist
    for (unsigned int i=0; i<outFields.size() ;i++)
      {
      OGRFeatureDefn &layerDefn = outLayer.GetLayerDefn();
      int idx = layerDefn.GetFieldIndex(outFields[i].c_str());

      if (idx >= 0)
        {
        if (layerDefn.GetFieldDefn(idx)->GetType() != OFTReal)
        otbAppLogFATAL("Field name "<< outFields[i]
          << " already exists with a different type!");
        }
      else
        {
        OGRFieldDefn predictedField(outFields[i].c_str(), OFTReal);
        ogr::FieldDefn predictedFieldDef(predictedField);
        outLayer.CreateField(predictedFieldDef);
        }
      }

    // Fill output layer
    unsigned int count=0;
    it = layer.cbegin();
    itEnd = layer.cend();
    for( ; it!=itEnd ; ++it, ++count)
      {
      ogr::Feature dstFeature(outLayer.GetLayerDefn());

      dstFeature.SetFrom( *it , TRUE);
      dstFeature.SetFID(it->GetFID());

      for (std::size_t i=0; i<outFields.size(); ++i)
        {
        dstFeature[outFields[i]].SetValue<double>(target->GetMeasurementVector(count)[i]);
        }
      if (updateMode)
        {
        outLayer.SetFeature(dstFeature);
        }
      else
        {
        outLayer.CreateFeature(dstFeature);
        }
      }

    if(outLayer.ogr().TestCapability("Transactions"))
      {
      const OGRErr errCommitX = outLayer.ogr().CommitTransaction();
      if (errCommitX != OGRERR_NONE)
        {
        otbAppLogFATAL(<< "Unable to commit transaction for OGR layer " <<
          outLayer.ogr().GetName() << ".");
        }
      }
    output->SyncToDisk();
    clock_t toc = clock();
    otbAppLogINFO( "Elapsed: "<< ((double)(toc - tic) / CLOCKS_PER_SEC)<<" seconds.");
    }

  ModelPointerType m_Model;
};

} // end of namespace Wrapper
} // end of namespace otb

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


<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qmessage.h"
#ifdef Q_OS_SYMBIAN
#include "qmessage_symbian_p.h"
#else
#include "qmessage_p.h"
#endif

#include <QTextCodec>
#include <QDebug>

QTM_BEGIN_NAMESPACE

namespace {

QList<QByteArray> charsets;

}

/*!
    \class QMessage

    \brief The QMessage class provides a convenient interface for working with messages.

    \inmodule QtMessaging

    \ingroup messaging

    QMessage supports a number of types. Including internet email messages,
    and the telephony types SMS and MMS.

    The QMessageId identifier for a message is returned by id(). Messages can be constructed by
    retrieval from the messaging store via their identifier using QMessageManager::message(). A
    QMessage can also be constructed piece by piece using functions such as
    setType(), setFrom(), setTo(), setSubject(), setBody() and appendAttachments().

    If a message has been modified since it was last constructed isModified() returns true.

    A list of attachments identifiers will be returned by attachmentIds() and an identifier for the
    message body will be returned by bodyId(). Attachments can be appended to the content of the
    message using appendAttachments(), the body of the message can be set with setBody().

    The folder and account a message is associated with are returned by parentFolderId() and
    parentAccountId() respectively.

    Message data that is less commonly accessed or relatively large should be lazily retrieved
    on demand by the associated getter function.

    Only phone numbers are valid destination addresses for SMS messages, only email addresses are valid
    destination addresses for Email messages, MMS messages may be addressed to either phone numbers
    or email addresses.

    \sa QMessageContentContainer, QMessageManager, QMessageId
*/

/*!
    \enum QMessage::Type

    This enum type is used to describe the type of a message.

    \value NoType             The message type is not defined.
    \value Mms                The message is an MMS, Multimedia Messaging Service object.
    \value Sms                The message is an SMS, Short Message Service object.
    \value Email              The message is an Email, Internet Message Format object.
    \value InstantMessage     The message is an instant message object, such as XMPP.
    \value AnyType            Bitflag value that matches any message type defined.

    \sa type(), setType()
*/

/*!
    \enum QMessage::Status

    This enum type is used to describe the status of a message.

    \value Read            This flag indicates that the content of this message has been displayed to the user.
    \value HasAttachments  This flag indicates that the message contains at least one sub-part with 'Attachment' disposition.
    \value Incoming        This flag indicates that the message has been sent from an external source.
    \value Removed         This flag indicates that the message has been deleted from or moved on the originating server.

    \sa status(), setStatus()
*/

/*!
    \enum QMessage::Priority

    Defines the priority of a message.

    \value HighPriority    The message is high priority.
    \value NormalPriority  The message is normal priority.
    \value LowPriority     The message is low priority.
*/

/*!
    \enum QMessage::StandardFolder

    Defines the standard folders.

    \value InboxFolder   Represents the standard inbox folder.
    \value DraftsFolder  Represents the standard drafts folder.
    \value OutboxFolder  Represents the standard outbox folder.
    \value SentFolder    Represents the standard sent folder.
    \value TrashFolder   Represents the standard trash folder.
*/

/*!
    \enum QMessage::ResponseType

    Defines the type of a response to an existing message.

    \value ReplyToSender    A response to the sender of the existing message.
    \value ReplyToAll       A response to the sender of the existing message, and any other recipients of that message.
    \value Forward          A response created to copy the content of the existing message to a new recipient.
*/

/*!
    \fn QMessage::QMessage()

    Constructs an empty message.
*/

/*!
    \fn QMessage::QMessage(const QMessageId& id)

    Constructs a message from data stored in the messaging store with identifier \a id.

    \sa QMessageManager::message()
*/

/*!
    \fn QMessage::QMessage(const QMessage &other)

    Constructs a copy of \a other.
*/

/*!
    \internal
    \fn QMessage::operator=(const QMessage& other)
*/

/*!
    \fn QMessage::~QMessage()

    Destroys the message.
*/

/*!
    \fn QMessage::id() const

    Returns the identifier of the message.

    \sa QMessageFilter::byId()
*/

/*!
    \fn QMessage::type() const

    Returns the Type of the message.

    \sa setType(), QMessageFilter::byType()
*/

/*!
    \fn QMessage::setType(Type t)

    Sets the Type of the message to \a t.

    The type of a message may be set for non-empty messages.

    \sa type()
*/

/*!
    \fn QMessage::parentAccountId() const

    Returns the identifier of the parent account of the message if any; otherwise returns an
    invalid identifier.
*/

/*!
    \fn QMessage::setParentAccountId(const QMessageAccountId &accountId)

    Sets the parent account of the message to the account with identifier \a accountId.

    This operation is only permitted on new messages that have not yet been inserted into
    the message store. Attempting to change the parent account of a message already
    in the message store will result in an error when attempting to update the message
    with QMessageStore::update().
*/

/*!
    \fn QMessage::parentFolderId() const

    Returns the identifier of the folder that contains the message if any; otherwise returns an
    invalid identifier.
*/

/*!
    \fn QMessage::standardFolder() const

    Returns the standard folder of the message.

    Defaults to DraftsFolder.
*/

/*!
    \fn QMessage::from() const

    Returns the originating address of the message.

    \sa setFrom(), QMessageFilter::bySender()
*/

/*!
    \fn QMessage::setFrom(const QMessageAddress &address)

    Sets the from address, that is the originating address of the message to \a address.

    \sa from()
*/

/*!
    \fn QMessage::subject() const

    Returns the subject of the message, if present; otherwise returns a null string.

    \sa setSubject(), QMessageFilter::bySubject()
*/

/*!
    \fn QMessage::setSubject(const QString &text)

    Sets the subject of the message to \a text.

    \sa subject()
*/

/*!
    \fn QMessage::date() const

    Returns the timestamp contained in the origination date header field of the message, if present;
    otherwise returns a null timestamp.

    \sa setDate(), QMessageFilter::byTimeStamp()
*/

/*!
    \fn QMessage::setDate(const QDateTime &d)

    Sets the origination date header field specifying the timestamp of the message to \a d.

    \sa date()
*/

/*!
    \fn QMessage::receivedDate() const

    Returns the timestamp placed in the message during reception by the device, if present;
    otherwise returns a null timestamp.

    \sa setReceivedDate(), QMessageFilter::byReceptionTimeStamp()
*/

/*!
    \fn QMessage::setReceivedDate(const QDateTime &d)

    Sets the timestamp indicating the time of message reception by the device to \a d.

    \sa receivedDate()
*/

/*!
    \fn QMessage::to() const

    Returns the list of primary recipients for the message.

    \sa setTo(), QMessageFilter::byRecipients()
*/

/*!
    \fn QMessage::setTo(const QMessageAddressList& toList)

    Sets the list of primary recipients for the message to \a toList.

    \sa to()
*/

/*!
    \fn QMessage::setTo(const QMessageAddress& address)

    Sets the primary recipient for the message to \a address.

    \sa to()
*/

/*!
    \fn QMessage::cc() const

    Returns the list of all the cc (carbon copy) recipients specified for the message.

    \sa to(), bcc(), setCc(), QMessageFilter::byRecipients()
*/

/*!
   \fn QMessage::setCc(const QMessageAddressList& ccList)

    Set the list of cc (carbon copy) recipients for the message to \a ccList.

    \sa cc(), setTo(), setBcc()
*/

/*!
    \fn QMessage::bcc() const

    Returns the list of all the bcc (blind carbon copy) recipients specified for the message.

    \sa to(), cc(), setBcc()
*/

/*!
    \fn QMessage::setBcc(const QMessageAddressList& bccList)

    Set the list of bcc (blind carbon copy) recipients for the message to \a bccList.

    \sa bcc(), setTo(), setCc()
*/

/*!
    \fn QMessage::status() const

    Returns the status flags value for the message.

    \sa setStatus(), QMessageFilter::byStatus()
*/

/*!
    \fn QMessage::setStatus(QMessage::StatusFlags newStatus)

    Sets the status flags value for the message to \a newStatus.

    \sa status()
*/

/*!
    \fn QMessage::setStatus(QMessage::Status flag, bool set)

    Sets the status flag \a flag for the message to have the value \a set.

    \sa status()
*/

/*!
    \fn QMessage::priority() const

    Returns the priority of the message.

    The default is NormalPriority.

    \sa setPriority(), QMessageFilter::byPriority()
*/

/*!
    \fn QMessage::setPriority(Priority newPriority)

    Sets the priority of the message to \a newPriority.

    \sa priority()
*/

/*!
    \fn QMessage::size() const

    Returns the complete size of the message as indicated on the originating server.

    \sa QMessageFilter::bySize()
*/

/*!
    \fn QMessage::bodyId() const

    Returns the identifier for the body content contained by the Message if a body exists;
    otherwise returns an invalid identifier.

    \sa QMessageContentContainer, setBody()
*/

/*!
    \fn QMessage::setBody(const QString &body, const QByteArray &mimeType)

    Sets the body text of the message to be the string \a body.

    The internet media (MIME) content type of the body is set to \a mimeType, if provided.
    If the \a mimeType is not specified, the content type will default to "text/plain", and
    the encoding charset will be as determined by preferredCharsets().

    \sa bodyId(), preferredCharsets()
*/

/*!
    \fn QMessage::setBody(QTextStream &in, const QByteArray &mimeType)

    Sets the body text of the message to be the text read from the stream \a in.

    The internet media (MIME) content type of the body is set to \a mimeType, if provided.
    If the \a mimeType is not specified, the content type will default to "text/plain", and
    the encoding charset will be as determined by preferredCharsets().

    \sa bodyId(), preferredCharsets()
*/

/*!
    \fn QMessage::attachmentIds() const

    Returns a list of attachment identifiers for the message.

    The body of the message will not be included in the list.

    \sa appendAttachments(), clearAttachments()
*/

/*!
    \fn QMessage::appendAttachments(const QStringList &fileNames)

    Append the contents of the files specified by \a fileNames to the end of the list of
    attachments for the message. The internet media (MIME) type of the attachments will be
    determined by examining the files or file names.

    Symbian OS based devices have a limit for MMS message size. The message size limit
    varies between different devices, but is frequently 600 000 bytes. If the attachment
    size is greater than the limit then message sending will fail when
    QMessageService::send() is called.

    \sa attachmentIds(), clearAttachments()
*/

/*!
    \fn QMessage::clearAttachments()

    Clears the list of attachments for the message, leaving only the message body, if any.

    \sa attachmentIds(), appendAttachments()
*/

/*!
    \fn QMessage::isModified() const

    Returns true if the message has been modified since it was constructed;
    otherwise returns false.
*/

/*!
    \fn QMessage::createResponseMessage(ResponseType type) const

    Creates a new message as a response to this message, with properties predetermined according to \a type.

    \sa QMessageService::compose()
*/

/*!
    \fn QMessage::setPreferredCharsets(const QList<QByteArray> &charsetNames)

    Sets the ordered-by-preference list of names of charsets to use when encoding
    unicode QString data to a serialized form to \a charsetNames.

    The set of valid charset names is returned by QTextCodec::availableCharsets().

    \sa preferredCharsets(), preferredCharsetFor(), setBody()
*/
void QMessage::setPreferredCharsets(const QList<QByteArray> &charsetNames)
{
    charsets = charsetNames;
}

/*!
    \fn QMessage::preferredCharsets()

    Returns an ordered-by-preference list of charset names to use when encoding
    unicode QString data to a serialized form.

    \sa setPreferredCharsets(), preferredCharsetFor(), setBody()
*/
QList<QByteArray> QMessage::preferredCharsets()
{
    return charsets;
}

/*!
    Returns the first charset from the preferred list that is capable of encoding
    the content of \a text.

    \sa preferredCharsets(), setBody()
*/
QByteArray QMessage::preferredCharsetFor(const QString &text)
{
    QList<QTextCodec*> codecs;
    foreach (const QByteArray &name, charsets) {
        if (QTextCodec* codec = QTextCodec::codecForName(name)) {
            codecs.append(codec);
        } else {
            qWarning() << "No codec is available for:" << name;
        }
    }

    if (!codecs.isEmpty()) {
        // See if any of these codecs can encode the data
        QString::const_iterator sit = text.begin(), end = text.end();
        for ( ; sit != end; ++sit) {
            QList<QTextCodec*>::iterator cit = codecs.begin();
            if (!(*cit)->canEncode(*sit)) {
                // This codec is not acceptable
                cit = codecs.erase(cit);
                if (codecs.isEmpty()) {
                    break;
                }
            } else {
                ++cit;
            }
        }

        if (!codecs.isEmpty()) {
            // Return the first remaining codec
            return codecs.first()->name();
        }
    }

    return QByteArray();
}

QTM_END_NAMESPACE
<commit_msg>Fix typo in doc.<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qmessage.h"
#ifdef Q_OS_SYMBIAN
#include "qmessage_symbian_p.h"
#else
#include "qmessage_p.h"
#endif

#include <QTextCodec>
#include <QDebug>

QTM_BEGIN_NAMESPACE

namespace {

QList<QByteArray> charsets;

}

/*!
    \class QMessage

    \brief The QMessage class provides a convenient interface for working with messages.

    \inmodule QtMessaging

    \ingroup messaging

    QMessage supports a number of types. Including internet email messages,
    and the telephony types SMS and MMS.

    The QMessageId identifier for a message is returned by id(). Messages can be constructed by
    retrieval from the messaging store via their identifier using QMessageManager::message(). A
    QMessage can also be constructed piece by piece using functions such as
    setType(), setFrom(), setTo(), setSubject(), setBody() and appendAttachments().

    If a message has been modified since it was last constructed isModified() returns true.

    A list of attachments identifiers will be returned by attachmentIds() and an identifier for the
    message body will be returned by bodyId(). Attachments can be appended to the content of the
    message using appendAttachments(), the body of the message can be set with setBody().

    The folder and account a message is associated with are returned by parentFolderId() and
    parentAccountId() respectively.

    Message data that is less commonly accessed or relatively large should be lazily retrieved
    on demand by the associated getter function.

    Only phone numbers are valid destination addresses for SMS messages, only email addresses are valid
    destination addresses for Email messages, MMS messages may be addressed to either phone numbers
    or email addresses.

    \sa QMessageContentContainer, QMessageManager, QMessageId
*/

/*!
    \enum QMessage::Type

    This enum type is used to describe the type of a message.

    \value NoType             The message type is not defined.
    \value Mms                The message is an MMS, Multimedia Messaging Service object.
    \value Sms                The message is an SMS, Short Message Service object.
    \value Email              The message is an Email, Internet Message Format object.
    \value InstantMessage     The message is an instant message object, such as XMPP.
    \value AnyType            Bitflag value that matches any message type defined.

    \sa type(), setType()
*/

/*!
    \enum QMessage::Status

    This enum type is used to describe the status of a message.

    \value Read            This flag indicates that the content of this message has been displayed to the user.
    \value HasAttachments  This flag indicates that the message contains at least one sub-part with 'Attachment' disposition.
    \value Incoming        This flag indicates that the message has been sent from an external source.
    \value Removed         This flag indicates that the message has been deleted from or moved on the originating server.

    \sa status(), setStatus()
*/

/*!
    \enum QMessage::Priority

    Defines the priority of a message.

    \value HighPriority    The message is high priority.
    \value NormalPriority  The message is normal priority.
    \value LowPriority     The message is low priority.
*/

/*!
    \enum QMessage::StandardFolder

    Defines the standard folders.

    \value InboxFolder   Represents the standard inbox folder.
    \value DraftsFolder  Represents the standard drafts folder.
    \value OutboxFolder  Represents the standard outbox folder.
    \value SentFolder    Represents the standard sent folder.
    \value TrashFolder   Represents the standard trash folder.
*/

/*!
    \enum QMessage::ResponseType

    Defines the type of a response to an existing message.

    \value ReplyToSender    A response to the sender of the existing message.
    \value ReplyToAll       A response to the sender of the existing message, and any other recipients of that message.
    \value Forward          A response created to copy the content of the existing message to a new recipient.
*/

/*!
    \fn QMessage::QMessage()

    Constructs an empty message.
*/

/*!
    \fn QMessage::QMessage(const QMessageId& id)

    Constructs a message from data stored in the messaging store with identifier \a id.

    \sa QMessageManager::message()
*/

/*!
    \fn QMessage::QMessage(const QMessage &other)

    Constructs a copy of \a other.
*/

/*!
    \internal
    \fn QMessage::operator=(const QMessage& other)
*/

/*!
    \fn QMessage::~QMessage()

    Destroys the message.
*/

/*!
    \fn QMessage::id() const

    Returns the identifier of the message.

    \sa QMessageFilter::byId()
*/

/*!
    \fn QMessage::type() const

    Returns the Type of the message.

    \sa setType(), QMessageFilter::byType()
*/

/*!
    \fn QMessage::setType(Type t)

    Sets the Type of the message to \a t.

    The type of a message may be set for non-empty messages.

    \sa type()
*/

/*!
    \fn QMessage::parentAccountId() const

    Returns the identifier of the parent account of the message if any; otherwise returns an
    invalid identifier.
*/

/*!
    \fn QMessage::setParentAccountId(const QMessageAccountId &accountId)

    Sets the parent account of the message to the account with identifier \a accountId.

    This operation is only permitted on new messages that have not yet been inserted into
    the message store. Attempting to change the parent account of a message already
    in the message store will result in an error when attempting to update the message
    with QMessageStore::update().
*/

/*!
    \fn QMessage::parentFolderId() const

    Returns the identifier of the folder that contains the message if any; otherwise returns an
    invalid identifier.
*/

/*!
    \fn QMessage::standardFolder() const

    Returns the standard folder of the message.

    Defaults to DraftsFolder.
*/

/*!
    \fn QMessage::from() const

    Returns the originating address of the message.

    \sa setFrom(), QMessageFilter::bySender()
*/

/*!
    \fn QMessage::setFrom(const QMessageAddress &address)

    Sets the from address, that is the originating address of the message to \a address.

    \sa from()
*/

/*!
    \fn QMessage::subject() const

    Returns the subject of the message, if present; otherwise returns a null string.

    \sa setSubject(), QMessageFilter::bySubject()
*/

/*!
    \fn QMessage::setSubject(const QString &text)

    Sets the subject of the message to \a text.

    \sa subject()
*/

/*!
    \fn QMessage::date() const

    Returns the timestamp contained in the origination date header field of the message, if present;
    otherwise returns a null timestamp.

    \sa setDate(), QMessageFilter::byTimeStamp()
*/

/*!
    \fn QMessage::setDate(const QDateTime &d)

    Sets the origination date header field specifying the timestamp of the message to \a d.

    \sa date()
*/

/*!
    \fn QMessage::receivedDate() const

    Returns the timestamp placed in the message during reception by the device, if present;
    otherwise returns a null timestamp.

    \sa setReceivedDate(), QMessageFilter::byReceptionTimeStamp()
*/

/*!
    \fn QMessage::setReceivedDate(const QDateTime &d)

    Sets the timestamp indicating the time of message reception by the device to \a d.

    \sa receivedDate()
*/

/*!
    \fn QMessage::to() const

    Returns the list of primary recipients for the message.

    \sa setTo(), QMessageFilter::byRecipients()
*/

/*!
    \fn QMessage::setTo(const QMessageAddressList& toList)

    Sets the list of primary recipients for the message to \a toList.

    \sa to()
*/

/*!
    \fn QMessage::setTo(const QMessageAddress& address)

    Sets the primary recipient for the message to \a address.

    \sa to()
*/

/*!
    \fn QMessage::cc() const

    Returns the list of all the cc (carbon copy) recipients specified for the message.

    \sa to(), bcc(), setCc(), QMessageFilter::byRecipients()
*/

/*!
   \fn QMessage::setCc(const QMessageAddressList& ccList)

    Set the list of cc (carbon copy) recipients for the message to \a ccList.

    \sa cc(), setTo(), setBcc()
*/

/*!
    \fn QMessage::bcc() const

    Returns the list of all the bcc (blind carbon copy) recipients specified for the message.

    \sa to(), cc(), setBcc()
*/

/*!
    \fn QMessage::setBcc(const QMessageAddressList& bccList)

    Set the list of bcc (blind carbon copy) recipients for the message to \a bccList.

    \sa bcc(), setTo(), setCc()
*/

/*!
    \fn QMessage::status() const

    Returns the status flags value for the message.

    \sa setStatus(), QMessageFilter::byStatus()
*/

/*!
    \fn QMessage::setStatus(QMessage::StatusFlags newStatus)

    Sets the status flags value for the message to \a newStatus.

    \sa status()
*/

/*!
    \fn QMessage::setStatus(QMessage::Status flag, bool set)

    Sets the status flag \a flag for the message to have the value \a set.

    \sa status()
*/

/*!
    \fn QMessage::priority() const

    Returns the priority of the message.

    The default is NormalPriority.

    \sa setPriority(), QMessageFilter::byPriority()
*/

/*!
    \fn QMessage::setPriority(Priority newPriority)

    Sets the priority of the message to \a newPriority.

    \sa priority()
*/

/*!
    \fn QMessage::size() const

    Returns the complete size of the message as indicated on the originating server.

    \sa QMessageFilter::bySize()
*/

/*!
    \fn QMessage::bodyId() const

    Returns the identifier for the body content contained by the Message if a body exists;
    otherwise returns an invalid identifier.

    \sa QMessageContentContainer, setBody()
*/

/*!
    \fn QMessage::setBody(const QString &body, const QByteArray &mimeType)

    Sets the body text of the message to be the string \a body.

    The internet media (MIME) content type of the body is set to \a mimeType, if provided.
    If the \a mimeType is not specified, the content type will default to "text/plain", and
    the encoding charset will be as determined by preferredCharsets().

    \sa bodyId(), preferredCharsets()
*/

/*!
    \fn QMessage::setBody(QTextStream &in, const QByteArray &mimeType)

    Sets the body text of the message to be the text read from the stream \a in.

    The internet media (MIME) content type of the body is set to \a mimeType, if provided.
    If the \a mimeType is not specified, the content type will default to "text/plain", and
    the encoding charset will be as determined by preferredCharsets().

    \sa bodyId(), preferredCharsets()
*/

/*!
    \fn QMessage::attachmentIds() const

    Returns a list of attachment identifiers for the message.

    The body of the message will not be included in the list.

    \sa appendAttachments(), clearAttachments()
*/

/*!
    \fn QMessage::appendAttachments(const QStringList &fileNames)

    Append the contents of the files specified by \a fileNames to the end of the list of
    attachments for the message. The internet media (MIME) type of the attachments will be
    determined by examining the files or file names.

    Symbian OS based devices have a limit for MMS message size. The message size limit
    varies between different devices, but is frequently 600 000 bytes. If the attachment
    size is greater than the limit then message sending will fail when
    QMessageService::send() is called.

    \sa attachmentIds(), clearAttachments()
*/

/*!
    \fn QMessage::clearAttachments()

    Clears the list of attachments for the message, leaving only the message body, if any.

    \sa attachmentIds(), appendAttachments()
*/

/*!
    \fn QMessage::isModified() const

    Returns true if the message has been modified since it was constructed;
    otherwise returns false.
*/

/*!
    \fn QMessage::createResponseMessage(ResponseType type) const

    Creates a new message as a response to this message, with properties predetermined according to \a type.

    \sa QMessageService::compose()
*/

/*!
    \fn QMessage::setPreferredCharsets(const QList<QByteArray> &charsetNames)

    Sets the ordered-by-preference list of names of charsets to use when encoding
    unicode QString data to a serialized form to \a charsetNames.

    The set of valid charset names is returned by QTextCodec::availableCodecs().

    \sa preferredCharsets(), preferredCharsetFor(), setBody()
*/
void QMessage::setPreferredCharsets(const QList<QByteArray> &charsetNames)
{
    charsets = charsetNames;
}

/*!
    \fn QMessage::preferredCharsets()

    Returns an ordered-by-preference list of charset names to use when encoding
    unicode QString data to a serialized form.

    \sa setPreferredCharsets(), preferredCharsetFor(), setBody()
*/
QList<QByteArray> QMessage::preferredCharsets()
{
    return charsets;
}

/*!
    Returns the first charset from the preferred list that is capable of encoding
    the content of \a text.

    \sa preferredCharsets(), setBody()
*/
QByteArray QMessage::preferredCharsetFor(const QString &text)
{
    QList<QTextCodec*> codecs;
    foreach (const QByteArray &name, charsets) {
        if (QTextCodec* codec = QTextCodec::codecForName(name)) {
            codecs.append(codec);
        } else {
            qWarning() << "No codec is available for:" << name;
        }
    }

    if (!codecs.isEmpty()) {
        // See if any of these codecs can encode the data
        QString::const_iterator sit = text.begin(), end = text.end();
        for ( ; sit != end; ++sit) {
            QList<QTextCodec*>::iterator cit = codecs.begin();
            if (!(*cit)->canEncode(*sit)) {
                // This codec is not acceptable
                cit = codecs.erase(cit);
                if (codecs.isEmpty()) {
                    break;
                }
            } else {
                ++cit;
            }
        }

        if (!codecs.isEmpty()) {
            // Return the first remaining codec
            return codecs.first()->name();
        }
    }

    return QByteArray();
}

QTM_END_NAMESPACE
<|endoftext|>


<commit_before>// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-443271.
//
// This file is part of the GLVis visualization tool and library. For more
// information and source code availability see https://glvis.org.
//
// GLVis is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.

#ifndef GLVIS_VSSOLUTION_3D_HPP
#define GLVIS_VSSOLUTION_3D_HPP

#include "mfem.hpp"
#include "gl/types.hpp"
#include <map>
using namespace mfem;

class VisualizationSceneSolution3d : public VisualizationSceneScalarData
{
protected:

   int drawmesh, drawelems, shading, draworder;
   int cplane;
   int cp_drawmesh, cp_drawelems, drawlsurf;
   // Algorithm used to draw the cutting plane when shading is 2 and cplane is 1
   // 0 - slower, more accurate algorithm for curved meshes (default)
   // 1 - faster algorithm suitable for meshes with planar faces
   int cp_algo;

   gl3::GlDrawable disp_buf;
   gl3::GlDrawable line_buf;
   gl3::GlDrawable cplane_buf;
   gl3::GlDrawable cplines_buf;
   gl3::GlDrawable lsurf_buf;
   gl3::GlDrawable other_buf;
   gl3::GlDrawable order_buf, order_noarrow_buf;

   double *node_pos;

   int nlevels;
   Array<double> levels;

   GridFunction *GridF;

   void Init();

   void GetFaceNormals(const int FaceNo, const int side,
                       const IntegrationRule &ir, DenseMatrix &normals);

   void DrawRefinedSurf (int n, double *points, int elem, int func,
                         int part = -1);
   void DrawRefinedSurf (int n, DenseMatrix &pointmat,
                         Vector &values, Array<int> &RefGeoms);
   void DrawRefinedSurfLevelLines (int n, DenseMatrix &pointmat,
                                   Vector &values, Array<int> &RefGeoms);
   void DrawRefinedSurfEdges (int n, DenseMatrix &pointmat,
                              Vector &values, Array<int> &RefEdges,
                              int part = -1);
   void LiftRefinedSurf (int n, DenseMatrix &pointmat,
                         Vector &values, int *RG);
   void DrawTetLevelSurf(gl3::GlDrawable& target, const DenseMatrix &verts,
                         const Vector &vals,
                         const int *ind, const Array<double> &levels,
                         const DenseMatrix *grad = NULL);

   static int GetPyramidFaceSplits(const Array<bool> &quad_diag,
                                   const Array<int> &faces,
                                   const Array<int> &ofaces);
   void DrawRefinedPyramidLevelSurf(
      gl3::GlDrawable& target,
      const DenseMatrix &verts, const Vector &vals, const int *RG, const int np,
      const int face_splits, const DenseMatrix *grad = NULL);

   static int GetWedgeFaceSplits(const Array<bool> &quad_diag,
                                 const Array<int> &faces,
                                 const Array<int> &ofaces);
   void DrawRefinedWedgeLevelSurf(
      gl3::GlDrawable& target,
      const DenseMatrix &verts, const Vector &vals, const int *RG, const int np,
      const int face_splits, const DenseMatrix *grad = NULL);

   static int GetHexFaceSplits(const Array<bool> &quad_diag,
                               const Array<int> &faces,
                               const Array<int> &ofaces);
   void DrawRefinedHexLevelSurf(
      gl3::GlDrawable& target,
      const DenseMatrix &verts, const Vector &vals, const int *RG, const int nh,
      const int face_splits, const DenseMatrix *grad = NULL);

   int GetAutoRefineFactor();

   bool CheckPositions(Array<int> &vertices) const
   {
      int n = 0;
      for (int j = 0; j < vertices.Size(); j++)
      {
         if (node_pos[vertices[j]] >= 0.0) { n++; }
      }
      return (n < vertices.Size());
   }

public:
   int TimesToRefine;
   double FaceShiftScale;

   Array<int> bdr_attr_to_show;

   VisualizationSceneSolution3d();
   VisualizationSceneSolution3d(Mesh & m, Vector & s);

   void SetGridFunction (GridFunction *gf) { GridF = gf; }

   void NewMeshAndSolution(Mesh *new_m, Vector *new_sol,
                           GridFunction *new_u = NULL);

   virtual ~VisualizationSceneSolution3d();

   virtual std::string GetHelpString() const;

   virtual void FindNewBox(bool prepare);
   virtual void FindNewValueRange(bool prepare);

   virtual void PrepareRuler()
   { VisualizationSceneScalarData::PrepareRuler(false); }
   virtual void PrepareFlat();
   virtual void PrepareLines();
   virtual void Prepare();
   virtual void PrepareOrderingCurve();
   virtual void PrepareOrderingCurve1(gl3::GlDrawable& buf, bool arrows,
                                      bool color);
   virtual gl3::SceneInfo GetSceneObjs();

   void ToggleDrawElems()
   { drawelems = !drawelems; Prepare(); }

   void ToggleDrawMesh();

   // 0 - none, 1 - no arrows (color), 2 - with arrows (color),
   //           3 - no arrows (black), 4 - with arrows (black)
   void ToggleDrawOrdering() { draworder = (draworder+1)%5; }

   void ToggleShading();
   int GetShading() { return shading; };
   virtual void SetShading(int, bool);
   virtual void SetRefineFactors(int, int);
   virtual void AutoRefine();
   virtual void ToggleAttributes(Array<int> &attr_list);

   void FindNodePos();

   void CuttingPlaneFunc (int type);
   // func: 0 - draw surface, 1 - draw level lines
   void CutRefinedElement(gl3::GlDrawable& target,
                          const DenseMatrix &verts, const Vector &vert_dist,
                          const Vector &vals, const Geometry::Type geom,
                          const int *elems, int num_elems, int func);
   void CutRefinedFace(gl3::GlDrawable& target,
                       const DenseMatrix &verts, const Vector &vert_dist,
                       const Vector &vals, const Geometry::Type geom,
                       const int *faces, int num_faces);
   void CPPrepare();
   void CPMoved();
   void PrepareFlat2();
   void PrepareLines2();
   virtual void PrepareCuttingPlane();
   void PrepareCuttingPlane2();
   void PrepareCuttingPlaneLines();
   void PrepareCuttingPlaneLines2();
   void PrepareLevelSurf();
   void ToggleCuttingPlane();
   void ToggleCPDrawElems();
   void ToggleCPDrawMesh();
   void ToggleCPAlgorithm();
   void MoveLevelSurf(int);
   void NumberOfLevelSurf(int);
   virtual void EventUpdateColors();
   virtual void UpdateLevelLines()
   { PrepareLines(); PrepareCuttingPlaneLines(); }
   virtual void UpdateValueRange(bool prepare);

   virtual void SetDrawMesh(int i)
   {
      if (drawmesh != i % 3)
      {
         drawmesh = i % 3;
         PrepareLines();
      }
   }
   virtual int GetDrawMesh() { return drawmesh; }
};

#endif
<commit_msg>make style<commit_after>// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-443271.
//
// This file is part of the GLVis visualization tool and library. For more
// information and source code availability see https://glvis.org.
//
// GLVis is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.

#ifndef GLVIS_VSSOLUTION_3D_HPP
#define GLVIS_VSSOLUTION_3D_HPP

#include "mfem.hpp"
#include "gl/types.hpp"
#include <map>
using namespace mfem;

class VisualizationSceneSolution3d : public VisualizationSceneScalarData
{
protected:

   int drawmesh, drawelems, shading, draworder;
   int cplane;
   int cp_drawmesh, cp_drawelems, drawlsurf;
   // Algorithm used to draw the cutting plane when shading is 2 and cplane is 1
   // 0 - slower, more accurate algorithm for curved meshes (default)
   // 1 - faster algorithm suitable for meshes with planar faces
   int cp_algo;

   gl3::GlDrawable disp_buf;
   gl3::GlDrawable line_buf;
   gl3::GlDrawable cplane_buf;
   gl3::GlDrawable cplines_buf;
   gl3::GlDrawable lsurf_buf;
   gl3::GlDrawable other_buf;
   gl3::GlDrawable order_buf, order_noarrow_buf;

   double *node_pos;

   int nlevels;
   Array<double> levels;

   GridFunction *GridF;

   void Init();

   void GetFaceNormals(const int FaceNo, const int side,
                       const IntegrationRule &ir, DenseMatrix &normals);

   void DrawRefinedSurf (int n, double *points, int elem, int func,
                         int part = -1);
   void DrawRefinedSurf (int n, DenseMatrix &pointmat,
                         Vector &values, Array<int> &RefGeoms);
   void DrawRefinedSurfLevelLines (int n, DenseMatrix &pointmat,
                                   Vector &values, Array<int> &RefGeoms);
   void DrawRefinedSurfEdges (int n, DenseMatrix &pointmat,
                              Vector &values, Array<int> &RefEdges,
                              int part = -1);
   void LiftRefinedSurf (int n, DenseMatrix &pointmat,
                         Vector &values, int *RG);
   void DrawTetLevelSurf(gl3::GlDrawable& target, const DenseMatrix &verts,
                         const Vector &vals,
                         const int *ind, const Array<double> &levels,
                         const DenseMatrix *grad = NULL);

   static int GetPyramidFaceSplits(const Array<bool> &quad_diag,
                                   const Array<int> &faces,
                                   const Array<int> &ofaces);
   void DrawRefinedPyramidLevelSurf(gl3::GlDrawable& target,
                                    const DenseMatrix &verts,
                                    const Vector &vals, const int *RG,
                                    const int np, const int face_splits,
                                    const DenseMatrix *grad = NULL);

   static int GetWedgeFaceSplits(const Array<bool> &quad_diag,
                                 const Array<int> &faces,
                                 const Array<int> &ofaces);
   void DrawRefinedWedgeLevelSurf(gl3::GlDrawable& target,
                                  const DenseMatrix &verts,
                                  const Vector &vals, const int *RG,
                                  const int np, const int face_splits,
                                  const DenseMatrix *grad = NULL);

   static int GetHexFaceSplits(const Array<bool> &quad_diag,
                               const Array<int> &faces,
                               const Array<int> &ofaces);
   void DrawRefinedHexLevelSurf(gl3::GlDrawable& target,
                                const DenseMatrix &verts,
                                const Vector &vals, const int *RG,
                                const int nh, const int face_splits,
                                const DenseMatrix *grad = NULL);

   int GetAutoRefineFactor();

   bool CheckPositions(Array<int> &vertices) const
   {
      int n = 0;
      for (int j = 0; j < vertices.Size(); j++)
      {
         if (node_pos[vertices[j]] >= 0.0) { n++; }
      }
      return (n < vertices.Size());
   }

public:
   int TimesToRefine;
   double FaceShiftScale;

   Array<int> bdr_attr_to_show;

   VisualizationSceneSolution3d();
   VisualizationSceneSolution3d(Mesh & m, Vector & s);

   void SetGridFunction (GridFunction *gf) { GridF = gf; }

   void NewMeshAndSolution(Mesh *new_m, Vector *new_sol,
                           GridFunction *new_u = NULL);

   virtual ~VisualizationSceneSolution3d();

   virtual std::string GetHelpString() const;

   virtual void FindNewBox(bool prepare);
   virtual void FindNewValueRange(bool prepare);

   virtual void PrepareRuler()
   { VisualizationSceneScalarData::PrepareRuler(false); }
   virtual void PrepareFlat();
   virtual void PrepareLines();
   virtual void Prepare();
   virtual void PrepareOrderingCurve();
   virtual void PrepareOrderingCurve1(gl3::GlDrawable& buf, bool arrows,
                                      bool color);
   virtual gl3::SceneInfo GetSceneObjs();

   void ToggleDrawElems()
   { drawelems = !drawelems; Prepare(); }

   void ToggleDrawMesh();

   // 0 - none, 1 - no arrows (color), 2 - with arrows (color),
   //           3 - no arrows (black), 4 - with arrows (black)
   void ToggleDrawOrdering() { draworder = (draworder+1)%5; }

   void ToggleShading();
   int GetShading() { return shading; };
   virtual void SetShading(int, bool);
   virtual void SetRefineFactors(int, int);
   virtual void AutoRefine();
   virtual void ToggleAttributes(Array<int> &attr_list);

   void FindNodePos();

   void CuttingPlaneFunc (int type);
   // func: 0 - draw surface, 1 - draw level lines
   void CutRefinedElement(gl3::GlDrawable& target,
                          const DenseMatrix &verts, const Vector &vert_dist,
                          const Vector &vals, const Geometry::Type geom,
                          const int *elems, int num_elems, int func);
   void CutRefinedFace(gl3::GlDrawable& target,
                       const DenseMatrix &verts, const Vector &vert_dist,
                       const Vector &vals, const Geometry::Type geom,
                       const int *faces, int num_faces);
   void CPPrepare();
   void CPMoved();
   void PrepareFlat2();
   void PrepareLines2();
   virtual void PrepareCuttingPlane();
   void PrepareCuttingPlane2();
   void PrepareCuttingPlaneLines();
   void PrepareCuttingPlaneLines2();
   void PrepareLevelSurf();
   void ToggleCuttingPlane();
   void ToggleCPDrawElems();
   void ToggleCPDrawMesh();
   void ToggleCPAlgorithm();
   void MoveLevelSurf(int);
   void NumberOfLevelSurf(int);
   virtual void EventUpdateColors();
   virtual void UpdateLevelLines()
   { PrepareLines(); PrepareCuttingPlaneLines(); }
   virtual void UpdateValueRange(bool prepare);

   virtual void SetDrawMesh(int i)
   {
      if (drawmesh != i % 3)
      {
         drawmesh = i % 3;
         PrepareLines();
      }
   }
   virtual int GetDrawMesh() { return drawmesh; }
};

#endif
<|endoftext|>


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

#include "chrome/renderer/devtools_agent_filter.h"

#include "base/message_loop.h"
#include "chrome/common/devtools_messages.h"
#include "chrome/common/render_messages.h"
#include "chrome/renderer/devtools_agent.h"
#include "chrome/renderer/plugin_channel_host.h"
#include "chrome/renderer/render_view.h"
#include "third_party/WebKit/WebKit/chromium/public/WebDevToolsAgent.h"
#include "third_party/WebKit/WebKit/chromium/public/WebDevToolsMessageData.h"
#include "third_party/WebKit/WebKit/chromium/public/WebString.h"
#include "webkit/glue/devtools_message_data.h"

using WebKit::WebDevToolsAgent;
using WebKit::WebString;

// static
void DevToolsAgentFilter::DispatchMessageLoop() {
  MessageLoop* current = MessageLoop::current();
  bool old_state = current->NestableTasksAllowed();
  current->SetNestableTasksAllowed(true);
  current->RunAllPending();
  current->SetNestableTasksAllowed(old_state);
}

// static
IPC::Channel* DevToolsAgentFilter::channel_ = NULL;
// static
int DevToolsAgentFilter::current_routing_id_ = 0;

DevToolsAgentFilter::DevToolsAgentFilter()
    : message_handled_(false) {
  WebDevToolsAgent::setMessageLoopDispatchHandler(
      &DevToolsAgentFilter::DispatchMessageLoop);
}

DevToolsAgentFilter::~DevToolsAgentFilter() {
}

bool DevToolsAgentFilter::OnMessageReceived(const IPC::Message& message) {
  // Dispatch debugger commands directly from IO.
  message_handled_ = true;
  current_routing_id_ = message.routing_id();
  IPC_BEGIN_MESSAGE_MAP(DevToolsAgentFilter, message)
    IPC_MESSAGE_HANDLER(DevToolsAgentMsg_DebuggerCommand, OnDebuggerCommand)
    IPC_MESSAGE_HANDLER(DevToolsAgentMsg_DebuggerPauseScript,
                        OnDebuggerPauseScript)
    IPC_MESSAGE_HANDLER(DevToolsAgentMsg_RpcMessage, OnRpcMessage)
    IPC_MESSAGE_UNHANDLED(message_handled_ = false)
  IPC_END_MESSAGE_MAP()
  return message_handled_;
}

void DevToolsAgentFilter::OnDebuggerCommand(const std::string& command) {
  WebDevToolsAgent::executeDebuggerCommand(
      WebString::fromUTF8(command), current_routing_id_);
}

void DevToolsAgentFilter::OnDebuggerPauseScript() {
  WebDevToolsAgent::debuggerPauseScript();
}

void DevToolsAgentFilter::OnRpcMessage(const DevToolsMessageData& data) {
  message_handled_ = WebDevToolsAgent::dispatchMessageFromFrontendOnIOThread(
      data.ToWebDevToolsMessageData());
}

// static
void DevToolsAgentFilter::SendRpcMessage(const DevToolsMessageData& data) {
  IPC::Message* m = new ViewHostMsg_ForwardToDevToolsClient(
      current_routing_id_,
      DevToolsClientMsg_RpcMessage(data));
  channel_->Send(m);
}
<commit_msg>Make WebDevToolsAgentClient::sendMessageToFrontendOnIOThread virtual.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/renderer/devtools_agent_filter.h"

#include "base/message_loop.h"
#include "chrome/common/devtools_messages.h"
#include "chrome/common/render_messages.h"
#include "chrome/renderer/devtools_agent.h"
#include "chrome/renderer/plugin_channel_host.h"
#include "chrome/renderer/render_view.h"
#include "third_party/WebKit/WebKit/chromium/public/WebDevToolsAgent.h"
#include "third_party/WebKit/WebKit/chromium/public/WebDevToolsMessageData.h"
#include "third_party/WebKit/WebKit/chromium/public/WebString.h"
#include "webkit/glue/devtools_message_data.h"

using WebKit::WebDevToolsAgent;
using WebKit::WebDevToolsMessageData;
using WebKit::WebDevToolsMessageTransport;
using WebKit::WebString;

// static
void DevToolsAgentFilter::DispatchMessageLoop() {
  MessageLoop* current = MessageLoop::current();
  bool old_state = current->NestableTasksAllowed();
  current->SetNestableTasksAllowed(true);
  current->RunAllPending();
  current->SetNestableTasksAllowed(old_state);
}

// static
IPC::Channel* DevToolsAgentFilter::channel_ = NULL;
// static
int DevToolsAgentFilter::current_routing_id_ = 0;

DevToolsAgentFilter::DevToolsAgentFilter()
    : message_handled_(false) {
  WebDevToolsAgent::setMessageLoopDispatchHandler(
      &DevToolsAgentFilter::DispatchMessageLoop);
}

DevToolsAgentFilter::~DevToolsAgentFilter() {
}

bool DevToolsAgentFilter::OnMessageReceived(const IPC::Message& message) {
  // Dispatch debugger commands directly from IO.
  message_handled_ = true;
  current_routing_id_ = message.routing_id();
  IPC_BEGIN_MESSAGE_MAP(DevToolsAgentFilter, message)
    IPC_MESSAGE_HANDLER(DevToolsAgentMsg_DebuggerCommand, OnDebuggerCommand)
    IPC_MESSAGE_HANDLER(DevToolsAgentMsg_DebuggerPauseScript,
                        OnDebuggerPauseScript)
    IPC_MESSAGE_HANDLER(DevToolsAgentMsg_RpcMessage, OnRpcMessage)
    IPC_MESSAGE_UNHANDLED(message_handled_ = false)
  IPC_END_MESSAGE_MAP()
  return message_handled_;
}

void DevToolsAgentFilter::OnDebuggerCommand(const std::string& command) {
  WebDevToolsAgent::executeDebuggerCommand(
      WebString::fromUTF8(command), current_routing_id_);
}

void DevToolsAgentFilter::OnDebuggerPauseScript() {
  WebDevToolsAgent::debuggerPauseScript();
}

namespace {

class WebDevToolsMessageTransportImpl : public WebDevToolsMessageTransport {
 public:
  void sendMessageToFrontendOnIOThread(const WebDevToolsMessageData& data) {
    DevToolsAgentFilter::SendRpcMessage(DevToolsMessageData(data));
  }
};

}  // namespace

void DevToolsAgentFilter::OnRpcMessage(const DevToolsMessageData& data) {
  WebDevToolsMessageTransportImpl transport;
  message_handled_ = WebDevToolsAgent::dispatchMessageFromFrontendOnIOThread(
      &transport,
      data.ToWebDevToolsMessageData());
}

// static
void DevToolsAgentFilter::SendRpcMessage(const DevToolsMessageData& data) {
  IPC::Message* m = new ViewHostMsg_ForwardToDevToolsClient(
      current_routing_id_,
      DevToolsClientMsg_RpcMessage(data));
  channel_->Send(m);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: giflzwc.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 15:41:33 $
 *
 *  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_goodies.hxx"

#include <tools/stream.hxx>
#include "giflzwc.hxx"

// ----------------------------
// - GIFImageDataOutputStream -
// ----------------------------

class GIFImageDataOutputStream
{
private:

    void        FlushBlockBuf();
    inline void FlushBitsBufsFullBytes();

    SvStream&   rStream;
    BYTE*       pBlockBuf;
    BYTE        nBlockBufSize;
    ULONG       nBitsBuf;
    USHORT      nBitsBufSize;

public:

                GIFImageDataOutputStream( SvStream & rGIF, BYTE nLZWDataSize );
                ~GIFImageDataOutputStream();

    inline void WriteBits( USHORT nCode, USHORT nCodeLen );
};

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

inline void GIFImageDataOutputStream::FlushBitsBufsFullBytes()
{
    while (nBitsBufSize>=8)
    {
        if( nBlockBufSize==255 )
            FlushBlockBuf();

        pBlockBuf[nBlockBufSize++] = (BYTE) nBitsBuf;
        nBitsBuf >>= 8;
        nBitsBufSize -= 8;
    }
}

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

inline void GIFImageDataOutputStream::WriteBits( USHORT nCode, USHORT nCodeLen )
{
    if( nBitsBufSize+nCodeLen>32 )
        FlushBitsBufsFullBytes();

    nBitsBuf |= (ULONG) nCode << nBitsBufSize;
    nBitsBufSize += nCodeLen;
}

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

GIFImageDataOutputStream::GIFImageDataOutputStream( SvStream & rGIF, BYTE nLZWDataSize ) :
        rStream(rGIF)
{
    pBlockBuf = new BYTE[ 255 ];
    nBlockBufSize = 0;
    nBitsBufSize = 0;
    nBitsBuf = 0;
    rStream << nLZWDataSize;
}

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

GIFImageDataOutputStream::~GIFImageDataOutputStream()
{
    WriteBits(0,7);
    FlushBitsBufsFullBytes();
    FlushBlockBuf();
    rStream << (BYTE)0;
    delete[] pBlockBuf;
}

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

void GIFImageDataOutputStream::FlushBlockBuf()
{
    if( nBlockBufSize )
    {
        rStream << (BYTE) nBlockBufSize;
        rStream.Write( pBlockBuf,nBlockBufSize );
        nBlockBufSize = 0;
    }
}

// -------------------
// - GIFLZWCTreeNode -
// -------------------

struct GIFLZWCTreeNode
{

    GIFLZWCTreeNode*    pBrother;       // naechster Knoten, der den selben Vater hat
    GIFLZWCTreeNode*    pFirstChild;    // erster Sohn
    USHORT              nCode;          // Der Code fuer den String von Pixelwerten, der sich ergibt, wenn
    USHORT              nValue;         // Der Pixelwert
};

// --------------------
// - GIFLZWCompressor -
// --------------------

GIFLZWCompressor::GIFLZWCompressor()
{
    pIDOS=NULL;
}

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

GIFLZWCompressor::~GIFLZWCompressor()
{
    if (pIDOS!=NULL) EndCompression();
}

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

void GIFLZWCompressor::StartCompression( SvStream& rGIF, USHORT nPixelSize )
{
    if( !pIDOS )
    {
        USHORT i;

        nDataSize = nPixelSize;

        if( nDataSize < 2 )
            nDataSize=2;

        nClearCode=1<<nDataSize;
        nEOICode=nClearCode+1;
        nTableSize=nEOICode+1;
        nCodeSize=nDataSize+1;

        pIDOS=new GIFImageDataOutputStream(rGIF,(BYTE)nDataSize);
        pTable=new GIFLZWCTreeNode[4096];

        for (i=0; i<4096; i++)
        {
            pTable[i].pBrother = pTable[i].pFirstChild = NULL;
            pTable[i].nValue = (BYTE) ( pTable[i].nCode = i );
        }

        pPrefix = NULL;
        pIDOS->WriteBits( nClearCode,nCodeSize );
    }
}

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

void GIFLZWCompressor::Compress( HPBYTE pSrc, ULONG nSize )
{
    if( pIDOS )
    {
        GIFLZWCTreeNode*    p;
        USHORT              i;
        BYTE                nV;

        if( !pPrefix && nSize )
        {
            pPrefix=pTable+(*pSrc++);
            nSize--;
        }

        while( nSize )
        {
            nSize--;
            nV=*pSrc++;
            for( p=pPrefix->pFirstChild; p!=NULL; p=p->pBrother )
            {
                if (p->nValue==nV)
                    break;
            }

            if( p)
                pPrefix=p;
            else
            {
                pIDOS->WriteBits(pPrefix->nCode,nCodeSize);

                if (nTableSize==4096)
                {
                    pIDOS->WriteBits(nClearCode,nCodeSize);

                    for (i=0; i<nClearCode; i++)
                        pTable[i].pFirstChild=NULL;

                    nCodeSize=nDataSize+1;
                    nTableSize=nEOICode+1;
                }
                else
                {
                    if(nTableSize==(USHORT)(1<<nCodeSize))
                        nCodeSize++;

                    p=pTable+(nTableSize++);
                    p->pBrother=pPrefix->pFirstChild;
                    pPrefix->pFirstChild=p;
                    p->nValue=nV;
                    p->pFirstChild=NULL;
                }

                pPrefix=pTable+nV;
            }
        }
    }
}

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

void GIFLZWCompressor::EndCompression()
{
    if( pIDOS )
    {
        if( pPrefix )
            pIDOS->WriteBits(pPrefix->nCode,nCodeSize);

        pIDOS->WriteBits( nEOICode,nCodeSize );
        delete[] pTable;
        delete pIDOS;
        pIDOS=NULL;
    }
}
<commit_msg>INTEGRATION: CWS sb59 (1.2.112); FILE MERGED 2006/08/07 14:31:07 sb 1.2.112.1: #i67487# Made code warning-free (wntmsci10).<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: giflzwc.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2006-10-12 15:33:45 $
 *
 *  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_goodies.hxx"

#include <tools/stream.hxx>
#include "giflzwc.hxx"

// ----------------------------
// - GIFImageDataOutputStream -
// ----------------------------

class GIFImageDataOutputStream
{
private:

    void        FlushBlockBuf();
    inline void FlushBitsBufsFullBytes();

    SvStream&   rStream;
    BYTE*       pBlockBuf;
    BYTE        nBlockBufSize;
    ULONG       nBitsBuf;
    USHORT      nBitsBufSize;

public:

                GIFImageDataOutputStream( SvStream & rGIF, BYTE nLZWDataSize );
                ~GIFImageDataOutputStream();

    inline void WriteBits( USHORT nCode, USHORT nCodeLen );
};

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

inline void GIFImageDataOutputStream::FlushBitsBufsFullBytes()
{
    while (nBitsBufSize>=8)
    {
        if( nBlockBufSize==255 )
            FlushBlockBuf();

        pBlockBuf[nBlockBufSize++] = (BYTE) nBitsBuf;
        nBitsBuf >>= 8;
        nBitsBufSize -= 8;
    }
}

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

inline void GIFImageDataOutputStream::WriteBits( USHORT nCode, USHORT nCodeLen )
{
    if( nBitsBufSize+nCodeLen>32 )
        FlushBitsBufsFullBytes();

    nBitsBuf |= (ULONG) nCode << nBitsBufSize;
    nBitsBufSize = nBitsBufSize + nCodeLen;
}

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

GIFImageDataOutputStream::GIFImageDataOutputStream( SvStream & rGIF, BYTE nLZWDataSize ) :
        rStream(rGIF)
{
    pBlockBuf = new BYTE[ 255 ];
    nBlockBufSize = 0;
    nBitsBufSize = 0;
    nBitsBuf = 0;
    rStream << nLZWDataSize;
}

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

GIFImageDataOutputStream::~GIFImageDataOutputStream()
{
    WriteBits(0,7);
    FlushBitsBufsFullBytes();
    FlushBlockBuf();
    rStream << (BYTE)0;
    delete[] pBlockBuf;
}

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

void GIFImageDataOutputStream::FlushBlockBuf()
{
    if( nBlockBufSize )
    {
        rStream << (BYTE) nBlockBufSize;
        rStream.Write( pBlockBuf,nBlockBufSize );
        nBlockBufSize = 0;
    }
}

// -------------------
// - GIFLZWCTreeNode -
// -------------------

struct GIFLZWCTreeNode
{

    GIFLZWCTreeNode*    pBrother;       // naechster Knoten, der den selben Vater hat
    GIFLZWCTreeNode*    pFirstChild;    // erster Sohn
    USHORT              nCode;          // Der Code fuer den String von Pixelwerten, der sich ergibt, wenn
    USHORT              nValue;         // Der Pixelwert
};

// --------------------
// - GIFLZWCompressor -
// --------------------

GIFLZWCompressor::GIFLZWCompressor()
{
    pIDOS=NULL;
}

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

GIFLZWCompressor::~GIFLZWCompressor()
{
    if (pIDOS!=NULL) EndCompression();
}

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

void GIFLZWCompressor::StartCompression( SvStream& rGIF, USHORT nPixelSize )
{
    if( !pIDOS )
    {
        USHORT i;

        nDataSize = nPixelSize;

        if( nDataSize < 2 )
            nDataSize=2;

        nClearCode=1<<nDataSize;
        nEOICode=nClearCode+1;
        nTableSize=nEOICode+1;
        nCodeSize=nDataSize+1;

        pIDOS=new GIFImageDataOutputStream(rGIF,(BYTE)nDataSize);
        pTable=new GIFLZWCTreeNode[4096];

        for (i=0; i<4096; i++)
        {
            pTable[i].pBrother = pTable[i].pFirstChild = NULL;
            pTable[i].nValue = (BYTE) ( pTable[i].nCode = i );
        }

        pPrefix = NULL;
        pIDOS->WriteBits( nClearCode,nCodeSize );
    }
}

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

void GIFLZWCompressor::Compress( HPBYTE pSrc, ULONG nSize )
{
    if( pIDOS )
    {
        GIFLZWCTreeNode*    p;
        USHORT              i;
        BYTE                nV;

        if( !pPrefix && nSize )
        {
            pPrefix=pTable+(*pSrc++);
            nSize--;
        }

        while( nSize )
        {
            nSize--;
            nV=*pSrc++;
            for( p=pPrefix->pFirstChild; p!=NULL; p=p->pBrother )
            {
                if (p->nValue==nV)
                    break;
            }

            if( p)
                pPrefix=p;
            else
            {
                pIDOS->WriteBits(pPrefix->nCode,nCodeSize);

                if (nTableSize==4096)
                {
                    pIDOS->WriteBits(nClearCode,nCodeSize);

                    for (i=0; i<nClearCode; i++)
                        pTable[i].pFirstChild=NULL;

                    nCodeSize=nDataSize+1;
                    nTableSize=nEOICode+1;
                }
                else
                {
                    if(nTableSize==(USHORT)(1<<nCodeSize))
                        nCodeSize++;

                    p=pTable+(nTableSize++);
                    p->pBrother=pPrefix->pFirstChild;
                    pPrefix->pFirstChild=p;
                    p->nValue=nV;
                    p->pFirstChild=NULL;
                }

                pPrefix=pTable+nV;
            }
        }
    }
}

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

void GIFLZWCompressor::EndCompression()
{
    if( pIDOS )
    {
        if( pPrefix )
            pIDOS->WriteBits(pPrefix->nCode,nCodeSize);

        pIDOS->WriteBits( nEOICode,nCodeSize );
        delete[] pTable;
        delete pIDOS;
        pIDOS=NULL;
    }
}
<|endoftext|>