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

#include "rtkCudaBackProjectionImageFilter.h"
#include "rtkCudaUtilities.hcu"
#include "rtkCudaBackProjectionImageFilter.hcu"

#include <itkImageRegionConstIterator.h>
#include <itkImageRegionIteratorWithIndex.h>
#include <itkLinearInterpolateImageFunction.h>
#include <itkMacro.h>

namespace rtk
{

CudaBackProjectionImageFilter
::CudaBackProjectionImageFilter()
{
}

void
CudaBackProjectionImageFilter
::GPUGenerateData()
{
  //this->AllocateOutputs();

  const unsigned int Dimension = ImageType::ImageDimension;
  const unsigned int nProj = this->GetInput(1)->GetLargestPossibleRegion().GetSize(Dimension-1);
  const unsigned int iFirstProj = this->GetInput(1)->GetLargestPossibleRegion().GetIndex(Dimension-1);

  // Ramp factor is the correction for ramp filter which did not account for the
  // divergence of the beam
  const GeometryPointer geometry = dynamic_cast<GeometryType *>(this->GetGeometry().GetPointer() );

  // Rotation center (assumed to be at 0 yet)
  ImageType::PointType rotCenterPoint;
  rotCenterPoint.Fill(0.0);
  itk::ContinuousIndex<double, Dimension> rotCenterIndex;
  this->GetInput(0)->TransformPhysicalPointToContinuousIndex(rotCenterPoint, rotCenterIndex);

  // Include non-zero index in matrix
  itk::Matrix<double, 4, 4> matrixIdxVol;
  matrixIdxVol.SetIdentity();
  for(unsigned int i=0; i<3; i++)
    {
    matrixIdxVol[i][3] = this->GetOutput()->GetRequestedRegion().GetIndex()[i];
    rotCenterIndex[i] -= this->GetOutput()->GetRequestedRegion().GetIndex()[i];
    }

  // Cuda convenient format for dimensions
  int projectionSize[2];
  projectionSize[0] = this->GetInput(1)->GetBufferedRegion().GetSize()[0];
  projectionSize[1] = this->GetInput(1)->GetBufferedRegion().GetSize()[1];

  int volumeSize[3];
  //volumeSize[0] = this->GetOutput()->GetRequestedRegion().GetSize()[0];
  //volumeSize[1] = this->GetOutput()->GetRequestedRegion().GetSize()[1];
  //volumeSize[2] = this->GetOutput()->GetRequestedRegion().GetSize()[2];

  volumeSize[0] = this->GetOutput()->GetBufferedRegion().GetSize()[0];
  volumeSize[1] = this->GetOutput()->GetBufferedRegion().GetSize()[1];
  volumeSize[2] = this->GetOutput()->GetBufferedRegion().GetSize()[2];

  float *pin  = *(float**)( this->GetInput()->GetCudaDataManager()->GetGPUBufferPointer() );
  float *pout = *(float**)( this->GetOutput()->GetCudaDataManager()->GetGPUBufferPointer() );

  // Go over each projection
  for(unsigned int iProj=iFirstProj; iProj<iFirstProj+nProj; iProj++)
    {
    // Extract the current slice
    ProjectionImagePointer projection = this->GetProjection<ProjectionImageType>(iProj);

    // Index to index matrix normalized to have a correct backprojection weight
    // (1 at the isocenter)
    ProjectionMatrixType matrix = GetIndexToIndexProjectionMatrix(iProj);

    // We correct the matrix for non zero indexes
    itk::Matrix<double, 3, 3> matrixIdxProj;
    matrixIdxProj.SetIdentity();
    for(unsigned int i=0; i<2; i++)
      //SR: 0.5 for 2D texture
      matrixIdxProj[i][2] = -1*(projection->GetBufferedRegion().GetIndex()[i])+0.5;

    matrix = matrixIdxProj.GetVnlMatrix() * matrix.GetVnlMatrix() * matrixIdxVol.GetVnlMatrix();

    double perspFactor = matrix[Dimension-1][Dimension];
    for(unsigned int j=0; j<Dimension; j++)
      perspFactor += matrix[Dimension-1][j] * rotCenterIndex[j];
    matrix /= perspFactor;

    float fMatrix[12];
    for (int j = 0; j < 12; j++)
      fMatrix[j] = matrix[j/4][j%4];

    CUDA_back_project(projectionSize,
                      volumeSize,
                      fMatrix,
                      pin,
                      pout,
                      *(float**)( projection->GetCudaDataManager()->GetGPUBufferPointer() )
                      );
    pin = pout;
    }
}

} // end namespace rtk
<commit_msg>Corrected the CudaBackProjectionImageFilter to avoid unnecessary memory transfers between CPU and GPU (the same correction had been applied earlier on CudaFDKBackProjectionImageFilter)<commit_after>/*=========================================================================
 *
 *  Copyright RTK Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

#include "rtkCudaBackProjectionImageFilter.h"
#include "rtkCudaUtilities.hcu"
#include "rtkCudaBackProjectionImageFilter.hcu"

#include <itkImageRegionConstIterator.h>
#include <itkImageRegionIteratorWithIndex.h>
#include <itkLinearInterpolateImageFunction.h>
#include <itkMacro.h>

namespace rtk
{

CudaBackProjectionImageFilter
::CudaBackProjectionImageFilter()
{
}

void
CudaBackProjectionImageFilter
::GPUGenerateData()
{
  //this->AllocateOutputs();

  const unsigned int Dimension = ImageType::ImageDimension;
  const unsigned int nProj = this->GetInput(1)->GetLargestPossibleRegion().GetSize(Dimension-1);
  const unsigned int iFirstProj = this->GetInput(1)->GetLargestPossibleRegion().GetIndex(Dimension-1);

  // Ramp factor is the correction for ramp filter which did not account for the
  // divergence of the beam
  const GeometryPointer geometry = dynamic_cast<GeometryType *>(this->GetGeometry().GetPointer() );

  // Rotation center (assumed to be at 0 yet)
  ImageType::PointType rotCenterPoint;
  rotCenterPoint.Fill(0.0);
  itk::ContinuousIndex<double, Dimension> rotCenterIndex;
  this->GetInput(0)->TransformPhysicalPointToContinuousIndex(rotCenterPoint, rotCenterIndex);

  // Include non-zero index in matrix
  itk::Matrix<double, 4, 4> matrixIdxVol;
  matrixIdxVol.SetIdentity();
  for(unsigned int i=0; i<3; i++)
    {
    matrixIdxVol[i][3] = this->GetOutput()->GetRequestedRegion().GetIndex()[i];
    rotCenterIndex[i] -= this->GetOutput()->GetRequestedRegion().GetIndex()[i];
    }

  // Cuda convenient format for dimensions
  int projectionSize[2];
  projectionSize[0] = this->GetInput(1)->GetBufferedRegion().GetSize()[0];
  projectionSize[1] = this->GetInput(1)->GetBufferedRegion().GetSize()[1];

  int volumeSize[3];
  //volumeSize[0] = this->GetOutput()->GetRequestedRegion().GetSize()[0];
  //volumeSize[1] = this->GetOutput()->GetRequestedRegion().GetSize()[1];
  //volumeSize[2] = this->GetOutput()->GetRequestedRegion().GetSize()[2];

  volumeSize[0] = this->GetOutput()->GetBufferedRegion().GetSize()[0];
  volumeSize[1] = this->GetOutput()->GetBufferedRegion().GetSize()[1];
  volumeSize[2] = this->GetOutput()->GetBufferedRegion().GetSize()[2];

  float *pin  = *(float**)( this->GetInput()->GetCudaDataManager()->GetGPUBufferPointer() );
  float *pout = *(float**)( this->GetOutput()->GetCudaDataManager()->GetGPUBufferPointer() );

  float *stackGPUPointer = *(float**)( this->GetInput(1)->GetCudaDataManager()->GetGPUBufferPointer() );
  ptrdiff_t projSize = this->GetInput(1)->GetBufferedRegion().GetSize()[0] *
                       this->GetInput(1)->GetBufferedRegion().GetSize()[1];
  stackGPUPointer += projSize * (iFirstProj-this->GetInput(1)->GetBufferedRegion().GetIndex()[2]);

  // Go over each projection
  for(unsigned int iProj=iFirstProj; iProj<iFirstProj+nProj; iProj++, stackGPUPointer += projSize)
    {
    // Index to index matrix normalized to have a correct backprojection weight
    // (1 at the isocenter)
    ProjectionMatrixType matrix = GetIndexToIndexProjectionMatrix(iProj);

    // We correct the matrix for non zero indexes
    itk::Matrix<double, 3, 3> matrixIdxProj;
    matrixIdxProj.SetIdentity();
    for(unsigned int i=0; i<2; i++)
      //SR: 0.5 for 2D texture
      matrixIdxProj[i][2] = -1*(this->GetInput(1)->GetBufferedRegion().GetIndex()[i])+0.5;

    matrix = matrixIdxProj.GetVnlMatrix() * matrix.GetVnlMatrix() * matrixIdxVol.GetVnlMatrix();

    double perspFactor = matrix[Dimension-1][Dimension];
    for(unsigned int j=0; j<Dimension; j++)
      perspFactor += matrix[Dimension-1][j] * rotCenterIndex[j];
    matrix /= perspFactor;

    float fMatrix[12];
    for (int j = 0; j < 12; j++)
      fMatrix[j] = matrix[j/4][j%4];

    CUDA_back_project(projectionSize,
                      volumeSize,
                      fMatrix,
                      pin,
                      pout,
                      stackGPUPointer
                      );
    pin = pout;
    }
}

} // end namespace rtk
<|endoftext|>


<commit_before>/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2010-2011, Willow Garage, Inc.
 *
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 * $Id$
 *
 */

#ifndef PCL_POINT_CLOUD_SPRING_IMPL_HPP_
#define PCL_POINT_CLOUD_SPRING_IMPL_HPP_

template <typename PointT> inline bool
pcl::PointCloudSpring<PointT>::initCompute ()
{
  if ((expand_policy_ != MIRROR) && (expand_policy_ != DUPLICATE))
  {
    PCL_THROW_EXCEPTION (InitFailedException,
                         "[pcl::PointCloudSpring::initCompute] init failed: "
                         << "expansion policy is either MIRROR or DUPLICATE");
    return false;
  }

  if ((direction_ != HORIZONTAL) && (direction_ != VERTICAL) && (direction_ != BOTH))
  {
    PCL_THROW_EXCEPTION (InitFailedException,
                         "[pcl::PointCloudSpring::initCompute] init failed: "
                         << "border must be a HORIZONTAL, VERTICAL or BOTH");
    return false;
  }

  if (amount_ <= 0)
  {
    PCL_THROW_EXCEPTION (InitFailedException,
                         "[pcl::PointCloudSpring::initCompute] init failed: "
                         << "expansion amount must be strict positive!");
    return false;
  }

  if (!input_->isOrganized () && (expand_policy_ == VERTICAL || expand_policy_ == BOTH))
  {
    PCL_THROW_EXCEPTION (InitFailedException,
                         "[pcl::PointCloudSpring::initCompute] init failed: "
                         << "vertical expansion requires organised point cloud");
    return false;
  }
  return true;
}

template <typename PointT> void
pcl::PointCloudSpring<PointT>::expandHorizontal(const PointT& val)
{
  uint32_t old_height = input_->height;
  uint32_t old_width = input_->width;
  uint32_t new_width = old_width + 2*amount_;
  for (int j = 0; j < input_->height; ++j)
  {
    iterator start = input_->begin() + (j * new_width);
    input_->insert (start, amount_, val);
    start = input_->begin() + (j * new_width) + old_width + amount_;
    input_->insert (start, amount_, val);
    input_->height = old_height;
  }
  input_->width = old_width + 2*amount_;
  input_->height = old_height;
}

template <typename PointT> void
pcl::PointCloudSpring<PointT>::expandVertical(const PointT& val)
{
  uint32_t old_height = input_->height;
  uint32_t old_width = input_->width;
  input_->insert (input_->begin (), amount_ * old_width, val);
  iterator last = input_->end () -1;
  input_->insert (last, amount_ * old_width, val);
  input_->width = old_width;
  input_->height = old_height + 2*amount_;
}

template <typename PointT> void
pcl::PointCloudSpring<PointT>::expandHorizontalDuplicate()
{
  int old_height = input_->height;
  int old_width = input_->width;
  int new_width = old_width + 2*amount_;
  for (int j = 0; j < old_height; ++j)
    for(int i = 0; i < amount_; ++i)
    {
      iterator start = input_->begin () + (j * new_width);
      input_->insert (start, *start);
      start = input_->begin () + (j * new_width) + old_width + i;
      input_->insert (start, *start);
    }

  input_->width = old_width + 2*amount_;
  input_->height = old_height;
}

template <typename PointT> void
pcl::PointCloudSpring<PointT>::expandVerticalDuplicate()
{
  uint32_t old_height = input_->height;
  uint32_t old_width = input_->width;
  for(int i = 0; i < amount_; ++i)
  {
    input_->insert (input_->begin (), input_->begin (), input_->begin () + old_width);
    input_->insert (input_->end (), input_->end () - old_width, input_->end ());
  }
  input_->width = old_width;
  input_->height = old_height + 2*amount_;
}

template <typename PointT> void
pcl::PointCloudSpring<PointT>::expandHorizontalMirror()
{
  int old_height = input_->height;
  int old_width = input_->width;
  int new_width = old_width + 2*amount_;
  for (int j = 0; j < old_height; ++j)
    for(int i = 0; i < amount_; ++i)
    {
      iterator start = input_->begin () + (j * new_width);
      input_->insert (start, *(start + 2*i));
      start = input_->begin () + (j * new_width) + old_width + 2*i;
      input_->insert (start+1, *(start - 2*i));
    }
  input_->width = old_width + 2*amount_;
  input_->height = old_height;
}

template <typename PointT> void
pcl::PointCloudSpring<PointT>::expandVerticalMirror()
{
  uint32_t old_height = input_->height;
  uint32_t old_width = input_->width;

  iterator up = input_->begin (), low = input_->end ();
  for(int i = 0; i < amount_; ++i)
  {
    input_->insert (input_->begin (), up, up + old_width);
    up+= old_width;
    input_->insert (input_->end (), low - old_width, low);
    low-= old_width;
  }
  input_->width = old_width;
  input_->height = old_height + 2*amount_;
}

template <typename PointT> inline void
pcl::PointCloudSpring<PointT>::deleteRows ()
{
  uint32_t old_height = input_->height;
  uint32_t old_width = input_->width;
  input_->erase (input_->begin (), input_->begin () + amount_ * old_width);
  input_->erase (input_->end () - amount_ * old_width, input_->end ());
  input_->height = old_height - 2*amount_;
  input_->width = old_width;
}

template <typename PointT> inline void
pcl::PointCloudSpring<PointT>::deleteCols ()
{
  uint32_t old_height = input_->height;
  uint32_t old_width = input_->width;
  uint32_t new_width = old_width - 2 * amount_;
  for(uint32_t j = 0; j < old_height; j++)
  {
    iterator start = input_->begin () + j * new_width;
    input_->erase (start, start + amount_);
    start = input_->begin () + (j+1) * new_width;
    input_->erase (start, start + amount_);
  }
  input_->height = old_height;
  input_->width = new_width;
}

#endif
<commit_msg>vector::insert invalidates all previously obtained iterators <commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2010-2011, Willow Garage, Inc.
 *
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 * $Id$
 *
 */

#ifndef PCL_POINT_CLOUD_SPRING_IMPL_HPP_
#define PCL_POINT_CLOUD_SPRING_IMPL_HPP_

template <typename PointT> inline bool
pcl::PointCloudSpring<PointT>::initCompute ()
{
  if ((expand_policy_ != MIRROR) && (expand_policy_ != DUPLICATE))
  {
    PCL_THROW_EXCEPTION (InitFailedException,
                         "[pcl::PointCloudSpring::initCompute] init failed: "
                         << "expansion policy is either MIRROR or DUPLICATE");
    return false;
  }

  if ((direction_ != HORIZONTAL) && (direction_ != VERTICAL) && (direction_ != BOTH))
  {
    PCL_THROW_EXCEPTION (InitFailedException,
                         "[pcl::PointCloudSpring::initCompute] init failed: "
                         << "border must be a HORIZONTAL, VERTICAL or BOTH");
    return false;
  }

  if (amount_ <= 0)
  {
    PCL_THROW_EXCEPTION (InitFailedException,
                         "[pcl::PointCloudSpring::initCompute] init failed: "
                         << "expansion amount must be strict positive!");
    return false;
  }

  if (!input_->isOrganized () && (expand_policy_ == VERTICAL || expand_policy_ == BOTH))
  {
    PCL_THROW_EXCEPTION (InitFailedException,
                         "[pcl::PointCloudSpring::initCompute] init failed: "
                         << "vertical expansion requires organised point cloud");
    return false;
  }
  return true;
}

template <typename PointT> void
pcl::PointCloudSpring<PointT>::expandHorizontal(const PointT& val)
{
  uint32_t old_height = input_->height;
  uint32_t old_width = input_->width;
  uint32_t new_width = old_width + 2*amount_;
  for (int j = 0; j < input_->height; ++j)
  {
    iterator start = input_->begin() + (j * new_width);
    input_->insert (start, amount_, val);
    start = input_->begin() + (j * new_width) + old_width + amount_;
    input_->insert (start, amount_, val);
    input_->height = old_height;
  }
  input_->width = old_width + 2*amount_;
  input_->height = old_height;
}

template <typename PointT> void
pcl::PointCloudSpring<PointT>::expandVertical(const PointT& val)
{
  uint32_t old_height = input_->height;
  uint32_t old_width = input_->width;
  input_->insert (input_->begin (), amount_ * old_width, val);
  iterator last = input_->end () -1;
  input_->insert (last, amount_ * old_width, val);
  input_->width = old_width;
  input_->height = old_height + 2*amount_;
}

template <typename PointT> void
pcl::PointCloudSpring<PointT>::expandHorizontalDuplicate()
{
  int old_height = input_->height;
  int old_width = input_->width;
  int new_width = old_width + 2*amount_;
  for (int j = 0; j < old_height; ++j)
    for(int i = 0; i < amount_; ++i)
    {
      iterator start = input_->begin () + (j * new_width);
      input_->insert (start, *start);
      start = input_->begin () + (j * new_width) + old_width + i;
      input_->insert (start, *start);
    }

  input_->width = old_width + 2*amount_;
  input_->height = old_height;
}

template <typename PointT> void
pcl::PointCloudSpring<PointT>::expandVerticalDuplicate()
{
  uint32_t old_height = input_->height;
  uint32_t old_width = input_->width;
  for(int i = 0; i < amount_; ++i)
  {
    input_->insert (input_->begin (), input_->begin (), input_->begin () + old_width);
    input_->insert (input_->end (), input_->end () - old_width, input_->end ());
  }
  input_->width = old_width;
  input_->height = old_height + 2*amount_;
}

template <typename PointT> void
pcl::PointCloudSpring<PointT>::expandHorizontalMirror()
{
  int old_height = input_->height;
  int old_width = input_->width;
  int new_width = old_width + 2*amount_;
  for (int j = 0; j < old_height; ++j)
    for(int i = 0; i < amount_; ++i)
    {
      iterator start = input_->begin () + (j * new_width);
      input_->insert (start, *(start + 2*i));
      start = input_->begin () + (j * new_width) + old_width + 2*i;
      input_->insert (start+1, *(start - 2*i));
    }
  input_->width = old_width + 2*amount_;
  input_->height = old_height;
}

template <typename PointT> void
pcl::PointCloudSpring<PointT>::expandVerticalMirror()
{
  uint32_t old_height = input_->height;
  uint32_t old_width = input_->width;

  iterator up = input_->begin (), low = input_->end ();
  for(int i = 0; i < amount_; ++i)
  {
    up = input_->begin () + 2*i*old_width;
    input_->insert (input_->begin (), up, up + old_width);
    low = input_->end () - 2*i*old_width;
    input_->insert (input_->end (), low - old_width, low);
  }
  input_->width = old_width;
  input_->height = old_height + 2*amount_;
}

template <typename PointT> inline void
pcl::PointCloudSpring<PointT>::deleteRows ()
{
  uint32_t old_height = input_->height;
  uint32_t old_width = input_->width;
  input_->erase (input_->begin (), input_->begin () + amount_ * old_width);
  input_->erase (input_->end () - amount_ * old_width, input_->end ());
  input_->height = old_height - 2*amount_;
  input_->width = old_width;
}

template <typename PointT> inline void
pcl::PointCloudSpring<PointT>::deleteCols ()
{
  uint32_t old_height = input_->height;
  uint32_t old_width = input_->width;
  uint32_t new_width = old_width - 2 * amount_;
  for(uint32_t j = 0; j < old_height; j++)
  {
    iterator start = input_->begin () + j * new_width;
    input_->erase (start, start + amount_);
    start = input_->begin () + (j+1) * new_width;
    input_->erase (start, start + amount_);
  }
  input_->height = old_height;
  input_->width = new_width;
}

#endif
<|endoftext|>


<commit_before>// -----------------------------------------------------------------------
// pion-common: a collection of common libraries used by the Pion Platform
// -----------------------------------------------------------------------
// Copyright (C) 2007-2008 Atomic Labs, Inc.  (http://www.atomiclabs.com)
//
// Distributed under the Boost Software License, Version 1.0.
// See http://www.boost.org/LICENSE_1_0.txt
//

#ifndef __PION_PIONPOOLALLOCATOR_HEADER__
#define __PION_PIONPOOLALLOCATOR_HEADER__

#include <cstdlib>
#include <boost/array.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/static_assert.hpp>
#include <boost/noncopyable.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/pool/pool.hpp>
#include <pion/PionConfig.hpp>
#include <pion/PionException.hpp>

namespace pion {	// begin namespace pion

///
/// PionPoolAllocator: a thread-safe, small object allocator that sacrifices
///                    memory utilization for performance.  It combines a
///                    collection of fixed-size pooled memory allocators with
///                    lock-free caches to achieve nearly wait-free, constant
///                    time performance when used for an extended period of time
///
template <std::size_t MinSize = 8, std::size_t MaxSize = 128>
class PionPoolAllocator
	: private boost::noncopyable
{
public:

	/// virtual destructor
	virtual ~PionPoolAllocator()
	{}

	/// default constructor
	PionPoolAllocator(void)
	{
		for (std::size_t n = 0; n < NumberOfAllocs; ++n) {
			m_pools[n].reset(new FixedSizeAlloc((n+1) * MinSize));
		}
	}

	/**
	 * allocates a block of memory
	 *
	 * @param n minimum size of the new memory block, in bytes
	 *
	 * @return void * raw pointer to the new memory block
	 */
	inline void *malloc(std::size_t n)
	{
		// check for size greater than MaxSize
		if (n > MaxSize)
			return ::malloc(n);
		FixedSizeAlloc *pool_ptr = getPool(n);
		boost::unique_lock<boost::mutex> pool_lock(pool_ptr->m_mutex);
		return getPool(n)->m_pool.malloc();
	}

	/**
	 * deallocates a block of memory
	 *
	 * @param ptr raw pointer to the block of memory
	 * @param n requested size of the memory block, in bytes (actual size may be larger)
	 */
	inline void free(void *ptr, std::size_t n)
	{
		// check for size greater than MaxSize
		if (n > MaxSize)
			return ::free(ptr);
		FixedSizeAlloc *pool_ptr = getPool(n);
		boost::unique_lock<boost::mutex> pool_lock(pool_ptr->m_mutex);
		return getPool(n)->m_pool.free(ptr);
	}

	/**
	 * releases every memory block that does not have any allocated chunks
	 *
	 * @param bool true if at least one block of memory was released
	 */
	inline bool release_memory(void)
	{
		bool result;
		for (std::size_t n = 0; n < NumberOfAllocs; ++n) {
			boost::unique_lock<boost::mutex> pool_lock(m_pools[n]->m_mutex);
			if (m_pools[n]->m_pool.release_memory())
				result = true;
		}
		return result;
	}

protected:

	/// ensure that:
	///   a) MinSize >= sizeof(void*)  [usually 4]
	///   b) MaxSize >= MinSize
	///   c) MaxSize is a multiple of MinSize
	BOOST_STATIC_ASSERT( (MinSize >= sizeof(void*))
		&& (MaxSize >= MinSize)
		&& (MaxSize % MinSize == 0) );

	/// constant representing the number of fixed-size pool allocators
	enum { NumberOfAllocs = ((MaxSize-1) / MinSize) + 1 };

	/**
	 * data structure used to represent a pooled memory
	 * allocator for blocks of a specific size
	 */
	struct FixedSizeAlloc
	{
		/**
		 * constructs a new fixed-size pool allocator
		 *
		 * @param size size of memory blocks managed by this allocator, in bytes
		 */
		FixedSizeAlloc(std::size_t size)
			: m_size(size), m_pool(size)
		{}

		/// size of memory blocks managed by this allocator, in bytes
		std::size_t		m_size;

		/// underlying pool allocator used for memory management
		boost::pool<>	m_pool;

		/// used to protect access to the memory pool
		boost::mutex	m_mutex;
	};

	/**
	 * gets an appropriate fixed-size pool allocator
	 *
	 * @param n the number of bytes to be (de)allocated
	 *
	 * @return FixedSizeAlloc* pointer to the appropriate fixed-size allocator
	 */
	inline FixedSizeAlloc* getPool(const std::size_t n)
	{
		PION_ASSERT(n > 0);
		PION_ASSERT(n <= MaxSize);
		return m_pools[ (n-1) / MinSize ].get();
	}

private:

	/// a collection of fixed-size pool allocators
	boost::array<boost::scoped_ptr<FixedSizeAlloc>, NumberOfAllocs>	m_pools;
};

}	// end namespace pion

#endif
<commit_msg>Some minor bug fixes & such<commit_after>// -----------------------------------------------------------------------
// pion-common: a collection of common libraries used by the Pion Platform
// -----------------------------------------------------------------------
// Copyright (C) 2007-2008 Atomic Labs, Inc.  (http://www.atomiclabs.com)
//
// Distributed under the Boost Software License, Version 1.0.
// See http://www.boost.org/LICENSE_1_0.txt
//

#ifndef __PION_PIONPOOLALLOCATOR_HEADER__
#define __PION_PIONPOOLALLOCATOR_HEADER__

#include <cstdlib>
#include <boost/array.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/static_assert.hpp>
#include <boost/noncopyable.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/pool/pool.hpp>
#include <pion/PionConfig.hpp>
#include <pion/PionException.hpp>

namespace pion {	// begin namespace pion

///
/// PionPoolAllocator: a thread-safe, small object allocator that sacrifices
///                    memory utilization for performance.  It combines a
///                    collection of fixed-size pooled memory allocators with
///                    lock-free caches to achieve nearly wait-free, constant
///                    time performance when used for an extended period of time
///
template <std::size_t MinSize = 8, std::size_t MaxSize = 128>
class PionPoolAllocator
	: private boost::noncopyable
{
public:

	/// virtual destructor
	virtual ~PionPoolAllocator()
	{}

	/// default constructor
	PionPoolAllocator(void)
	{
		for (std::size_t n = 0; n < NumberOfAllocs; ++n) {
			m_pools[n].reset(new FixedSizeAlloc((n+1) * MinSize));
		}
	}

	/**
	 * allocates a block of memory
	 *
	 * @param n minimum size of the new memory block, in bytes
	 *
	 * @return void * raw pointer to the new memory block
	 */
	inline void *malloc(std::size_t n)
	{
		// check for size greater than MaxSize
		if (n > MaxSize)
			return ::malloc(n);
		FixedSizeAlloc *pool_ptr = getPool(n);
		boost::unique_lock<boost::mutex> pool_lock(pool_ptr->m_mutex);
		return pool_ptr->m_pool.malloc();
	}

	/**
	 * deallocates a block of memory
	 *
	 * @param ptr raw pointer to the block of memory
	 * @param n requested size of the memory block, in bytes (actual size may be larger)
	 */
	inline void free(void *ptr, std::size_t n)
	{
		// check for size greater than MaxSize
		if (n > MaxSize) {
			::free(ptr);
			return;
		}
		FixedSizeAlloc *pool_ptr = getPool(n);
		boost::unique_lock<boost::mutex> pool_lock(pool_ptr->m_mutex);
		return pool_ptr->m_pool.free(ptr);
	}

	/**
	 * releases every memory block that does not have any allocated chunks
	 *
	 * @param bool true if at least one block of memory was released
	 */
	inline bool release_memory(void)
	{
		bool result = false;
		for (std::size_t n = 0; n < NumberOfAllocs; ++n) {
			boost::unique_lock<boost::mutex> pool_lock(m_pools[n]->m_mutex);
			if (m_pools[n]->m_pool.release_memory())
				result = true;
		}
		return result;
	}

protected:

	/// ensure that:
	///   a) MinSize >= sizeof(void*)  [usually 4]
	///   b) MaxSize >= MinSize
	///   c) MaxSize is a multiple of MinSize
	BOOST_STATIC_ASSERT( (MinSize >= sizeof(void*))
		&& (MaxSize >= MinSize)
		&& (MaxSize % MinSize == 0) );

	/// constant representing the number of fixed-size pool allocators
	enum { NumberOfAllocs = ((MaxSize-1) / MinSize) + 1 };

	/**
	 * data structure used to represent a pooled memory
	 * allocator for blocks of a specific size
	 */
	struct FixedSizeAlloc
	{
		/**
		 * constructs a new fixed-size pool allocator
		 *
		 * @param size size of memory blocks managed by this allocator, in bytes
		 */
		FixedSizeAlloc(std::size_t size)
			: m_size(size), m_pool(size)
		{}

		/// size of memory blocks managed by this allocator, in bytes
		std::size_t		m_size;

		/// underlying pool allocator used for memory management
		boost::pool<>	m_pool;

		/// used to protect access to the memory pool
		boost::mutex	m_mutex;
	};

	/**
	 * gets an appropriate fixed-size pool allocator
	 *
	 * @param n the number of bytes to be (de)allocated
	 *
	 * @return FixedSizeAlloc* pointer to the appropriate fixed-size allocator
	 */
	inline FixedSizeAlloc* getPool(const std::size_t n)
	{
		PION_ASSERT(n > 0);
		PION_ASSERT(n <= MaxSize);
		return m_pools[ (n-1) / MinSize ].get();
	}

private:

	/// a collection of fixed-size pool allocators
	boost::array<boost::scoped_ptr<FixedSizeAlloc>, NumberOfAllocs>	m_pools;
};

}	// end namespace pion

#endif
<|endoftext|>


<commit_before>// Copyright 2014 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 "components/domain_reliability/uploader.h"

#include "base/bind.h"
#include "base/memory/scoped_vector.h"
#include "base/metrics/sparse_histogram.h"
#include "base/stl_util.h"
#include "base/supports_user_data.h"
#include "net/base/load_flags.h"
#include "net/url_request/url_fetcher.h"
#include "net/url_request/url_fetcher_delegate.h"
#include "net/url_request/url_request_context_getter.h"

namespace domain_reliability {

namespace {

class UploadUserData : public base::SupportsUserData::Data {
 public:
  static net::URLFetcher::CreateDataCallback CreateCreateDataCallback() {
    return base::Bind(&UploadUserData::CreateUploadUserData);
  }

  static const void* kUserDataKey;

 private:
  static base::SupportsUserData::Data* CreateUploadUserData() {
    return new UploadUserData();
  }
};

const void* UploadUserData::kUserDataKey =
    static_cast<const void*>(&UploadUserData::kUserDataKey);

class DomainReliabilityUploaderImpl
    : public DomainReliabilityUploader, net::URLFetcherDelegate {
 public:
  DomainReliabilityUploaderImpl(
      scoped_refptr<net::URLRequestContextGetter> url_request_context_getter)
      : url_request_context_getter_(url_request_context_getter) {}

  virtual ~DomainReliabilityUploaderImpl() {
    // Delete any in-flight URLFetchers.
    STLDeleteContainerPairFirstPointers(
        upload_callbacks_.begin(), upload_callbacks_.end());
  }

  // DomainReliabilityUploader implementation:
  virtual void UploadReport(
      const std::string& report_json,
      const GURL& upload_url,
      const DomainReliabilityUploader::UploadCallback& callback) OVERRIDE {
    VLOG(1) << "Uploading report to " << upload_url;
    VLOG(2) << "Report JSON: " << report_json;

    net::URLFetcher* fetcher =
        net::URLFetcher::Create(0, upload_url, net::URLFetcher::POST, this);
    fetcher->SetRequestContext(url_request_context_getter_);
    fetcher->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
                          net::LOAD_DO_NOT_SAVE_COOKIES);
    fetcher->SetUploadData("text/json", report_json);
    fetcher->SetAutomaticallyRetryOn5xx(false);
    fetcher->SetURLRequestUserData(
        UploadUserData::kUserDataKey,
        UploadUserData::CreateCreateDataCallback());
    fetcher->Start();

    upload_callbacks_[fetcher] = callback;
  }

  // net::URLFetcherDelegate implementation:
  virtual void OnURLFetchComplete(
      const net::URLFetcher* fetcher) OVERRIDE {
    DCHECK(fetcher);

    UploadCallbackMap::iterator callback_it = upload_callbacks_.find(fetcher);
    DCHECK(callback_it != upload_callbacks_.end());

    VLOG(1) << "Upload finished with " << fetcher->GetResponseCode();

    UMA_HISTOGRAM_SPARSE_SLOWLY("DomainReliability.UploadResponseCode",
                                fetcher->GetResponseCode());

    bool success = fetcher->GetResponseCode() == 200;
    callback_it->second.Run(success);

    delete callback_it->first;
    upload_callbacks_.erase(callback_it);
  }

 private:
  using DomainReliabilityUploader::UploadCallback;
  typedef std::map<const net::URLFetcher*, UploadCallback> UploadCallbackMap;

  scoped_refptr<net::URLRequestContextGetter> url_request_context_getter_;
  UploadCallbackMap upload_callbacks_;
};

}  // namespace

DomainReliabilityUploader::DomainReliabilityUploader() {}

DomainReliabilityUploader::~DomainReliabilityUploader() {}

// static
scoped_ptr<DomainReliabilityUploader> DomainReliabilityUploader::Create(
    scoped_refptr<net::URLRequestContextGetter> url_request_context_getter) {
  return scoped_ptr<DomainReliabilityUploader>(
      new DomainReliabilityUploaderImpl(url_request_context_getter));
}

// static
bool DomainReliabilityUploader::URLRequestIsUpload(
    const net::URLRequest& request) {
  return request.GetUserData(UploadUserData::kUserDataKey) != NULL;
}

}  // namespace domain_reliability
<commit_msg>Domain Reliability: Use "application/json; charset=utf-8" MIME type<commit_after>// Copyright 2014 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 "components/domain_reliability/uploader.h"

#include "base/bind.h"
#include "base/memory/scoped_vector.h"
#include "base/metrics/sparse_histogram.h"
#include "base/stl_util.h"
#include "base/supports_user_data.h"
#include "net/base/load_flags.h"
#include "net/url_request/url_fetcher.h"
#include "net/url_request/url_fetcher_delegate.h"
#include "net/url_request/url_request_context_getter.h"

namespace domain_reliability {

namespace {

const char* kJsonMimeType = "application/json; charset=utf-8";

class UploadUserData : public base::SupportsUserData::Data {
 public:
  static net::URLFetcher::CreateDataCallback CreateCreateDataCallback() {
    return base::Bind(&UploadUserData::CreateUploadUserData);
  }

  static const void* kUserDataKey;

 private:
  static base::SupportsUserData::Data* CreateUploadUserData() {
    return new UploadUserData();
  }
};

const void* UploadUserData::kUserDataKey =
    static_cast<const void*>(&UploadUserData::kUserDataKey);

class DomainReliabilityUploaderImpl
    : public DomainReliabilityUploader, net::URLFetcherDelegate {
 public:
  DomainReliabilityUploaderImpl(
      scoped_refptr<net::URLRequestContextGetter> url_request_context_getter)
      : url_request_context_getter_(url_request_context_getter) {}

  virtual ~DomainReliabilityUploaderImpl() {
    // Delete any in-flight URLFetchers.
    STLDeleteContainerPairFirstPointers(
        upload_callbacks_.begin(), upload_callbacks_.end());
  }

  // DomainReliabilityUploader implementation:
  virtual void UploadReport(
      const std::string& report_json,
      const GURL& upload_url,
      const DomainReliabilityUploader::UploadCallback& callback) OVERRIDE {
    VLOG(1) << "Uploading report to " << upload_url;
    VLOG(2) << "Report JSON: " << report_json;

    net::URLFetcher* fetcher =
        net::URLFetcher::Create(0, upload_url, net::URLFetcher::POST, this);
    fetcher->SetRequestContext(url_request_context_getter_);
    fetcher->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
                          net::LOAD_DO_NOT_SAVE_COOKIES);
    fetcher->SetUploadData(kJsonMimeType, report_json);
    fetcher->SetAutomaticallyRetryOn5xx(false);
    fetcher->SetURLRequestUserData(
        UploadUserData::kUserDataKey,
        UploadUserData::CreateCreateDataCallback());
    fetcher->Start();

    upload_callbacks_[fetcher] = callback;
  }

  // net::URLFetcherDelegate implementation:
  virtual void OnURLFetchComplete(
      const net::URLFetcher* fetcher) OVERRIDE {
    DCHECK(fetcher);

    UploadCallbackMap::iterator callback_it = upload_callbacks_.find(fetcher);
    DCHECK(callback_it != upload_callbacks_.end());

    VLOG(1) << "Upload finished with " << fetcher->GetResponseCode();

    UMA_HISTOGRAM_SPARSE_SLOWLY("DomainReliability.UploadResponseCode",
                                fetcher->GetResponseCode());

    bool success = fetcher->GetResponseCode() == 200;
    callback_it->second.Run(success);

    delete callback_it->first;
    upload_callbacks_.erase(callback_it);
  }

 private:
  using DomainReliabilityUploader::UploadCallback;
  typedef std::map<const net::URLFetcher*, UploadCallback> UploadCallbackMap;

  scoped_refptr<net::URLRequestContextGetter> url_request_context_getter_;
  UploadCallbackMap upload_callbacks_;
};

}  // namespace

DomainReliabilityUploader::DomainReliabilityUploader() {}

DomainReliabilityUploader::~DomainReliabilityUploader() {}

// static
scoped_ptr<DomainReliabilityUploader> DomainReliabilityUploader::Create(
    scoped_refptr<net::URLRequestContextGetter> url_request_context_getter) {
  return scoped_ptr<DomainReliabilityUploader>(
      new DomainReliabilityUploaderImpl(url_request_context_getter));
}

// static
bool DomainReliabilityUploader::URLRequestIsUpload(
    const net::URLRequest& request) {
  return request.GetUserData(UploadUserData::kUserDataKey) != NULL;
}

}  // namespace domain_reliability
<|endoftext|>


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

#ifndef _CONNECTIVITY_ADABAS_TABLE_HXX_
#define _CONNECTIVITY_ADABAS_TABLE_HXX_

#ifndef _CONNECTIVITY_SDBCX_TABLE_HXX_
#include "connectivity/sdbcx/VTable.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_
#include <com/sun/star/sdbc/XDatabaseMetaData.hpp>
#endif
#ifndef _CONNECTIVITY_ADABAS_BCONNECTION_HXX_
#include "adabas/BConnection.hxx"
#endif
#ifndef CONNECTIVITY_TABLEHELPER_HXX
#include "connectivity/TTableHelper.hxx"
#endif

namespace connectivity
{
    namespace adabas
    {
        typedef connectivity::OTableHelper OTable_TYPEDEF;

        ::rtl::OUString getTypeString(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& xColProp);

        class OAdabasTable : public OTableHelper
        {
            OAdabasConnection* m_pConnection;
        protected:
            /** creates the column collection for the table
                @param  _rNames
                    The column names.
            */
            virtual sdbcx::OCollection* createColumns(const TStringVector& _rNames);

            /** creates the key collection for the table
                @param  _rNames
                    The key names.
            */
            virtual sdbcx::OCollection* createKeys(const TStringVector& _rNames);

            /** creates the index collection for the table
                @param  _rNames
                    The index names.
            */
            virtual sdbcx::OCollection* createIndexes(const TStringVector& _rNames);

        public:
            OAdabasTable(   sdbcx::OCollection* _pTables,
                            OAdabasConnection* _pConnection);
            OAdabasTable(   sdbcx::OCollection* _pTables,
                            OAdabasConnection* _pConnection,
                    const ::rtl::OUString& _Name,
                    const ::rtl::OUString& _Type,
                    const ::rtl::OUString& _Description = ::rtl::OUString(),
                    const ::rtl::OUString& _SchemaName = ::rtl::OUString(),
                    const ::rtl::OUString& _CatalogName = ::rtl::OUString()
                );

            OAdabasConnection* getConnection() { return m_pConnection;}

            ::rtl::OUString getTableName() const { return m_Name; }
            ::rtl::OUString getSchema() const { return m_SchemaName; }

            // com::sun::star::lang::XUnoTunnel
            virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException);
            static ::com::sun::star::uno::Sequence< sal_Int8 > getUnoTunnelImplementationId();

            // XAlterTable
            virtual void SAL_CALL alterColumnByName( const ::rtl::OUString& colName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& descriptor ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::container::NoSuchElementException, ::com::sun::star::uno::RuntimeException);
            // XNamed
            virtual ::rtl::OUString SAL_CALL getName() throw(::com::sun::star::uno::RuntimeException);
            /**
                returns the ALTER TABLE XXX COLUMN statement
            */
            ::rtl::OUString getAlterTableColumnPart(const ::rtl::OUString& _rsColumnName );

            // starts a sql transaaction
            void beginTransAction();
            // rolls back a sql transaaction
            void rollbackTransAction();
            // ends a sql transaaction
            void endTransAction();
            // some methods to alter table structures
            void alterColumnType(sal_Int32 nNewType,const ::rtl::OUString& _rColName,const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _xDescriptor);
            void alterNotNullValue(sal_Int32 _nNewNullable,const ::rtl::OUString& _rColName);
            void alterDefaultValue(const ::rtl::OUString& _sNewDefault,const ::rtl::OUString& _rColName);
            void dropDefaultValue(const ::rtl::OUString& _sNewDefault);
            void addDefaultValue(const ::rtl::OUString& _sNewDefault,const ::rtl::OUString& _rColName);
        };
    }
}
#endif // _CONNECTIVITY_ADABAS_TABLE_HXX_

<commit_msg>INTEGRATION: CWS ooo19126 (1.13.320); FILE MERGED 2005/09/05 17:24:56 rt 1.13.320.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: BTable.hxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 06:46:32 $
 *
 *  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 _CONNECTIVITY_ADABAS_TABLE_HXX_
#define _CONNECTIVITY_ADABAS_TABLE_HXX_

#ifndef _CONNECTIVITY_SDBCX_TABLE_HXX_
#include "connectivity/sdbcx/VTable.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_
#include <com/sun/star/sdbc/XDatabaseMetaData.hpp>
#endif
#ifndef _CONNECTIVITY_ADABAS_BCONNECTION_HXX_
#include "adabas/BConnection.hxx"
#endif
#ifndef CONNECTIVITY_TABLEHELPER_HXX
#include "connectivity/TTableHelper.hxx"
#endif

namespace connectivity
{
    namespace adabas
    {
        typedef connectivity::OTableHelper OTable_TYPEDEF;

        ::rtl::OUString getTypeString(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& xColProp);

        class OAdabasTable : public OTableHelper
        {
            OAdabasConnection* m_pConnection;
        protected:
            /** creates the column collection for the table
                @param  _rNames
                    The column names.
            */
            virtual sdbcx::OCollection* createColumns(const TStringVector& _rNames);

            /** creates the key collection for the table
                @param  _rNames
                    The key names.
            */
            virtual sdbcx::OCollection* createKeys(const TStringVector& _rNames);

            /** creates the index collection for the table
                @param  _rNames
                    The index names.
            */
            virtual sdbcx::OCollection* createIndexes(const TStringVector& _rNames);

        public:
            OAdabasTable(   sdbcx::OCollection* _pTables,
                            OAdabasConnection* _pConnection);
            OAdabasTable(   sdbcx::OCollection* _pTables,
                            OAdabasConnection* _pConnection,
                    const ::rtl::OUString& _Name,
                    const ::rtl::OUString& _Type,
                    const ::rtl::OUString& _Description = ::rtl::OUString(),
                    const ::rtl::OUString& _SchemaName = ::rtl::OUString(),
                    const ::rtl::OUString& _CatalogName = ::rtl::OUString()
                );

            OAdabasConnection* getConnection() { return m_pConnection;}

            ::rtl::OUString getTableName() const { return m_Name; }
            ::rtl::OUString getSchema() const { return m_SchemaName; }

            // com::sun::star::lang::XUnoTunnel
            virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException);
            static ::com::sun::star::uno::Sequence< sal_Int8 > getUnoTunnelImplementationId();

            // XAlterTable
            virtual void SAL_CALL alterColumnByName( const ::rtl::OUString& colName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& descriptor ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::container::NoSuchElementException, ::com::sun::star::uno::RuntimeException);
            // XNamed
            virtual ::rtl::OUString SAL_CALL getName() throw(::com::sun::star::uno::RuntimeException);
            /**
                returns the ALTER TABLE XXX COLUMN statement
            */
            ::rtl::OUString getAlterTableColumnPart(const ::rtl::OUString& _rsColumnName );

            // starts a sql transaaction
            void beginTransAction();
            // rolls back a sql transaaction
            void rollbackTransAction();
            // ends a sql transaaction
            void endTransAction();
            // some methods to alter table structures
            void alterColumnType(sal_Int32 nNewType,const ::rtl::OUString& _rColName,const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _xDescriptor);
            void alterNotNullValue(sal_Int32 _nNewNullable,const ::rtl::OUString& _rColName);
            void alterDefaultValue(const ::rtl::OUString& _sNewDefault,const ::rtl::OUString& _rColName);
            void dropDefaultValue(const ::rtl::OUString& _sNewDefault);
            void addDefaultValue(const ::rtl::OUString& _sNewDefault,const ::rtl::OUString& _rColName);
        };
    }
}
#endif // _CONNECTIVITY_ADABAS_TABLE_HXX_

<|endoftext|>


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

#include "content/plugin/webplugin_delegate_stub.h"

#include "build/build_config.h"

#include "base/bind.h"
#include "base/command_line.h"
#include "base/strings/string_number_conversions.h"
#include "content/child/plugin_messages.h"
#include "content/plugin/plugin_channel.h"
#include "content/plugin/plugin_thread.h"
#include "content/plugin/webplugin_proxy.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_constants.h"
#include "content/public/common/content_switches.h"
#include "skia/ext/platform_device.h"
#include "third_party/WebKit/public/web/WebBindings.h"
#include "third_party/WebKit/public/web/WebCursorInfo.h"
#include "third_party/npapi/bindings/npapi.h"
#include "third_party/npapi/bindings/npruntime.h"
#include "webkit/common/cursors/webcursor.h"
#include "webkit/plugins/npapi/plugin_instance.h"
#include "webkit/plugins/npapi/webplugin_delegate_impl.h"

using WebKit::WebBindings;
using WebKit::WebCursorInfo;
using webkit::npapi::WebPlugin;
using webkit::npapi::WebPluginResourceClient;

namespace content {

static void DestroyWebPluginAndDelegate(
    base::WeakPtr<NPObjectStub> scriptable_object,
    webkit::npapi::WebPluginDelegateImpl* delegate,
    WebPlugin* webplugin) {
  // The plugin may not expect us to try to release the scriptable object
  // after calling NPP_Destroy on the instance, so delete the stub now.
  if (scriptable_object.get())
    scriptable_object->DeleteSoon();

  if (delegate) {
    // Un-register the plugin instance as an object owner.
    WebBindings::unregisterObjectOwner(delegate->GetPluginNPP());

    // WebPlugin must outlive WebPluginDelegate.
    delegate->PluginDestroyed();
  }

  base::MessageLoop::current()->DeleteSoon(FROM_HERE, webplugin);
}

WebPluginDelegateStub::WebPluginDelegateStub(
    const std::string& mime_type, int instance_id, PluginChannel* channel) :
    mime_type_(mime_type),
    instance_id_(instance_id),
    channel_(channel),
    delegate_(NULL),
    webplugin_(NULL),
    in_destructor_(false) {
  DCHECK(channel);
}

WebPluginDelegateStub::~WebPluginDelegateStub() {
  in_destructor_ = true;
  GetContentClient()->SetActiveURL(page_url_);

  if (channel_->in_send()) {
    // The delegate or an npobject is in the callstack, so don't delete it
    // right away.
    base::MessageLoop::current()->PostNonNestableTask(
        FROM_HERE,
        base::Bind(&DestroyWebPluginAndDelegate,
                   plugin_scriptable_object_,
                   delegate_,
                   webplugin_));
  } else {
    // Safe to delete right away.
    DestroyWebPluginAndDelegate(
        plugin_scriptable_object_, delegate_, webplugin_);
  }

  // Remove the NPObject owner mapping for this instance.
  channel_->RemoveMappingForNPObjectOwner(instance_id_);
}

bool WebPluginDelegateStub::OnMessageReceived(const IPC::Message& msg) {
  GetContentClient()->SetActiveURL(page_url_);

  // A plugin can execute a script to delete itself in any of its NPP methods.
  // Hold an extra reference to ourself so that if this does occur and we're
  // handling a sync message, we don't crash when attempting to send a reply.
  // The exception to this is when we're already in the destructor.
  if (!in_destructor_)
    AddRef();

  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(WebPluginDelegateStub, msg)
    IPC_MESSAGE_HANDLER(PluginMsg_Init, OnInit)
    IPC_MESSAGE_HANDLER(PluginMsg_WillSendRequest, OnWillSendRequest)
    IPC_MESSAGE_HANDLER(PluginMsg_DidReceiveResponse, OnDidReceiveResponse)
    IPC_MESSAGE_HANDLER(PluginMsg_DidReceiveData, OnDidReceiveData)
    IPC_MESSAGE_HANDLER(PluginMsg_DidFinishLoading, OnDidFinishLoading)
    IPC_MESSAGE_HANDLER(PluginMsg_DidFail, OnDidFail)
    IPC_MESSAGE_HANDLER(PluginMsg_DidFinishLoadWithReason,
                        OnDidFinishLoadWithReason)
    IPC_MESSAGE_HANDLER(PluginMsg_SetFocus, OnSetFocus)
    IPC_MESSAGE_HANDLER(PluginMsg_HandleInputEvent, OnHandleInputEvent)
    IPC_MESSAGE_HANDLER(PluginMsg_Paint, OnPaint)
    IPC_MESSAGE_HANDLER(PluginMsg_DidPaint, OnDidPaint)
    IPC_MESSAGE_HANDLER(PluginMsg_GetPluginScriptableObject,
                        OnGetPluginScriptableObject)
    IPC_MESSAGE_HANDLER(PluginMsg_GetFormValue, OnGetFormValue)
    IPC_MESSAGE_HANDLER(PluginMsg_UpdateGeometry, OnUpdateGeometry)
    IPC_MESSAGE_HANDLER(PluginMsg_UpdateGeometrySync, OnUpdateGeometry)
    IPC_MESSAGE_HANDLER(PluginMsg_SendJavaScriptStream,
                        OnSendJavaScriptStream)
    IPC_MESSAGE_HANDLER(PluginMsg_SetContentAreaFocus, OnSetContentAreaFocus)
#if defined(OS_WIN) && !defined(USE_AURA)
    IPC_MESSAGE_HANDLER(PluginMsg_ImeCompositionUpdated,
                        OnImeCompositionUpdated)
    IPC_MESSAGE_HANDLER(PluginMsg_ImeCompositionCompleted,
                        OnImeCompositionCompleted)
#endif
#if defined(OS_MACOSX)
    IPC_MESSAGE_HANDLER(PluginMsg_SetWindowFocus, OnSetWindowFocus)
    IPC_MESSAGE_HANDLER(PluginMsg_ContainerHidden, OnContainerHidden)
    IPC_MESSAGE_HANDLER(PluginMsg_ContainerShown, OnContainerShown)
    IPC_MESSAGE_HANDLER(PluginMsg_WindowFrameChanged, OnWindowFrameChanged)
    IPC_MESSAGE_HANDLER(PluginMsg_ImeCompositionCompleted,
                        OnImeCompositionCompleted)
#endif
    IPC_MESSAGE_HANDLER(PluginMsg_DidReceiveManualResponse,
                        OnDidReceiveManualResponse)
    IPC_MESSAGE_HANDLER(PluginMsg_DidReceiveManualData, OnDidReceiveManualData)
    IPC_MESSAGE_HANDLER(PluginMsg_DidFinishManualLoading,
                        OnDidFinishManualLoading)
    IPC_MESSAGE_HANDLER(PluginMsg_DidManualLoadFail, OnDidManualLoadFail)
    IPC_MESSAGE_HANDLER(PluginMsg_HandleURLRequestReply,
                        OnHandleURLRequestReply)
    IPC_MESSAGE_HANDLER(PluginMsg_HTTPRangeRequestReply,
                        OnHTTPRangeRequestReply)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()

  if (!in_destructor_)
    Release();

  DCHECK(handled);
  return handled;
}

bool WebPluginDelegateStub::Send(IPC::Message* msg) {
  return channel_->Send(msg);
}

void WebPluginDelegateStub::OnInit(const PluginMsg_Init_Params& params,
                                   bool* transparent,
                                   bool* result) {
  page_url_ = params.page_url;
  GetContentClient()->SetActiveURL(page_url_);

  *transparent = false;
  *result = false;
  if (params.arg_names.size() != params.arg_values.size()) {
    NOTREACHED();
    return;
  }

  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
  base::FilePath path =
      command_line.GetSwitchValuePath(switches::kPluginPath);

  webplugin_ = new WebPluginProxy(channel_.get(),
                                  instance_id_,
                                  page_url_,
                                  params.host_render_view_routing_id);
  delegate_ = webkit::npapi::WebPluginDelegateImpl::Create(path, mime_type_);
  if (delegate_) {
    webplugin_->set_delegate(delegate_);
    std::vector<std::string> arg_names = params.arg_names;
    std::vector<std::string> arg_values = params.arg_values;

    // Register the plugin as a valid object owner.
    WebBindings::registerObjectOwner(delegate_->GetPluginNPP());

    // Add an NPObject owner mapping for this instance, to support ownership
    // tracking in the renderer.
    channel_->AddMappingForNPObjectOwner(instance_id_,
                                         delegate_->GetPluginNPP());

    *result = delegate_->Initialize(params.url,
                                    arg_names,
                                    arg_values,
                                    webplugin_,
                                    params.load_manually);
    *transparent = delegate_->instance()->transparent();
  }
}

void WebPluginDelegateStub::OnWillSendRequest(int id, const GURL& url,
                                              int http_status_code) {
  WebPluginResourceClient* client = webplugin_->GetResourceClient(id);
  if (!client)
    return;

  client->WillSendRequest(url, http_status_code);
}

void WebPluginDelegateStub::OnDidReceiveResponse(
    const PluginMsg_DidReceiveResponseParams& params) {
  WebPluginResourceClient* client = webplugin_->GetResourceClient(params.id);
  if (!client)
    return;

  client->DidReceiveResponse(params.mime_type,
                             params.headers,
                             params.expected_length,
                             params.last_modified,
                             params.request_is_seekable);
}

void WebPluginDelegateStub::OnDidReceiveData(int id,
                                             const std::vector<char>& buffer,
                                             int data_offset) {
  WebPluginResourceClient* client = webplugin_->GetResourceClient(id);
  if (!client)
    return;

  client->DidReceiveData(&buffer.front(), static_cast<int>(buffer.size()),
                         data_offset);
}

void WebPluginDelegateStub::OnDidFinishLoading(int id) {
  WebPluginResourceClient* client = webplugin_->GetResourceClient(id);
  if (!client)
    return;

  client->DidFinishLoading();
}

void WebPluginDelegateStub::OnDidFail(int id) {
  WebPluginResourceClient* client = webplugin_->GetResourceClient(id);
  if (!client)
    return;

  client->DidFail();
}

void WebPluginDelegateStub::OnDidFinishLoadWithReason(
    const GURL& url, int reason, int notify_id) {
  delegate_->DidFinishLoadWithReason(url, reason, notify_id);
}

void WebPluginDelegateStub::OnSetFocus(bool focused) {
  delegate_->SetFocus(focused);
#if defined(OS_WIN) && !defined(USE_AURA)
  if (focused)
    webplugin_->UpdateIMEStatus();
#endif
}

void WebPluginDelegateStub::OnHandleInputEvent(
    const WebKit::WebInputEvent *event,
    bool* handled,
    WebCursor* cursor) {
  WebCursor::CursorInfo cursor_info;
  *handled = delegate_->HandleInputEvent(*event, &cursor_info);
  cursor->InitFromCursorInfo(cursor_info);
}

void WebPluginDelegateStub::OnPaint(const gfx::Rect& damaged_rect) {
  webplugin_->Paint(damaged_rect);
}

void WebPluginDelegateStub::OnDidPaint() {
  webplugin_->DidPaint();
}

void WebPluginDelegateStub::OnUpdateGeometry(
    const PluginMsg_UpdateGeometry_Param& param) {
  webplugin_->UpdateGeometry(
      param.window_rect, param.clip_rect,
      param.windowless_buffer0, param.windowless_buffer1,
      param.windowless_buffer_index);
}

void WebPluginDelegateStub::OnGetPluginScriptableObject(int* route_id) {
  NPObject* object = delegate_->GetPluginScriptableObject();
  if (!object) {
    *route_id = MSG_ROUTING_NONE;
    return;
  }

  *route_id = channel_->GenerateRouteID();
  // We will delete the stub immediately before calling PluginDestroyed on the
  // delegate. It will delete itself sooner if the proxy tells it that it has
  // been released, or if the channel to the proxy is closed.
  NPObjectStub* scriptable_stub = new NPObjectStub(
      object, channel_.get(), *route_id,
      webplugin_->host_render_view_routing_id(), page_url_);
  plugin_scriptable_object_ = scriptable_stub->AsWeakPtr();

  // Release ref added by GetPluginScriptableObject (our stub holds its own).
  WebBindings::releaseObject(object);
}

void WebPluginDelegateStub::OnGetFormValue(string16* value, bool* success) {
  *success = false;
  if (!delegate_)
    return;
  *success = delegate_->GetFormValue(value);
}

void WebPluginDelegateStub::OnSendJavaScriptStream(const GURL& url,
                                                   const std::string& result,
                                                   bool success,
                                                   int notify_id) {
  delegate_->SendJavaScriptStream(url, result, success, notify_id);
}

void WebPluginDelegateStub::OnSetContentAreaFocus(bool has_focus) {
  if (delegate_)
    delegate_->SetContentAreaHasFocus(has_focus);
}

#if defined(OS_WIN) && !defined(USE_AURA)
void WebPluginDelegateStub::OnImeCompositionUpdated(
    const string16& text,
    const std::vector<int>& clauses,
    const std::vector<int>& target,
    int cursor_position) {
  if (delegate_)
    delegate_->ImeCompositionUpdated(text, clauses, target, cursor_position);
#if defined(OS_WIN) && !defined(USE_AURA)
  webplugin_->UpdateIMEStatus();
#endif
}

void WebPluginDelegateStub::OnImeCompositionCompleted(const string16& text) {
  if (delegate_)
    delegate_->ImeCompositionCompleted(text);
}
#endif

#if defined(OS_MACOSX)
void WebPluginDelegateStub::OnSetWindowFocus(bool has_focus) {
  if (delegate_)
    delegate_->SetWindowHasFocus(has_focus);
}

void WebPluginDelegateStub::OnContainerHidden() {
  if (delegate_)
    delegate_->SetContainerVisibility(false);
}

void WebPluginDelegateStub::OnContainerShown(gfx::Rect window_frame,
                                             gfx::Rect view_frame,
                                             bool has_focus) {
  if (delegate_) {
    delegate_->WindowFrameChanged(window_frame, view_frame);
    delegate_->SetContainerVisibility(true);
    delegate_->SetWindowHasFocus(has_focus);
  }
}

void WebPluginDelegateStub::OnWindowFrameChanged(const gfx::Rect& window_frame,
                                                 const gfx::Rect& view_frame) {
  if (delegate_)
    delegate_->WindowFrameChanged(window_frame, view_frame);
}

void WebPluginDelegateStub::OnImeCompositionCompleted(const string16& text) {
  if (delegate_)
    delegate_->ImeCompositionCompleted(text);
}
#endif  // OS_MACOSX

void WebPluginDelegateStub::OnDidReceiveManualResponse(
    const GURL& url,
    const PluginMsg_DidReceiveResponseParams& params) {
  delegate_->DidReceiveManualResponse(url, params.mime_type, params.headers,
                                      params.expected_length,
                                      params.last_modified);
}

void WebPluginDelegateStub::OnDidReceiveManualData(
    const std::vector<char>& buffer) {
  delegate_->DidReceiveManualData(&buffer.front(),
                                  static_cast<int>(buffer.size()));
}

void WebPluginDelegateStub::OnDidFinishManualLoading() {
  delegate_->DidFinishManualLoading();
}

void WebPluginDelegateStub::OnDidManualLoadFail() {
  delegate_->DidManualLoadFail();
}

void WebPluginDelegateStub::OnHandleURLRequestReply(
    unsigned long resource_id, const GURL& url, int notify_id) {
  WebPluginResourceClient* resource_client =
      delegate_->CreateResourceClient(resource_id, url, notify_id);
  webplugin_->OnResourceCreated(resource_id, resource_client);
}

void WebPluginDelegateStub::OnHTTPRangeRequestReply(
    unsigned long resource_id, int range_request_id) {
  WebPluginResourceClient* resource_client =
      delegate_->CreateSeekableResourceClient(resource_id, range_request_id);
  webplugin_->OnResourceCreated(resource_id, resource_client);
}

}  // namespace content
<commit_msg>Revert 208912 "Make plugin destruction asynchronous."<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/plugin/webplugin_delegate_stub.h"

#include "build/build_config.h"

#include "base/bind.h"
#include "base/command_line.h"
#include "base/strings/string_number_conversions.h"
#include "content/child/plugin_messages.h"
#include "content/plugin/plugin_channel.h"
#include "content/plugin/plugin_thread.h"
#include "content/plugin/webplugin_proxy.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_constants.h"
#include "content/public/common/content_switches.h"
#include "skia/ext/platform_device.h"
#include "third_party/WebKit/public/web/WebBindings.h"
#include "third_party/WebKit/public/web/WebCursorInfo.h"
#include "third_party/npapi/bindings/npapi.h"
#include "third_party/npapi/bindings/npruntime.h"
#include "webkit/common/cursors/webcursor.h"
#include "webkit/plugins/npapi/plugin_instance.h"
#include "webkit/plugins/npapi/webplugin_delegate_impl.h"

using WebKit::WebBindings;
using WebKit::WebCursorInfo;
using webkit::npapi::WebPlugin;
using webkit::npapi::WebPluginResourceClient;

namespace content {

static void DestroyWebPluginAndDelegate(
    base::WeakPtr<NPObjectStub> scriptable_object,
    webkit::npapi::WebPluginDelegateImpl* delegate,
    WebPlugin* webplugin) {
  // The plugin may not expect us to try to release the scriptable object
  // after calling NPP_Destroy on the instance, so delete the stub now.
  if (scriptable_object.get())
    scriptable_object->DeleteSoon();

  if (delegate) {
    // Un-register the plugin instance as an object owner.
    WebBindings::unregisterObjectOwner(delegate->GetPluginNPP());

    // WebPlugin must outlive WebPluginDelegate.
    delegate->PluginDestroyed();
  }

  delete webplugin;
}

WebPluginDelegateStub::WebPluginDelegateStub(
    const std::string& mime_type, int instance_id, PluginChannel* channel) :
    mime_type_(mime_type),
    instance_id_(instance_id),
    channel_(channel),
    delegate_(NULL),
    webplugin_(NULL),
    in_destructor_(false) {
  DCHECK(channel);
}

WebPluginDelegateStub::~WebPluginDelegateStub() {
  in_destructor_ = true;
  GetContentClient()->SetActiveURL(page_url_);

  if (channel_->in_send()) {
    // The delegate or an npobject is in the callstack, so don't delete it
    // right away.
    base::MessageLoop::current()->PostNonNestableTask(
        FROM_HERE,
        base::Bind(&DestroyWebPluginAndDelegate,
                   plugin_scriptable_object_,
                   delegate_,
                   webplugin_));
  } else {
    // Safe to delete right away.
    DestroyWebPluginAndDelegate(
        plugin_scriptable_object_, delegate_, webplugin_);
  }

  // Remove the NPObject owner mapping for this instance.
  channel_->RemoveMappingForNPObjectOwner(instance_id_);
}

bool WebPluginDelegateStub::OnMessageReceived(const IPC::Message& msg) {
  GetContentClient()->SetActiveURL(page_url_);

  // A plugin can execute a script to delete itself in any of its NPP methods.
  // Hold an extra reference to ourself so that if this does occur and we're
  // handling a sync message, we don't crash when attempting to send a reply.
  // The exception to this is when we're already in the destructor.
  if (!in_destructor_)
    AddRef();

  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(WebPluginDelegateStub, msg)
    IPC_MESSAGE_HANDLER(PluginMsg_Init, OnInit)
    IPC_MESSAGE_HANDLER(PluginMsg_WillSendRequest, OnWillSendRequest)
    IPC_MESSAGE_HANDLER(PluginMsg_DidReceiveResponse, OnDidReceiveResponse)
    IPC_MESSAGE_HANDLER(PluginMsg_DidReceiveData, OnDidReceiveData)
    IPC_MESSAGE_HANDLER(PluginMsg_DidFinishLoading, OnDidFinishLoading)
    IPC_MESSAGE_HANDLER(PluginMsg_DidFail, OnDidFail)
    IPC_MESSAGE_HANDLER(PluginMsg_DidFinishLoadWithReason,
                        OnDidFinishLoadWithReason)
    IPC_MESSAGE_HANDLER(PluginMsg_SetFocus, OnSetFocus)
    IPC_MESSAGE_HANDLER(PluginMsg_HandleInputEvent, OnHandleInputEvent)
    IPC_MESSAGE_HANDLER(PluginMsg_Paint, OnPaint)
    IPC_MESSAGE_HANDLER(PluginMsg_DidPaint, OnDidPaint)
    IPC_MESSAGE_HANDLER(PluginMsg_GetPluginScriptableObject,
                        OnGetPluginScriptableObject)
    IPC_MESSAGE_HANDLER(PluginMsg_GetFormValue, OnGetFormValue)
    IPC_MESSAGE_HANDLER(PluginMsg_UpdateGeometry, OnUpdateGeometry)
    IPC_MESSAGE_HANDLER(PluginMsg_UpdateGeometrySync, OnUpdateGeometry)
    IPC_MESSAGE_HANDLER(PluginMsg_SendJavaScriptStream,
                        OnSendJavaScriptStream)
    IPC_MESSAGE_HANDLER(PluginMsg_SetContentAreaFocus, OnSetContentAreaFocus)
#if defined(OS_WIN) && !defined(USE_AURA)
    IPC_MESSAGE_HANDLER(PluginMsg_ImeCompositionUpdated,
                        OnImeCompositionUpdated)
    IPC_MESSAGE_HANDLER(PluginMsg_ImeCompositionCompleted,
                        OnImeCompositionCompleted)
#endif
#if defined(OS_MACOSX)
    IPC_MESSAGE_HANDLER(PluginMsg_SetWindowFocus, OnSetWindowFocus)
    IPC_MESSAGE_HANDLER(PluginMsg_ContainerHidden, OnContainerHidden)
    IPC_MESSAGE_HANDLER(PluginMsg_ContainerShown, OnContainerShown)
    IPC_MESSAGE_HANDLER(PluginMsg_WindowFrameChanged, OnWindowFrameChanged)
    IPC_MESSAGE_HANDLER(PluginMsg_ImeCompositionCompleted,
                        OnImeCompositionCompleted)
#endif
    IPC_MESSAGE_HANDLER(PluginMsg_DidReceiveManualResponse,
                        OnDidReceiveManualResponse)
    IPC_MESSAGE_HANDLER(PluginMsg_DidReceiveManualData, OnDidReceiveManualData)
    IPC_MESSAGE_HANDLER(PluginMsg_DidFinishManualLoading,
                        OnDidFinishManualLoading)
    IPC_MESSAGE_HANDLER(PluginMsg_DidManualLoadFail, OnDidManualLoadFail)
    IPC_MESSAGE_HANDLER(PluginMsg_HandleURLRequestReply,
                        OnHandleURLRequestReply)
    IPC_MESSAGE_HANDLER(PluginMsg_HTTPRangeRequestReply,
                        OnHTTPRangeRequestReply)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()

  if (!in_destructor_)
    Release();

  DCHECK(handled);
  return handled;
}

bool WebPluginDelegateStub::Send(IPC::Message* msg) {
  return channel_->Send(msg);
}

void WebPluginDelegateStub::OnInit(const PluginMsg_Init_Params& params,
                                   bool* transparent,
                                   bool* result) {
  page_url_ = params.page_url;
  GetContentClient()->SetActiveURL(page_url_);

  *transparent = false;
  *result = false;
  if (params.arg_names.size() != params.arg_values.size()) {
    NOTREACHED();
    return;
  }

  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
  base::FilePath path =
      command_line.GetSwitchValuePath(switches::kPluginPath);

  webplugin_ = new WebPluginProxy(channel_.get(),
                                  instance_id_,
                                  page_url_,
                                  params.host_render_view_routing_id);
  delegate_ = webkit::npapi::WebPluginDelegateImpl::Create(path, mime_type_);
  if (delegate_) {
    webplugin_->set_delegate(delegate_);
    std::vector<std::string> arg_names = params.arg_names;
    std::vector<std::string> arg_values = params.arg_values;

    // Register the plugin as a valid object owner.
    WebBindings::registerObjectOwner(delegate_->GetPluginNPP());

    // Add an NPObject owner mapping for this instance, to support ownership
    // tracking in the renderer.
    channel_->AddMappingForNPObjectOwner(instance_id_,
                                         delegate_->GetPluginNPP());

    *result = delegate_->Initialize(params.url,
                                    arg_names,
                                    arg_values,
                                    webplugin_,
                                    params.load_manually);
    *transparent = delegate_->instance()->transparent();
  }
}

void WebPluginDelegateStub::OnWillSendRequest(int id, const GURL& url,
                                              int http_status_code) {
  WebPluginResourceClient* client = webplugin_->GetResourceClient(id);
  if (!client)
    return;

  client->WillSendRequest(url, http_status_code);
}

void WebPluginDelegateStub::OnDidReceiveResponse(
    const PluginMsg_DidReceiveResponseParams& params) {
  WebPluginResourceClient* client = webplugin_->GetResourceClient(params.id);
  if (!client)
    return;

  client->DidReceiveResponse(params.mime_type,
                             params.headers,
                             params.expected_length,
                             params.last_modified,
                             params.request_is_seekable);
}

void WebPluginDelegateStub::OnDidReceiveData(int id,
                                             const std::vector<char>& buffer,
                                             int data_offset) {
  WebPluginResourceClient* client = webplugin_->GetResourceClient(id);
  if (!client)
    return;

  client->DidReceiveData(&buffer.front(), static_cast<int>(buffer.size()),
                         data_offset);
}

void WebPluginDelegateStub::OnDidFinishLoading(int id) {
  WebPluginResourceClient* client = webplugin_->GetResourceClient(id);
  if (!client)
    return;

  client->DidFinishLoading();
}

void WebPluginDelegateStub::OnDidFail(int id) {
  WebPluginResourceClient* client = webplugin_->GetResourceClient(id);
  if (!client)
    return;

  client->DidFail();
}

void WebPluginDelegateStub::OnDidFinishLoadWithReason(
    const GURL& url, int reason, int notify_id) {
  delegate_->DidFinishLoadWithReason(url, reason, notify_id);
}

void WebPluginDelegateStub::OnSetFocus(bool focused) {
  delegate_->SetFocus(focused);
#if defined(OS_WIN) && !defined(USE_AURA)
  if (focused)
    webplugin_->UpdateIMEStatus();
#endif
}

void WebPluginDelegateStub::OnHandleInputEvent(
    const WebKit::WebInputEvent *event,
    bool* handled,
    WebCursor* cursor) {
  WebCursor::CursorInfo cursor_info;
  *handled = delegate_->HandleInputEvent(*event, &cursor_info);
  cursor->InitFromCursorInfo(cursor_info);
}

void WebPluginDelegateStub::OnPaint(const gfx::Rect& damaged_rect) {
  webplugin_->Paint(damaged_rect);
}

void WebPluginDelegateStub::OnDidPaint() {
  webplugin_->DidPaint();
}

void WebPluginDelegateStub::OnUpdateGeometry(
    const PluginMsg_UpdateGeometry_Param& param) {
  webplugin_->UpdateGeometry(
      param.window_rect, param.clip_rect,
      param.windowless_buffer0, param.windowless_buffer1,
      param.windowless_buffer_index);
}

void WebPluginDelegateStub::OnGetPluginScriptableObject(int* route_id) {
  NPObject* object = delegate_->GetPluginScriptableObject();
  if (!object) {
    *route_id = MSG_ROUTING_NONE;
    return;
  }

  *route_id = channel_->GenerateRouteID();
  // We will delete the stub immediately before calling PluginDestroyed on the
  // delegate. It will delete itself sooner if the proxy tells it that it has
  // been released, or if the channel to the proxy is closed.
  NPObjectStub* scriptable_stub = new NPObjectStub(
      object, channel_.get(), *route_id,
      webplugin_->host_render_view_routing_id(), page_url_);
  plugin_scriptable_object_ = scriptable_stub->AsWeakPtr();

  // Release ref added by GetPluginScriptableObject (our stub holds its own).
  WebBindings::releaseObject(object);
}

void WebPluginDelegateStub::OnGetFormValue(string16* value, bool* success) {
  *success = false;
  if (!delegate_)
    return;
  *success = delegate_->GetFormValue(value);
}

void WebPluginDelegateStub::OnSendJavaScriptStream(const GURL& url,
                                                   const std::string& result,
                                                   bool success,
                                                   int notify_id) {
  delegate_->SendJavaScriptStream(url, result, success, notify_id);
}

void WebPluginDelegateStub::OnSetContentAreaFocus(bool has_focus) {
  if (delegate_)
    delegate_->SetContentAreaHasFocus(has_focus);
}

#if defined(OS_WIN) && !defined(USE_AURA)
void WebPluginDelegateStub::OnImeCompositionUpdated(
    const string16& text,
    const std::vector<int>& clauses,
    const std::vector<int>& target,
    int cursor_position) {
  if (delegate_)
    delegate_->ImeCompositionUpdated(text, clauses, target, cursor_position);
#if defined(OS_WIN) && !defined(USE_AURA)
  webplugin_->UpdateIMEStatus();
#endif
}

void WebPluginDelegateStub::OnImeCompositionCompleted(const string16& text) {
  if (delegate_)
    delegate_->ImeCompositionCompleted(text);
}
#endif

#if defined(OS_MACOSX)
void WebPluginDelegateStub::OnSetWindowFocus(bool has_focus) {
  if (delegate_)
    delegate_->SetWindowHasFocus(has_focus);
}

void WebPluginDelegateStub::OnContainerHidden() {
  if (delegate_)
    delegate_->SetContainerVisibility(false);
}

void WebPluginDelegateStub::OnContainerShown(gfx::Rect window_frame,
                                             gfx::Rect view_frame,
                                             bool has_focus) {
  if (delegate_) {
    delegate_->WindowFrameChanged(window_frame, view_frame);
    delegate_->SetContainerVisibility(true);
    delegate_->SetWindowHasFocus(has_focus);
  }
}

void WebPluginDelegateStub::OnWindowFrameChanged(const gfx::Rect& window_frame,
                                                 const gfx::Rect& view_frame) {
  if (delegate_)
    delegate_->WindowFrameChanged(window_frame, view_frame);
}

void WebPluginDelegateStub::OnImeCompositionCompleted(const string16& text) {
  if (delegate_)
    delegate_->ImeCompositionCompleted(text);
}
#endif  // OS_MACOSX

void WebPluginDelegateStub::OnDidReceiveManualResponse(
    const GURL& url,
    const PluginMsg_DidReceiveResponseParams& params) {
  delegate_->DidReceiveManualResponse(url, params.mime_type, params.headers,
                                      params.expected_length,
                                      params.last_modified);
}

void WebPluginDelegateStub::OnDidReceiveManualData(
    const std::vector<char>& buffer) {
  delegate_->DidReceiveManualData(&buffer.front(),
                                  static_cast<int>(buffer.size()));
}

void WebPluginDelegateStub::OnDidFinishManualLoading() {
  delegate_->DidFinishManualLoading();
}

void WebPluginDelegateStub::OnDidManualLoadFail() {
  delegate_->DidManualLoadFail();
}

void WebPluginDelegateStub::OnHandleURLRequestReply(
    unsigned long resource_id, const GURL& url, int notify_id) {
  WebPluginResourceClient* resource_client =
      delegate_->CreateResourceClient(resource_id, url, notify_id);
  webplugin_->OnResourceCreated(resource_id, resource_client);
}

void WebPluginDelegateStub::OnHTTPRangeRequestReply(
    unsigned long resource_id, int range_request_id) {
  WebPluginResourceClient* resource_client =
      delegate_->CreateSeekableResourceClient(resource_id, range_request_id);
  webplugin_->OnResourceCreated(resource_id, resource_client);
}

}  // namespace content
<|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 "webkit/glue/plugins/plugin_list.h"

#include "base/file_util.h"
#include "base/path_service.h"

namespace {

// We build up a list of files and mtimes so we can sort them.
typedef std::pair<FilePath, base::Time> FileAndTime;
typedef std::vector<FileAndTime> FileTimeList;

// Comparator used to sort by descending mtime then ascending filename.
bool CompareTime(const FileAndTime& a, const FileAndTime& b) {
  if (a.second == b.second) {
    // Fall back on filename sorting, just to make the predicate valid.
    return a.first < b.first;
  }

  // Sort by mtime, descending.
  return a.second > b.second;
}

}

namespace NPAPI {

void PluginList::PlatformInit() {
}

void PluginList::GetPluginDirectories(std::vector<FilePath>* plugin_dirs) {
  // Mozilla code to reference:
  // http://mxr.mozilla.org/firefox/ident?i=NS_APP_PLUGINS_DIR_LIST
  // and tens of accompanying files (mxr is very helpful).
  // This code carefully matches their behavior for compat reasons.

  // 1) MOZ_PLUGIN_PATH env variable.
  const char* moz_plugin_path = getenv("MOZ_PLUGIN_PATH");
  if (moz_plugin_path)
    plugin_dirs->push_back(FilePath(moz_plugin_path));

  // 2) NS_USER_PLUGINS_DIR: ~/.mozilla/plugins.
  // This is a de-facto standard, so even though we're not Mozilla, let's
  // look in there too.
  const char* home = getenv("HOME");
  if (home)
    plugin_dirs->push_back(FilePath(home).Append(".mozilla/plugins"));
  // TODO(evanm): maybe consult our own plugins dir, like
  // ~/.config/chromium/Plugins?

  // 3) NS_APP_PLUGINS_DIR: the binary dir + "plugins/".
  FilePath dir;
  PathService::Get(base::DIR_EXE, &dir);
  plugin_dirs->push_back(dir.Append("plugins"));

  // 4) NS_SYSTEM_PLUGINS_DIR:
  // This varies across different versions of Firefox, so check 'em all.
  plugin_dirs->push_back(FilePath("/usr/lib/mozilla/plugins"));
  plugin_dirs->push_back(FilePath("/usr/lib/firefox/plugins"));
  plugin_dirs->push_back(FilePath("/usr/lib/xulrunner-addons/plugins"));
}

void PluginList::LoadPluginsFromDir(const FilePath& path,
                                    std::vector<WebPluginInfo>* plugins) {
  // See ScanPluginsDirectory near
  // http://mxr.mozilla.org/firefox/source/modules/plugin/base/src/nsPluginHostImpl.cpp#5052

  // Construct and stat a list of all filenames under consideration, for
  // later sorting by mtime.
  FileTimeList files;
  file_util::FileEnumerator enumerator(path,
                                       false, // not recursive
                                       file_util::FileEnumerator::FILES);
  for (FilePath path = enumerator.Next(); !path.value().empty();
       path = enumerator.Next()) {
    // Skip over Mozilla .xpt files.
    if (path.MatchesExtension(FILE_PATH_LITERAL(".xpt")))
      continue;

    // Java doesn't like being loaded through a symlink, since it uses
    // its path to find dependent data files.
    // file_util::AbsolutePath calls through to realpath(), which resolves
    // symlinks.
    file_util::AbsolutePath(&path);

    // Get mtime.
    file_util::FileInfo info;
    if (!file_util::GetFileInfo(path, &info))
      continue;

    // Skip duplicates of the same file in our list.
    bool skip = false;
    for (size_t i = 0; i < plugins->size(); ++i) {
      if (plugins->at(i).path == path) {
        skip = true;
        break;
      }
    }
    if (skip)
      continue;

    files.push_back(std::make_pair(path, info.last_modified));
  }

  // Sort the file list by time (and filename).
  std::sort(files.begin(), files.end(), CompareTime);

  // Load the files in order.
  for (FileTimeList::const_iterator i = files.begin(); i != files.end(); ++i) {
    LoadPlugin(i->first, plugins);
  }
}

bool PluginList::ShouldLoadPlugin(const WebPluginInfo& info,
                                  std::vector<WebPluginInfo>* plugins) {
  // TODO(evanm): blacklist nspluginwrapper here?
  // TODO(evanm): prefer the newest version of flash here?

  return true;
}

void PluginList::LoadInternalPlugins(std::vector<WebPluginInfo>* plugins) {
  // none for now
}

} // namespace NPAPI
<commit_msg>linux: prefer non-nspluginwrapper/crossover plugins<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 "webkit/glue/plugins/plugin_list.h"

#include "base/file_util.h"
#include "base/path_service.h"

namespace {

// We build up a list of files and mtimes so we can sort them.
typedef std::pair<FilePath, base::Time> FileAndTime;
typedef std::vector<FileAndTime> FileTimeList;

// Comparator used to sort by descending mtime then ascending filename.
bool CompareTime(const FileAndTime& a, const FileAndTime& b) {
  if (a.second == b.second) {
    // Fall back on filename sorting, just to make the predicate valid.
    return a.first < b.first;
  }

  // Sort by mtime, descending.
  return a.second > b.second;
}

// Some plugins are shells around other plugins; we prefer to use the
// real plugin directly, if it's available.  This function returns
// true if we should prefer other plugins over this one.  We'll still
// use a "undesirable" plugin if no other option is available.
bool IsUndesirablePlugin(const WebPluginInfo& info) {
  std::string filename = info.path.BaseName().value();
  return (filename.find("npcxoffice") != std::string::npos || // Crossover
          filename.find("npwrapper") != std::string::npos);   // nspluginwrapper
}

}  // anonymous namespace

namespace NPAPI {

void PluginList::PlatformInit() {
}

void PluginList::GetPluginDirectories(std::vector<FilePath>* plugin_dirs) {
  // Mozilla code to reference:
  // http://mxr.mozilla.org/firefox/ident?i=NS_APP_PLUGINS_DIR_LIST
  // and tens of accompanying files (mxr is very helpful).
  // This code carefully matches their behavior for compat reasons.

  // 1) MOZ_PLUGIN_PATH env variable.
  const char* moz_plugin_path = getenv("MOZ_PLUGIN_PATH");
  if (moz_plugin_path)
    plugin_dirs->push_back(FilePath(moz_plugin_path));

  // 2) NS_USER_PLUGINS_DIR: ~/.mozilla/plugins.
  // This is a de-facto standard, so even though we're not Mozilla, let's
  // look in there too.
  const char* home = getenv("HOME");
  if (home)
    plugin_dirs->push_back(FilePath(home).Append(".mozilla/plugins"));
  // TODO(evanm): maybe consult our own plugins dir, like
  // ~/.config/chromium/Plugins?

  // 3) NS_APP_PLUGINS_DIR: the binary dir + "plugins/".
  FilePath dir;
  PathService::Get(base::DIR_EXE, &dir);
  plugin_dirs->push_back(dir.Append("plugins"));

  // 4) NS_SYSTEM_PLUGINS_DIR:
  // This varies across different versions of Firefox, so check 'em all.
  plugin_dirs->push_back(FilePath("/usr/lib/mozilla/plugins"));
  plugin_dirs->push_back(FilePath("/usr/lib/firefox/plugins"));
  plugin_dirs->push_back(FilePath("/usr/lib/xulrunner-addons/plugins"));
}

void PluginList::LoadPluginsFromDir(const FilePath& path,
                                    std::vector<WebPluginInfo>* plugins) {
  // See ScanPluginsDirectory near
  // http://mxr.mozilla.org/firefox/source/modules/plugin/base/src/nsPluginHostImpl.cpp#5052

  // Construct and stat a list of all filenames under consideration, for
  // later sorting by mtime.
  FileTimeList files;
  file_util::FileEnumerator enumerator(path,
                                       false, // not recursive
                                       file_util::FileEnumerator::FILES);
  for (FilePath path = enumerator.Next(); !path.value().empty();
       path = enumerator.Next()) {
    // Skip over Mozilla .xpt files.
    if (path.MatchesExtension(FILE_PATH_LITERAL(".xpt")))
      continue;

    // Java doesn't like being loaded through a symlink, since it uses
    // its path to find dependent data files.
    // file_util::AbsolutePath calls through to realpath(), which resolves
    // symlinks.
    file_util::AbsolutePath(&path);

    // Get mtime.
    file_util::FileInfo info;
    if (!file_util::GetFileInfo(path, &info))
      continue;

    // Skip duplicates of the same file in our list.
    bool skip = false;
    for (size_t i = 0; i < plugins->size(); ++i) {
      if (plugins->at(i).path == path) {
        skip = true;
        break;
      }
    }
    if (skip)
      continue;

    files.push_back(std::make_pair(path, info.last_modified));
  }

  // Sort the file list by time (and filename).
  std::sort(files.begin(), files.end(), CompareTime);

  // Load the files in order.
  for (FileTimeList::const_iterator i = files.begin(); i != files.end(); ++i) {
    LoadPlugin(i->first, plugins);
  }
}

bool PluginList::ShouldLoadPlugin(const WebPluginInfo& info,
                                  std::vector<WebPluginInfo>* plugins) {
  if (IsUndesirablePlugin(info)) {
    // See if we have a better version of this plugin.
    for (size_t i = 0; i < plugins->size(); ++i) {
      if (plugins->at(i).name == info.name &&
          !IsUndesirablePlugin(plugins->at(i))) {
        // Skip the current undesirable one so we can use the better one
        // we just found.
        return false;
      }
    }
  }

  // TODO(evanm): prefer the newest version of flash, etc. here?

  return true;
}

void PluginList::LoadInternalPlugins(std::vector<WebPluginInfo>* plugins) {
  // none for now
}

} // namespace NPAPI
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/system_wrappers/interface/logging.h"

#include <string.h>

#include <sstream>

#include "webrtc/common_types.h"
#include "webrtc/system_wrappers/interface/trace.h"

namespace webrtc {
namespace {

TraceLevel WebRtcSeverity(LoggingSeverity sev) {
  switch (sev) {
    // TODO(ajm): SENSITIVE doesn't have a corresponding webrtc level.
    case LS_SENSITIVE:  return kTraceInfo;
    case LS_VERBOSE:    return kTraceInfo;
    case LS_INFO:       return kTraceTerseInfo;
    case LS_WARNING:    return kTraceWarning;
    case LS_ERROR:      return kTraceError;
    default:            return kTraceNone;
  }
}

const char* DescribeFile(const char* file) {
  const char* end1 = ::strrchr(file, '/');
  const char* end2 = ::strrchr(file, '\\');
  if (!end1 && !end2)
    return file;
  else
    return (end1 > end2) ? end1 + 1 : end2 + 1;
}

}  // namespace

LogMessage::LogMessage(const char* file, int line, LoggingSeverity sev)
    : severity_(sev) {
  print_stream_ << "(" << DescribeFile(file) << ":" << line << "): ";
}

bool LogMessage::Loggable(LoggingSeverity sev) {
  // |level_filter| is a bitmask, unlike libjingle's minimum severity value.
  return WebRtcSeverity(sev) & Trace::level_filter() ? true : false;
}

LogMessage::~LogMessage() {
  const std::string& str = print_stream_.str();
  Trace::Add(WebRtcSeverity(severity_), kTraceUndefined, 0, str.c_str());
}

}  // namespace webrtc
<commit_msg>Fix ::~LogMessage to print as a string.<commit_after>/*
 *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/system_wrappers/interface/logging.h"

#include <string.h>

#include <sstream>

#include "webrtc/common_types.h"
#include "webrtc/system_wrappers/interface/trace.h"

namespace webrtc {
namespace {

TraceLevel WebRtcSeverity(LoggingSeverity sev) {
  switch (sev) {
    // TODO(ajm): SENSITIVE doesn't have a corresponding webrtc level.
    case LS_SENSITIVE:  return kTraceInfo;
    case LS_VERBOSE:    return kTraceInfo;
    case LS_INFO:       return kTraceTerseInfo;
    case LS_WARNING:    return kTraceWarning;
    case LS_ERROR:      return kTraceError;
    default:            return kTraceNone;
  }
}

const char* DescribeFile(const char* file) {
  const char* end1 = ::strrchr(file, '/');
  const char* end2 = ::strrchr(file, '\\');
  if (!end1 && !end2)
    return file;
  else
    return (end1 > end2) ? end1 + 1 : end2 + 1;
}

}  // namespace

LogMessage::LogMessage(const char* file, int line, LoggingSeverity sev)
    : severity_(sev) {
  print_stream_ << "(" << DescribeFile(file) << ":" << line << "): ";
}

bool LogMessage::Loggable(LoggingSeverity sev) {
  // |level_filter| is a bitmask, unlike libjingle's minimum severity value.
  return WebRtcSeverity(sev) & Trace::level_filter() ? true : false;
}

LogMessage::~LogMessage() {
  const std::string& str = print_stream_.str();
  Trace::Add(WebRtcSeverity(severity_), kTraceUndefined, 0, "%s", str.c_str());
}

}  // namespace webrtc
<|endoftext|>


<commit_before><commit_msg>high restart interval<commit_after><|endoftext|>