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

  Program: Bender

  Copyright (c) Kitware Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0.txt

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

=========================================================================*/

// Bender includes
#include "CreateTetrahedralMeshCLP.h"
#include "benderIOUtils.h"

// ITK includes
#include "itkBinaryThresholdImageFilter.h"
#include "itkCastImageFilter.h"
#include "itkImageFileWriter.h"
#include "itkImageRegionIterator.h"
#include "itkRelabelComponentImageFilter.h"
#include "itkConstantPadImageFilter.h"

// Slicer includes
#include "itkPluginUtilities.h"

// VTK includes
#include <vtkCleanPolyData.h>
#include <vtkCellArray.h>
#include <vtkCellData.h>
#include <vtkTetra.h>
#include <vtkPolyData.h>
#include <vtkPolyDataWriter.h>
#include <vtkNew.h>
#include <vtkSmartPointer.h>

// Cleaver includes
#include <Cleaver/Cleaver.h>
#include <Cleaver/InverseField.h>
#include <Cleaver/PaddedVolume.h>
#include <Cleaver/ScalarField.h>
#include <Cleaver/Volume.h>
#include <LabelMapField.h>

// Use an anonymous namespace to keep class types and function names
// from colliding when module is used as shared object module.  Every
// thing should be in an anonymous namespace except for the module
// entry point, e.g. main()
//
namespace
{
template <class T> int DoIt( int argc, char * argv[] );

std::vector<Cleaver::LabelMapField::ImageType::Pointer> SplitLabelMaps(
  int    argc,
  char * argv[]);
} // end of anonymous namespace

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

  PARSE_ARGS;

  itk::ImageIOBase::IOPixelType     pixelType;
  itk::ImageIOBase::IOComponentType componentType;

  try
    {
    itk::GetImageType(InputVolume, pixelType, componentType);

    switch( componentType )
      {
    case itk::ImageIOBase::UCHAR:
      return DoIt<unsigned char>( argc, argv );
      break;
    case itk::ImageIOBase::CHAR:
      return DoIt<char>( argc, argv );
      break;
    case itk::ImageIOBase::USHORT:
      return DoIt<unsigned short>( argc, argv );
      break;
    case itk::ImageIOBase::SHORT:
      return DoIt<short>( argc, argv );
      break;
    case itk::ImageIOBase::UINT:
      return DoIt<unsigned int>( argc, argv );
      break;
    case itk::ImageIOBase::INT:
      return DoIt<int>( argc, argv );
      break;
    case itk::ImageIOBase::ULONG:
      return DoIt<unsigned long>( argc, argv );
      break;
    case itk::ImageIOBase::LONG:
      return DoIt<long>( argc, argv );
      break;
    case itk::ImageIOBase::FLOAT:
      return DoIt<float>( argc, argv );
      break;
    case itk::ImageIOBase::DOUBLE:
      return DoIt<double>( argc, argv );
      break;
    case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE:
    default:
      std::cerr << "Unknown component type: " << componentType << std::endl;
      break;
      }
    }

  catch( itk::ExceptionObject & excep )
    {
    std::cerr << argv[0] << ": exception caught !" << std::endl;
    std::cerr << excep << std::endl;
    return EXIT_FAILURE;
    }
  return EXIT_SUCCESS;
}

// Use an anonymous namespace to keep class types and function names
// from colliding when module is used as shared object module.  Every
// thing should be in an anonymous namespace except for the module
// entry point, e.g. main()
//
namespace
{
std::vector<Cleaver::LabelMapField::ImageType::Pointer >
SplitLabelMaps(Cleaver::LabelMapField::ImageType *image)
{

  typedef Cleaver::LabelMapField::ImageType LabelImageType;
  typedef itk::RelabelComponentImageFilter<LabelImageType,
                                           LabelImageType> RelabelFilterType;
  typedef itk::BinaryThresholdImageFilter<LabelImageType,
                                          LabelImageType> ThresholdFilterType;
  typedef itk::ImageFileWriter<LabelImageType> ImageWriterType;

  // Assign continuous labels to the connected components, background is
  // considered to be 0 and will be ignored in the relabeling process.
  RelabelFilterType::Pointer relabelFilter = RelabelFilterType::New();
  relabelFilter->SetInput( image );
  relabelFilter->Update();

  std::cout << "Total Number of Labels: " <<
    relabelFilter->GetNumberOfObjects() << std::endl;

  // Extract the labels
  typedef RelabelFilterType::LabelType LabelType;
  ThresholdFilterType::Pointer skinThresholdFilter =
    ThresholdFilterType::New();

  // Create a list of images corresponding to labels
  std::vector<LabelImageType::Pointer> labels;

  // The skin label will become background for internal (smaller) organs
  skinThresholdFilter->SetInput(relabelFilter->GetOutput());
  skinThresholdFilter->SetLowerThreshold(1);
  skinThresholdFilter->SetUpperThreshold(relabelFilter->GetNumberOfObjects()+1);
  skinThresholdFilter->SetInsideValue(-1);
  skinThresholdFilter->SetOutsideValue(0);
  skinThresholdFilter->Update();
  labels.push_back(skinThresholdFilter->GetOutput());

  for (LabelType i = 1, end = relabelFilter->GetNumberOfObjects()+1; i < end;
       ++i)
    {
    ThresholdFilterType::Pointer organThresholdFilter =
      ThresholdFilterType::New();
    organThresholdFilter->SetInput(relabelFilter->GetOutput());
    organThresholdFilter->SetLowerThreshold(i);
    organThresholdFilter->SetUpperThreshold(i);
    organThresholdFilter->SetInsideValue(i);
    organThresholdFilter->SetOutsideValue(-1);
    organThresholdFilter->Update();

    labels.push_back(organThresholdFilter->GetOutput());
    }

  return labels;
}

template <class T>
int DoIt( int argc, char * argv[] )
{

  PARSE_ARGS;

  typedef Cleaver::LabelMapField::ImageType LabelImageType;
  typedef T InputPixelType;
  typedef itk::Image<InputPixelType,3> InputImageType;
  typedef itk::CastImageFilter<InputImageType,
                               LabelImageType> CastFilterType;
  typedef itk::ImageFileReader<InputImageType> ReaderType;
  typedef itk::ConstantPadImageFilter<InputImageType,
                                      InputImageType> ConstantPadType;

  typename CastFilterType::Pointer castingFilter = CastFilterType::New();
  typename ReaderType::Pointer reader            = ReaderType::New();
  reader->SetFileName( InputVolume );
  reader->Update();
//   if(padding)
//     {
//     typename ConstantPadType::Pointer paddingFilter = ConstantPadType::New();
//     paddingFilter->SetInput(reader->GetOutput());
//     typename InputImageType::SizeType lowerExtendRegion;
//     lowerExtendRegion[0] = 1;
//     lowerExtendRegion[1] = 1;
//
//     typename InputImageType::SizeType upperExtendRegion;
//     upperExtendRegion[0] = 1;
//     upperExtendRegion[1] = 1;
//
//     paddingFilter->SetPadLowerBound(lowerExtendRegion);
//     paddingFilter->SetPadUpperBound(upperExtendRegion);
//     paddingFilter->SetConstant(0);
//     paddingFilter->Update();
//     castingFilter->SetInput(paddingFilter->GetOutput());
//     }
//   else
//     {
  castingFilter->SetInput(reader->GetOutput());
//     }

  std::vector<Cleaver::ScalarField*> labelMaps;

  std::vector<LabelImageType::Pointer> labels =
    SplitLabelMaps(castingFilter->GetOutput());

  std::cout << "Total labels found:  " << labels.size() << std::endl;
  for(size_t i = 0; i < labels.size(); ++i)
    {
    labelMaps.push_back(new Cleaver::LabelMapField(labels[i]));
    static_cast<Cleaver::LabelMapField*>(labelMaps.back())->
      SetGenerateDataFromLabels(true);
    }

  if(labelMaps.empty())
    {
    std::cerr << "Failed to load image data. Terminating." << std::endl;
    return 0;
    }
  if(labelMaps.size() < 2)
    {
    labelMaps.push_back(new Cleaver::InverseField(labelMaps[0]));
    }

  Cleaver::AbstractVolume *volume = new Cleaver::Volume(labelMaps);

  if(padding)
    volume = new Cleaver::PaddedVolume(volume);

  std::cout << "Creating Mesh with Volume Size " << volume->size().toString() <<
    std::endl;

  //--------------------------------
  //  Create Mesher & TetMesh
  //--------------------------------
  Cleaver::TetMesh *cleaverMesh =
    Cleaver::createMeshFromVolume(volume, verbose);

  //------------------
  //  Compute Angles
  //------------------
  if(verbose)
    {
    cleaverMesh->computeAngles();
    std::cout.precision(12);
    std::cout << "Worst Angles:" << std::endl;
    std::cout << "min: " << cleaverMesh->min_angle << std::endl;
    std::cout << "max: " << cleaverMesh->max_angle << std::endl;
    }

  const int            airLabel = 1;
  vtkNew<vtkCellArray> meshTetras;
  vtkNew<vtkIntArray>  cellData;
  for(size_t i = 0, end = cleaverMesh->tets.size(); i < end; ++i)
    {
    int label = cleaverMesh->tets[i]->mat_label+1;
    if(label == airLabel)
      {
      continue;
      }
    vtkNew<vtkTetra> meshTetra;
    meshTetra->GetPointIds()->SetId(0,
      cleaverMesh->tets[i]->verts[0]->tm_v_index);
    meshTetra->GetPointIds()->SetId(1,
      cleaverMesh->tets[i]->verts[1]->tm_v_index);
    meshTetra->GetPointIds()->SetId(2,
      cleaverMesh->tets[i]->verts[2]->tm_v_index);
    meshTetra->GetPointIds()->SetId(3,
      cleaverMesh->tets[i]->verts[3]->tm_v_index);
    meshTetras->InsertNextCell(meshTetra.GetPointer());
    cellData->InsertNextValue(label);
    }

  vtkNew<vtkPoints> points;
  points->SetNumberOfPoints(cleaverMesh->verts.size());
  for (size_t i = 0, end = cleaverMesh->verts.size(); i < end; ++i)
    {
    Cleaver::vec3 &pos = cleaverMesh->verts[i]->pos();
    points->SetPoint(i, pos.x,pos.y,pos.z);
    }

  vtkSmartPointer<vtkPolyData> vtkMesh = vtkSmartPointer<vtkPolyData>::New();
  vtkMesh->SetPoints(points.GetPointer());
  vtkMesh->SetPolys(meshTetras.GetPointer());
  vtkMesh->GetCellData()->SetScalars(cellData.GetPointer());

  vtkNew<vtkCleanPolyData> cleanFilter;
  cleanFilter->SetInput(vtkMesh);

  bender::IOUtils::WritePolyData(cleanFilter->GetOutput(), OutputMesh);

  return EXIT_SUCCESS;
}

} // end of anonymous namespace

<commit_msg>Keep the input label value for the mesh material<commit_after>/*=========================================================================

  Program: Bender

  Copyright (c) Kitware Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0.txt

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

=========================================================================*/

// Bender includes
#include "CreateTetrahedralMeshCLP.h"
#include "benderIOUtils.h"

// ITK includes
#include "itkBinaryThresholdImageFilter.h"
#include "itkCastImageFilter.h"
#include "itkImageFileWriter.h"
#include "itkImageRegionConstIterator.h"
#include "itkImageRegionIterator.h"
#include "itkRelabelComponentImageFilter.h"
#include "itkConstantPadImageFilter.h"

// Slicer includes
#include "itkPluginUtilities.h"

// VTK includes
#include <vtkCleanPolyData.h>
#include <vtkCellArray.h>
#include <vtkCellData.h>
#include <vtkTetra.h>
#include <vtkPolyData.h>
#include <vtkPolyDataWriter.h>
#include <vtkNew.h>
#include <vtkSmartPointer.h>

// Cleaver includes
#include <Cleaver/Cleaver.h>
#include <Cleaver/InverseField.h>
#include <Cleaver/PaddedVolume.h>
#include <Cleaver/ScalarField.h>
#include <Cleaver/Volume.h>
#include <LabelMapField.h>

// Use an anonymous namespace to keep class types and function names
// from colliding when module is used as shared object module.  Every
// thing should be in an anonymous namespace except for the module
// entry point, e.g. main()
//
namespace
{
template <class T> int DoIt( int argc, char * argv[] );

std::vector<Cleaver::LabelMapField::ImageType::Pointer> SplitLabelMaps(
  int    argc,
  char * argv[]);
} // end of anonymous namespace

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

  PARSE_ARGS;

  itk::ImageIOBase::IOPixelType     pixelType;
  itk::ImageIOBase::IOComponentType componentType;

  try
    {
    itk::GetImageType(InputVolume, pixelType, componentType);

    switch( componentType )
      {
    case itk::ImageIOBase::UCHAR:
      return DoIt<unsigned char>( argc, argv );
      break;
    case itk::ImageIOBase::CHAR:
      return DoIt<char>( argc, argv );
      break;
    case itk::ImageIOBase::USHORT:
      return DoIt<unsigned short>( argc, argv );
      break;
    case itk::ImageIOBase::SHORT:
      return DoIt<short>( argc, argv );
      break;
    case itk::ImageIOBase::UINT:
      return DoIt<unsigned int>( argc, argv );
      break;
    case itk::ImageIOBase::INT:
      return DoIt<int>( argc, argv );
      break;
    case itk::ImageIOBase::ULONG:
      return DoIt<unsigned long>( argc, argv );
      break;
    case itk::ImageIOBase::LONG:
      return DoIt<long>( argc, argv );
      break;
    case itk::ImageIOBase::FLOAT:
      return DoIt<float>( argc, argv );
      break;
    case itk::ImageIOBase::DOUBLE:
      return DoIt<double>( argc, argv );
      break;
    case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE:
    default:
      std::cerr << "Unknown component type: " << componentType << std::endl;
      break;
      }
    }

  catch( itk::ExceptionObject & excep )
    {
    std::cerr << argv[0] << ": exception caught !" << std::endl;
    std::cerr << excep << std::endl;
    return EXIT_FAILURE;
    }
  return EXIT_SUCCESS;
}

// Use an anonymous namespace to keep class types and function names
// from colliding when module is used as shared object module.  Every
// thing should be in an anonymous namespace except for the module
// entry point, e.g. main()
//
namespace
{
std::vector<Cleaver::LabelMapField::ImageType::Pointer >
SplitLabelMaps(Cleaver::LabelMapField::ImageType *image)
{

  typedef Cleaver::LabelMapField::ImageType LabelImageType;
  typedef itk::RelabelComponentImageFilter<LabelImageType,
                                           LabelImageType> RelabelFilterType;
  typedef itk::BinaryThresholdImageFilter<LabelImageType,
                                          LabelImageType> ThresholdFilterType;
  typedef itk::ImageFileWriter<LabelImageType> ImageWriterType;

  // Assign continuous labels to the connected components, background is
  // considered to be 0 and will be ignored in the relabeling process.
  RelabelFilterType::Pointer relabelFilter = RelabelFilterType::New();
  relabelFilter->SetInput( image );
  relabelFilter->Update();

  std::cout << "Total Number of Labels: " <<
    relabelFilter->GetNumberOfObjects() << std::endl;

  // Extract the labels
  typedef RelabelFilterType::LabelType LabelType;
  ThresholdFilterType::Pointer skinThresholdFilter =
    ThresholdFilterType::New();

  // Create a list of images corresponding to labels
  std::vector<LabelImageType::Pointer> labels;

  // The skin label will become background for internal (smaller) organs
  skinThresholdFilter->SetInput(relabelFilter->GetOutput());
  skinThresholdFilter->SetLowerThreshold(1);
  skinThresholdFilter->SetUpperThreshold(relabelFilter->GetNumberOfObjects()+1);
  skinThresholdFilter->SetInsideValue(-1);
  skinThresholdFilter->SetOutsideValue(0);
  skinThresholdFilter->Update();
  labels.push_back(skinThresholdFilter->GetOutput());

  for (LabelType i = 1, end = relabelFilter->GetNumberOfObjects()+1; i < end;
       ++i)
    {
    ThresholdFilterType::Pointer organThresholdFilter =
      ThresholdFilterType::New();
    organThresholdFilter->SetInput(relabelFilter->GetOutput());
    organThresholdFilter->SetLowerThreshold(i);
    organThresholdFilter->SetUpperThreshold(i);
    organThresholdFilter->SetInsideValue(i);
    organThresholdFilter->SetOutsideValue(-1);
    organThresholdFilter->Update();

    labels.push_back(organThresholdFilter->GetOutput());
    }

  return labels;
}

template <class T>
int DoIt( int argc, char * argv[] )
{

  PARSE_ARGS;

  typedef Cleaver::LabelMapField::ImageType LabelImageType;
  typedef T InputPixelType;
  typedef itk::Image<InputPixelType,3> InputImageType;
  typedef itk::CastImageFilter<InputImageType,
                               LabelImageType> CastFilterType;
  typedef itk::ImageFileReader<InputImageType> ReaderType;
  typedef itk::ConstantPadImageFilter<InputImageType,
                                      InputImageType> ConstantPadType;

  typename CastFilterType::Pointer castingFilter = CastFilterType::New();
  typename ReaderType::Pointer reader            = ReaderType::New();
  reader->SetFileName( InputVolume );
  reader->Update();
//   if(padding)
//     {
//     typename ConstantPadType::Pointer paddingFilter = ConstantPadType::New();
//     paddingFilter->SetInput(reader->GetOutput());
//     typename InputImageType::SizeType lowerExtendRegion;
//     lowerExtendRegion[0] = 1;
//     lowerExtendRegion[1] = 1;
//
//     typename InputImageType::SizeType upperExtendRegion;
//     upperExtendRegion[0] = 1;
//     upperExtendRegion[1] = 1;
//
//     paddingFilter->SetPadLowerBound(lowerExtendRegion);
//     paddingFilter->SetPadUpperBound(upperExtendRegion);
//     paddingFilter->SetConstant(0);
//     paddingFilter->Update();
//     castingFilter->SetInput(paddingFilter->GetOutput());
//     }
//   else
//     {
  castingFilter->SetInput(reader->GetOutput());
//     }

  std::vector<Cleaver::ScalarField*> labelMaps;

  std::vector<LabelImageType::Pointer> labels =
    SplitLabelMaps(castingFilter->GetOutput());

  // Get a map from the original labels to the new labels
  std::map<InputPixelType, InputPixelType> originalLabels;

  for(size_t i = 0; i < labels.size(); ++i)
    {
    itk::ImageRegionConstIterator<InputImageType> imageIterator(
      reader->GetOutput(), reader->GetOutput()->GetLargestPossibleRegion());
    itk::ImageRegionConstIterator<LabelImageType> labelsIterator(
      labels[i], labels[i]->GetLargestPossibleRegion());
    bool foundCorrespondence = false;
    while(!imageIterator.IsAtEnd()
      && !labelsIterator.IsAtEnd()
      && !foundCorrespondence)
      {
      if (labelsIterator.Value() > 0)
        {
        originalLabels[labelsIterator.Value()] = imageIterator.Value();
        }

      ++imageIterator;
      ++labelsIterator;
      }
    }

  std::cout << "Total labels found:  " << labels.size() << std::endl;
  for(size_t i = 0; i < labels.size(); ++i)
    {
    labelMaps.push_back(new Cleaver::LabelMapField(labels[i]));
    static_cast<Cleaver::LabelMapField*>(labelMaps.back())->
      SetGenerateDataFromLabels(true);
    }

  if(labelMaps.empty())
    {
    std::cerr << "Failed to load image data. Terminating." << std::endl;
    return 0;
    }
  if(labelMaps.size() < 2)
    {
    labelMaps.push_back(new Cleaver::InverseField(labelMaps[0]));
    }

  Cleaver::AbstractVolume *volume = new Cleaver::Volume(labelMaps);

  if(padding)
    volume = new Cleaver::PaddedVolume(volume);

  std::cout << "Creating Mesh with Volume Size " << volume->size().toString() <<
    std::endl;

  //--------------------------------
  //  Create Mesher & TetMesh
  //--------------------------------
  Cleaver::TetMesh *cleaverMesh =
    Cleaver::createMeshFromVolume(volume, verbose);

  //------------------
  //  Compute Angles
  //------------------
  if(verbose)
    {
    cleaverMesh->computeAngles();
    std::cout.precision(12);
    std::cout << "Worst Angles:" << std::endl;
    std::cout << "min: " << cleaverMesh->min_angle << std::endl;
    std::cout << "max: " << cleaverMesh->max_angle << std::endl;
    }

  const int airLabel = 0;
  int paddedVolumeLabel = labels.size();
  vtkNew<vtkCellArray> meshTetras;
  vtkNew<vtkIntArray>  cellData;
  for(size_t i = 0, end = cleaverMesh->tets.size(); i < end; ++i)
    {
    int label = cleaverMesh->tets[i]->mat_label;

    if(label == airLabel || label == paddedVolumeLabel)
      {
      continue;
      }
    vtkNew<vtkTetra> meshTetra;
    meshTetra->GetPointIds()->SetId(0,
      cleaverMesh->tets[i]->verts[0]->tm_v_index);
    meshTetra->GetPointIds()->SetId(1,
      cleaverMesh->tets[i]->verts[1]->tm_v_index);
    meshTetra->GetPointIds()->SetId(2,
      cleaverMesh->tets[i]->verts[2]->tm_v_index);
    meshTetra->GetPointIds()->SetId(3,
      cleaverMesh->tets[i]->verts[3]->tm_v_index);
    meshTetras->InsertNextCell(meshTetra.GetPointer());
    cellData->InsertNextValue(originalLabels[label]);
    }

  vtkNew<vtkPoints> points;
  points->SetNumberOfPoints(cleaverMesh->verts.size());
  for (size_t i = 0, end = cleaverMesh->verts.size(); i < end; ++i)
    {
    Cleaver::vec3 &pos = cleaverMesh->verts[i]->pos();
    points->SetPoint(i, pos.x,pos.y,pos.z);
    }

  vtkSmartPointer<vtkPolyData> vtkMesh = vtkSmartPointer<vtkPolyData>::New();
  vtkMesh->SetPoints(points.GetPointer());
  vtkMesh->SetPolys(meshTetras.GetPointer());
  vtkMesh->GetCellData()->SetScalars(cellData.GetPointer());

  vtkNew<vtkCleanPolyData> cleanFilter;
  cleanFilter->SetInput(vtkMesh);

  bender::IOUtils::WritePolyData(cleanFilter->GetOutput(), OutputMesh);

  return EXIT_SUCCESS;
}

} // end of anonymous namespace

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: cppinterfaceproxy.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 22:09: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
 *
 ************************************************************************/

#ifndef INCLUDED_BRIDGES_CPP_UNO_SHARED_CPPINTERFACEPROXY_HXX
#define INCLUDED_BRIDGES_CPP_UNO_SHARED_CPPINTERFACEPROXY_HXX

#include "osl/interlck.h"
#include "rtl/ustring.hxx"
#include "sal/types.h"
#include "typelib/typedescription.h"
#include "uno/dispatcher.h"
#include "uno/environment.h"

namespace com { namespace sun { namespace star { namespace uno {
    class XInterface;
} } } }

namespace bridges { namespace cpp_uno { namespace shared {

class Bridge;

/**
 * A cpp proxy wrapping a uno interface.
 */
class CppInterfaceProxy {
public:
    // Interface for Bridge:

    static com::sun::star::uno::XInterface * create(
        Bridge * pBridge, uno_Interface * pUnoI,
        typelib_InterfaceTypeDescription * pTypeDescr,
        rtl::OUString const & rOId) SAL_THROW(());

    static void SAL_CALL free(uno_ExtEnvironment * pEnv, void * pInterface)
        SAL_THROW(());

    // Interface for individual CPP--UNO bridges:

    Bridge * getBridge() { return pBridge; }
    uno_Interface * getUnoI() { return pUnoI; }
    typelib_InterfaceTypeDescription * getTypeDescr() { return pTypeDescr; }
    rtl::OUString getOid() { return oid; }

    // non virtual methods called on incoming vtable calls #1, #2
    void acquireProxy() SAL_THROW(());
    void releaseProxy() SAL_THROW(());

    static CppInterfaceProxy * castInterfaceToProxy(void * pInterface);

private:
    CppInterfaceProxy(CppInterfaceProxy &); // not implemented
    void operator =(CppInterfaceProxy); // not implemented

    CppInterfaceProxy(
        Bridge * pBridge_, uno_Interface * pUnoI_,
        typelib_InterfaceTypeDescription * pTypeDescr_,
        rtl::OUString const & rOId_) SAL_THROW(());

    ~CppInterfaceProxy();

    static com::sun::star::uno::XInterface * castProxyToInterface(
        CppInterfaceProxy * pProxy);

    oslInterlockedCount nRef;
    Bridge * pBridge;

    // mapping information
    uno_Interface * pUnoI; // wrapped interface
    typelib_InterfaceTypeDescription * pTypeDescr;
    rtl::OUString oid;

    void ** vtables[1];
};

} } }

#endif
<commit_msg>INTEGRATION: CWS warnings01 (1.2.100); FILE MERGED 2005/09/22 18:05:06 sb 1.2.100.2: RESYNC: (1.2-1.3); FILE MERGED 2005/09/09 12:37:19 sb 1.2.100.1: #i53898# Made code warning-free.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: cppinterfaceproxy.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 23:38:14 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef INCLUDED_BRIDGES_CPP_UNO_SHARED_CPPINTERFACEPROXY_HXX
#define INCLUDED_BRIDGES_CPP_UNO_SHARED_CPPINTERFACEPROXY_HXX

#include "osl/interlck.h"
#include "rtl/ustring.hxx"
#include "sal/types.h"
#include "typelib/typedescription.h"
#include "uno/dispatcher.h"
#include "uno/environment.h"

namespace com { namespace sun { namespace star { namespace uno {
    class XInterface;
} } } }

namespace bridges { namespace cpp_uno { namespace shared {

class Bridge;

extern "C" typedef void SAL_CALL FreeCppInterfaceProxy(
    uno_ExtEnvironment * pEnv, void * pInterface);
FreeCppInterfaceProxy freeCppInterfaceProxy;

/**
 * A cpp proxy wrapping a uno interface.
 */
class CppInterfaceProxy {
public:
    // Interface for Bridge:

    static com::sun::star::uno::XInterface * create(
        Bridge * pBridge, uno_Interface * pUnoI,
        typelib_InterfaceTypeDescription * pTypeDescr,
        rtl::OUString const & rOId) SAL_THROW(());

    // Interface for individual CPP--UNO bridges:

    Bridge * getBridge() { return pBridge; }
    uno_Interface * getUnoI() { return pUnoI; }
    typelib_InterfaceTypeDescription * getTypeDescr() { return pTypeDescr; }
    rtl::OUString getOid() { return oid; }

    // non virtual methods called on incoming vtable calls #1, #2
    void acquireProxy() SAL_THROW(());
    void releaseProxy() SAL_THROW(());

    static CppInterfaceProxy * castInterfaceToProxy(void * pInterface);

private:
    CppInterfaceProxy(CppInterfaceProxy &); // not implemented
    void operator =(CppInterfaceProxy); // not implemented

    CppInterfaceProxy(
        Bridge * pBridge_, uno_Interface * pUnoI_,
        typelib_InterfaceTypeDescription * pTypeDescr_,
        rtl::OUString const & rOId_) SAL_THROW(());

    ~CppInterfaceProxy();

    static com::sun::star::uno::XInterface * castProxyToInterface(
        CppInterfaceProxy * pProxy);

    oslInterlockedCount nRef;
    Bridge * pBridge;

    // mapping information
    uno_Interface * pUnoI; // wrapped interface
    typelib_InterfaceTypeDescription * pTypeDescr;
    rtl::OUString oid;

    void ** vtables[1];

    friend void SAL_CALL freeCppInterfaceProxy(
        uno_ExtEnvironment * pEnv, void * pInterface);
};

} } }

#endif
<|endoftext|>


<commit_before>// ParallelExecutionOfCommands.cpp :
// This aplication aims to provide functionality for parallel execution of Behat commands.
//

//#include "stdafx.h"
#include <iostream>
#include <string>
#include <cstring>
#include <stdlib.h>
//#include <unistd.h>
#include <thread>

using namespace std;

int main()
{
	// Declaration of needed variables.
	int processes_Count;
	char command[128];
	string behat_Profile;
	string behat_Feature_Folder;
	string behat_Bin = "bin/behat -p ";
	string result_Command_String;
	thread thread_Array[100];
	bool parallel_Execution = true;

	// Entering values for the variables.
	cout << "Enter number of processes you want to execute: ";
	cin >> processes_Count;
	cout << "Enter Behat profile you want to use: ";
	cin >> behat_Profile;
	cout << "Enter Behat feature folder or file location you want to execute: ";
	cin >> behat_Feature_Folder;

	// Creting command for execution.
	result_Command_String = behat_Bin + behat_Profile + " features/" + behat_Feature_Folder;
	strcpy(command, result_Command_String.c_str());

	cout << "You will execute " << processes_Count << " processes with the following command: " << command << ".\n";

	// Creating threads to handle the command execution.
	for (size_t i = 0; i < processes_Count; i++)
	{
		thread_Array[i] = thread(system, command);
	}
	for (size_t i = 0; i < sizeof(thread_Array); i++)
	{
		thread_Array[i].detach();
	}

	//// Creating process for execution of the command.
	//pid_t pids[processes_Count];
	//for (size_t i = 0; i < processes_Count; i++)
	//{
	//	if ((pids[i] = fork()) < 0)
	//	{
	//		perror("Process was unable to be created.");
	//		abort();
	//	}
	//	else if (pids[i] == 0)
	//	{
	//		system(command);
	//		exit(0);
	//	}
	//}

    return 0;
}

<commit_msg>Using  join() for threads.<commit_after>// ParallelExecutionOfCommands.cpp :
// This aplication aims to provide functionality for parallel execution of Behat commands.
//

//#include "stdafx.h"
#include <iostream>
#include <string>
#include <cstring>
#include <stdlib.h>
//#include <unistd.h>
#include <thread>

using namespace std;

int main()
{
	// Declaration of needed variables.
	int processes_Count;
	char command[128];
	string behat_Profile;
	string behat_Feature_Folder;
	string behat_Bin = "bin/behat -p ";
	string result_Command_String;
	thread thread_Array[100];
	bool parallel_Execution = true;

	// Entering values for the variables.
	cout << "Enter number of processes you want to execute: ";
	cin >> processes_Count;
	cout << "Enter Behat profile you want to use: ";
	cin >> behat_Profile;
	cout << "Enter Behat feature folder or file location you want to execute: ";
	cin >> behat_Feature_Folder;

	// Creting command for execution.
	result_Command_String = behat_Bin + behat_Profile + " features/" + behat_Feature_Folder;
	strcpy(command, result_Command_String.c_str());

	cout << "You will execute " << processes_Count << " processes with the following command: " << command << ".\n";

	// Creating threads to handle the command execution.
	for (size_t i = 0; i < processes_Count; i++)
	{
		thread_Array[i] = thread(system, command);
		thread_Array[i].join();
	}
	for (size_t i = 0; i < sizeof(thread_Array); i++)
	{
		thread_Array[i].detach();
	}

	//// Creating process for execution of the command.
	//pid_t pids[processes_Count];
	//for (size_t i = 0; i < processes_Count; i++)
	//{
	//	if ((pids[i] = fork()) < 0)
	//	{
	//		perror("Process was unable to be created.");
	//		abort();
	//	}
	//	else if (pids[i] == 0)
	//	{
	//		system(command);
	//		exit(0);
	//	}
	//}

    return 0;
}

<|endoftext|>


<commit_before>#include "GL_Widget.h"
#include <QtOpenGL/QGLFunctions>

//////////////////////////////////////////////////////////////////////////

GL_Widget::GL_Widget(QWidget* parent)
	: QGLWidget(QGLFormat(QGL::DepthBuffer | QGL::Rgba | QGL::NoStencilBuffer), parent)
{
	//setAttribute(Qt::WA_PaintOnScreen);
}

//////////////////////////////////////////////////////////////////////////

GL_Widget::~GL_Widget()
{
	q::System::destroy();
}

//////////////////////////////////////////////////////////////////////////

void GL_Widget::initializeGL()
{
	auto renderer = new q::video::GLES_Renderer();

	q::System::create();
	q::System::inst().init(q::video::Renderer_ptr(renderer));

	renderer->init(math::vec2u32(width() + 1, height()) + 1,
		q::video::Render_Target::Color_Format::RGBA_8,
		q::video::Render_Target::Depth_Format::FULL,
		q::video::Render_Target::Stencil_Format::FULL);

	renderer->get_render_target()->set_color_clear_value(math::vec4f(0.6f, 0.6f, 0.6f, 1.f));

	q::System::inst().get_file_system().mount("fonts", q::data::Data_Pack_uptr(new q::data::Folder_Data_Pack(q::Path("data/fonts"))));
	q::System::inst().get_file_system().mount("techniques", q::data::Data_Pack_uptr(new q::data::Folder_Data_Pack(q::Path("data/techniques"))));
	q::System::inst().get_file_system().mount("models", q::data::Data_Pack_uptr(new q::data::Folder_Data_Pack(q::Path("data/models"))));
}

//////////////////////////////////////////////////////////////////////////

void GL_Widget::paintGL()
{
}

<commit_msg>Disabled vsync<commit_after>#include "GL_Widget.h"
#include <QtOpenGL/QGLFunctions>

//////////////////////////////////////////////////////////////////////////

GL_Widget::GL_Widget(QWidget* parent)
    : QGLWidget(parent)
{
	//setAttribute(Qt::WA_PaintOnScreen);

    QGLFormat format(QGL::DepthBuffer | QGL::Rgba | QGL::NoStencilBuffer);
    format.setSwapInterval(0);
    setFormat(format);
}

//////////////////////////////////////////////////////////////////////////

GL_Widget::~GL_Widget()
{
	q::System::destroy();
}

//////////////////////////////////////////////////////////////////////////

void GL_Widget::initializeGL()
{
	auto renderer = new q::video::GLES_Renderer();

	q::System::create();
	q::System::inst().init(q::video::Renderer_ptr(renderer));

	renderer->init(math::vec2u32(width() + 1, height()) + 1,
		q::video::Render_Target::Color_Format::RGBA_8,
		q::video::Render_Target::Depth_Format::FULL,
		q::video::Render_Target::Stencil_Format::FULL);

	renderer->get_render_target()->set_color_clear_value(math::vec4f(0.6f, 0.6f, 0.6f, 1.f));

	q::System::inst().get_file_system().mount("fonts", q::data::Data_Pack_uptr(new q::data::Folder_Data_Pack(q::Path("data/fonts"))));
	q::System::inst().get_file_system().mount("techniques", q::data::Data_Pack_uptr(new q::data::Folder_Data_Pack(q::Path("data/techniques"))));
	q::System::inst().get_file_system().mount("models", q::data::Data_Pack_uptr(new q::data::Folder_Data_Pack(q::Path("data/models"))));
}

//////////////////////////////////////////////////////////////////////////

void GL_Widget::paintGL()
{
}

<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the config.tests of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** 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.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qwaylandintegration.h"

#include "qwaylanddisplay.h"
#include "qwaylandshmbackingstore.h"
#include "qwaylandshmwindow.h"
#include "qwaylandnativeinterface.h"
#include "qwaylandclipboard.h"
#include "qwaylanddnd.h"

#include "QtPlatformSupport/private/qgenericunixfontdatabase_p.h"
#include <QtPlatformSupport/private/qgenericunixeventdispatcher_p.h>

#include <QtGui/private/qguiapplication_p.h>

#include <QtGui/QWindowSystemInterface>
#include <QtGui/QPlatformCursor>
#include <QtGui/QSurfaceFormat>
#include <QtGui/QGuiGLContext>

#ifdef QT_WAYLAND_GL_SUPPORT
#include "gl_integration/qwaylandglintegration.h"
#endif

QWaylandIntegration::QWaylandIntegration()
    : mFontDb(new QGenericUnixFontDatabase())
    , mEventDispatcher(createUnixEventDispatcher())
    , mNativeInterface(new QWaylandNativeInterface)
{
    QGuiApplicationPrivate::instance()->setEventDispatcher(mEventDispatcher);
    mDisplay = new QWaylandDisplay();

    foreach (QPlatformScreen *screen, mDisplay->screens())
        screenAdded(screen);
}

QPlatformNativeInterface * QWaylandIntegration::nativeInterface() const
{
    return mNativeInterface;
}

bool QWaylandIntegration::hasCapability(QPlatformIntegration::Capability cap) const
{
    switch (cap) {
    case ThreadedPixmaps: return true;
    case OpenGL:
#ifdef QT_WAYLAND_GL_SUPPORT
        return true;
#else
        return false;
#endif
    default: return QPlatformIntegration::hasCapability(cap);
    }
}

QPlatformWindow *QWaylandIntegration::createPlatformWindow(QWindow *window) const
{
#ifdef QT_WAYLAND_GL_SUPPORT
    if (window->surfaceType() == QWindow::OpenGLSurface)
        return mDisplay->eglIntegration()->createEglWindow(window);
#endif
    return new QWaylandShmWindow(window);
}

QPlatformGLContext *QWaylandIntegration::createPlatformGLContext(QGuiGLContext *context) const
{
#ifdef QT_WAYLAND_GL_SUPPORT
    return mDisplay->eglIntegration()->createPlatformGLContext(context->format(), context->shareHandle());
#else
    Q_UNUSED(glFormat);
    Q_UNUSED(share);
    return 0;
#endif
}

QPlatformBackingStore *QWaylandIntegration::createPlatformBackingStore(QWindow *window) const
{
    return new QWaylandShmBackingStore(window);
}

QAbstractEventDispatcher *QWaylandIntegration::guiThreadEventDispatcher() const
{
    return mEventDispatcher;
}

QPlatformFontDatabase *QWaylandIntegration::fontDatabase() const
{
    return mFontDb;
}

QPlatformClipboard *QWaylandIntegration::clipboard() const
{
    return QWaylandClipboard::instance(mDisplay);
}

QPlatformDrag *QWaylandIntegration::drag() const
{
    return QWaylandDrag::instance(mDisplay);
}
<commit_msg>Introduce new platform capability ThreadedOpenGL.<commit_after>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the config.tests of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** 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.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qwaylandintegration.h"

#include "qwaylanddisplay.h"
#include "qwaylandshmbackingstore.h"
#include "qwaylandshmwindow.h"
#include "qwaylandnativeinterface.h"
#include "qwaylandclipboard.h"
#include "qwaylanddnd.h"

#include "QtPlatformSupport/private/qgenericunixfontdatabase_p.h"
#include <QtPlatformSupport/private/qgenericunixeventdispatcher_p.h>

#include <QtGui/private/qguiapplication_p.h>

#include <QtGui/QWindowSystemInterface>
#include <QtGui/QPlatformCursor>
#include <QtGui/QSurfaceFormat>
#include <QtGui/QGuiGLContext>

#ifdef QT_WAYLAND_GL_SUPPORT
#include "gl_integration/qwaylandglintegration.h"
#endif

QWaylandIntegration::QWaylandIntegration()
    : mFontDb(new QGenericUnixFontDatabase())
    , mEventDispatcher(createUnixEventDispatcher())
    , mNativeInterface(new QWaylandNativeInterface)
{
    QGuiApplicationPrivate::instance()->setEventDispatcher(mEventDispatcher);
    mDisplay = new QWaylandDisplay();

    foreach (QPlatformScreen *screen, mDisplay->screens())
        screenAdded(screen);
}

QPlatformNativeInterface * QWaylandIntegration::nativeInterface() const
{
    return mNativeInterface;
}

bool QWaylandIntegration::hasCapability(QPlatformIntegration::Capability cap) const
{
    switch (cap) {
    case ThreadedPixmaps: return true;
    case OpenGL:
#ifdef QT_WAYLAND_GL_SUPPORT
        return true;
#else
        return false;
#endif
    case ThreadedOpenGL:
        return hasCapability(OpenGL);
    default: return QPlatformIntegration::hasCapability(cap);
    }
}

QPlatformWindow *QWaylandIntegration::createPlatformWindow(QWindow *window) const
{
#ifdef QT_WAYLAND_GL_SUPPORT
    if (window->surfaceType() == QWindow::OpenGLSurface)
        return mDisplay->eglIntegration()->createEglWindow(window);
#endif
    return new QWaylandShmWindow(window);
}

QPlatformGLContext *QWaylandIntegration::createPlatformGLContext(QGuiGLContext *context) const
{
#ifdef QT_WAYLAND_GL_SUPPORT
    return mDisplay->eglIntegration()->createPlatformGLContext(context->format(), context->shareHandle());
#else
    Q_UNUSED(glFormat);
    Q_UNUSED(share);
    return 0;
#endif
}

QPlatformBackingStore *QWaylandIntegration::createPlatformBackingStore(QWindow *window) const
{
    return new QWaylandShmBackingStore(window);
}

QAbstractEventDispatcher *QWaylandIntegration::guiThreadEventDispatcher() const
{
    return mEventDispatcher;
}

QPlatformFontDatabase *QWaylandIntegration::fontDatabase() const
{
    return mFontDb;
}

QPlatformClipboard *QWaylandIntegration::clipboard() const
{
    return QWaylandClipboard::instance(mDisplay);
}

QPlatformDrag *QWaylandIntegration::drag() const
{
    return QWaylandDrag::instance(mDisplay);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: DragMethod_Base.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: vg $ $Date: 2007-05-22 18:07:16 $
 *
 *  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_chart2.hxx"

#include "DragMethod_Base.hxx"

#include "Strings.hrc"
#include "ResId.hxx"
#include "macros.hxx"
#include "ObjectNameProvider.hxx"
#include "ObjectIdentifier.hxx"

#ifndef INCLUDED_RTL_MATH_HXX
#include <rtl/math.hxx>
#endif
//header for class SdrPageView
#ifndef _SVDPAGV_HXX
#include <svx/svdpagv.hxx>
#endif
#ifndef _SVX_ACTIONDESCRIPTIONPROVIDER_HXX
#include <svx/ActionDescriptionProvider.hxx>
#endif

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

//.............................................................................
namespace chart
{
//.............................................................................

using namespace ::com::sun::star;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::WeakReference;

DragMethod_Base::DragMethod_Base( DrawViewWrapper& rDrawViewWrapper
                                             , const rtl::OUString& rObjectCID
                                             , const Reference< frame::XModel >& xChartModel
                                             , ActionDescriptionProvider::ActionType eActionType )
    : SdrDragMethod( rDrawViewWrapper )
    , m_rDrawViewWrapper(rDrawViewWrapper)
    , m_aObjectCID(rObjectCID)
    , m_eActionType( eActionType )
    , m_xChartModel( WeakReference< frame::XModel >(xChartModel) )
{
}
DragMethod_Base::~DragMethod_Base()
{
}

Reference< frame::XModel > DragMethod_Base::getChartModel() const
{
    return Reference< frame::XModel >( m_xChartModel );;
}

rtl::OUString DragMethod_Base::getUndoDescription() const
{
    return ActionDescriptionProvider::createDescription(
                m_eActionType,
                ObjectNameProvider::getName( ObjectIdentifier::getObjectType( m_aObjectCID )));
}
void DragMethod_Base::TakeComment(String& rStr) const
{
    rStr = String( getUndoDescription() );
}
void DragMethod_Base::Brk()
{
    Hide();
}
Pointer DragMethod_Base::GetPointer() const
{
    if( IsDraggingPoints() || IsDraggingGluePoints() )
        return Pointer(POINTER_MOVEPOINT);
    else
        return Pointer(POINTER_MOVE);
}
FASTBOOL DragMethod_Base::IsMoveOnly() const
{
    return TRUE;
}
//.............................................................................
} //namespace chart
//.............................................................................
<commit_msg>INTEGRATION: CWS changefileheader (1.2.126); FILE MERGED 2008/04/01 15:04:11 thb 1.2.126.3: #i85898# Stripping all external header guards 2008/04/01 10:50:26 thb 1.2.126.2: #i85898# Stripping all external header guards 2008/03/28 16:43:50 rt 1.2.126.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: DragMethod_Base.cxx,v $
 * $Revision: 1.3 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include "DragMethod_Base.hxx"

#include "Strings.hrc"
#include "ResId.hxx"
#include "macros.hxx"
#include "ObjectNameProvider.hxx"
#include "ObjectIdentifier.hxx"
#include <rtl/math.hxx>
//header for class SdrPageView
#include <svx/svdpagv.hxx>
#include <svx/ActionDescriptionProvider.hxx>
#include <com/sun/star/beans/XPropertySet.hpp>

//.............................................................................
namespace chart
{
//.............................................................................

using namespace ::com::sun::star;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::WeakReference;

DragMethod_Base::DragMethod_Base( DrawViewWrapper& rDrawViewWrapper
                                             , const rtl::OUString& rObjectCID
                                             , const Reference< frame::XModel >& xChartModel
                                             , ActionDescriptionProvider::ActionType eActionType )
    : SdrDragMethod( rDrawViewWrapper )
    , m_rDrawViewWrapper(rDrawViewWrapper)
    , m_aObjectCID(rObjectCID)
    , m_eActionType( eActionType )
    , m_xChartModel( WeakReference< frame::XModel >(xChartModel) )
{
}
DragMethod_Base::~DragMethod_Base()
{
}

Reference< frame::XModel > DragMethod_Base::getChartModel() const
{
    return Reference< frame::XModel >( m_xChartModel );;
}

rtl::OUString DragMethod_Base::getUndoDescription() const
{
    return ActionDescriptionProvider::createDescription(
                m_eActionType,
                ObjectNameProvider::getName( ObjectIdentifier::getObjectType( m_aObjectCID )));
}
void DragMethod_Base::TakeComment(String& rStr) const
{
    rStr = String( getUndoDescription() );
}
void DragMethod_Base::Brk()
{
    Hide();
}
Pointer DragMethod_Base::GetPointer() const
{
    if( IsDraggingPoints() || IsDraggingGluePoints() )
        return Pointer(POINTER_MOVEPOINT);
    else
        return Pointer(POINTER_MOVE);
}
FASTBOOL DragMethod_Base::IsMoveOnly() const
{
    return TRUE;
}
//.............................................................................
} //namespace chart
//.............................................................................
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: DataSeriesProperties.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 00:57:18 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef CHART_DATASERIESPROPERTIES_HXX
#define CHART_DATASERIESPROPERTIES_HXX

#include "PropertyHelper.hxx"
#include "FastPropertyIdRanges.hxx"

#ifndef _COM_SUN_STAR_BEANS_PROPERTY_HPP_
#include <com/sun/star/beans/Property.hpp>
#endif

#include <vector>

namespace chart
{

class DataSeriesProperties
{
public:
    enum
    {
        PROP_DATASERIES_DATA_POINT_STYLE = FAST_PROPERTY_ID_START_DATA_SERIES,
        PROP_DATASERIES_ATTRIBUTED_DATA_POINTS,
        PROP_DATASERIES_IDENTIFIER
    };

    static void AddPropertiesToVector(
        ::std::vector< ::com::sun::star::beans::Property > & rOutProperties,
        bool bIncludeStyleProperties = false );

    static void AddDefaultsToMap( helper::tPropertyValueMap & rOutMap, bool bIncludeStyleProperties = false );

private:
    // not implemented
    DataSeriesProperties();
};

} //  namespace chart

// CHART_DATASERIESPROPERTIES_HXX
#endif
<commit_msg>INTEGRATION: CWS chart2mst3 (1.1.1.1.4); FILE MERGED 2007/04/20 08:06:44 iha 1.1.1.1.4.11: #i75393# Connect Bars per diagram not per series 2007/04/19 16:07:00 iha 1.1.1.1.4.10: #i76130# write attribute sort-by-x-values per plot-area not per series 2006/08/21 17:02:45 iha 1.1.1.1.4.9: #i46521# replace modal x value sorting dialog by a checkbox in the chartwizard; perform sorting in view only and not in the cached chart data (as there is no cached data in the model anymore) 2005/12/21 21:29:18 iha 1.1.1.1.4.8: remove identifiers from model objects and create an index based CID protocol instead for selection purposes 2005/11/28 15:35:41 bm 1.1.1.1.4.7: BarConnectors implemented the old way (all series at once) but model offers the property ConnectDataPoints for each series independently 2005/10/24 11:06:45 iha 1.1.1.1.4.6: coordinate system restructure 2005/10/07 11:53:44 bm 1.1.1.1.4.5: RESYNC: (1.1.1.1-1.2); FILE MERGED 2005/07/28 09:34:51 bm 1.1.1.1.4.4: usage of color schemes and the VaryColorsByPoint property to have correct pie colors and legend entries 2005/07/14 13:00:23 iha 1.1.1.1.4.3: remove unused parameter 'bIncludeStyleProperties' from series and point properties 2004/09/15 17:32:02 bm 1.1.1.1.4.2: API simplification 2004/02/13 16:51:29 bm 1.1.1.1.4.1: join from changes on branch bm_post_chart01<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: DataSeriesProperties.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: vg $ $Date: 2007-05-22 18:35:03 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef CHART_DATASERIESPROPERTIES_HXX
#define CHART_DATASERIESPROPERTIES_HXX

#include "PropertyHelper.hxx"
#include "FastPropertyIdRanges.hxx"

#ifndef _COM_SUN_STAR_BEANS_PROPERTY_HPP_
#include <com/sun/star/beans/Property.hpp>
#endif

#include <vector>

namespace chart
{

class DataSeriesProperties
{
public:
    enum
    {
        PROP_DATASERIES_ATTRIBUTED_DATA_POINTS = FAST_PROPERTY_ID_START_DATA_SERIES,
        PROP_DATASERIES_STACKING_DIRECTION,
        PROP_DATASERIES_VARY_COLORS_BY_POINT,
        PROP_DATASERIES_ATTACHED_AXIS_INDEX
    };

    static void AddPropertiesToVector(
        ::std::vector< ::com::sun::star::beans::Property > & rOutProperties );

    static void AddDefaultsToMap( tPropertyValueMap & rOutMap );

private:
    // not implemented
    DataSeriesProperties();
};

} //  namespace chart

// CHART_DATASERIESPROPERTIES_HXX
#endif
<|endoftext|>


<commit_before>// Copyright (c) 2011 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/browser/chrome_quota_permission_context.h"

#include <string>

#include "base/bind.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/infobars/infobar_tab_helper.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tab_contents/confirm_infobar_delegate.h"
#include "chrome/browser/tab_contents/tab_util.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/common/pref_names.h"
#include "content/browser/browser_thread.h"
#include "content/browser/tab_contents/navigation_details.h"
#include "googleurl/src/gurl.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "net/base/net_util.h"
#include "ui/base/l10n/l10n_util.h"
#include "webkit/quota/quota_types.h"

namespace {

// If we requested larger quota than this threshold, show a different
// message to the user.
const int64 kRequestLargeQuotaThreshold = 5 * 1024 * 1024;

class RequestQuotaInfoBarDelegate : public ConfirmInfoBarDelegate {
 public:
  typedef QuotaPermissionContext::PermissionCallback PermissionCallback;

  RequestQuotaInfoBarDelegate(
      InfoBarTabHelper* infobar_helper,
      ChromeQuotaPermissionContext* context,
      const GURL& origin_url,
      int64 requested_quota,
      const std::string& display_languages,
      const PermissionCallback& callback)
      : ConfirmInfoBarDelegate(infobar_helper),
        context_(context),
        origin_url_(origin_url),
        display_languages_(display_languages),
        requested_quota_(requested_quota),
        callback_(callback) {}

 private:
  virtual ~RequestQuotaInfoBarDelegate() {
    if (!callback_.is_null())
      context_->DispatchCallbackOnIOThread(
          callback_, QuotaPermissionContext::kResponseCancelled);
  }

  virtual bool ShouldExpire(
      const content::LoadCommittedDetails& details)
      const OVERRIDE {
    return false;
  }

  virtual string16 GetMessageText() const OVERRIDE;
  virtual void InfoBarDismissed() OVERRIDE;
  virtual bool Accept() OVERRIDE;
  virtual bool Cancel() OVERRIDE;

  scoped_refptr<ChromeQuotaPermissionContext> context_;
  GURL origin_url_;
  std::string display_languages_;
  int64 requested_quota_;
  PermissionCallback callback_;
  DISALLOW_COPY_AND_ASSIGN(RequestQuotaInfoBarDelegate);
};

void RequestQuotaInfoBarDelegate::InfoBarDismissed() {
  context_->DispatchCallbackOnIOThread(
      callback_, QuotaPermissionContext::kResponseCancelled);
}

string16 RequestQuotaInfoBarDelegate::GetMessageText() const {
  return l10n_util::GetStringFUTF16(
      (requested_quota_ > kRequestLargeQuotaThreshold ?
          IDS_REQUEST_LARGE_QUOTA_INFOBAR_QUESTION :
          IDS_REQUEST_QUOTA_INFOBAR_QUESTION),
      net::FormatUrl(origin_url_, display_languages_));
}

bool RequestQuotaInfoBarDelegate::Accept() {
  context_->DispatchCallbackOnIOThread(
      callback_, QuotaPermissionContext::kResponseAllow);
  return true;
}

bool RequestQuotaInfoBarDelegate::Cancel() {
  context_->DispatchCallbackOnIOThread(
      callback_, QuotaPermissionContext::kResponseCancelled);
  return true;
}

}  // anonymous namespace

ChromeQuotaPermissionContext::ChromeQuotaPermissionContext() {
}

ChromeQuotaPermissionContext::~ChromeQuotaPermissionContext() {
}

void ChromeQuotaPermissionContext::RequestQuotaPermission(
    const GURL& origin_url,
    quota::StorageType type,
    int64 requested_quota,
    int render_process_id,
    int render_view_id,
    const PermissionCallback& callback) {
  if (type != quota::kStorageTypePersistent) {
    // For now we only support requesting quota with this interface
    // for Persistent storage type.
    callback.Run(kResponseDisallow);
    return;
  }

  if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
    BrowserThread::PostTask(
        BrowserThread::UI, FROM_HERE,
        base::Bind(&ChromeQuotaPermissionContext::RequestQuotaPermission, this,
                   origin_url, type, requested_quota,render_process_id,
                   render_view_id, callback));
    return;
  }

  TabContents* tab_contents =
      tab_util::GetTabContentsByID(render_process_id, render_view_id);
  if (!tab_contents) {
    // The tab may have gone away or the request may not be from a tab.
    LOG(WARNING) << "Attempt to request quota tabless renderer: "
                 << render_process_id << "," << render_view_id;
    DispatchCallbackOnIOThread(callback, kResponseCancelled);
    return;
  }

  TabContentsWrapper* wrapper =
      TabContentsWrapper::GetCurrentWrapperForContents(tab_contents);
  InfoBarTabHelper* infobar_helper = wrapper->infobar_tab_helper();
  infobar_helper->AddInfoBar(new RequestQuotaInfoBarDelegate(
      infobar_helper, this, origin_url, requested_quota,
      wrapper->profile()->GetPrefs()->GetString(prefs::kAcceptLanguages),
      callback));
}

void ChromeQuotaPermissionContext::DispatchCallbackOnIOThread(
    const PermissionCallback& callback,
    Response response) {
  DCHECK_EQ(false, callback.is_null());

  if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
    BrowserThread::PostTask(
        BrowserThread::IO, FROM_HERE,
        base::Bind(&ChromeQuotaPermissionContext::DispatchCallbackOnIOThread,
                   this, callback, response));
    return;
  }

  callback.Run(response);
}
<commit_msg>Fix build break: use NewRunnableMethod for bind that requires 7-arity.<commit_after>// Copyright (c) 2011 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/browser/chrome_quota_permission_context.h"

#include <string>

#include "base/bind.h"
#include "base/task.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/infobars/infobar_tab_helper.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tab_contents/confirm_infobar_delegate.h"
#include "chrome/browser/tab_contents/tab_util.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/common/pref_names.h"
#include "content/browser/browser_thread.h"
#include "content/browser/tab_contents/navigation_details.h"
#include "googleurl/src/gurl.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "net/base/net_util.h"
#include "ui/base/l10n/l10n_util.h"
#include "webkit/quota/quota_types.h"

namespace {

// If we requested larger quota than this threshold, show a different
// message to the user.
const int64 kRequestLargeQuotaThreshold = 5 * 1024 * 1024;

class RequestQuotaInfoBarDelegate : public ConfirmInfoBarDelegate {
 public:
  typedef QuotaPermissionContext::PermissionCallback PermissionCallback;

  RequestQuotaInfoBarDelegate(
      InfoBarTabHelper* infobar_helper,
      ChromeQuotaPermissionContext* context,
      const GURL& origin_url,
      int64 requested_quota,
      const std::string& display_languages,
      const PermissionCallback& callback)
      : ConfirmInfoBarDelegate(infobar_helper),
        context_(context),
        origin_url_(origin_url),
        display_languages_(display_languages),
        requested_quota_(requested_quota),
        callback_(callback) {}

 private:
  virtual ~RequestQuotaInfoBarDelegate() {
    if (!callback_.is_null())
      context_->DispatchCallbackOnIOThread(
          callback_, QuotaPermissionContext::kResponseCancelled);
  }

  virtual bool ShouldExpire(
      const content::LoadCommittedDetails& details)
      const OVERRIDE {
    return false;
  }

  virtual string16 GetMessageText() const OVERRIDE;
  virtual void InfoBarDismissed() OVERRIDE;
  virtual bool Accept() OVERRIDE;
  virtual bool Cancel() OVERRIDE;

  scoped_refptr<ChromeQuotaPermissionContext> context_;
  GURL origin_url_;
  std::string display_languages_;
  int64 requested_quota_;
  PermissionCallback callback_;
  DISALLOW_COPY_AND_ASSIGN(RequestQuotaInfoBarDelegate);
};

void RequestQuotaInfoBarDelegate::InfoBarDismissed() {
  context_->DispatchCallbackOnIOThread(
      callback_, QuotaPermissionContext::kResponseCancelled);
}

string16 RequestQuotaInfoBarDelegate::GetMessageText() const {
  return l10n_util::GetStringFUTF16(
      (requested_quota_ > kRequestLargeQuotaThreshold ?
          IDS_REQUEST_LARGE_QUOTA_INFOBAR_QUESTION :
          IDS_REQUEST_QUOTA_INFOBAR_QUESTION),
      net::FormatUrl(origin_url_, display_languages_));
}

bool RequestQuotaInfoBarDelegate::Accept() {
  context_->DispatchCallbackOnIOThread(
      callback_, QuotaPermissionContext::kResponseAllow);
  return true;
}

bool RequestQuotaInfoBarDelegate::Cancel() {
  context_->DispatchCallbackOnIOThread(
      callback_, QuotaPermissionContext::kResponseCancelled);
  return true;
}

}  // anonymous namespace

ChromeQuotaPermissionContext::ChromeQuotaPermissionContext() {
}

ChromeQuotaPermissionContext::~ChromeQuotaPermissionContext() {
}

void ChromeQuotaPermissionContext::RequestQuotaPermission(
    const GURL& origin_url,
    quota::StorageType type,
    int64 requested_quota,
    int render_process_id,
    int render_view_id,
    const PermissionCallback& callback) {
  if (type != quota::kStorageTypePersistent) {
    // For now we only support requesting quota with this interface
    // for Persistent storage type.
    callback.Run(kResponseDisallow);
    return;
  }

  if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
    BrowserThread::PostTask(
        BrowserThread::UI, FROM_HERE,
        NewRunnableMethod(
            this, &ChromeQuotaPermissionContext::RequestQuotaPermission,
            origin_url, type, requested_quota, render_process_id,
            render_view_id, callback));
    return;
  }

  TabContents* tab_contents =
      tab_util::GetTabContentsByID(render_process_id, render_view_id);
  if (!tab_contents) {
    // The tab may have gone away or the request may not be from a tab.
    LOG(WARNING) << "Attempt to request quota tabless renderer: "
                 << render_process_id << "," << render_view_id;
    DispatchCallbackOnIOThread(callback, kResponseCancelled);
    return;
  }

  TabContentsWrapper* wrapper =
      TabContentsWrapper::GetCurrentWrapperForContents(tab_contents);
  InfoBarTabHelper* infobar_helper = wrapper->infobar_tab_helper();
  infobar_helper->AddInfoBar(new RequestQuotaInfoBarDelegate(
      infobar_helper, this, origin_url, requested_quota,
      wrapper->profile()->GetPrefs()->GetString(prefs::kAcceptLanguages),
      callback));
}

void ChromeQuotaPermissionContext::DispatchCallbackOnIOThread(
    const PermissionCallback& callback,
    Response response) {
  DCHECK_EQ(false, callback.is_null());

  if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
    BrowserThread::PostTask(
        BrowserThread::IO, FROM_HERE,
        base::Bind(&ChromeQuotaPermissionContext::DispatchCallbackOnIOThread,
                   this, callback, response));
    return;
  }

  callback.Run(response);
}
<|endoftext|>


<commit_before>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include "ConstantPropagationWholeProgramState.h"

#include "IPConstantPropagationAnalysis.h"
#include "Walkers.h"

using namespace constant_propagation;

namespace {

/*
 * Walk all the static or instance fields in :cls, copying their bindings in
 * :field_env over to :field_partition.
 */
void set_fields_in_partition(const DexClass* cls,
                             const FieldEnvironment& field_env,
                             const FieldType& field_type,
                             ConstantFieldPartition* field_partition) {
  // Note that we *must* iterate over the list of fields in the class and not
  // the bindings in field_env here. This ensures that fields whose values are
  // unknown (and therefore implicitly represented by Top in the field_env)
  // get correctly bound to Top in field_partition (which defaults its
  // bindings to Bottom).
  const auto& fields =
      field_type == FieldType::STATIC ? cls->get_sfields() : cls->get_ifields();
  for (auto& field : fields) {
    auto value = field_env.get(field);
    if (!value.is_top()) {
      TRACE(ICONSTP, 2, "%s has value %s after <clinit> or <init>",
            SHOW(field), SHOW(value));
      always_assert(field->get_class() == cls->get_type());
    } else {
      TRACE(ICONSTP, 2, "%s has unknown value after <clinit> or <init>",
            SHOW(field));
    }
    field_partition->set(field, value);
  }
}

/*
 * Record in :field_partition the values of the static fields after the class
 * initializers have finished executing.
 *
 * XXX this assumes that there are no cycles in the class initialization graph!
 */
void analyze_clinits(const Scope& scope,
                     const interprocedural::FixpointIterator& fp_iter,
                     ConstantFieldPartition* field_partition) {
  for (DexClass* cls : scope) {
    auto& dmethods = cls->get_dmethods();
    auto clinit = cls->get_clinit();
    if (clinit == nullptr) {
      // If there is no class initializer, then the initial field values are
      // simply the DexEncodedValues.
      ConstantEnvironment env;
      set_encoded_values(cls, &env);
      set_fields_in_partition(cls, env.get_field_environment(),
                              FieldType::STATIC, field_partition);
      continue;
    }
    IRCode* code = clinit->get_code();
    auto& cfg = code->cfg();
    auto intra_cp = fp_iter.get_intraprocedural_analysis(clinit);
    auto env = intra_cp->get_exit_state_at(cfg.exit_block());
    set_fields_in_partition(cls, env.get_field_environment(), FieldType::STATIC,
                            field_partition);
  }
}

bool analyze_gets_helper(const WholeProgramState* whole_program_state,
                         const IRInstruction* insn,
                         ConstantEnvironment* env) {
  if (whole_program_state == nullptr) {
    return false;
  }
  auto field = resolve_field(insn->get_field());
  if (field == nullptr) {
    return false;
  }
  auto value = whole_program_state->get_field_value(field);
  if (value.is_top()) {
    return false;
  }
  env->set(RESULT_REGISTER, value);
  return true;
}

bool not_eligible_ifield(DexField* field) {
  return is_static(field) || field->is_external() || !can_delete(field) ||
         is_volatile(field);
}

/**
 * Initialize non-external, can be deleted instance fields' value to be 0.
 */
void initialize_ifields(const Scope& scope,
                        ConstantFieldPartition* field_partition) {
  walk::fields(scope, [&](DexField* field) {
    if (not_eligible_ifield(field)) {
      return;
    }
    field_partition->set(field, SignedConstantDomain(0));
  });
}

} // namespace

namespace constant_propagation {

WholeProgramState::WholeProgramState(
    const Scope& scope,
    const interprocedural::FixpointIterator& fp_iter,
    const std::vector<DexMethod*>& non_true_virtuals,
    const std::unordered_set<const DexType*>& field_black_list) {
  walk::fields(scope, [&](DexField* field) {
    // We exclude those marked by keep rules: keep-marked fields may be
    // written to by non-Dex bytecode.
    // All fields not in m_known_fields will be bound to Top.
    if (field_black_list.count(field->get_class())) {
      return;
    }
    if (is_static(field) && !root(field)) {
      m_known_fields.emplace(field);
    }
    if (not_eligible_ifield(field)) {
      return;
    }
    m_known_fields.emplace(field);
  });
  // Put non-root non true virtual methods in known methods.
  for (const auto& non_true_virtual : non_true_virtuals) {
    if (!root(non_true_virtual)) {
      m_known_methods.emplace(non_true_virtual);
    }
  }
  walk::code(scope, [&](DexMethod* method, const IRCode&) {
    if (!method->is_virtual()) {
      // Put non virtual methods in known methods.
      m_known_methods.emplace(method);
    }
  });
  analyze_clinits(scope, fp_iter, &m_field_partition);
  collect(scope, fp_iter);
}

/*
 * Walk over the entire program, doing a join over the values written to each
 * field, as well as a join over the values returned by each method.
 */
void WholeProgramState::collect(
    const Scope& scope, const interprocedural::FixpointIterator& fp_iter) {
  initialize_ifields(scope, &m_field_partition);
  walk::methods(scope, [&](DexMethod* method) {
    IRCode* code = method->get_code();
    if (code == nullptr) {
      return;
    }
    auto& cfg = code->cfg();
    auto intra_cp = fp_iter.get_intraprocedural_analysis(method);
    for (cfg::Block* b : cfg.blocks()) {
      auto env = intra_cp->get_entry_state_at(b);
      for (auto& mie : InstructionIterable(b)) {
        auto* insn = mie.insn;
        intra_cp->analyze_instruction(insn, &env);
        collect_field_values(insn, env,
                             is_clinit(method) ? method->get_class() : nullptr);
        collect_return_values(insn, env, method);
      }
    }
  });
}

/*
 * For each field, do a join over all the values that may have been
 * written to it at any point in the program.
 *
 * If we are encountering a static field write of some value to Foo.someField
 * in the body of Foo.<clinit>, don't do anything -- that value will only be
 * visible to other methods if it remains unchanged up until the end of the
 * <clinit>. In that case, analyze_clinits() will record it.
 */
void WholeProgramState::collect_field_values(const IRInstruction* insn,
                                             const ConstantEnvironment& env,
                                             const DexType* clinit_cls) {
  if (!is_sput(insn->opcode()) && !is_iput(insn->opcode())) {
    return;
  }
  auto field = resolve_field(insn->get_field());
  if (field != nullptr && m_known_fields.count(field)) {
    if (is_sput(insn->opcode()) && field->get_class() == clinit_cls) {
      return;
    }
    auto value = env.get(insn->src(0));
    m_field_partition.update(field, [&value](auto* current_value) {
      current_value->join_with(value);
    });
  }
}

/*
 * For each method, do a join over all the values that can be returned by it.
 *
 * If there are no reachable return opcodes in the method, then it never
 * returns. Its return value will be represented by Bottom in our analysis.
 */
void WholeProgramState::collect_return_values(const IRInstruction* insn,
                                              const ConstantEnvironment& env,
                                              const DexMethod* method) {
  auto op = insn->opcode();
  if (!is_return(op)) {
    return;
  }
  if (op == OPCODE_RETURN_VOID) {
    // We must set the binding to Top here to record the fact that this method
    // does indeed return -- even though `void` is not actually a return value,
    // this tells us that the code following any invoke of this method is
    // reachable.
    m_method_partition.update(
        method, [](auto* current_value) { current_value->set_to_top(); });
    return;
  }
  auto value = env.get(insn->src(0));
  m_method_partition.update(method, [&value](auto* current_value) {
    current_value->join_with(value);
  });
}

void WholeProgramState::collect_static_finals(const DexClass* cls,
                                              FieldEnvironment field_env) {
  for (auto* field : cls->get_sfields()) {
    if (is_static(field) && is_final(field) && !field->is_external()) {
      m_known_fields.emplace(field);
    } else {
      field_env.set(field, ConstantValue::top());
    }
  }
  set_fields_in_partition(cls, field_env, FieldType::STATIC,
                          &m_field_partition);
}

void WholeProgramState::collect_instance_finals(
    const DexClass* cls,
    const EligibleIfields& eligible_ifields,
    FieldEnvironment field_env) {
  always_assert(!cls->is_external());
  if (cls->get_ctors().size() > 1) {
    // Not dealing with instance field in class not having exact 1 constructor
    // now. TODO(suree404): Might be able to improve?
    for (auto* field : cls->get_ifields()) {
      field_env.set(field, ConstantValue::top());
    }
  } else {
    for (auto* field : cls->get_ifields()) {
      if (eligible_ifields.count(field)) {
        m_known_fields.emplace(field);
      } else {
        field_env.set(field, ConstantValue::top());
      }
    }
  }
  set_fields_in_partition(cls, field_env, FieldType::INSTANCE,
                          &m_field_partition);
}

bool WholeProgramAwareAnalyzer::analyze_sget(
    const WholeProgramState* whole_program_state,
    const IRInstruction* insn,
    ConstantEnvironment* env) {
  return analyze_gets_helper(whole_program_state, insn, env);
}

bool WholeProgramAwareAnalyzer::analyze_iget(
    const WholeProgramState* whole_program_state,
    const IRInstruction* insn,
    ConstantEnvironment* env) {
  return analyze_gets_helper(whole_program_state, insn, env);
}

bool WholeProgramAwareAnalyzer::analyze_invoke(
    const WholeProgramState* whole_program_state,
    const IRInstruction* insn,
    ConstantEnvironment* env) {
  if (whole_program_state == nullptr) {
    return false;
  }
  auto op = insn->opcode();
  if (op != OPCODE_INVOKE_DIRECT && op != OPCODE_INVOKE_STATIC &&
      op != OPCODE_INVOKE_VIRTUAL) {
    return false;
  }
  auto method = resolve_method(insn->get_method(), opcode_to_search(insn));
  if (method == nullptr) {
    return false;
  }
  auto value = whole_program_state->get_return_value(method);
  if (value.is_top()) {
    return false;
  }
  env->set(RESULT_REGISTER, value);
  return true;
}

} // namespace constant_propagation
<commit_msg>fix possile bug in IPCP<commit_after>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include "ConstantPropagationWholeProgramState.h"

#include "IPConstantPropagationAnalysis.h"
#include "Walkers.h"

using namespace constant_propagation;

namespace {

/*
 * Walk all the static or instance fields in :cls, copying their bindings in
 * :field_env over to :field_partition.
 */
void set_fields_in_partition(const DexClass* cls,
                             const FieldEnvironment& field_env,
                             const FieldType& field_type,
                             ConstantFieldPartition* field_partition) {
  // Note that we *must* iterate over the list of fields in the class and not
  // the bindings in field_env here. This ensures that fields whose values are
  // unknown (and therefore implicitly represented by Top in the field_env)
  // get correctly bound to Top in field_partition (which defaults its
  // bindings to Bottom).
  const auto& fields =
      field_type == FieldType::STATIC ? cls->get_sfields() : cls->get_ifields();
  for (auto& field : fields) {
    auto value = field_env.get(field);
    if (!value.is_top()) {
      TRACE(ICONSTP, 2, "%s has value %s after <clinit> or <init>",
            SHOW(field), SHOW(value));
      always_assert(field->get_class() == cls->get_type());
    } else {
      TRACE(ICONSTP, 2, "%s has unknown value after <clinit> or <init>",
            SHOW(field));
    }
    field_partition->set(field, value);
  }
}

/*
 * Record in :field_partition the values of the static fields after the class
 * initializers have finished executing.
 *
 * XXX this assumes that there are no cycles in the class initialization graph!
 */
void analyze_clinits(const Scope& scope,
                     const interprocedural::FixpointIterator& fp_iter,
                     ConstantFieldPartition* field_partition) {
  for (DexClass* cls : scope) {
    auto& dmethods = cls->get_dmethods();
    auto clinit = cls->get_clinit();
    if (clinit == nullptr) {
      // If there is no class initializer, then the initial field values are
      // simply the DexEncodedValues.
      ConstantEnvironment env;
      set_encoded_values(cls, &env);
      set_fields_in_partition(cls, env.get_field_environment(),
                              FieldType::STATIC, field_partition);
      continue;
    }
    IRCode* code = clinit->get_code();
    auto& cfg = code->cfg();
    auto intra_cp = fp_iter.get_intraprocedural_analysis(clinit);
    auto env = intra_cp->get_exit_state_at(cfg.exit_block());
    set_fields_in_partition(cls, env.get_field_environment(), FieldType::STATIC,
                            field_partition);
  }
}

bool analyze_gets_helper(const WholeProgramState* whole_program_state,
                         const IRInstruction* insn,
                         ConstantEnvironment* env) {
  if (whole_program_state == nullptr) {
    return false;
  }
  auto field = resolve_field(insn->get_field());
  if (field == nullptr) {
    return false;
  }
  auto value = whole_program_state->get_field_value(field);
  if (value.is_top()) {
    return false;
  }
  env->set(RESULT_REGISTER, value);
  return true;
}

bool not_eligible_ifield(DexField* field) {
  return is_static(field) || field->is_external() || !can_delete(field) ||
         is_volatile(field);
}

/**
 * Initialize non-external, can be deleted instance fields' value to be 0.
 */
void initialize_ifields(const Scope& scope,
                        ConstantFieldPartition* field_partition) {
  walk::fields(scope, [&](DexField* field) {
    if (not_eligible_ifield(field)) {
      return;
    }
    field_partition->set(field, SignedConstantDomain(0));
  });
}

} // namespace

namespace constant_propagation {

WholeProgramState::WholeProgramState(
    const Scope& scope,
    const interprocedural::FixpointIterator& fp_iter,
    const std::vector<DexMethod*>& non_true_virtuals,
    const std::unordered_set<const DexType*>& field_black_list) {
  walk::fields(scope, [&](DexField* field) {
    // We exclude those marked by keep rules: keep-marked fields may be
    // written to by non-Dex bytecode.
    // All fields not in m_known_fields will be bound to Top.
    if (field_black_list.count(field->get_class())) {
      return;
    }
    if (is_static(field) && !root(field)) {
      m_known_fields.emplace(field);
    }
    if (not_eligible_ifield(field)) {
      return;
    }
    m_known_fields.emplace(field);
  });
  // Put non-root non true virtual methods in known methods.
  for (const auto& non_true_virtual : non_true_virtuals) {
    if (!root(non_true_virtual) && non_true_virtual->get_code()) {
      m_known_methods.emplace(non_true_virtual);
    }
  }
  walk::code(scope, [&](DexMethod* method, const IRCode&) {
    if (!method->is_virtual() && method->get_code()) {
      // Put non virtual methods in known methods.
      m_known_methods.emplace(method);
    }
  });
  analyze_clinits(scope, fp_iter, &m_field_partition);
  collect(scope, fp_iter);
}

/*
 * Walk over the entire program, doing a join over the values written to each
 * field, as well as a join over the values returned by each method.
 */
void WholeProgramState::collect(
    const Scope& scope, const interprocedural::FixpointIterator& fp_iter) {
  initialize_ifields(scope, &m_field_partition);
  walk::methods(scope, [&](DexMethod* method) {
    IRCode* code = method->get_code();
    if (code == nullptr) {
      return;
    }
    auto& cfg = code->cfg();
    auto intra_cp = fp_iter.get_intraprocedural_analysis(method);
    for (cfg::Block* b : cfg.blocks()) {
      auto env = intra_cp->get_entry_state_at(b);
      for (auto& mie : InstructionIterable(b)) {
        auto* insn = mie.insn;
        intra_cp->analyze_instruction(insn, &env);
        collect_field_values(insn, env,
                             is_clinit(method) ? method->get_class() : nullptr);
        collect_return_values(insn, env, method);
      }
    }
  });
}

/*
 * For each field, do a join over all the values that may have been
 * written to it at any point in the program.
 *
 * If we are encountering a static field write of some value to Foo.someField
 * in the body of Foo.<clinit>, don't do anything -- that value will only be
 * visible to other methods if it remains unchanged up until the end of the
 * <clinit>. In that case, analyze_clinits() will record it.
 */
void WholeProgramState::collect_field_values(const IRInstruction* insn,
                                             const ConstantEnvironment& env,
                                             const DexType* clinit_cls) {
  if (!is_sput(insn->opcode()) && !is_iput(insn->opcode())) {
    return;
  }
  auto field = resolve_field(insn->get_field());
  if (field != nullptr && m_known_fields.count(field)) {
    if (is_sput(insn->opcode()) && field->get_class() == clinit_cls) {
      return;
    }
    auto value = env.get(insn->src(0));
    m_field_partition.update(field, [&value](auto* current_value) {
      current_value->join_with(value);
    });
  }
}

/*
 * For each method, do a join over all the values that can be returned by it.
 *
 * If there are no reachable return opcodes in the method, then it never
 * returns. Its return value will be represented by Bottom in our analysis.
 */
void WholeProgramState::collect_return_values(const IRInstruction* insn,
                                              const ConstantEnvironment& env,
                                              const DexMethod* method) {
  auto op = insn->opcode();
  if (!is_return(op)) {
    return;
  }
  if (op == OPCODE_RETURN_VOID) {
    // We must set the binding to Top here to record the fact that this method
    // does indeed return -- even though `void` is not actually a return value,
    // this tells us that the code following any invoke of this method is
    // reachable.
    m_method_partition.update(
        method, [](auto* current_value) { current_value->set_to_top(); });
    return;
  }
  auto value = env.get(insn->src(0));
  m_method_partition.update(method, [&value](auto* current_value) {
    current_value->join_with(value);
  });
}

void WholeProgramState::collect_static_finals(const DexClass* cls,
                                              FieldEnvironment field_env) {
  for (auto* field : cls->get_sfields()) {
    if (is_static(field) && is_final(field) && !field->is_external()) {
      m_known_fields.emplace(field);
    } else {
      field_env.set(field, ConstantValue::top());
    }
  }
  set_fields_in_partition(cls, field_env, FieldType::STATIC,
                          &m_field_partition);
}

void WholeProgramState::collect_instance_finals(
    const DexClass* cls,
    const EligibleIfields& eligible_ifields,
    FieldEnvironment field_env) {
  always_assert(!cls->is_external());
  if (cls->get_ctors().size() > 1) {
    // Not dealing with instance field in class not having exact 1 constructor
    // now. TODO(suree404): Might be able to improve?
    for (auto* field : cls->get_ifields()) {
      field_env.set(field, ConstantValue::top());
    }
  } else {
    for (auto* field : cls->get_ifields()) {
      if (eligible_ifields.count(field)) {
        m_known_fields.emplace(field);
      } else {
        field_env.set(field, ConstantValue::top());
      }
    }
  }
  set_fields_in_partition(cls, field_env, FieldType::INSTANCE,
                          &m_field_partition);
}

bool WholeProgramAwareAnalyzer::analyze_sget(
    const WholeProgramState* whole_program_state,
    const IRInstruction* insn,
    ConstantEnvironment* env) {
  return analyze_gets_helper(whole_program_state, insn, env);
}

bool WholeProgramAwareAnalyzer::analyze_iget(
    const WholeProgramState* whole_program_state,
    const IRInstruction* insn,
    ConstantEnvironment* env) {
  return analyze_gets_helper(whole_program_state, insn, env);
}

bool WholeProgramAwareAnalyzer::analyze_invoke(
    const WholeProgramState* whole_program_state,
    const IRInstruction* insn,
    ConstantEnvironment* env) {
  if (whole_program_state == nullptr) {
    return false;
  }
  auto op = insn->opcode();
  if (op != OPCODE_INVOKE_DIRECT && op != OPCODE_INVOKE_STATIC &&
      op != OPCODE_INVOKE_VIRTUAL) {
    return false;
  }
  auto method = resolve_method(insn->get_method(), opcode_to_search(insn));
  if (method == nullptr) {
    return false;
  }
  auto value = whole_program_state->get_return_value(method);
  if (value.is_top()) {
    return false;
  }
  env->set(RESULT_REGISTER, value);
  return true;
}

} // namespace constant_propagation
<|endoftext|>