<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_SURFACE_IMPL_MLS_H_
#define PCL_SURFACE_IMPL_MLS_H_

#include "pcl/surface/mls.h"
#include <pcl/common/io.h>
#include <pcl/common/centroid.h>
#include <pcl/common/eigen.h>

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename NormalOutT> void
pcl::MovingLeastSquares<PointInT, NormalOutT>::reconstruct (PointCloudIn &output)
{
  // check if normals have to be computed/saved
  if (normals_)
  {
    // Copy the header
    normals_->header = input_->header;
    // Clear the fields in case the method exits before computation
    normals_->width = normals_->height = 0;
    normals_->points.clear ();
  }

  // Copy the header
  output.header = input_->header;

  if (search_radius_ <= 0 || sqr_gauss_param_ <= 0)
  {
    PCL_ERROR ("[pcl::%s::reconstruct] Invalid search radius (%f) or Gaussian parameter (%f)!\n", getClassName ().c_str (), search_radius_, sqr_gauss_param_);
    output.width = output.height = 0;
    output.points.clear ();
    return;
  }

  if (!initCompute ())
  {
    output.width = output.height = 0;
    output.points.clear ();
    return;
  }

  // Initialize the spatial locator
  if (!tree_)
  {
    KdTreePtr tree;
    if (input_->isOrganized ())
      tree.reset (new pcl::search::OrganizedNeighbor<PointInT> ());
    else
      tree.reset (new pcl::search::KdTree<PointInT> (false));
    setSearchMethod (tree);
  }

  // Send the surface dataset to the spatial locator
  tree_->setInputCloud (input_, indices_);

  // Use original point positions for fitting
  // \note no up/down/adapting-sampling or hole filling possible like this
  output.points.resize (indices_->size ());
  // Check if fake indices were used, otherwise the output loses its organized structure
  if (!fake_indices_)
    pcl::copyPointCloud (*input_, *indices_, output);
  else
    output = *input_;

  // Resize the output normal dataset
  if (normals_)
  {
    normals_->points.resize (output.points.size ());
    normals_->width    = output.width;
    normals_->height   = output.height;
    normals_->is_dense = output.is_dense;
  }

  // Perform the actual surface reconstruction
  performReconstruction (output);

  deinitCompute ();
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename NormalOutT> void
pcl::MovingLeastSquares<PointInT, NormalOutT>::computeMLSPointNormal (PointInT &pt,
                                                                      const PointCloudIn &input,
                                                                      const std::vector<int> &nn_indices,
                                                                      std::vector<float> &nn_sqr_dists,
                                                                      Eigen::Vector4f &model_coefficients)
{
  // Compute the plane coefficients
  //pcl::computePointNormal<PointInT> (*input_, nn_indices, model_coefficients, curvature);
  EIGEN_ALIGN16 Eigen::Matrix3f covariance_matrix;
  Eigen::Vector4f xyz_centroid;

  // Estimate the XYZ centroid
  pcl::compute3DCentroid (input, nn_indices, xyz_centroid);

  // Compute the 3x3 covariance matrix
  pcl::computeCovarianceMatrix (input, nn_indices, xyz_centroid, covariance_matrix);

  // Get the plane normal
  EIGEN_ALIGN16 Eigen::Vector3f::Scalar eigen_value;
  EIGEN_ALIGN16 Eigen::Vector3f eigen_vector;
  pcl::eigen33 (covariance_matrix, eigen_value, eigen_vector);
  model_coefficients.head<3> () = eigen_vector;
  model_coefficients[3] = -1 * model_coefficients.dot (xyz_centroid);

  // Projected point
  Eigen::Vector3f point = pt.getVector3fMap ();
  float distance = point.dot (model_coefficients.head<3> ()) + model_coefficients[3];
  point -= distance * model_coefficients.head<3> ();

  float curvature = covariance_matrix.trace ();
  // Compute the curvature surface change
  if (curvature != 0)
    curvature = fabs (eigen_value / curvature);

  // Perform polynomial fit to update point and normal
  ////////////////////////////////////////////////////
  if (polynomial_fit_ && (int)nn_indices.size () >= nr_coeff_)
  {
    // Get a copy of the plane normal easy access
    Eigen::Vector3d plane_normal = model_coefficients.head<3> ().cast<double> ();

    // Update neighborhood, since point was projected, and computing relative
    // positions. Note updating only distances for the weights for speed
    std::vector<Eigen::Vector3d> de_meaned (nn_indices.size ());
    for (size_t ni = 0; ni < nn_indices.size (); ++ni)
    {
      de_meaned[ni][0] = input_->points[nn_indices[ni]].x - point[0];
      de_meaned[ni][1] = input_->points[nn_indices[ni]].y - point[1];
      de_meaned[ni][2] = input_->points[nn_indices[ni]].z - point[2];
      nn_sqr_dists[ni] = de_meaned[ni].dot (de_meaned[ni]);
    }

    // Allocate matrices and vectors to hold the data used for the polynomial fit
    Eigen::VectorXd weight_vec (nn_indices.size ());
    Eigen::MatrixXd P (nr_coeff_, nn_indices.size ());
    Eigen::VectorXd f_vec (nn_indices.size ());
    Eigen::VectorXd c_vec;
    Eigen::MatrixXd P_weight; // size will be (nr_coeff_, nn_indices.size ());
    Eigen::MatrixXd P_weight_Pt (nr_coeff_, nr_coeff_);

    // Get local coordinate system (Darboux frame)
    Eigen::Vector3d v = plane_normal.unitOrthogonal ();
    Eigen::Vector3d u = plane_normal.cross (v);

    // Go through neighbors, transform them in the local coordinate system,
    // save height and the evaluation of the polynome's terms
    double u_coord, v_coord, u_pow, v_pow;
    for (size_t ni = 0; ni < nn_indices.size (); ++ni)
    {
      // (re-)compute weights
      weight_vec (ni) = exp (-nn_sqr_dists[ni] / sqr_gauss_param_);

      // transforming coordinates
      u_coord = de_meaned[ni].dot (u);
      v_coord = de_meaned[ni].dot (v);
      f_vec (ni) = de_meaned[ni].dot (plane_normal);

      // compute the polynomial's terms at the current point
      int j = 0;
      u_pow = 1;
      for (int ui = 0; ui <= order_; ++ui)
      {
        v_pow = 1;
        for (int vi = 0; vi <= order_ - ui; ++vi)
        {
          P (j++, ni) = u_pow * v_pow;
          v_pow *= v_coord;
        }
        u_pow *= u_coord;
      }
    }

    // Computing coefficients
    P_weight = P * weight_vec.asDiagonal ();
    P_weight_Pt = P_weight * P.transpose ();
    c_vec = P_weight * f_vec;
    P_weight_Pt.llt ().solveInPlace (c_vec);

    // Projection onto MLS surface along Darboux normal to the height at (0,0)
    if (pcl_isfinite (c_vec[0]))
    {
      point += (c_vec[0] * plane_normal).cast<float> ();

      // Compute tangent vectors using the partial derivates evaluated at (0,0) which is c_vec[order_+1] and c_vec[1]
      if (normals_)
      {
        Eigen::Vector3d normal = c_vec[order_ + 1] * u + c_vec[1] * v - plane_normal;
        model_coefficients.head<3> () = normal.cast<float> ();
        model_coefficients.head<3> ().normalize ();
      }
    }
  }

  // Save the smoothed results
  pt.x = point[0];
  pt.y = point[1];
  pt.z = point[2];

  model_coefficients[3] = curvature;
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename NormalOutT> void
pcl::MovingLeastSquares<PointInT, NormalOutT>::performReconstruction (PointCloudIn &output)
{
  // Compute the number of coefficients
  nr_coeff_ = (order_ + 1) * (order_ + 2) / 2;

  // Allocate enough space to hold the results of nearest neighbor searches
  // \note resize is irrelevant for a radiusSearch ().
  std::vector<int> nn_indices;
  std::vector<float> nn_sqr_dists;

  // For all points
  for (size_t cp = 0; cp < indices_->size (); ++cp)
  {
    // Get the initial estimates of point positions and their neighborhoods
    if (!searchForNeighbors ((*indices_)[cp], nn_indices, nn_sqr_dists))
    {
      if (normals_)
        normals_->points[cp].normal[0] = normals_->points[cp].normal[1] = normals_->points[cp].normal[2] = normals_->points[cp].curvature = std::numeric_limits<float>::quiet_NaN ();
      continue;
    }

    // Check the number of nearest neighbors for normal estimation (and later
    // for polynomial fit as well)
    if (nn_indices.size () < 3)
      continue;

    Eigen::Vector4f model_coefficients;
    // Get a plane approximating the local surface's tangent and project point onto it
    computeMLSPointNormal (output.points[cp], *input_, nn_indices, nn_sqr_dists,
                           model_coefficients);

    // Save results to output cloud
    if (normals_)
    {
      normals_->points[cp].normal[0] = model_coefficients[0];
      normals_->points[cp].normal[1] = model_coefficients[1];
      normals_->points[cp].normal[2] = model_coefficients[2];
      normals_->points[cp].curvature = model_coefficients[3];
    }
  }
}

#define PCL_INSTANTIATE_MovingLeastSquares(T,OutT) template class PCL_EXPORTS pcl::MovingLeastSquares<T,OutT>;

#endif    // PCL_SURFACE_IMPL_MLS_H_

<commit_msg>bugfix, set eigenvalue to negative value to indicate that the smallest one needs to be computed, otherwise its assumed that its given and calculates the corresponding eigenvalue<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_SURFACE_IMPL_MLS_H_
#define PCL_SURFACE_IMPL_MLS_H_

#include "pcl/surface/mls.h"
#include <pcl/common/io.h>
#include <pcl/common/centroid.h>
#include <pcl/common/eigen.h>

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename NormalOutT> void
pcl::MovingLeastSquares<PointInT, NormalOutT>::reconstruct (PointCloudIn &output)
{
  // check if normals have to be computed/saved
  if (normals_)
  {
    // Copy the header
    normals_->header = input_->header;
    // Clear the fields in case the method exits before computation
    normals_->width = normals_->height = 0;
    normals_->points.clear ();
  }

  // Copy the header
  output.header = input_->header;

  if (search_radius_ <= 0 || sqr_gauss_param_ <= 0)
  {
    PCL_ERROR ("[pcl::%s::reconstruct] Invalid search radius (%f) or Gaussian parameter (%f)!\n", getClassName ().c_str (), search_radius_, sqr_gauss_param_);
    output.width = output.height = 0;
    output.points.clear ();
    return;
  }

  if (!initCompute ())
  {
    output.width = output.height = 0;
    output.points.clear ();
    return;
  }

  // Initialize the spatial locator
  if (!tree_)
  {
    KdTreePtr tree;
    if (input_->isOrganized ())
      tree.reset (new pcl::search::OrganizedNeighbor<PointInT> ());
    else
      tree.reset (new pcl::search::KdTree<PointInT> (false));
    setSearchMethod (tree);
  }

  // Send the surface dataset to the spatial locator
  tree_->setInputCloud (input_, indices_);

  // Use original point positions for fitting
  // \note no up/down/adapting-sampling or hole filling possible like this
  output.points.resize (indices_->size ());
  // Check if fake indices were used, otherwise the output loses its organized structure
  if (!fake_indices_)
    pcl::copyPointCloud (*input_, *indices_, output);
  else
    output = *input_;

  // Resize the output normal dataset
  if (normals_)
  {
    normals_->points.resize (output.points.size ());
    normals_->width    = output.width;
    normals_->height   = output.height;
    normals_->is_dense = output.is_dense;
  }

  // Perform the actual surface reconstruction
  performReconstruction (output);

  deinitCompute ();
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename NormalOutT> void
pcl::MovingLeastSquares<PointInT, NormalOutT>::computeMLSPointNormal (PointInT &pt,
                                                                      const PointCloudIn &input,
                                                                      const std::vector<int> &nn_indices,
                                                                      std::vector<float> &nn_sqr_dists,
                                                                      Eigen::Vector4f &model_coefficients)
{
  // Compute the plane coefficients
  //pcl::computePointNormal<PointInT> (*input_, nn_indices, model_coefficients, curvature);
  EIGEN_ALIGN16 Eigen::Matrix3f covariance_matrix;
  Eigen::Vector4f xyz_centroid;

  // Estimate the XYZ centroid
  pcl::compute3DCentroid (input, nn_indices, xyz_centroid);

  // Compute the 3x3 covariance matrix
  pcl::computeCovarianceMatrix (input, nn_indices, xyz_centroid, covariance_matrix);

  // Get the plane normal
  EIGEN_ALIGN16 Eigen::Vector3f::Scalar eigen_value = -1;
  EIGEN_ALIGN16 Eigen::Vector3f eigen_vector;
  pcl::eigen33 (covariance_matrix, eigen_value, eigen_vector);
  model_coefficients.head<3> () = eigen_vector;
  model_coefficients[3] = -1 * model_coefficients.dot (xyz_centroid);

  // Projected point
  Eigen::Vector3f point = pt.getVector3fMap ();
  float distance = point.dot (model_coefficients.head<3> ()) + model_coefficients[3];
  point -= distance * model_coefficients.head<3> ();

  float curvature = covariance_matrix.trace ();
  // Compute the curvature surface change
  if (curvature != 0)
    curvature = fabs (eigen_value / curvature);

  // Perform polynomial fit to update point and normal
  ////////////////////////////////////////////////////
  if (polynomial_fit_ && (int)nn_indices.size () >= nr_coeff_)
  {
    // Get a copy of the plane normal easy access
    Eigen::Vector3d plane_normal = model_coefficients.head<3> ().cast<double> ();

    // Update neighborhood, since point was projected, and computing relative
    // positions. Note updating only distances for the weights for speed
    std::vector<Eigen::Vector3d> de_meaned (nn_indices.size ());
    for (size_t ni = 0; ni < nn_indices.size (); ++ni)
    {
      de_meaned[ni][0] = input_->points[nn_indices[ni]].x - point[0];
      de_meaned[ni][1] = input_->points[nn_indices[ni]].y - point[1];
      de_meaned[ni][2] = input_->points[nn_indices[ni]].z - point[2];
      nn_sqr_dists[ni] = de_meaned[ni].dot (de_meaned[ni]);
    }

    // Allocate matrices and vectors to hold the data used for the polynomial fit
    Eigen::VectorXd weight_vec (nn_indices.size ());
    Eigen::MatrixXd P (nr_coeff_, nn_indices.size ());
    Eigen::VectorXd f_vec (nn_indices.size ());
    Eigen::VectorXd c_vec;
    Eigen::MatrixXd P_weight; // size will be (nr_coeff_, nn_indices.size ());
    Eigen::MatrixXd P_weight_Pt (nr_coeff_, nr_coeff_);

    // Get local coordinate system (Darboux frame)
    Eigen::Vector3d v = plane_normal.unitOrthogonal ();
    Eigen::Vector3d u = plane_normal.cross (v);

    // Go through neighbors, transform them in the local coordinate system,
    // save height and the evaluation of the polynome's terms
    double u_coord, v_coord, u_pow, v_pow;
    for (size_t ni = 0; ni < nn_indices.size (); ++ni)
    {
      // (re-)compute weights
      weight_vec (ni) = exp (-nn_sqr_dists[ni] / sqr_gauss_param_);

      // transforming coordinates
      u_coord = de_meaned[ni].dot (u);
      v_coord = de_meaned[ni].dot (v);
      f_vec (ni) = de_meaned[ni].dot (plane_normal);

      // compute the polynomial's terms at the current point
      int j = 0;
      u_pow = 1;
      for (int ui = 0; ui <= order_; ++ui)
      {
        v_pow = 1;
        for (int vi = 0; vi <= order_ - ui; ++vi)
        {
          P (j++, ni) = u_pow * v_pow;
          v_pow *= v_coord;
        }
        u_pow *= u_coord;
      }
    }

    // Computing coefficients
    P_weight = P * weight_vec.asDiagonal ();
    P_weight_Pt = P_weight * P.transpose ();
    c_vec = P_weight * f_vec;
    P_weight_Pt.llt ().solveInPlace (c_vec);

    // Projection onto MLS surface along Darboux normal to the height at (0,0)
    if (pcl_isfinite (c_vec[0]))
    {
      point += (c_vec[0] * plane_normal).cast<float> ();

      // Compute tangent vectors using the partial derivates evaluated at (0,0) which is c_vec[order_+1] and c_vec[1]
      if (normals_)
      {
        Eigen::Vector3d normal = c_vec[order_ + 1] * u + c_vec[1] * v - plane_normal;
        model_coefficients.head<3> () = normal.cast<float> ();
        model_coefficients.head<3> ().normalize ();
      }
    }
  }

  // Save the smoothed results
  pt.x = point[0];
  pt.y = point[1];
  pt.z = point[2];

  model_coefficients[3] = curvature;
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename NormalOutT> void
pcl::MovingLeastSquares<PointInT, NormalOutT>::performReconstruction (PointCloudIn &output)
{
  // Compute the number of coefficients
  nr_coeff_ = (order_ + 1) * (order_ + 2) / 2;

  // Allocate enough space to hold the results of nearest neighbor searches
  // \note resize is irrelevant for a radiusSearch ().
  std::vector<int> nn_indices;
  std::vector<float> nn_sqr_dists;

  // For all points
  for (size_t cp = 0; cp < indices_->size (); ++cp)
  {
    // Get the initial estimates of point positions and their neighborhoods
    if (!searchForNeighbors ((*indices_)[cp], nn_indices, nn_sqr_dists))
    {
      if (normals_)
        normals_->points[cp].normal[0] = normals_->points[cp].normal[1] = normals_->points[cp].normal[2] = normals_->points[cp].curvature = std::numeric_limits<float>::quiet_NaN ();
      continue;
    }

    // Check the number of nearest neighbors for normal estimation (and later
    // for polynomial fit as well)
    if (nn_indices.size () < 3)
      continue;

    Eigen::Vector4f model_coefficients;
    // Get a plane approximating the local surface's tangent and project point onto it
    computeMLSPointNormal (output.points[cp], *input_, nn_indices, nn_sqr_dists,
                           model_coefficients);

    // Save results to output cloud
    if (normals_)
    {
      normals_->points[cp].normal[0] = model_coefficients[0];
      normals_->points[cp].normal[1] = model_coefficients[1];
      normals_->points[cp].normal[2] = model_coefficients[2];
      normals_->points[cp].curvature = model_coefficients[3];
    }
  }
}

#define PCL_INSTANTIATE_MovingLeastSquares(T,OutT) template class PCL_EXPORTS pcl::MovingLeastSquares<T,OutT>;

#endif    // PCL_SURFACE_IMPL_MLS_H_

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fmtextcontrolfeature.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 15:58:24 $
 *
 *  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 SVX_SOURCE_INC_FMTEXTCONTROLFEATURE_HXX
#include "fmtextcontrolfeature.hxx"
#endif

/** === begin UNO includes === **/
/** === end UNO includes === **/

//........................................................................
namespace svx
{
//........................................................................

    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::frame;
    using namespace ::com::sun::star::lang;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::util;

    //====================================================================
    //= FmTextControlFeature
    //====================================================================
    //--------------------------------------------------------------------
    FmTextControlFeature::FmTextControlFeature( const Reference< XDispatch >& _rxDispatcher, const URL& _rFeatureURL, SfxSlotId _nSlotId, ISlotInvalidator* _pInvalidator )
        :m_xDispatcher    ( _rxDispatcher )
        ,m_aFeatureURL    ( _rFeatureURL  )
        ,m_nSlotId        ( _nSlotId      )
        ,m_pInvalidator   ( _pInvalidator )
        ,m_bFeatureEnabled( false         )
    {
        OSL_ENSURE( _rxDispatcher.is(), "FmTextControlFeature::FmTextControlFeature: invalid dispatcher!"  );
        OSL_ENSURE( m_nSlotId,          "FmTextControlFeature::FmTextControlFeature: invalid slot id!"     );
        OSL_ENSURE( m_pInvalidator,     "FmTextControlFeature::FmTextControlFeature: invalid invalidator!" );

        osl_incrementInterlockedCount( &m_refCount );
        try
        {
            m_xDispatcher->addStatusListener( this, m_aFeatureURL );
        }
        catch( const Exception& )
        {
            OSL_ENSURE( sal_False, "FmTextControlFeature::FmTextControlFeature: caught an exception!" );
        }
        osl_decrementInterlockedCount( &m_refCount );
    }

    //--------------------------------------------------------------------
    FmTextControlFeature::~FmTextControlFeature( )
    {
    }

    //--------------------------------------------------------------------
    void FmTextControlFeature::dispatch() const SAL_THROW(())
    {
        dispatch( Sequence< PropertyValue >( ) );
    }

    //--------------------------------------------------------------------
    void FmTextControlFeature::dispatch( const Sequence< PropertyValue >& _rArgs ) const SAL_THROW(())
    {
        try
        {
            if ( m_xDispatcher.is() )
                m_xDispatcher->dispatch( m_aFeatureURL, _rArgs );
        }
        catch( const Exception& )
        {
            OSL_ENSURE( sal_False, "FmTextControlFeature::dispatch: caught an exception!" );
        }
    }

    //--------------------------------------------------------------------
    void SAL_CALL FmTextControlFeature::statusChanged( const FeatureStateEvent& _rState ) throw (RuntimeException)
    {
        m_aFeatureState   = _rState.State;
        m_bFeatureEnabled = _rState.IsEnabled;

        if ( m_pInvalidator )
            m_pInvalidator->Invalidate( m_nSlotId );
    }

    //--------------------------------------------------------------------
    void SAL_CALL FmTextControlFeature::disposing( const EventObject& /*Source*/ ) throw (RuntimeException)
    {
        // nothing to do
    }

    //--------------------------------------------------------------------
    void FmTextControlFeature::dispose() SAL_THROW(())
    {
        try
        {
            m_xDispatcher->removeStatusListener( this, m_aFeatureURL );
            m_xDispatcher.clear();
        }
        catch( const Exception& )
        {
            OSL_ENSURE( sal_False, "FmTextControlFeature::dispose: caught an exception!" );
        }
    }

//........................................................................
}   // namespace svx
//........................................................................

<commit_msg>INTEGRATION: CWS pchfix02 (1.4.116); FILE MERGED 2006/09/01 17:46:52 kaib 1.4.116.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fmtextcontrolfeature.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 05:10:20 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#ifndef SVX_SOURCE_INC_FMTEXTCONTROLFEATURE_HXX
#include "fmtextcontrolfeature.hxx"
#endif

/** === begin UNO includes === **/
/** === end UNO includes === **/

//........................................................................
namespace svx
{
//........................................................................

    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::frame;
    using namespace ::com::sun::star::lang;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::util;

    //====================================================================
    //= FmTextControlFeature
    //====================================================================
    //--------------------------------------------------------------------
    FmTextControlFeature::FmTextControlFeature( const Reference< XDispatch >& _rxDispatcher, const URL& _rFeatureURL, SfxSlotId _nSlotId, ISlotInvalidator* _pInvalidator )
        :m_xDispatcher    ( _rxDispatcher )
        ,m_aFeatureURL    ( _rFeatureURL  )
        ,m_nSlotId        ( _nSlotId      )
        ,m_pInvalidator   ( _pInvalidator )
        ,m_bFeatureEnabled( false         )
    {
        OSL_ENSURE( _rxDispatcher.is(), "FmTextControlFeature::FmTextControlFeature: invalid dispatcher!"  );
        OSL_ENSURE( m_nSlotId,          "FmTextControlFeature::FmTextControlFeature: invalid slot id!"     );
        OSL_ENSURE( m_pInvalidator,     "FmTextControlFeature::FmTextControlFeature: invalid invalidator!" );

        osl_incrementInterlockedCount( &m_refCount );
        try
        {
            m_xDispatcher->addStatusListener( this, m_aFeatureURL );
        }
        catch( const Exception& )
        {
            OSL_ENSURE( sal_False, "FmTextControlFeature::FmTextControlFeature: caught an exception!" );
        }
        osl_decrementInterlockedCount( &m_refCount );
    }

    //--------------------------------------------------------------------
    FmTextControlFeature::~FmTextControlFeature( )
    {
    }

    //--------------------------------------------------------------------
    void FmTextControlFeature::dispatch() const SAL_THROW(())
    {
        dispatch( Sequence< PropertyValue >( ) );
    }

    //--------------------------------------------------------------------
    void FmTextControlFeature::dispatch( const Sequence< PropertyValue >& _rArgs ) const SAL_THROW(())
    {
        try
        {
            if ( m_xDispatcher.is() )
                m_xDispatcher->dispatch( m_aFeatureURL, _rArgs );
        }
        catch( const Exception& )
        {
            OSL_ENSURE( sal_False, "FmTextControlFeature::dispatch: caught an exception!" );
        }
    }

    //--------------------------------------------------------------------
    void SAL_CALL FmTextControlFeature::statusChanged( const FeatureStateEvent& _rState ) throw (RuntimeException)
    {
        m_aFeatureState   = _rState.State;
        m_bFeatureEnabled = _rState.IsEnabled;

        if ( m_pInvalidator )
            m_pInvalidator->Invalidate( m_nSlotId );
    }

    //--------------------------------------------------------------------
    void SAL_CALL FmTextControlFeature::disposing( const EventObject& /*Source*/ ) throw (RuntimeException)
    {
        // nothing to do
    }

    //--------------------------------------------------------------------
    void FmTextControlFeature::dispose() SAL_THROW(())
    {
        try
        {
            m_xDispatcher->removeStatusListener( this, m_aFeatureURL );
            m_xDispatcher.clear();
        }
        catch( const Exception& )
        {
            OSL_ENSURE( sal_False, "FmTextControlFeature::dispose: caught an exception!" );
        }
    }

//........................................................................
}   // namespace svx
//........................................................................

<|endoftext|>


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

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

#ifndef _SDR_PROPERTIES_PROPERTIES_HXX
#include <svx/sdr/properties/properties.hxx>
#endif

#ifndef _SDR_PROPERTIES_ITEMSETTOOLS_HXX
#include <svx/sdr/properties/itemsettools.hxx>
#endif

#ifndef _SFXITEMSET_HXX
#include <svtools/itemset.hxx>
#endif

#ifndef _SVDOGRP_HXX
#include <svx/svdogrp.hxx>
#endif

#ifndef _SVDITER_HXX
#include <svditer.hxx>
#endif

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

namespace sdr
{
    namespace properties
    {
        BaseProperties::BaseProperties(SdrObject& rObj)
        :   mrObject(rObj)
        {
        }

        BaseProperties::BaseProperties(const BaseProperties& /*rProps*/, SdrObject& rObj)
        :   mrObject(rObj)
        {
        }

        BaseProperties::~BaseProperties()
        {
        }

        const SfxItemSet& BaseProperties::GetMergedItemSet() const
        {
            // default implementation falls back to GetObjectItemSet()
            return GetObjectItemSet();
        }

        void BaseProperties::SetMergedItemSet(const SfxItemSet& rSet, sal_Bool bClearAllItems)
        {
            // clear items if requested
            if(bClearAllItems)
            {
                ClearObjectItem();
            }

            // default implementation falls back to SetObjectItemSet()
            SetObjectItemSet(rSet);
        }

        void BaseProperties::SetMergedItem(const SfxPoolItem& rItem)
        {
            // default implementation falls back to SetObjectItem()
            SetObjectItem(rItem);
        }

        void BaseProperties::ClearMergedItem(const sal_uInt16 nWhich)
        {
            // default implementation falls back to ClearObjectItem()
            ClearObjectItem(nWhich);
        }

        void BaseProperties::Scale(const Fraction& /*rScale*/)
        {
            // default implementation does nothing; overload where
            // an ItemSet is implemented.
        }

        void BaseProperties::MoveToItemPool(SfxItemPool* /*pSrcPool*/, SfxItemPool* /*pDestPool*/, SdrModel* /*pNewModel*/)
        {
            // Move properties to a new ItemPool. Default implementation does nothing.
            // Overload where an ItemSet is implemented.
        }

        void BaseProperties::SetModel(SdrModel* /*pOldModel*/, SdrModel* /*pNewModel*/)
        {
            // Set new model. Default implementation does nothing.
            // Overload where an ItemSet is implemented.
        }

        void BaseProperties::ForceStyleToHardAttributes()
        {
            // force all attributes which come from styles to hard attributes
            // to be able to live without the style. Default implementation does nothing.
            // Overload where an ItemSet is implemented.
        }

        //void BaseProperties::SetItemAndBroadcast(const SfxPoolItem& rItem)
        //{
        //  ItemChangeBroadcaster aC(GetSdrObject());
        //  SetObjectItem(rItem);
        //  BroadcastItemChange(aC);
        //}

        //void BaseProperties::ClearItemAndBroadcast(const sal_uInt16 nWhich)
        //{
        //  ItemChangeBroadcaster aC(GetSdrObject());
        //  ClearObjectItem(nWhich);
        //  BroadcastItemChange(aC);
        //}

        void BaseProperties::SetMergedItemSetAndBroadcast(const SfxItemSet& rSet, sal_Bool bClearAllItems)
        {
            ItemChangeBroadcaster aC(GetSdrObject());

            if(bClearAllItems)
            {
                ClearObjectItem();
            }

            SetMergedItemSet(rSet);
            BroadcastItemChange(aC);
        }

        const SfxPoolItem& BaseProperties::GetItem(const sal_uInt16 nWhich) const
        {
            return GetObjectItemSet().Get(nWhich);
        }

        void BaseProperties::BroadcastItemChange(const ItemChangeBroadcaster& rChange)
        {
            const sal_uInt32 nCount(rChange.GetRectangleCount());

            // #110094#-14 Reduce to do only second change
            //// invalidate all remembered rectangles
            //for(sal_uInt32 a(0); a < nCount; a++)
            //{
            //  GetSdrObject().BroadcastObjectChange(rChange.GetRectangle(a));
            //}

            // invalidate all new rectangles
            if(GetSdrObject().ISA(SdrObjGroup))
            {
                SdrObjListIter aIter((SdrObjGroup&)GetSdrObject(), IM_DEEPNOGROUPS);

                while(aIter.IsMore())
                {
                    SdrObject* pObj = aIter.Next();
                    // This is done with ItemSetChanged
                    // pObj->SetChanged();
                    pObj->BroadcastObjectChange();
                }
            }
            else
            {
                // This is done with ItemSetChanged
                // GetSdrObject().SetChanged();
                GetSdrObject().BroadcastObjectChange();
            }

            // also send the user calls
            for(sal_uInt32 a(0L); a < nCount; a++)
            {
                GetSdrObject().SendUserCall(SDRUSERCALL_CHGATTR, rChange.GetRectangle(a));
            }
        }
    } // end of namespace properties
} // end of namespace sdr

//////////////////////////////////////////////////////////////////////////////
// eof
<commit_msg>INTEGRATION: CWS changefileheader (1.7.368); FILE MERGED 2008/04/01 15:51:33 thb 1.7.368.3: #i85898# Stripping all external header guards 2008/04/01 12:49:44 thb 1.7.368.2: #i85898# Stripping all external header guards 2008/03/31 14:23:15 rt 1.7.368.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: properties.cxx,v $
 * $Revision: 1.8 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#include <svx/sdr/properties/properties.hxx>
#include <svx/sdr/properties/itemsettools.hxx>
#include <svtools/itemset.hxx>
#include <svx/svdogrp.hxx>
#include <svditer.hxx>

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

namespace sdr
{
    namespace properties
    {
        BaseProperties::BaseProperties(SdrObject& rObj)
        :   mrObject(rObj)
        {
        }

        BaseProperties::BaseProperties(const BaseProperties& /*rProps*/, SdrObject& rObj)
        :   mrObject(rObj)
        {
        }

        BaseProperties::~BaseProperties()
        {
        }

        const SfxItemSet& BaseProperties::GetMergedItemSet() const
        {
            // default implementation falls back to GetObjectItemSet()
            return GetObjectItemSet();
        }

        void BaseProperties::SetMergedItemSet(const SfxItemSet& rSet, sal_Bool bClearAllItems)
        {
            // clear items if requested
            if(bClearAllItems)
            {
                ClearObjectItem();
            }

            // default implementation falls back to SetObjectItemSet()
            SetObjectItemSet(rSet);
        }

        void BaseProperties::SetMergedItem(const SfxPoolItem& rItem)
        {
            // default implementation falls back to SetObjectItem()
            SetObjectItem(rItem);
        }

        void BaseProperties::ClearMergedItem(const sal_uInt16 nWhich)
        {
            // default implementation falls back to ClearObjectItem()
            ClearObjectItem(nWhich);
        }

        void BaseProperties::Scale(const Fraction& /*rScale*/)
        {
            // default implementation does nothing; overload where
            // an ItemSet is implemented.
        }

        void BaseProperties::MoveToItemPool(SfxItemPool* /*pSrcPool*/, SfxItemPool* /*pDestPool*/, SdrModel* /*pNewModel*/)
        {
            // Move properties to a new ItemPool. Default implementation does nothing.
            // Overload where an ItemSet is implemented.
        }

        void BaseProperties::SetModel(SdrModel* /*pOldModel*/, SdrModel* /*pNewModel*/)
        {
            // Set new model. Default implementation does nothing.
            // Overload where an ItemSet is implemented.
        }

        void BaseProperties::ForceStyleToHardAttributes()
        {
            // force all attributes which come from styles to hard attributes
            // to be able to live without the style. Default implementation does nothing.
            // Overload where an ItemSet is implemented.
        }

        //void BaseProperties::SetItemAndBroadcast(const SfxPoolItem& rItem)
        //{
        //  ItemChangeBroadcaster aC(GetSdrObject());
        //  SetObjectItem(rItem);
        //  BroadcastItemChange(aC);
        //}

        //void BaseProperties::ClearItemAndBroadcast(const sal_uInt16 nWhich)
        //{
        //  ItemChangeBroadcaster aC(GetSdrObject());
        //  ClearObjectItem(nWhich);
        //  BroadcastItemChange(aC);
        //}

        void BaseProperties::SetMergedItemSetAndBroadcast(const SfxItemSet& rSet, sal_Bool bClearAllItems)
        {
            ItemChangeBroadcaster aC(GetSdrObject());

            if(bClearAllItems)
            {
                ClearObjectItem();
            }

            SetMergedItemSet(rSet);
            BroadcastItemChange(aC);
        }

        const SfxPoolItem& BaseProperties::GetItem(const sal_uInt16 nWhich) const
        {
            return GetObjectItemSet().Get(nWhich);
        }

        void BaseProperties::BroadcastItemChange(const ItemChangeBroadcaster& rChange)
        {
            const sal_uInt32 nCount(rChange.GetRectangleCount());

            // #110094#-14 Reduce to do only second change
            //// invalidate all remembered rectangles
            //for(sal_uInt32 a(0); a < nCount; a++)
            //{
            //  GetSdrObject().BroadcastObjectChange(rChange.GetRectangle(a));
            //}

            // invalidate all new rectangles
            if(GetSdrObject().ISA(SdrObjGroup))
            {
                SdrObjListIter aIter((SdrObjGroup&)GetSdrObject(), IM_DEEPNOGROUPS);

                while(aIter.IsMore())
                {
                    SdrObject* pObj = aIter.Next();
                    // This is done with ItemSetChanged
                    // pObj->SetChanged();
                    pObj->BroadcastObjectChange();
                }
            }
            else
            {
                // This is done with ItemSetChanged
                // GetSdrObject().SetChanged();
                GetSdrObject().BroadcastObjectChange();
            }

            // also send the user calls
            for(sal_uInt32 a(0L); a < nCount; a++)
            {
                GetSdrObject().SendUserCall(SDRUSERCALL_CHGATTR, rChange.GetRectangle(a));
            }
        }
    } // end of namespace properties
} // end of namespace sdr

//////////////////////////////////////////////////////////////////////////////
// eof
<|endoftext|>


<commit_before> /*************************************************************************
 *
 *  $RCSfile: accfrmobjslist.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: vg $ $Date: 2003-04-17 13:36:33 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#ifndef _PAGEFRM_HXX
#include <pagefrm.hxx>
#endif
#ifndef _ACCFRMOBJSLIST_HXX
#include <accfrmobjslist.hxx>
#endif

SwFrmOrObjSList_const_iterator::SwFrmOrObjSList_const_iterator(
    const SwFrmOrObjSList& rLst, sal_Bool ) :
    rList( rLst ), aCurr( rList.pFrm->GetLower() ), nNextObj( 0 )
{
    if( !aCurr.GetSwFrm() )
    {
        if( rList.pFrm->IsPageFrm() )
        {
            const SwPageFrm *pPgFrm =
                static_cast< const SwPageFrm * >( rList.pFrm );
            const SwSortDrawObjs *pObjs = pPgFrm->GetSortedObjs();
            if( pObjs && pObjs->Count() )
                aCurr = (*pObjs)[nNextObj++];
        }
        else if( rList.pFrm->IsTxtFrm() )
        {
            const SwDrawObjs *pObjs = rList.pFrm->GetDrawObjs();
            if( pObjs && pObjs->Count() )
            {
                aCurr = (*pObjs)[nNextObj++];
                while( aCurr.IsValid() && !aCurr.IsBoundAsChar() )
                    aCurr = (nNextObj < pObjs->Count())
                                ? (*pObjs)[nNextObj++]
                                : static_cast< const SdrObject *>( 0 );

            }
        }
    }
    if( rList.bVisibleOnly )
    {
        // Find the first visible
        while( aCurr.IsValid() &&
               !aCurr.GetBox().IsOver( rList.aVisArea ) )
            next();
    }
}

SwFrmOrObjSList_const_iterator& SwFrmOrObjSList_const_iterator::next()
{
    sal_Bool bGetSdrObject = sal_False;
    if( aCurr.GetSdrObject() )
    {
        bGetSdrObject = sal_True;
    }
    else if( aCurr.GetSwFrm() )
    {
        aCurr = aCurr.GetSwFrm()->GetNext();
        if( !aCurr.GetSwFrm() )
            bGetSdrObject = sal_True;
    }

    if( bGetSdrObject )
    {
        if( rList.pFrm->IsPageFrm() )
        {
            const SwPageFrm *pPgFrm =
                static_cast< const SwPageFrm * >( rList.pFrm );
            const SwSortDrawObjs *pObjs = pPgFrm->GetSortedObjs();
            aCurr = (pObjs && nNextObj < pObjs->Count())
                            ? (*pObjs)[nNextObj++]
                            : static_cast< const SdrObject *>( 0 );
        }
        else if( rList.pFrm->IsTxtFrm() )
        {
            const SwDrawObjs *pObjs = rList.pFrm->GetDrawObjs();
            aCurr = (pObjs && nNextObj < pObjs->Count())
                            ? (*pObjs)[nNextObj++]
                            : static_cast< const SdrObject *>( 0 );
            while( aCurr.IsValid() && !aCurr.IsBoundAsChar() )
                aCurr = (nNextObj < pObjs->Count())
                            ? (*pObjs)[nNextObj++]
                            : static_cast< const SdrObject *>( 0 );
        }
    }

    return *this;
}

SwFrmOrObjSList_const_iterator& SwFrmOrObjSList_const_iterator::next_visible()
{
    next();
    while( aCurr.IsValid() &&
           !aCurr.GetBox().IsOver( rList.aVisArea ) )
        next();

    return *this;
}
<commit_msg>INTEGRATION: CWS swobjpos04 (1.3.522); FILE MERGED 2004/06/30 14:43:18 od 1.3.522.4: #i28701# - merge changes of cws swdrawpositioning 	 - further adjustments for the new object positioning 2004/06/14 08:45:18 od 1.3.522.3: #i28701# - correct comment 2004/05/24 12:46:31 od 1.3.522.2: #i28701# - usage of new class <SwSortedObjs> 2004/05/07 15:21:34 od 1.3.522.1: #i28701# - usage of new class <SwSortedObjs><commit_after> /*************************************************************************
 *
 *  $RCSfile: accfrmobjslist.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: kz $ $Date: 2004-08-02 13:59:56 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#ifndef _PAGEFRM_HXX
#include <pagefrm.hxx>
#endif
// OD 2004-05-24 #i28701#
#ifndef _SORTEDOBJS_HXX
#include <sortedobjs.hxx>
#endif
#ifndef _ACCFRMOBJSLIST_HXX
#include <accfrmobjslist.hxx>
#endif

SwFrmOrObjSList_const_iterator::SwFrmOrObjSList_const_iterator(
    const SwFrmOrObjSList& rLst, sal_Bool ) :
    rList( rLst ), aCurr( rList.pFrm->GetLower() ), nNextObj( 0 )
{
    if( !aCurr.GetSwFrm() )
    {
        if( rList.pFrm->IsPageFrm() )
        {
            const SwPageFrm *pPgFrm =
                static_cast< const SwPageFrm * >( rList.pFrm );
            const SwSortedObjs *pObjs = pPgFrm->GetSortedObjs();
            if( pObjs && pObjs->Count() )
                aCurr = (*pObjs)[nNextObj++]->GetDrawObj();
        }
        else if( rList.pFrm->IsTxtFrm() )
        {
            const SwSortedObjs *pObjs = rList.pFrm->GetDrawObjs();
            if( pObjs && pObjs->Count() )
            {
                aCurr = (*pObjs)[nNextObj++]->GetDrawObj();
                while( aCurr.IsValid() && !aCurr.IsBoundAsChar() )
                    aCurr = (nNextObj < pObjs->Count())
                                ? (*pObjs)[nNextObj++]->GetDrawObj()
                                : static_cast< const SdrObject *>( 0 );

            }
        }
    }
    if( rList.bVisibleOnly )
    {
        // Find the first visible
        while( aCurr.IsValid() &&
               !aCurr.GetBox().IsOver( rList.aVisArea ) )
            next();
    }
}

SwFrmOrObjSList_const_iterator& SwFrmOrObjSList_const_iterator::next()
{
    sal_Bool bGetSdrObject = sal_False;
    if( aCurr.GetSdrObject() )
    {
        bGetSdrObject = sal_True;
    }
    else if( aCurr.GetSwFrm() )
    {
        aCurr = aCurr.GetSwFrm()->GetNext();
        if( !aCurr.GetSwFrm() )
            bGetSdrObject = sal_True;
    }

    if( bGetSdrObject )
    {
        if( rList.pFrm->IsPageFrm() )
        {
            const SwPageFrm *pPgFrm =
                static_cast< const SwPageFrm * >( rList.pFrm );
            const SwSortedObjs *pObjs = pPgFrm->GetSortedObjs();
            aCurr = (pObjs && nNextObj < pObjs->Count())
                            ? (*pObjs)[nNextObj++]->GetDrawObj()
                            : static_cast< const SdrObject *>( 0 );
        }
        else if( rList.pFrm->IsTxtFrm() )
        {
            const SwSortedObjs *pObjs = rList.pFrm->GetDrawObjs();
            aCurr = (pObjs && nNextObj < pObjs->Count())
                            ? (*pObjs)[nNextObj++]->GetDrawObj()
                            : static_cast< const SdrObject *>( 0 );
            while( aCurr.IsValid() && !aCurr.IsBoundAsChar() )
                aCurr = (nNextObj < pObjs->Count())
                            ? (*pObjs)[nNextObj++]->GetDrawObj()
                            : static_cast< const SdrObject *>( 0 );
        }
    }

    return *this;
}

SwFrmOrObjSList_const_iterator& SwFrmOrObjSList_const_iterator::next_visible()
{
    next();
    while( aCurr.IsValid() &&
           !aCurr.GetBox().IsOver( rList.aVisArea ) )
        next();

    return *this;
}
<|endoftext|>


<commit_before>/***************************************************************************
    copyright            : (C) 2006 by Lukáš Lalinský
    email                : lalinsky@gmail.com

    copyright            : (C) 2004 by Allan Sandfeld Jensen
    email                : kde@carewolf.org
                           (original MPC implementation)
 ***************************************************************************/

/***************************************************************************
 *   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., 51 Franklin Street, Fifth Floor, Boston, MA         *
 *   02110-1301  USA                                                       *
 *                                                                         *
 *   Alternatively, this file is available under the Mozilla Public        *
 *   License Version 1.1.  You may obtain a copy of the License at         *
 *   http://www.mozilla.org/MPL/                                           *
 ***************************************************************************/

#include <tstring.h>
#include <tdebug.h>
#include <bitset>

#include "trueaudioproperties.h"
#include "trueaudiofile.h"

using namespace TagLib;

class TrueAudio::Properties::PropertiesPrivate
{
public:
  PropertiesPrivate(const ByteVector &d, long length, ReadStyle s) :
    data(d),
    streamLength(length),
    style(s),
    version(0),
    length(0),
    bitrate(0),
    sampleRate(0),
    channels(0),
    bitsPerSample(0) {}

  ByteVector data;
  long streamLength;
  ReadStyle style;
  int version;
  int length;
  int bitrate;
  int sampleRate;
  int channels;
  int bitsPerSample;
};

////////////////////////////////////////////////////////////////////////////////
// public members
////////////////////////////////////////////////////////////////////////////////

TrueAudio::Properties::Properties(const ByteVector &data, long streamLength, ReadStyle style) : AudioProperties(style)
{
  d = new PropertiesPrivate(data, streamLength, style);
  read();
}

TrueAudio::Properties::~Properties()
{
  delete d;
}

int TrueAudio::Properties::length() const
{
  return d->length;
}

int TrueAudio::Properties::bitrate() const
{
  return d->bitrate;
}

int TrueAudio::Properties::sampleRate() const
{
  return d->sampleRate;
}

int TrueAudio::Properties::bitsPerSample() const
{
  return d->bitsPerSample;
}

int TrueAudio::Properties::channels() const
{
  return d->channels;
}

int TrueAudio::Properties::ttaVersion() const
{
  return d->version;
}

////////////////////////////////////////////////////////////////////////////////
// private members
////////////////////////////////////////////////////////////////////////////////

void TrueAudio::Properties::read()
{
  if(!d->data.startsWith("TTA"))
    return;

  int pos = 3;

  d->version = d->data[pos] - '0';
  pos += 1 + 2;

  d->channels = d->data.mid(pos, 2).toShort(false);
  pos += 2;

  d->bitsPerSample = d->data.mid(pos, 2).toShort(false);
  pos += 2;

  d->sampleRate = d->data.mid(pos, 4).toUInt(false);
  pos += 4;

  unsigned long samples = d->data.mid(pos, 4).toUInt(false);
  d->length = samples / d->sampleRate;

  d->bitrate = d->length > 0 ? ((d->streamLength * 8L) / d->length) / 1000 : 0;
}
<commit_msg>Check if the header is TTA1 before parsing<commit_after>/***************************************************************************
    copyright            : (C) 2006 by Lukáš Lalinský
    email                : lalinsky@gmail.com

    copyright            : (C) 2004 by Allan Sandfeld Jensen
    email                : kde@carewolf.org
                           (original MPC implementation)
 ***************************************************************************/

/***************************************************************************
 *   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., 51 Franklin Street, Fifth Floor, Boston, MA         *
 *   02110-1301  USA                                                       *
 *                                                                         *
 *   Alternatively, this file is available under the Mozilla Public        *
 *   License Version 1.1.  You may obtain a copy of the License at         *
 *   http://www.mozilla.org/MPL/                                           *
 ***************************************************************************/

#include <tstring.h>
#include <tdebug.h>
#include <bitset>

#include "trueaudioproperties.h"
#include "trueaudiofile.h"

using namespace TagLib;

class TrueAudio::Properties::PropertiesPrivate
{
public:
  PropertiesPrivate(const ByteVector &d, long length, ReadStyle s) :
    data(d),
    streamLength(length),
    style(s),
    version(0),
    length(0),
    bitrate(0),
    sampleRate(0),
    channels(0),
    bitsPerSample(0) {}

  ByteVector data;
  long streamLength;
  ReadStyle style;
  int version;
  int length;
  int bitrate;
  int sampleRate;
  int channels;
  int bitsPerSample;
};

////////////////////////////////////////////////////////////////////////////////
// public members
////////////////////////////////////////////////////////////////////////////////

TrueAudio::Properties::Properties(const ByteVector &data, long streamLength, ReadStyle style) : AudioProperties(style)
{
  d = new PropertiesPrivate(data, streamLength, style);
  read();
}

TrueAudio::Properties::~Properties()
{
  delete d;
}

int TrueAudio::Properties::length() const
{
  return d->length;
}

int TrueAudio::Properties::bitrate() const
{
  return d->bitrate;
}

int TrueAudio::Properties::sampleRate() const
{
  return d->sampleRate;
}

int TrueAudio::Properties::bitsPerSample() const
{
  return d->bitsPerSample;
}

int TrueAudio::Properties::channels() const
{
  return d->channels;
}

int TrueAudio::Properties::ttaVersion() const
{
  return d->version;
}

////////////////////////////////////////////////////////////////////////////////
// private members
////////////////////////////////////////////////////////////////////////////////

void TrueAudio::Properties::read()
{
  if(!d->data.startsWith("TTA"))
    return;

  int pos = 3;

  d->version = d->data[pos] - '0';
  pos += 1;

  // According to http://en.true-audio.com/TTA_Lossless_Audio_Codec_-_Format_Description
  // TTA2 headers are in development, and have a different format
  if(1 == d->version) {
    // Skip the audio format
    pos += 2;

    d->channels = d->data.mid(pos, 2).toShort(false);
    pos += 2;

    d->bitsPerSample = d->data.mid(pos, 2).toShort(false);
    pos += 2;

    d->sampleRate = d->data.mid(pos, 4).toUInt(false);
    pos += 4;

    uint sampleFrames = d->data.mid(pos, 4).toUInt(false);
    d->length = d->sampleRate > 0 ? sampleFrames / d->sampleRate : 0;

    d->bitrate = d->length > 0 ? ((d->streamLength * 8L) / d->length) / 1000 : 0;
  }
}
<|endoftext|>


<commit_before>#include "testApp.h"
#include "ofAppGlutWindow.h"

int main() {
	ofAppGlutWindow window;
	window.setGlutDisplayString("rgba double samples>=8 depth");
	ofSetupOpenGL(&window, 1280, 720, OF_FULLSCREEN);
	ofRunApp(new testApp());
}
<commit_msg>removed osx-specific line. closes #74.<commit_after>#include "testApp.h"
#include "ofAppGlutWindow.h"

int main() {
	ofAppGlutWindow window;
	ofSetupOpenGL(&window, 1280, 720, OF_FULLSCREEN);
	ofRunApp(new testApp());
}
<|endoftext|>


<commit_before>/*
 *     Copyright 2010 NorthScale, Inc.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   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 "config.h"
#include <stdio.h>

#include "item.hh"
#include "stored-value.hh"
#include "ep.hh"
#include "vbucket.hh"

static void display(const char *name, size_t size) {
    std::cout << name << "\t" << size << std::endl;
}

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

    std::string s();

    display("GIGANTOR", GIGANTOR);
    display("Small Stored Value", StoredValue::sizeOf(true));
    display("Featured Stored Value", StoredValue::sizeOf(false));

    display("... Small data", sizeof(struct small_data));
    display("... Feature data", sizeof(struct feature_data));
    display("... Bodies Union", sizeof(union stored_value_bodies));

    display("Stored Value Factory", sizeof(StoredValueFactory));
    display("Blob", sizeof(Blob));
    display("value_t", sizeof(value_t));
    display("HashTable", sizeof(HashTable));
    display("Item", sizeof(Item));
    display("QueuedItem", sizeof(QueuedItem));
    display("VBucket", sizeof(VBucket));
    display("VBucketHolder", sizeof(VBucketHolder));
    display("VBucketMap", sizeof(VBucketMap));
    display("Stats", sizeof(EPStats));
    display("Histogram<whatever>", sizeof(Histogram<size_t>));
    display("HistogramBin<size_t>", sizeof(HistogramBin<size_t>));
    display("HistogramBin<hrtime_t>", sizeof(HistogramBin<hrtime_t>));
    display("HistogramBin<int>", sizeof(HistogramBin<int>));
    return 0;
}
<commit_msg>Include histo.hh in sizes.<commit_after>/*
 *     Copyright 2010 NorthScale, Inc.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   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 "config.h"
#include <stdio.h>

#include "item.hh"
#include "stored-value.hh"
#include "ep.hh"
#include "vbucket.hh"
#include "histo.hh"

static void display(const char *name, size_t size) {
    std::cout << name << "\t" << size << std::endl;
}

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

    std::string s();

    display("GIGANTOR", GIGANTOR);
    display("Small Stored Value", StoredValue::sizeOf(true));
    display("Featured Stored Value", StoredValue::sizeOf(false));

    display("... Small data", sizeof(struct small_data));
    display("... Feature data", sizeof(struct feature_data));
    display("... Bodies Union", sizeof(union stored_value_bodies));

    display("Stored Value Factory", sizeof(StoredValueFactory));
    display("Blob", sizeof(Blob));
    display("value_t", sizeof(value_t));
    display("HashTable", sizeof(HashTable));
    display("Item", sizeof(Item));
    display("QueuedItem", sizeof(QueuedItem));
    display("VBucket", sizeof(VBucket));
    display("VBucketHolder", sizeof(VBucketHolder));
    display("VBucketMap", sizeof(VBucketMap));
    display("Stats", sizeof(EPStats));
    display("Histogram<whatever>", sizeof(Histogram<size_t>));
    display("HistogramBin<size_t>", sizeof(HistogramBin<size_t>));
    display("HistogramBin<hrtime_t>", sizeof(HistogramBin<hrtime_t>));
    display("HistogramBin<int>", sizeof(HistogramBin<int>));
    return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2010 Alexey 'l1feh4ck3r' Antonov
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include <QtGui>

#include <QGraphicsView>

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include "imagepreview.h"
#include "imagescene.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow),
    matrix_of_camera_calibration(3,3)
{
    ui->setupUi(this);

    setup_ui();

    setup_connections();

    setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
}

MainWindow::~MainWindow()
{
    delete ui;

    images.clear();
}

void MainWindow::add_image()
{
    QString image_file_name = QFileDialog::getOpenFileName(this,
                                                           tr("Select meta file."),
                                                           "",
                                                           tr("Images (*.png *.jpg)"));
    if (image_file_name.isEmpty())
        return;

    // create image
    ImageInfo image(image_file_name);
    if (image.is_valid())
    {
        images.append(image);
        // add image to the preview widget
        image_preview_model->add_image(image.get_image());
    }
}

void MainWindow::element_of_matrix_of_calibration_changed(int row, int column)
{
    bool ok;
    float value = table_widget->item(row, column)->data(Qt::EditRole).toFloat(&ok);
    if (ok)
        images[image_preview_list->currentIndex().row()].set_element_of_matrif_of_calibration(row, column, value);
}

///////////////////////////////////////////////////////////////////////////////
//! Setting up selected image and it's bounding rectangle to image view
//!
//! @param index Image index in preview window
///////////////////////////////////////////////////////////////////////////////
void MainWindow::image_selected(QModelIndex index)
{
    int image_index = index.row();
    const QImage &image = images[image_index].get_image();

    // add image to the scene
    image_scene->set_image(image);

    // add bounding rectangle to the scene
    image_scene->set_rectangle(images[image_index].get_bounding_rectangle());

    // set calibration matrix
    const matrix<float> & calibration_matrix = images[image_index].get_matrix_of_calibration();

    for (int i = 0; i < calibration_matrix.RowNo(); ++i)
        for (int j = 0; j < calibration_matrix.ColNo(); ++j)
            table_widget->setItem(i, j, new QTableWidgetItem(QString("%1").arg(calibration_matrix(i, j))));
}

///////////////////////////////////////////////////////////////////////////////
//! Load meta file and all needed files from meta file definitions
///////////////////////////////////////////////////////////////////////////////
void MainWindow::load_metafile()
{
    QString filename = QFileDialog::getOpenFileName(this, tr("Select meta file."));

    if (filename.isEmpty())
        return;

    QFile file(filename);
    file.open(QIODevice::ReadOnly);
    if (!file.isOpen())
        return;

    QDataStream in(&file);

    size_t image_number;
    in >> image_number;

    // loading matrix of calibration
    // TODO: CAUTION: type-specific code
    // TODO: code duplication with "from line 159"
    for (size_t i=0; i < matrix_of_camera_calibration.RowNo(); ++i)
        for (size_t j=0; j < matrix_of_camera_calibration.ColNo(); ++j)
        {
            float x;
            in >> x;
            matrix_of_camera_calibration(i,j) = x;
        }

    image_preview_model->clear();

    images.clear();
    images.resize(image_number);

    // load images names with bounding sqares from meta file
    for (size_t i = 0; i < image_number; ++i)
    {
        // loading image file name
        QString image_file_name;
        in >> image_file_name;

        QRectF bounding_square;
        in >> bounding_square;

        // loading matrix of calibration
        matrix<float> matrix_of_calibration(3,3);
        // TODO: CAUTION: type-specific code
        for (size_t i=0; i < matrix_of_calibration.RowNo(); ++i)
            for (size_t j=0; j < matrix_of_calibration.ColNo(); ++j)
            {
                float x;
                in >> x;
                matrix_of_calibration(i,j) = x;
            }

        // create image
        ImageInfo image(image_file_name, matrix_of_calibration, bounding_square);
        if (image.is_valid())
        {
            images.append(image);
            // add image to the preview widget
            image_preview_model->add_image(image.get_image());
        }
    }

    //close input file
    file.close();
}

void MainWindow::rectangle_changed(QRectF rectangle)
{
    images[image_preview_list->currentIndex().row()].set_bounding_rectangle(rectangle);
}

///////////////////////////////////////////////////////////////////////////////
//! Save all information in meta file.
///////////////////////////////////////////////////////////////////////////////
void MainWindow::save_metafile()
{
    QString filename = QFileDialog::getOpenFileName(this, tr("Select meta file."));

    if (filename.isEmpty())
        return;

    QFile file(filename);
    file.open(QIODevice::WriteOnly);
    if (!file.isOpen())
        return;

    QDataStream out(&file);

    out << images.size();

    out << "\n";

    //save matrix of camera calibration
    // TODO: CAUTION: type-specific code
    for (size_t i=0; i < matrix_of_camera_calibration.RowNo(); ++i)
        for (size_t j=0; j < matrix_of_camera_calibration.ColNo(); ++j)
            out << matrix_of_camera_calibration(i,j);

    // saving images names with bounding sqares from meta file
    for (size_t i = 0; i < images.size(); ++i)
    {
        // save image file name
        out << images[i].get_path_to_image();

        out << "\n";

        out << images[i].get_bounding_rectangle();

        out << "\n";

        // saving matrix of calibration
        // TODO: CAUTION: type-specific code
        for (size_t i=0; i < images[i].get_matrix_of_calibration().RowNo(); ++r)
        {
            for (size_t j=0; j < images[i].get_matrix_of_calibration().ColNo(); ++c)
                out << images[i].get_matrix_of_calibration()(r,c);

            out << "\n";
        }
    }

    //close input file
    file.close();
}

///////////////////////////////////////////////////////////////////////////////
//! Setup qt connections
///////////////////////////////////////////////////////////////////////////////
void MainWindow::setup_connections()
{
    connect(ui->actionAdd_image, SIGNAL(triggered()), this, SLOT(add_image()));
    connect(ui->actionLoad_metafile, SIGNAL(triggered()), this, SLOT(load_metafile()));
    connect(ui->actionQuit, SIGNAL(triggered()), this, SLOT(close()));

    connect(image_preview_list, SIGNAL(clicked(QModelIndex)), this, SLOT(image_selected(QModelIndex)));
    connect(image_scene, SIGNAL(rectangle_changed(QRectF)) , this, SLOT(rectangle_changed(QRectF)));
    connect(table_widget, SIGNAL(cellChanged(int,int)), this, SLOT(element_of_matrix_of_calibration_changed(int,int)));
}

///////////////////////////////////////////////////////////////////////////////
//! Setup ui
///////////////////////////////////////////////////////////////////////////////
void MainWindow::setup_ui()
{
    //create left vertical layout for images preview and calibration matrix
    QVBoxLayout * verticalLayout = new QVBoxLayout(this);

    //create images preview
    image_preview_list = new QListView;
    image_preview_list->setViewMode(QListView::IconMode);
    image_preview_list->setIconSize(QSize(90, 90));
    image_preview_list->setGridSize(QSize(100, 100));
    image_preview_list->setSpacing(10);
    image_preview_list->setMovement(QListView::Snap);

    image_preview_model = new ImagePreview(this);
    image_preview_list->setModel(image_preview_model);

    //create table widget for calibration matrix
    table_widget = new QTableWidget(this);
    table_widget->setMaximumHeight(100);
    table_widget->setColumnCount(3);
    table_widget->setColumnWidth(0, 45);
    table_widget->setColumnWidth(1, 45);
    table_widget->setColumnWidth(2, 45);
    table_widget->setRowCount(3);
    table_widget->horizontalHeader()->hide();
    table_widget->verticalHeader()->hide();

    //create images view (main widget)
    image_view = new QGraphicsView(this);
    image_view->setMinimumSize(650, 599);
    image_view->setFrameStyle(QFrame::Sunken | QFrame::StyledPanel);

    image_scene = new ImageScene(this);
    //TODO: magic numbers
    image_scene->setSceneRect(0.0, 0.0, 645.0, 595.0);
    image_scene->set_rectangle(QRectF(0.0, 0.0, 0.0, 0.0));
    image_view->setScene(image_scene);

    verticalLayout->addWidget(image_preview_list);
    verticalLayout->addWidget(table_widget);

    ui->horizontalLayout->addLayout(verticalLayout);
    ui->horizontalLayout->addWidget(image_view);
}
<commit_msg>qcovc: bugfixes.<commit_after>/*
 * Copyright (c) 2010 Alexey 'l1feh4ck3r' Antonov
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include <QtGui>

#include <QGraphicsView>

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include "imagepreview.h"
#include "imagescene.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow),
    matrix_of_camera_calibration(3,3)
{
    ui->setupUi(this);

    setup_ui();

    setup_connections();

    setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
}

MainWindow::~MainWindow()
{
    delete ui;

    images.clear();
}

void MainWindow::add_image()
{
    QString image_file_name = QFileDialog::getOpenFileName(this,
                                                           tr("Select meta file."),
                                                           "",
                                                           tr("Images (*.png *.jpg)"));
    if (image_file_name.isEmpty())
        return;

    // create image
    ImageInfo image(image_file_name);
    if (image.is_valid())
    {
        images.append(image);
        // add image to the preview widget
        image_preview_model->add_image(image.get_image());
    }
}

void MainWindow::element_of_matrix_of_calibration_changed(int row, int column)
{
    bool ok;
    float value = table_widget->item(row, column)->data(Qt::EditRole).toFloat(&ok);
    if (ok)
        images[image_preview_list->currentIndex().row()].set_element_of_matrif_of_calibration(row, column, value);
}

///////////////////////////////////////////////////////////////////////////////
//! Setting up selected image and it's bounding rectangle to image view
//!
//! @param index Image index in preview window
///////////////////////////////////////////////////////////////////////////////
void MainWindow::image_selected(QModelIndex index)
{
    int image_index = index.row();
    const QImage &image = images[image_index].get_image();

    // add image to the scene
    image_scene->set_image(image);

    // add bounding rectangle to the scene
    image_scene->set_rectangle(images[image_index].get_bounding_rectangle());

    // set calibration matrix
    const matrix<float> & calibration_matrix = images[image_index].get_matrix_of_calibration();

    for (int i = 0; i < calibration_matrix.RowNo(); ++i)
        for (int j = 0; j < calibration_matrix.ColNo(); ++j)
            table_widget->setItem(i, j, new QTableWidgetItem(QString("%1").arg(calibration_matrix(i, j))));
}

///////////////////////////////////////////////////////////////////////////////
//! Load meta file and all needed files from meta file definitions
///////////////////////////////////////////////////////////////////////////////
void MainWindow::load_metafile()
{
    QString filename = QFileDialog::getOpenFileName(this, tr("Select meta file."));

    if (filename.isEmpty())
        return;

    QFile file(filename);
    file.open(QIODevice::ReadOnly);
    if (!file.isOpen())
        return;

    QDataStream in(&file);

    size_t image_number;
    in >> image_number;

    // loading matrix of calibration
    // TODO: CAUTION: type-specific code
    // TODO: code duplication with "from line 159"
    for (size_t r=0; r < matrix_of_camera_calibration.RowNo(); ++r)
        for (size_t c=0; c < matrix_of_camera_calibration.ColNo(); ++c)
        {
            float x;
            in >> x;
            matrix_of_camera_calibration(r,c) = x;
        }

    image_preview_model->clear();

    images.clear();
    images.resize(image_number);

    // load images names with bounding sqares from meta file
    for (size_t i = 0; i < image_number; ++i)
    {
        // loading image file name
        QString image_file_name;
        in >> image_file_name;

        QRectF bounding_square;
        in >> bounding_square;

        // loading matrix of calibration
        matrix<float> matrix_of_calibration(3,3);
        // TODO: CAUTION: type-specific code
        for (size_t r=0; r < matrix_of_calibration.RowNo(); ++r)
            for (size_t c=0; c < matrix_of_calibration.ColNo(); ++c)
            {
                float x;
                in >> x;
                matrix_of_calibration(r,c) = x;
            }

        // create image
        ImageInfo image(image_file_name, matrix_of_calibration, bounding_square);
        if (image.is_valid())
        {
            images.append(image);
            // add image to the preview widget
            image_preview_model->add_image(image.get_image());
        }
    }

    //close input file
    file.close();
}

void MainWindow::rectangle_changed(QRectF rectangle)
{
    images[image_preview_list->currentIndex().row()].set_bounding_rectangle(rectangle);
}

///////////////////////////////////////////////////////////////////////////////
//! Save all information in meta file.
///////////////////////////////////////////////////////////////////////////////
void MainWindow::save_metafile()
{
    QString filename = QFileDialog::getOpenFileName(this, tr("Select meta file."));

    if (filename.isEmpty())
        return;

    QFile file(filename);
    file.open(QIODevice::WriteOnly);
    if (!file.isOpen())
        return;

    QDataStream out(&file);

    out << images.size();

    out << "\n";

    //save matrix of camera calibration
    // TODO: CAUTION: type-specific code
    for (size_t r=0; r < matrix_of_camera_calibration.RowNo(); ++r)
        for (size_t c=0; c < matrix_of_camera_calibration.ColNo(); ++c)
            out << matrix_of_camera_calibration(r,c);

    // saving images names with bounding sqares from meta file
    for (size_t i = 0; i < images.size(); ++i)
    {
        // save image file name
        out << images[i].get_path_to_image();

        out << "\n";

        out << images[i].get_bounding_rectangle();

        out << "\n";

        // saving matrix of calibration
        // TODO: CAUTION: type-specific code
        for (size_t r=0; r < images[i].get_matrix_of_calibration().RowNo(); ++r)
        {
            for (size_t c=0; c < images[i].get_matrix_of_calibration().ColNo(); ++c)
                out << images[i].get_matrix_of_calibration()(r,c);

            out << "\n";
        }
    }

    //close input file
    file.close();
}

///////////////////////////////////////////////////////////////////////////////
//! Setup qt connections
///////////////////////////////////////////////////////////////////////////////
void MainWindow::setup_connections()
{
    connect(ui->actionAdd_image, SIGNAL(triggered()), this, SLOT(add_image()));
    connect(ui->actionLoad_metafile, SIGNAL(triggered()), this, SLOT(load_metafile()));
    connect(ui->actionQuit, SIGNAL(triggered()), this, SLOT(close()));

    connect(image_preview_list, SIGNAL(clicked(QModelIndex)), this, SLOT(image_selected(QModelIndex)));
    connect(image_scene, SIGNAL(rectangle_changed(QRectF)) , this, SLOT(rectangle_changed(QRectF)));
    connect(table_widget, SIGNAL(cellChanged(int,int)), this, SLOT(element_of_matrix_of_calibration_changed(int,int)));
}

///////////////////////////////////////////////////////////////////////////////
//! Setup ui
///////////////////////////////////////////////////////////////////////////////
void MainWindow::setup_ui()
{
    //create left vertical layout for images preview and calibration matrix
    QVBoxLayout * verticalLayout = new QVBoxLayout(this);

    //create images preview
    image_preview_list = new QListView;
    image_preview_list->setViewMode(QListView::IconMode);
    image_preview_list->setIconSize(QSize(90, 90));
    image_preview_list->setGridSize(QSize(100, 100));
    image_preview_list->setSpacing(10);
    image_preview_list->setMovement(QListView::Snap);

    image_preview_model = new ImagePreview(this);
    image_preview_list->setModel(image_preview_model);

    //create table widget for calibration matrix
    table_widget = new QTableWidget(this);
    table_widget->setMaximumHeight(100);
    table_widget->setColumnCount(3);
    table_widget->setColumnWidth(0, 45);
    table_widget->setColumnWidth(1, 45);
    table_widget->setColumnWidth(2, 45);
    table_widget->setRowCount(3);
    table_widget->horizontalHeader()->hide();
    table_widget->verticalHeader()->hide();

    //create images view (main widget)
    image_view = new QGraphicsView(this);
    image_view->setMinimumSize(650, 599);
    image_view->setFrameStyle(QFrame::Sunken | QFrame::StyledPanel);

    image_scene = new ImageScene(this);
    //TODO: magic numbers
    image_scene->setSceneRect(0.0, 0.0, 645.0, 595.0);
    image_scene->set_rectangle(QRectF(0.0, 0.0, 0.0, 0.0));
    image_view->setScene(image_scene);

    verticalLayout->addWidget(image_preview_list);
    verticalLayout->addWidget(table_widget);

    ui->horizontalLayout->addLayout(verticalLayout);
    ui->horizontalLayout->addWidget(image_view);
}
<|endoftext|>