<commit_before>/*=========================================================================
 *
 *  Copyright NumFOCUS
 *
 *  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 "itkGaussianImageSource.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkKullbackLeiblerCompareHistogramImageToImageMetric.h"
#include "itkTranslationTransform.h"
#include "itkTestingMacros.h"

/** This test uses two 2D-Gaussians (standard deviation RegionSize/2).
    This test computes the mutual information between the two images.
*/
int
itkCompareHistogramImageToImageMetricTest(int, char *[])
{

  // Create two simple images.
  constexpr unsigned int ImageDimension = 2;
  using PixelType = double;
  using CoordinateRepresentationType = double;

  // Allocate Images
  using MovingImageType = itk::Image<PixelType, ImageDimension>;
  using FixedImageType = itk::Image<PixelType, ImageDimension>;

  // Declare Gaussian Sources
  using MovingImageSourceType = itk::GaussianImageSource<MovingImageType>;
  using FixedImageSourceType = itk::GaussianImageSource<FixedImageType>;

  // Note: the following declarations are classical arrays
  FixedImageType::SizeValueType  fixedImageSize[] = { 100, 100 };
  MovingImageType::SizeValueType movingImageSize[] = { 100, 100 };

  FixedImageType::SpacingValueType  fixedImageSpacing[] = { 1.0f, 1.0f };
  MovingImageType::SpacingValueType movingImageSpacing[] = { 1.0f, 1.0f };

  FixedImageType::PointValueType  fixedImageOrigin[] = { 0.0f, 0.0f };
  MovingImageType::PointValueType movingImageOrigin[] = { 0.0f, 0.0f };

  MovingImageSourceType::Pointer movingImageSource = MovingImageSourceType::New();
  FixedImageSourceType::Pointer  fixedImageSource = FixedImageSourceType::New();

  movingImageSource->SetSize(movingImageSize);
  movingImageSource->SetOrigin(movingImageOrigin);
  movingImageSource->SetSpacing(movingImageSpacing);
  movingImageSource->SetNormalized(false);
  movingImageSource->SetScale(250.0f);

  fixedImageSource->SetSize(fixedImageSize);
  fixedImageSource->SetOrigin(fixedImageOrigin);
  fixedImageSource->SetSpacing(fixedImageSpacing);
  fixedImageSource->SetNormalized(false);
  fixedImageSource->SetScale(250.0f);

  ITK_TRY_EXPECT_NO_EXCEPTION(movingImageSource->Update()); // Force the filter to run
  ITK_TRY_EXPECT_NO_EXCEPTION(fixedImageSource->Update());  // Force the filter to run

  MovingImageType::Pointer movingImage = movingImageSource->GetOutput();
  FixedImageType::Pointer  fixedImage = fixedImageSource->GetOutput();

  // Set up the metric.
  using MetricType = itk::KullbackLeiblerCompareHistogramImageToImageMetric<FixedImageType, MovingImageType>;
  using TransformBaseType = MetricType::TransformType;
  using ScalesType = MetricType::ScalesType;
  using ParametersType = TransformBaseType::ParametersType;

  MetricType::Pointer metric = MetricType::New();

  ITK_EXERCISE_BASIC_OBJECT_METHODS(
    metric, KullbackLeiblerCompareHistogramImageToImageMetric, CompareHistogramImageToImageMetric);

  auto epsilon = 1e-12;
  ITK_TEST_SET_GET_VALUE(epsilon, metric->GetEpsilon());

  unsigned int                        nBins = 256;
  MetricType::HistogramType::SizeType histSize;

  histSize.SetSize(2);

  histSize[0] = nBins;
  histSize[1] = nBins;
  metric->SetHistogramSize(histSize);

  // Plug the images into the metric.
  metric->SetFixedImage(fixedImage);
  metric->SetMovingImage(movingImage);

  // Set up a transform.
  using TransformType = itk::TranslationTransform<CoordinateRepresentationType, ImageDimension>;

  TransformType::Pointer transform = TransformType::New();
  metric->SetTransform(transform);

  // Set up an interpolator.
  using InterpolatorType = itk::LinearInterpolateImageFunction<MovingImageType, double>;

  InterpolatorType::Pointer interpolator = InterpolatorType::New();
  interpolator->SetInputImage(movingImage);
  metric->SetInterpolator(interpolator);

  // Define the region over which the metric will be computed.
  metric->SetFixedImageRegion(fixedImage->GetBufferedRegion());

  // Set up transform parameters.
  ParametersType parameters(transform->GetNumberOfParameters());

  for (unsigned int k = 0; k < ImageDimension; ++k)
  {
    parameters[k] = 0.0f;
  }

  // Set scales for derivative calculation.
  ScalesType scales(transform->GetNumberOfParameters());

  for (unsigned int k = 0; k < transform->GetNumberOfParameters(); ++k)
  {
    scales[k] = 1;
  }

  metric->SetDerivativeStepLengthScales(scales);

  // Now set up the Training Stuff
  metric->SetTrainingTransform(transform);
  metric->SetTrainingFixedImage(fixedImage);
  metric->SetTrainingFixedImageRegion(fixedImage->GetBufferedRegion());
  metric->SetTrainingMovingImage(movingImage);
  metric->SetTrainingInterpolator(interpolator);

  // Initialize the metric.
  metric->Initialize();

  // Print out metric value and derivative.
  MetricType::MeasureType    measure = metric->GetValue(parameters);
  MetricType::DerivativeType derivative;
  metric->GetDerivative(parameters, derivative);

  std::cout << "Metric value = " << measure << std::endl << "Derivative = " << derivative << std::endl;

  std::cout << "Test finished." << std::endl;
  return EXIT_SUCCESS;
}
<commit_msg>ENH: Improve KLCompareHistogramImageToImageMetric coverage<commit_after>/*=========================================================================
 *
 *  Copyright NumFOCUS
 *
 *  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 "itkGaussianImageSource.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkKullbackLeiblerCompareHistogramImageToImageMetric.h"
#include "itkTranslationTransform.h"
#include "itkTestingMacros.h"

/** This test uses two 2D-Gaussians (standard deviation RegionSize/2).
    This test computes the mutual information between the two images.
*/
int
itkCompareHistogramImageToImageMetricTest(int, char *[])
{

  // Create two simple images.
  constexpr unsigned int ImageDimension = 2;
  using PixelType = double;
  using CoordinateRepresentationType = double;

  // Allocate Images
  using MovingImageType = itk::Image<PixelType, ImageDimension>;
  using FixedImageType = itk::Image<PixelType, ImageDimension>;

  // Declare Gaussian Sources
  using MovingImageSourceType = itk::GaussianImageSource<MovingImageType>;
  using FixedImageSourceType = itk::GaussianImageSource<FixedImageType>;

  // Note: the following declarations are classical arrays
  FixedImageType::SizeValueType  fixedImageSize[] = { 100, 100 };
  MovingImageType::SizeValueType movingImageSize[] = { 100, 100 };

  FixedImageType::SpacingValueType  fixedImageSpacing[] = { 1.0f, 1.0f };
  MovingImageType::SpacingValueType movingImageSpacing[] = { 1.0f, 1.0f };

  FixedImageType::PointValueType  fixedImageOrigin[] = { 0.0f, 0.0f };
  MovingImageType::PointValueType movingImageOrigin[] = { 0.0f, 0.0f };

  MovingImageSourceType::Pointer movingImageSource = MovingImageSourceType::New();
  FixedImageSourceType::Pointer  fixedImageSource = FixedImageSourceType::New();

  movingImageSource->SetSize(movingImageSize);
  movingImageSource->SetOrigin(movingImageOrigin);
  movingImageSource->SetSpacing(movingImageSpacing);
  movingImageSource->SetNormalized(false);
  movingImageSource->SetScale(250.0f);

  fixedImageSource->SetSize(fixedImageSize);
  fixedImageSource->SetOrigin(fixedImageOrigin);
  fixedImageSource->SetSpacing(fixedImageSpacing);
  fixedImageSource->SetNormalized(false);
  fixedImageSource->SetScale(250.0f);

  ITK_TRY_EXPECT_NO_EXCEPTION(movingImageSource->Update()); // Force the filter to run
  ITK_TRY_EXPECT_NO_EXCEPTION(fixedImageSource->Update());  // Force the filter to run

  MovingImageType::Pointer movingImage = movingImageSource->GetOutput();
  FixedImageType::Pointer  fixedImage = fixedImageSource->GetOutput();

  // Set up the metric.
  using MetricType = itk::KullbackLeiblerCompareHistogramImageToImageMetric<FixedImageType, MovingImageType>;
  using TransformBaseType = MetricType::TransformType;
  using ScalesType = MetricType::ScalesType;
  using ParametersType = TransformBaseType::ParametersType;

  MetricType::Pointer metric = MetricType::New();

  ITK_EXERCISE_BASIC_OBJECT_METHODS(
    metric, KullbackLeiblerCompareHistogramImageToImageMetric, CompareHistogramImageToImageMetric);

  auto epsilon = 1e-12;
  metric->SetEpsilon(epsilon);
  ITK_TEST_SET_GET_VALUE(epsilon, metric->GetEpsilon());

  unsigned int                        nBins = 256;
  MetricType::HistogramType::SizeType histSize;

  histSize.SetSize(2);

  histSize[0] = nBins;
  histSize[1] = nBins;
  metric->SetHistogramSize(histSize);

  // Plug the images into the metric.
  metric->SetFixedImage(fixedImage);
  metric->SetMovingImage(movingImage);

  // Set up a transform.
  using TransformType = itk::TranslationTransform<CoordinateRepresentationType, ImageDimension>;

  TransformType::Pointer transform = TransformType::New();
  metric->SetTransform(transform);

  // Set up an interpolator.
  using InterpolatorType = itk::LinearInterpolateImageFunction<MovingImageType, double>;

  InterpolatorType::Pointer interpolator = InterpolatorType::New();
  interpolator->SetInputImage(movingImage);
  metric->SetInterpolator(interpolator);

  // Define the region over which the metric will be computed.
  metric->SetFixedImageRegion(fixedImage->GetBufferedRegion());

  // Set up transform parameters.
  ParametersType parameters(transform->GetNumberOfParameters());

  for (unsigned int k = 0; k < ImageDimension; ++k)
  {
    parameters[k] = 0.0f;
  }

  // Set scales for derivative calculation.
  ScalesType scales(transform->GetNumberOfParameters());

  for (unsigned int k = 0; k < transform->GetNumberOfParameters(); ++k)
  {
    scales[k] = 1;
  }

  metric->SetDerivativeStepLengthScales(scales);

  // Now set up the Training Stuff
  metric->SetTrainingTransform(transform);
  metric->SetTrainingFixedImage(fixedImage);
  metric->SetTrainingFixedImageRegion(fixedImage->GetBufferedRegion());
  metric->SetTrainingMovingImage(movingImage);
  metric->SetTrainingInterpolator(interpolator);

  // Initialize the metric.
  metric->Initialize();

  // Print out metric value and derivative.
  MetricType::MeasureType    measure = metric->GetValue(parameters);
  MetricType::DerivativeType derivative;
  metric->GetDerivative(parameters, derivative);

  std::cout << "Metric value = " << measure << std::endl << "Derivative = " << derivative << std::endl;

  std::cout << "Test finished." << std::endl;
  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/**
 * @file r_tree_descent_heuristic_impl.hpp
 * @author Andrew Wells
 *
 * Implementation of RTreeDescentHeuristic, a class that chooses the best child
 * of a node in an R tree when inserting a new point.
 */
#ifndef __MLPACK_CORE_TREE_RECTANGLE_TREE_R_TREE_DESCENT_HEURISTIC_IMPL_HPP
#define __MLPACK_CORE_TREE_RECTANGLE_TREE_R_TREE_DESCENT_HEURISTIC_IMPL_HPP

#include "r_tree_descent_heuristic.hpp"

namespace mlpack {
namespace tree {

template<typename TreeType>
inline size_t RTreeDescentHeuristic::ChooseDescentNode(const TreeType* node,
                                                       const arma::vec& point)
{
  std::vector<double> scores(node->NumChildren());
  std::vector<int> vols(node->NumChildren());
  double minScore = DBL_MAX;
  int bestIndex = 0;
  bool tied = false;

  for (size_t i = 0; i < node->NumChildren(); i++)
  {
    double v1 = 1.0;
    double v2 = 1.0;
    for (size_t j = 0; j < node->Children()[i]->Bound().Dim(); j++)
    {
      v1 *= node->Children()[i]->Bound()[j].Width();
      v2 *= node->Children()[i]->Bound()[j].Contains(point[j]) ?
          node->Children()[i]->Bound()[j].Width() :
          (node->Children()[i]->Bound()[j].Hi() < point[j] ?
              (point[j] - node->Children()[i]->Bound()[j].Lo()) :
              (node->Children()[i]->Bound()[j].Hi() - point[j]));
    }

    assert(v2 - v1 >= 0);

    vols[i] = v1;
    scores[i] = v2 - v1;

    if (v2 - v1 < minScore)
    {
      minScore = v2 - v1;
      bestIndex = i;
    }
    else if (v2 - v1 == minScore)
    {
      tied = true;
    }
  }

  if (tied)
  {
    // We break ties by choosing the smallest bound.
    double minVol = DBL_MAX;
    bestIndex = 0;
    for (int i = 0; i < scores.size(); i++)
    {
      if (scores[i] == minScore)
      {
        if (vols[i] < minVol)
        {
          minVol = vols[i];
          bestIndex = i;
        }
      }
    }
  }

  return bestIndex;
}

template<typename TreeType>
inline size_t RTreeDescentHeuristic::ChooseDescentNode(
    const TreeType* node,
    const TreeType* insertedNode)
{
  std::vector<double> scores(node->NumChildren());
  std::vector<int> vols(node->NumChildren());

  double minScore = DBL_MAX;
  int bestIndex = 0;
  bool tied = false;

  for (size_t i = 0; i < node->NumChildren(); i++)
  {
    double v1 = 1.0;
    double v2 = 1.0;
    for (size_t j = 0; j < node->Children()[i]->Bound().Dim(); j++)
    {
      v1 *= node->Children()[i]->Bound()[j].Width();
      v2 *= node->Children()[i]->Bound()[j].Contains(insertedNode->Bound()[j]) ?
          node->Children()[i]->Bound()[j].Width() :
          (insertedNode->Bound()[j].Contains(node->Children()[i]->Bound()[j]) ?
          insertedNode->Bound()[j].Width() :
          (insertedNode->Bound()[j].Lo() < node->Children()[i]->Bound()[j].Lo()
          ? (node->Children()[i]->Bound()[j].Hi() -
          insertedNode->Bound()[j].Lo()) : (insertedNode->Bound()[j].Hi() -
          node->Children()[i]->Bound()[j].Lo())));
    }

    assert(v2 - v1 >= 0);

    vols[i] = v1;
    scores[i] = v2 - v1;

    if (v2 - v1 < minScore)
    {
      minScore = v2 - v1;
      bestIndex = i;
    }
    else if (v2 - v1 == minScore)
    {
      tied = true;
    }
  }

  if (tied)
  {
    // We break ties by choosing the smallest bound.
    double minVol = DBL_MAX;
    bestIndex = 0;
    for (int i = 0; i < scores.size(); i++)
    {
      if (scores[i] == minScore)
      {
        if(vols[i] < minVol)
        {
          minVol = vols[i];
          bestIndex = i;
        }
      }
    }
  }

  return bestIndex;
}

}; // namespace tree
}; // namespace mlpack

#endif
<commit_msg>Don't use auxiliary structures; find the best node with O(1) storage.  Minor speed improvement.<commit_after>/**
 * @file r_tree_descent_heuristic_impl.hpp
 * @author Andrew Wells
 *
 * Implementation of RTreeDescentHeuristic, a class that chooses the best child
 * of a node in an R tree when inserting a new point.
 */
#ifndef __MLPACK_CORE_TREE_RECTANGLE_TREE_R_TREE_DESCENT_HEURISTIC_IMPL_HPP
#define __MLPACK_CORE_TREE_RECTANGLE_TREE_R_TREE_DESCENT_HEURISTIC_IMPL_HPP

#include "r_tree_descent_heuristic.hpp"

namespace mlpack {
namespace tree {

template<typename TreeType>
inline size_t RTreeDescentHeuristic::ChooseDescentNode(const TreeType* node,
                                                       const arma::vec& point)
{
  double minScore = DBL_MAX;
  int bestIndex = 0;
  double bestVol = 0.0;

  for (size_t i = 0; i < node->NumChildren(); i++)
  {
    double v1 = 1.0;
    double v2 = 1.0;
    for (size_t j = 0; j < node->Children()[i]->Bound().Dim(); j++)
    {
      v1 *= node->Children()[i]->Bound()[j].Width();
      v2 *= node->Children()[i]->Bound()[j].Contains(point[j]) ?
          node->Children()[i]->Bound()[j].Width() :
          (node->Children()[i]->Bound()[j].Hi() < point[j] ?
              (point[j] - node->Children()[i]->Bound()[j].Lo()) :
              (node->Children()[i]->Bound()[j].Hi() - point[j]));
    }

    assert(v2 - v1 >= 0);

    if ((v2 - v1) < minScore)
    {
      minScore = v2 - v1;
      bestVol = v1;
      bestIndex = i;
    }
    else if ((v2 - v1) == minScore && v1 < bestVol)
    {
      bestVol = v1;
      bestIndex = i;
    }
  }

  return bestIndex;
}

template<typename TreeType>
inline size_t RTreeDescentHeuristic::ChooseDescentNode(
    const TreeType* node,
    const TreeType* insertedNode)
{
  double minScore = DBL_MAX;
  int bestIndex = 0;
  double bestVol = 0.0;

  for (size_t i = 0; i < node->NumChildren(); i++)
  {
    double v1 = 1.0;
    double v2 = 1.0;
    for (size_t j = 0; j < node->Children()[i]->Bound().Dim(); j++)
    {
      v1 *= node->Children()[i]->Bound()[j].Width();
      v2 *= node->Children()[i]->Bound()[j].Contains(insertedNode->Bound()[j]) ?
          node->Children()[i]->Bound()[j].Width() :
          (insertedNode->Bound()[j].Contains(node->Children()[i]->Bound()[j]) ?
          insertedNode->Bound()[j].Width() :
          (insertedNode->Bound()[j].Lo() < node->Children()[i]->Bound()[j].Lo()
          ? (node->Children()[i]->Bound()[j].Hi() -
          insertedNode->Bound()[j].Lo()) : (insertedNode->Bound()[j].Hi() -
          node->Children()[i]->Bound()[j].Lo())));
    }

    assert(v2 - v1 >= 0);

    if ((v2 - v1) < minScore)
    {
      minScore = v2 - v1;
      bestVol = v1;
      bestIndex = i;
    }
    else if ((v2 - v1) == minScore && v1 < bestVol)
    {
      bestVol = v1;
      bestIndex = i;
    }
  }

  return bestIndex;
}

}; // namespace tree
}; // namespace mlpack

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: vclxaccessiblecomponent.hxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: fs $ $Date: 2002-04-25 11:21:20 $
 *
 *  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 _TOOLKIT_AWT_VCLXACCESSIBLECOMPONENT_HXX_
#define _TOOLKIT_AWT_VCLXACCESSIBLECOMPONENT_HXX_

#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_
#include <drafts/com/sun/star/accessibility/XAccessible.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLECONTEXT_HPP_
#include <drafts/com/sun/star/accessibility/XAccessibleContext.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEEXTENDEDCOMPONENT_HPP_
#include <drafts/com/sun/star/accessibility/XAccessibleExtendedComponent.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEEVENTBROADCASTER_HPP_
#include <drafts/com/sun/star/accessibility/XAccessibleEventBroadcaster.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_
#include <com/sun/star/awt/XWindow.hpp>
#endif

#ifndef _CPPUHELPER_COMPBASE3_HXX_
#include <cppuhelper/compbase3.hxx>
#endif
#ifndef COMPHELPER_ACCIMPLACCESS_HXX
#include <comphelper/accimplaccess.hxx>
#endif
#ifndef COMPHELPER_ACCESSIBLE_COMPONENT_HELPER_HXX
#include <comphelper/accessiblecomponenthelper.hxx>
#endif

#include <tools/gen.hxx>    // Size
#include <tools/link.hxx>   // Size

class Window;
class VCLXWindow;
class VclSimpleEvent;
class VclWindowEvent;

namespace utl {
class AccessibleStateSetHelper;
}

//class MutexHelper_Impl
//{
//protected:
//  ::osl::Mutex    maMutex;
//};

//typedef cppu::WeakComponentImplHelper3<
//    ::drafts::com::sun::star::accessibility::XAccessibleContext,
//  ::drafts::com::sun::star::accessibility::XAccessibleExtendedComponent,
//    ::drafts::com::sun::star::accessibility::XAccessibleEventBroadcaster
//    > VCLXAccessibleComponentBase;

typedef ::comphelper::OAccessibleExtendedComponentHelper    VCLXAccessibleComponentBase;

//  ----------------------------------------------------
//  class VCLXAccessibleComponent
//  ----------------------------------------------------

class VCLXAccessibleComponent
        :public VCLXAccessibleComponentBase
        ,public ::comphelper::OAccessibleImplementationAccess
{
private:
    ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow> mxWindow;
    VCLXWindow*                         mpVCLXindow;

    ULONG                           nDummy1;
    ULONG                           nDummy2;
    void*                           pDummy1;
    void*                           pDummy2;

protected:
//  ::osl::Mutex&   GetMutex() { return maMutex; }
     DECL_LINK( WindowEventListener, VclSimpleEvent* );

    virtual void    ProcessWindowEvent( const VclWindowEvent& rVclWindowEvent );
    virtual void    FillAccessibleStateSet( utl::AccessibleStateSetHelper& rStateSet );

public:
    VCLXAccessibleComponent( VCLXWindow* pVCLXindow );
    ~VCLXAccessibleComponent();

    VCLXWindow*    GetVCLXWindow() const { return mpVCLXindow; }
    Window*        GetWindow() const;

    virtual void SAL_CALL disposing();

    // ::com::sun::star::uno::XInterface
    DECLARE_XINTERFACE()
    // ::com::sun::star::lang::XTypeProvider
    DECLARE_XTYPEPROVIDER()

    // ::drafts::com::sun::star::accessibility::XAccessibleContext
    sal_Int32 SAL_CALL getAccessibleChildCount(  ) throw (::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleChild( sal_Int32 i ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleParent(  ) throw (::com::sun::star::uno::RuntimeException);
    sal_Int32 SAL_CALL getAccessibleIndexInParent(  ) throw (::com::sun::star::uno::RuntimeException);
    sal_Int16 SAL_CALL getAccessibleRole(  ) throw (::com::sun::star::uno::RuntimeException);
    ::rtl::OUString SAL_CALL getAccessibleDescription(  ) throw (::com::sun::star::uno::RuntimeException);
    ::rtl::OUString SAL_CALL getAccessibleName(  ) throw (::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessibleRelationSet > SAL_CALL getAccessibleRelationSet(  ) throw (::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessibleStateSet > SAL_CALL getAccessibleStateSet(  ) throw (::com::sun::star::uno::RuntimeException);
    ::com::sun::star::lang::Locale SAL_CALL getLocale(  ) throw (::drafts::com::sun::star::accessibility::IllegalAccessibleComponentStateException, ::com::sun::star::uno::RuntimeException);

    // ::drafts::com::sun::star::accessibility::XAccessibleComponent
    ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleAt( const ::com::sun::star::awt::Point& aPoint ) throw (::com::sun::star::uno::RuntimeException);
    ::com::sun::star::awt::Point SAL_CALL getLocationOnScreen(  ) throw (::com::sun::star::uno::RuntimeException);
    sal_Bool SAL_CALL isShowing(  ) throw (::com::sun::star::uno::RuntimeException);
    sal_Bool SAL_CALL isVisible(  ) throw (::com::sun::star::uno::RuntimeException);
    sal_Bool SAL_CALL isFocusTraversable(  ) throw (::com::sun::star::uno::RuntimeException);
    void SAL_CALL addFocusListener( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFocusListener >& xListener ) throw (::com::sun::star::uno::RuntimeException);
    void SAL_CALL removeFocusListener( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFocusListener >& xListener ) throw (::com::sun::star::uno::RuntimeException);
    void SAL_CALL grabFocus(  ) throw (::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Any SAL_CALL getAccessibleKeyBinding(  ) throw (::com::sun::star::uno::RuntimeException);

    // ::drafts::com::sun::star::accessibility::XAccessibleExtendedComponent
    virtual sal_Int32 SAL_CALL getForeground(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual sal_Int32 SAL_CALL getBackground(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFont > SAL_CALL getFont(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::awt::FontDescriptor SAL_CALL getFontMetrics( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFont >& xFont ) throw (::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL isEnabled(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::rtl::OUString SAL_CALL getTitledBorderText(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::rtl::OUString SAL_CALL getToolTipText(  ) throw (::com::sun::star::uno::RuntimeException);

protected:
    // base class overridables
    ::com::sun::star::awt::Rectangle SAL_CALL implGetBounds(  ) throw (::com::sun::star::uno::RuntimeException);

private:
    /** we may be reparented (if external components use OAccessibleImplementationAccess base class),
        so this method here returns the parent in the VCL world, in opposite to the parent
        an external component gave us
    @precond
        the caller must ensure thread safety, i.e. our mutex must be locked
    */
    ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible >
            getVclParent() const;
};

/* ----------------------------------------------------------
  Accessibility only for the Window hierarchy!
  Maybe derived classes must overwrite these Accessibility interfaces:

    // XAccessibleContext:
    sal_Int16 getAccessibleRole() => VCL Window::GetAccessibleRole()
    OUString getAccessibleDescription() => VCL Window::GetAccessibleDescription
    OUString getAccessibleName() => VCL Window::GetAccessibleText() => Most windows return Window::GetText()
    Reference< XAccessibleRelationSet > getAccessibleRelationSet()
    Reference< XAccessibleStateSet > getAccessibleStateSet() => overload FillAccessibleStateSet( ... )

// ::drafts::com::sun::star::accessibility::XAccessibleComponent
    sal_Bool isFocusTraversable()
    Any getAccessibleKeyBinding()

---------------------------------------------------------- */

#endif // _TOOLKIT_AWT_VCLXACCESSIBLECOMPONENT_HXX_

<commit_msg>#98750# removed some obsolete (commented anyway) stuff left over from the previous change<commit_after>/*************************************************************************
 *
 *  $RCSfile: vclxaccessiblecomponent.hxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: fs $ $Date: 2002-04-26 14:34:58 $
 *
 *  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 _TOOLKIT_AWT_VCLXACCESSIBLECOMPONENT_HXX_
#define _TOOLKIT_AWT_VCLXACCESSIBLECOMPONENT_HXX_

#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_
#include <drafts/com/sun/star/accessibility/XAccessible.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLECONTEXT_HPP_
#include <drafts/com/sun/star/accessibility/XAccessibleContext.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEEXTENDEDCOMPONENT_HPP_
#include <drafts/com/sun/star/accessibility/XAccessibleExtendedComponent.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEEVENTBROADCASTER_HPP_
#include <drafts/com/sun/star/accessibility/XAccessibleEventBroadcaster.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_
#include <com/sun/star/awt/XWindow.hpp>
#endif

#ifndef _CPPUHELPER_COMPBASE3_HXX_
#include <cppuhelper/compbase3.hxx>
#endif
#ifndef COMPHELPER_ACCIMPLACCESS_HXX
#include <comphelper/accimplaccess.hxx>
#endif
#ifndef COMPHELPER_ACCESSIBLE_COMPONENT_HELPER_HXX
#include <comphelper/accessiblecomponenthelper.hxx>
#endif

#include <tools/gen.hxx>    // Size
#include <tools/link.hxx>   // Size

class Window;
class VCLXWindow;
class VclSimpleEvent;
class VclWindowEvent;

namespace utl {
class AccessibleStateSetHelper;
}

typedef ::comphelper::OAccessibleExtendedComponentHelper    VCLXAccessibleComponentBase;

//  ----------------------------------------------------
//  class VCLXAccessibleComponent
//  ----------------------------------------------------

class VCLXAccessibleComponent
        :public VCLXAccessibleComponentBase
        ,public ::comphelper::OAccessibleImplementationAccess
{
private:
    ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow> mxWindow;
    VCLXWindow*                         mpVCLXindow;

    ULONG                           nDummy1;
    ULONG                           nDummy2;
    void*                           pDummy1;
    void*                           pDummy2;

protected:
     DECL_LINK( WindowEventListener, VclSimpleEvent* );

    virtual void    ProcessWindowEvent( const VclWindowEvent& rVclWindowEvent );
    virtual void    FillAccessibleStateSet( utl::AccessibleStateSetHelper& rStateSet );

public:
    VCLXAccessibleComponent( VCLXWindow* pVCLXindow );
    ~VCLXAccessibleComponent();

    VCLXWindow*    GetVCLXWindow() const { return mpVCLXindow; }
    Window*        GetWindow() const;

    virtual void SAL_CALL disposing();

    // ::com::sun::star::uno::XInterface
    DECLARE_XINTERFACE()
    // ::com::sun::star::lang::XTypeProvider
    DECLARE_XTYPEPROVIDER()

    // ::drafts::com::sun::star::accessibility::XAccessibleContext
    sal_Int32 SAL_CALL getAccessibleChildCount(  ) throw (::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleChild( sal_Int32 i ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleParent(  ) throw (::com::sun::star::uno::RuntimeException);
    sal_Int32 SAL_CALL getAccessibleIndexInParent(  ) throw (::com::sun::star::uno::RuntimeException);
    sal_Int16 SAL_CALL getAccessibleRole(  ) throw (::com::sun::star::uno::RuntimeException);
    ::rtl::OUString SAL_CALL getAccessibleDescription(  ) throw (::com::sun::star::uno::RuntimeException);
    ::rtl::OUString SAL_CALL getAccessibleName(  ) throw (::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessibleRelationSet > SAL_CALL getAccessibleRelationSet(  ) throw (::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessibleStateSet > SAL_CALL getAccessibleStateSet(  ) throw (::com::sun::star::uno::RuntimeException);
    ::com::sun::star::lang::Locale SAL_CALL getLocale(  ) throw (::drafts::com::sun::star::accessibility::IllegalAccessibleComponentStateException, ::com::sun::star::uno::RuntimeException);

    // ::drafts::com::sun::star::accessibility::XAccessibleComponent
    ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleAt( const ::com::sun::star::awt::Point& aPoint ) throw (::com::sun::star::uno::RuntimeException);
    ::com::sun::star::awt::Point SAL_CALL getLocationOnScreen(  ) throw (::com::sun::star::uno::RuntimeException);
    sal_Bool SAL_CALL isShowing(  ) throw (::com::sun::star::uno::RuntimeException);
    sal_Bool SAL_CALL isVisible(  ) throw (::com::sun::star::uno::RuntimeException);
    sal_Bool SAL_CALL isFocusTraversable(  ) throw (::com::sun::star::uno::RuntimeException);
    void SAL_CALL addFocusListener( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFocusListener >& xListener ) throw (::com::sun::star::uno::RuntimeException);
    void SAL_CALL removeFocusListener( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFocusListener >& xListener ) throw (::com::sun::star::uno::RuntimeException);
    void SAL_CALL grabFocus(  ) throw (::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Any SAL_CALL getAccessibleKeyBinding(  ) throw (::com::sun::star::uno::RuntimeException);

    // ::drafts::com::sun::star::accessibility::XAccessibleExtendedComponent
    virtual sal_Int32 SAL_CALL getForeground(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual sal_Int32 SAL_CALL getBackground(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFont > SAL_CALL getFont(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::awt::FontDescriptor SAL_CALL getFontMetrics( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFont >& xFont ) throw (::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL isEnabled(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::rtl::OUString SAL_CALL getTitledBorderText(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::rtl::OUString SAL_CALL getToolTipText(  ) throw (::com::sun::star::uno::RuntimeException);

protected:
    // base class overridables
    ::com::sun::star::awt::Rectangle SAL_CALL implGetBounds(  ) throw (::com::sun::star::uno::RuntimeException);

private:
    /** we may be reparented (if external components use OAccessibleImplementationAccess base class),
        so this method here returns the parent in the VCL world, in opposite to the parent
        an external component gave us
    @precond
        the caller must ensure thread safety, i.e. our mutex must be locked
    */
    ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible >
            getVclParent() const;
};

/* ----------------------------------------------------------
  Accessibility only for the Window hierarchy!
  Maybe derived classes must overwrite these Accessibility interfaces:

    // XAccessibleContext:
    sal_Int16 getAccessibleRole() => VCL Window::GetAccessibleRole()
    OUString getAccessibleDescription() => VCL Window::GetAccessibleDescription
    OUString getAccessibleName() => VCL Window::GetAccessibleText() => Most windows return Window::GetText()
    Reference< XAccessibleRelationSet > getAccessibleRelationSet()
    Reference< XAccessibleStateSet > getAccessibleStateSet() => overload FillAccessibleStateSet( ... )

// ::drafts::com::sun::star::accessibility::XAccessibleComponent
    sal_Bool isFocusTraversable()
    Any getAccessibleKeyBinding()

---------------------------------------------------------- */

#endif // _TOOLKIT_AWT_VCLXACCESSIBLECOMPONENT_HXX_

<|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/gtk_plugin_container_manager.h"

#include <gtk/gtk.h>

#include "app/gfx/gtk_util.h"
#include "base/logging.h"
#include "webkit/glue/plugins/gtk_plugin_container.h"
#include "webkit/glue/webplugin.h"

GtkWidget* GtkPluginContainerManager::CreatePluginContainer(
    gfx::PluginWindowHandle id) {
  DCHECK(host_widget_);
  GtkWidget *widget = gtk_plugin_container_new();
  plugin_window_to_widget_map_.insert(std::make_pair(id, widget));

  // The Realize callback is responsible for adding the plug into the socket.
  // The reason is 2-fold:
  // - the plug can't be added until the socket is realized, but this may not
  // happen until the socket is attached to a top-level window, which isn't the
  // case for background tabs.
  // - when dragging tabs, the socket gets unrealized, which breaks the XEMBED
  // connection. We need to make it again when the tab is reattached, and the
  // socket gets realized again.
  //
  // Note, the RealizeCallback relies on the plugin_window_to_widget_map_ to
  // have the mapping.
  g_signal_connect(G_OBJECT(widget), "realize",
                   G_CALLBACK(RealizeCallback), this);

  // Don't destroy the widget when the plug is removed.
  g_signal_connect(G_OBJECT(widget), "plug-removed",
                   G_CALLBACK(gtk_true), NULL);

  gtk_container_add(GTK_CONTAINER(host_widget_), widget);
  gtk_widget_show(widget);

  return widget;
}

void GtkPluginContainerManager::DestroyPluginContainer(
    gfx::PluginWindowHandle id) {
  DCHECK(host_widget_);
  GtkWidget* widget = MapIDToWidget(id);
  if (widget)
    gtk_widget_destroy(widget);

  plugin_window_to_widget_map_.erase(id);
}

void GtkPluginContainerManager::MovePluginContainer(
    const webkit_glue::WebPluginGeometry& move) {
  DCHECK(host_widget_);
  GtkWidget *widget = MapIDToWidget(move.window);
  if (!widget)
    return;

  DCHECK(!GTK_WIDGET_NO_WINDOW(widget));
  DCHECK(GTK_WIDGET_REALIZED(widget));

  if (!move.visible) {
    gtk_widget_hide(widget);
    return;
  } else {
    gtk_widget_show(widget);
  }

  GdkRectangle clip_rect = move.clip_rect.ToGdkRectangle();
  GdkRegion* clip_region = gdk_region_rectangle(&clip_rect);
  gfx::SubtractRectanglesFromRegion(clip_region, move.cutout_rects);
  gdk_window_shape_combine_region(widget->window, clip_region, 0, 0);
  gdk_region_destroy(clip_region);

  // Update the window position.  Resizing is handled by WebPluginDelegate.
  // TODO(deanm): Verify that we only need to move and not resize.
  // TODO(evanm): we should cache the last shape and position and skip all
  // of this business in the common case where nothing has changed.
  int current_x, current_y;

  // Until the above TODO is resolved, we can grab the last position
  // off of the GtkFixed with a bit of hackery.
  GValue value = {0};
  g_value_init(&value, G_TYPE_INT);
  gtk_container_child_get_property(GTK_CONTAINER(host_widget_), widget,
                                   "x", &value);
  current_x = g_value_get_int(&value);
  gtk_container_child_get_property(GTK_CONTAINER(host_widget_), widget,
                                   "y", &value);
  current_y = g_value_get_int(&value);
  g_value_unset(&value);

  if (move.window_rect.x() != current_x ||
      move.window_rect.y() != current_y) {
    // Calling gtk_fixed_move unnecessarily is a no-no, as it causes the
    // parent window to repaint!
    gtk_fixed_move(GTK_FIXED(host_widget_),
                   widget,
                   move.window_rect.x(),
                   move.window_rect.y());
  }

  gtk_plugin_container_set_size(widget,
                                move.window_rect.width(),
                                move.window_rect.height());
}

GtkWidget* GtkPluginContainerManager::MapIDToWidget(
    gfx::PluginWindowHandle id) {
  PluginWindowToWidgetMap::const_iterator i =
      plugin_window_to_widget_map_.find(id);
  if (i != plugin_window_to_widget_map_.end())
    return i->second;

  LOG(ERROR) << "Request for widget host for unknown window id " << id;

  return NULL;
}

gfx::PluginWindowHandle GtkPluginContainerManager::MapWidgetToID(
     GtkWidget* widget) {
  for (PluginWindowToWidgetMap::const_iterator i =
          plugin_window_to_widget_map_.begin();
       i != plugin_window_to_widget_map_.end(); ++i) {
    if (i->second == widget)
      return i->first;
  }

  LOG(ERROR) << "Request for id for unknown widget";
  return 0;
}

// static
void GtkPluginContainerManager::RealizeCallback(GtkWidget* widget,
                                                void* user_data) {
  GtkPluginContainerManager* plugin_container_manager =
      static_cast<GtkPluginContainerManager*>(user_data);

  gfx::PluginWindowHandle id = plugin_container_manager->MapWidgetToID(widget);
  if (id)
    gtk_socket_add_id(GTK_SOCKET(widget), id);
}
<commit_msg>linux: obey move.rects_valid in WebPluginGeometry<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/gtk_plugin_container_manager.h"

#include <gtk/gtk.h>

#include "app/gfx/gtk_util.h"
#include "base/logging.h"
#include "webkit/glue/plugins/gtk_plugin_container.h"
#include "webkit/glue/webplugin.h"

GtkWidget* GtkPluginContainerManager::CreatePluginContainer(
    gfx::PluginWindowHandle id) {
  DCHECK(host_widget_);
  GtkWidget *widget = gtk_plugin_container_new();
  plugin_window_to_widget_map_.insert(std::make_pair(id, widget));

  // The Realize callback is responsible for adding the plug into the socket.
  // The reason is 2-fold:
  // - the plug can't be added until the socket is realized, but this may not
  // happen until the socket is attached to a top-level window, which isn't the
  // case for background tabs.
  // - when dragging tabs, the socket gets unrealized, which breaks the XEMBED
  // connection. We need to make it again when the tab is reattached, and the
  // socket gets realized again.
  //
  // Note, the RealizeCallback relies on the plugin_window_to_widget_map_ to
  // have the mapping.
  g_signal_connect(G_OBJECT(widget), "realize",
                   G_CALLBACK(RealizeCallback), this);

  // Don't destroy the widget when the plug is removed.
  g_signal_connect(G_OBJECT(widget), "plug-removed",
                   G_CALLBACK(gtk_true), NULL);

  gtk_container_add(GTK_CONTAINER(host_widget_), widget);
  gtk_widget_show(widget);

  return widget;
}

void GtkPluginContainerManager::DestroyPluginContainer(
    gfx::PluginWindowHandle id) {
  DCHECK(host_widget_);
  GtkWidget* widget = MapIDToWidget(id);
  if (widget)
    gtk_widget_destroy(widget);

  plugin_window_to_widget_map_.erase(id);
}

void GtkPluginContainerManager::MovePluginContainer(
    const webkit_glue::WebPluginGeometry& move) {
  DCHECK(host_widget_);
  GtkWidget *widget = MapIDToWidget(move.window);
  if (!widget)
    return;

  DCHECK(!GTK_WIDGET_NO_WINDOW(widget));

  if (!move.visible) {
    gtk_widget_hide(widget);
    return;
  }

  DCHECK(GTK_WIDGET_REALIZED(widget));
  gtk_widget_show(widget);

  if (!move.rects_valid)
    return;

  GdkRectangle clip_rect = move.clip_rect.ToGdkRectangle();
  GdkRegion* clip_region = gdk_region_rectangle(&clip_rect);
  gfx::SubtractRectanglesFromRegion(clip_region, move.cutout_rects);
  gdk_window_shape_combine_region(widget->window, clip_region, 0, 0);
  gdk_region_destroy(clip_region);

  // Update the window position.  Resizing is handled by WebPluginDelegate.
  // TODO(deanm): Verify that we only need to move and not resize.
  // TODO(evanm): we should cache the last shape and position and skip all
  // of this business in the common case where nothing has changed.
  int current_x, current_y;

  // Until the above TODO is resolved, we can grab the last position
  // off of the GtkFixed with a bit of hackery.
  GValue value = {0};
  g_value_init(&value, G_TYPE_INT);
  gtk_container_child_get_property(GTK_CONTAINER(host_widget_), widget,
                                   "x", &value);
  current_x = g_value_get_int(&value);
  gtk_container_child_get_property(GTK_CONTAINER(host_widget_), widget,
                                   "y", &value);
  current_y = g_value_get_int(&value);
  g_value_unset(&value);

  if (move.window_rect.x() != current_x ||
      move.window_rect.y() != current_y) {
    // Calling gtk_fixed_move unnecessarily is a no-no, as it causes the
    // parent window to repaint!
    gtk_fixed_move(GTK_FIXED(host_widget_),
                   widget,
                   move.window_rect.x(),
                   move.window_rect.y());
  }

  gtk_plugin_container_set_size(widget,
                                move.window_rect.width(),
                                move.window_rect.height());
}

GtkWidget* GtkPluginContainerManager::MapIDToWidget(
    gfx::PluginWindowHandle id) {
  PluginWindowToWidgetMap::const_iterator i =
      plugin_window_to_widget_map_.find(id);
  if (i != plugin_window_to_widget_map_.end())
    return i->second;

  LOG(ERROR) << "Request for widget host for unknown window id " << id;

  return NULL;
}

gfx::PluginWindowHandle GtkPluginContainerManager::MapWidgetToID(
     GtkWidget* widget) {
  for (PluginWindowToWidgetMap::const_iterator i =
          plugin_window_to_widget_map_.begin();
       i != plugin_window_to_widget_map_.end(); ++i) {
    if (i->second == widget)
      return i->first;
  }

  LOG(ERROR) << "Request for id for unknown widget";
  return 0;
}

// static
void GtkPluginContainerManager::RealizeCallback(GtkWidget* widget,
                                                void* user_data) {
  GtkPluginContainerManager* plugin_container_manager =
      static_cast<GtkPluginContainerManager*>(user_data);

  gfx::PluginWindowHandle id = plugin_container_manager->MapWidgetToID(widget);
  if (id)
    gtk_socket_add_id(GTK_SOCKET(widget), id);
}
<|endoftext|>


<commit_before><commit_msg>COMP: more typename outside template declaration<commit_after><|endoftext|>


<commit_before>#ifndef CUTEHMI_LIBMODBUS_INCLUDE_MODBUS_INTERNAL_REGISTERTRAITS_HPP
#define CUTEHMI_LIBMODBUS_INCLUDE_MODBUS_INTERNAL_REGISTERTRAITS_HPP

#include "DataContainer.hpp"
#include "../InputRegister.hpp"
#include "../HoldingRegister.hpp"
#include "../DiscreteInput.hpp"
#include "../Coil.hpp"

namespace cutehmi {
namespace modbus {
namespace internal {

template <typename R>
struct RegisterTraits
{
	typedef typename RegisterTraits<R>::Container Container;
};

template <>
struct RegisterTraits<InputRegister>
{
	typedef DataContainer<InputRegister *> Container;
};

template <>
struct RegisterTraits<HoldingRegister>
{
	typedef DataContainer<HoldingRegister *> Container;
};

template <>
struct RegisterTraits<DiscreteInput>
{
	typedef DataContainer<DiscreteInput *> Container;
};

template <>
struct RegisterTraits<Coil>
{
	typedef DataContainer<Coil *> Container;
};

}
}
}

#endif

//(c)MP: Copyright © 2017, Michal Policht. All rights reserved.
//(c)MP: This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
<commit_msg>Remove self-recurring "Container" typedef.<commit_after>#ifndef CUTEHMI_LIBMODBUS_INCLUDE_MODBUS_INTERNAL_REGISTERTRAITS_HPP
#define CUTEHMI_LIBMODBUS_INCLUDE_MODBUS_INTERNAL_REGISTERTRAITS_HPP

#include "DataContainer.hpp"
#include "../InputRegister.hpp"
#include "../HoldingRegister.hpp"
#include "../DiscreteInput.hpp"
#include "../Coil.hpp"

namespace cutehmi {
namespace modbus {
namespace internal {

template <typename R>
struct RegisterTraits
{
};

template <>
struct RegisterTraits<InputRegister>
{
	typedef DataContainer<InputRegister *> Container;
};

template <>
struct RegisterTraits<HoldingRegister>
{
	typedef DataContainer<HoldingRegister *> Container;
};

template <>
struct RegisterTraits<DiscreteInput>
{
	typedef DataContainer<DiscreteInput *> Container;
};

template <>
struct RegisterTraits<Coil>
{
	typedef DataContainer<Coil *> Container;
};

}
}
}

#endif

//(c)MP: Copyright © 2017, Michal Policht. All rights reserved.
//(c)MP: This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
<|endoftext|>


<commit_before><commit_msg>Rotation<commit_after><|endoftext|>


<commit_before>#include "timezoneview.h"

#include "dcpdatetime.h"
#include "datetimetranslation.h"
#include "dcptable.h"
#include "dcptimezonedelegate.h"
#include "dcptimezonedata.h"
#include "dcptimezoneconf.h"

#include <duitextedit.h>
#include <QGraphicsLinearLayout>
#include <QStandardItemModel>
#include <QSortFilterProxyModel>
#include <DuiSceneManager>
#include <QModelIndex>

TimeZoneView::TimeZoneView(QGraphicsWidget *parent)
             :DcpWidget(parent),
              m_SelectedItem(-1)
{
    setReferer(DcpDateTime::Main);
    initWidget();
}

TimeZoneView::~TimeZoneView()
{
}

void TimeZoneView::initWidget()
{
    // mainLayout
    QGraphicsLinearLayout* layout = new QGraphicsLinearLayout(Qt::Vertical, this);

    // m_TextEdit
    m_TextEdit = new DuiTextEdit(DuiTextEditModel::SingleLine,
                                 DcpDateTime::InputCountryText,
                                 this);
    m_TextEdit->setObjectName("InputTextEdit");
    m_TextEdit->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    connect(m_TextEdit, SIGNAL(gainedFocus(DuiTextEdit *, Qt::FocusReason)),
            this, SLOT(clearTextEdit(DuiTextEdit *)));
    connect(m_TextEdit, SIGNAL(textChanged()), this, SLOT(filteringListItems()));
    layout->addItem(m_TextEdit);

    // model:
    m_FullModel = new QStandardItemModel(this);
    // TODO XXX: this has to be optimized, a lot of copying
    QMultiMap<QString, DcpTimeZoneData*> zoneMap =
                                         DcpTimeZoneConf::instance()->getMap();
    QMultiMap<QString, DcpTimeZoneData*>::ConstIterator zoneIter =
                                         zoneMap.constBegin();
    QString defaultCity = DcpTimeZoneConf::instance()->defaultTimeZone().city();
    while (zoneIter != zoneMap.constEnd()) {
        DcpTimeZoneData* tz = zoneIter.value();

        QStandardItem* item = new QStandardItem();
        item->setData(tz->city(), DcpTimeZoneDelegate::TextRole1);
        item->setData(tz->gmt() + " " + tz->city(),
                      DcpTimeZoneDelegate::TextRole2);

        bool selected = false;
        if (m_SelectedItem == -1 && tz->city() == defaultCity) {
            m_SelectedItem = m_FullModel->rowCount();
            selected = true;
        }
        item->setData(selected, DcpTimeZoneDelegate::CheckedRole);

        item->setData(tz->timeZone(), DcpTimeZoneDelegate::ZoneIdRole);

        m_FullModel->appendRow(item);
        zoneIter++;
    }

    QSortFilterProxyModel* filterModel = new QSortFilterProxyModel(this);
    filterModel->setSourceModel(m_FullModel);
    filterModel->setFilterRole(DcpTimeZoneDelegate::TextRole1);
    filterModel->setSortRole(DcpTimeZoneDelegate::TextRole1);
    filterModel->sort(0);

    // Table:
    m_Table = new DcpTable();
    m_Table->setDelegate(new DcpTimeZoneDelegate());
    m_Table->setModel(filterModel);
    connect (m_Table, SIGNAL(clicked ( const QModelIndex &)),
             this, SLOT(onItemClicked( const QModelIndex &)));
    layout->addItem(m_Table);

    // handle orientation
    connect(DuiSceneManager::instance(),
            SIGNAL(orientationChanged(const Dui::Orientation &)),
            this, SLOT(orientationChanged()));
    orientationChanged();
}

void TimeZoneView::clearTextEdit(DuiTextEdit *textEdit)
{
    if (textEdit->text() == DcpDateTime::InputCountryText) {
        textEdit->setText("");
    }
}

void TimeZoneView::filteringListItems()
{
    QString sample = m_TextEdit->text();
    if (sample == DcpDateTime::InputCountryText)
        sample = "";
    proxyModel()->setFilterRegExp(QRegExp(sample, Qt::CaseInsensitive,
                                             QRegExp::FixedString));
}

QSortFilterProxyModel*
TimeZoneView::proxyModel()
{
    QSortFilterProxyModel* proxyModel =
        qobject_cast<QSortFilterProxyModel*>(m_Table->model());
    Q_ASSERT(proxyModel);
    return proxyModel;
}

void TimeZoneView::orientationChanged()
{
    QSize size = DuiSceneManager::instance()->visibleSceneSize();
    setMinimumHeight(size.height()-60);
}

void
TimeZoneView::onItemClicked( const QModelIndex &index)
{
    if (m_SelectedItem != -1) {
        selectItem(m_SelectedItem, false);
    }
    m_SelectedItem = proxyModel()->mapToSource(index).row();
    if (m_SelectedItem != -1) {
        selectItem(m_SelectedItem);
    }
}

void
TimeZoneView::selectItem(int item, bool selected)
{
    m_FullModel->setData( m_FullModel->index(item, 0),
                          selected, DcpTimeZoneDelegate::CheckedRole);
}

bool TimeZoneView::back()
{
    QString zoneId = m_FullModel->index(m_SelectedItem,0).data(
                                    DcpTimeZoneDelegate::ZoneIdRole).toString();
    if (!zoneId.isEmpty()) {
        DcpTimeZoneConf::instance()->setDefaultTimeZone(zoneId);
    }
    return DcpWidget::back();
}

<commit_msg>show country too<commit_after>#include "timezoneview.h"

#include "dcpdatetime.h"
#include "datetimetranslation.h"
#include "dcptable.h"
#include "dcptimezonedelegate.h"
#include "dcptimezonedata.h"
#include "dcptimezoneconf.h"

#include <duitextedit.h>
#include <QGraphicsLinearLayout>
#include <QStandardItemModel>
#include <QSortFilterProxyModel>
#include <DuiSceneManager>
#include <QModelIndex>

TimeZoneView::TimeZoneView(QGraphicsWidget *parent)
             :DcpWidget(parent),
              m_SelectedItem(-1)
{
    setReferer(DcpDateTime::Main);
    initWidget();
}

TimeZoneView::~TimeZoneView()
{
}

void TimeZoneView::initWidget()
{
    // mainLayout
    QGraphicsLinearLayout* layout = new QGraphicsLinearLayout(Qt::Vertical, this);

    // m_TextEdit
    m_TextEdit = new DuiTextEdit(DuiTextEditModel::SingleLine,
                                 DcpDateTime::InputCountryText,
                                 this);
    m_TextEdit->setObjectName("InputTextEdit");
    m_TextEdit->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    connect(m_TextEdit, SIGNAL(gainedFocus(DuiTextEdit *, Qt::FocusReason)),
            this, SLOT(clearTextEdit(DuiTextEdit *)));
    connect(m_TextEdit, SIGNAL(textChanged()), this, SLOT(filteringListItems()));
    layout->addItem(m_TextEdit);

    // model:
    m_FullModel = new QStandardItemModel(this);
    // TODO XXX: this has to be optimized, a lot of copying
    QMultiMap<QString, DcpTimeZoneData*> zoneMap =
                                         DcpTimeZoneConf::instance()->getMap();
    QMultiMap<QString, DcpTimeZoneData*>::ConstIterator zoneIter =
                                         zoneMap.constBegin();
    QString defaultCity = DcpTimeZoneConf::instance()->defaultTimeZone().city();
    while (zoneIter != zoneMap.constEnd()) {
        DcpTimeZoneData* tz = zoneIter.value();

        QStandardItem* item = new QStandardItem();
        item->setData(tz->city(), DcpTimeZoneDelegate::TextRole1);
        item->setData(tz->gmt() + " " + tz->country(),
                      DcpTimeZoneDelegate::TextRole2);

        bool selected = false;
        if (m_SelectedItem == -1 && tz->city() == defaultCity) {
            m_SelectedItem = m_FullModel->rowCount();
            selected = true;
        }
        item->setData(selected, DcpTimeZoneDelegate::CheckedRole);

        item->setData(tz->timeZone(), DcpTimeZoneDelegate::ZoneIdRole);

        m_FullModel->appendRow(item);
        zoneIter++;
    }

    QSortFilterProxyModel* filterModel = new QSortFilterProxyModel(this);
    filterModel->setSourceModel(m_FullModel);
    filterModel->setFilterRole(DcpTimeZoneDelegate::TextRole1);
    filterModel->setSortRole(DcpTimeZoneDelegate::TextRole1);
    filterModel->sort(0);

    // Table:
    m_Table = new DcpTable();
    m_Table->setDelegate(new DcpTimeZoneDelegate());
    m_Table->setModel(filterModel);
    connect (m_Table, SIGNAL(clicked ( const QModelIndex &)),
             this, SLOT(onItemClicked( const QModelIndex &)));
    layout->addItem(m_Table);

    // handle orientation
    connect(DuiSceneManager::instance(),
            SIGNAL(orientationChanged(const Dui::Orientation &)),
            this, SLOT(orientationChanged()));
    orientationChanged();
}

void TimeZoneView::clearTextEdit(DuiTextEdit *textEdit)
{
    if (textEdit->text() == DcpDateTime::InputCountryText) {
        textEdit->setText("");
    }
}

void TimeZoneView::filteringListItems()
{
    QString sample = m_TextEdit->text();
    if (sample == DcpDateTime::InputCountryText)
        sample = "";
    proxyModel()->setFilterRegExp(QRegExp(sample, Qt::CaseInsensitive,
                                             QRegExp::FixedString));
}

QSortFilterProxyModel*
TimeZoneView::proxyModel()
{
    QSortFilterProxyModel* proxyModel =
        qobject_cast<QSortFilterProxyModel*>(m_Table->model());
    Q_ASSERT(proxyModel);
    return proxyModel;
}

void TimeZoneView::orientationChanged()
{
    QSize size = DuiSceneManager::instance()->visibleSceneSize();
    setMinimumHeight(size.height()-60);
}

void
TimeZoneView::onItemClicked( const QModelIndex &index)
{
    if (m_SelectedItem != -1) {
        selectItem(m_SelectedItem, false);
    }
    m_SelectedItem = proxyModel()->mapToSource(index).row();
    if (m_SelectedItem != -1) {
        selectItem(m_SelectedItem);
    }
}

void
TimeZoneView::selectItem(int item, bool selected)
{
    m_FullModel->setData( m_FullModel->index(item, 0),
                          selected, DcpTimeZoneDelegate::CheckedRole);
}

bool TimeZoneView::back()
{
    QString zoneId = m_FullModel->index(m_SelectedItem,0).data(
                                    DcpTimeZoneDelegate::ZoneIdRole).toString();
    if (!zoneId.isEmpty()) {
        DcpTimeZoneConf::instance()->setDefaultTimeZone(zoneId);
    }
    return DcpWidget::back();
}

<|endoftext|>


<commit_before>//=============================================================================================================
/**
 * @file     settingscontrollergui.cpp
 * @author   Juan GPC <juangpc@gmail.com>
 * @since    0.1.0
 * @date     May, 2020
 *
 * @section  LICENSE
 *
 * Copyright (C) 2020, Juan GPC. 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 MNE-CPP authors 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.
 *
 *
 * @brief    SettingsControllerGUI class definition.
 *
 */

//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "settingscontrollergui.h"
#include "mainwindow.h"

//=============================================================================================================
// QT INCLUDES
//=============================================================================================================

#include <QDir>
#include <QStandardPaths>
#include <QDesktopServices>
#include <QDateTime>
#include <QtGlobal>

//=============================================================================================================
// EIGEN INCLUDES
//=============================================================================================================

//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace MNEANONYMIZE;

//=============================================================================================================
// DEFINE GLOBAL METHODS
//=============================================================================================================

//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================

SettingsControllerGui::SettingsControllerGui(const QStringList& arguments)
: m_pWin(QSharedPointer<MainWindow> (new MainWindow(this)))
{
    initParser();
    parseInputs(arguments);
    setupCommunication();

    initializeOptionsState();

    m_pWin->show();
//    m_bInputFileInformationVisible = m_pWin->getExtraInfoVisibility();

//    readData();
    QString msg("Mellow greetings!");
    m_pWin->statusMsg(msg,2000);
}

void SettingsControllerGui::executeAnonymizer()
{
    m_pWin->statusMsg("Anonymizing the input file into the output file.",2000);
    m_pAnonymizer->anonymizeFile();
    m_pWin->statusMsg("Your file is ready!");
}

void SettingsControllerGui::readData()
{
    if(m_pAnonymizer->isFileInSet())
    {

        QString stringTempDir(QStandardPaths::writableLocation(QStandardPaths::TempLocation));
        QString fileOutStr(QDir(stringTempDir).filePath(generateRandomFileName()));
        m_pAnonymizer->setFileOut(fileOutStr);
        m_pWin->setDefaultStateExtraInfo();
        bool verboseMode(m_pAnonymizer->getVerboseMode());
        m_pAnonymizer->setVerboseMode(false);
        m_pWin->statusMsg("Reading input file information...",0);
        m_pAnonymizer->anonymizeFile();
        QFile fileOut(fileOutStr);
        fileOut.remove();
        m_pAnonymizer->setFileOut(m_fiOutFileInfo.absoluteFilePath());
        m_pAnonymizer->setVerboseMode(verboseMode);
        QString msg2("Input file information read correctly.");
        m_pWin->statusMsg(msg2,2000);
    } else {
        m_pWin->winPopup("Cannot read data. Please select a valid input file first.");
    }
}

void SettingsControllerGui::fileInChanged(const QString& strInFile)
{
    QFileInfo newfiInFile(strInFile);

    if(newfiInFile.isDir())
    {
        m_pWin->statusMsg("Invalid input file. That's a directory");
        m_pWin->setLineEditInFile(m_fiInFileInfo.absoluteFilePath());
        return;
    }
    if(QString::compare(newfiInFile.suffix(),QString("fif")) != 0)
    {
        m_pWin->statusMsg("The input file extension must be \".fif\" 0.");
        m_pWin->setLineEditOutFile(m_fiOutFileInfo.absoluteFilePath());
        return;
    }
    QFileInfo inDir(newfiInFile.absolutePath());
    if(!inDir.isReadable())
    {
        m_pWin->statusMsg("You might not have reading permissions to this folder");
        m_pWin->setLineEditInFile(m_fiInFileInfo.absoluteFilePath());
        return;
    }

    if( m_fiInFileInfo != newfiInFile )
    {
        m_fiInFileInfo.setFile(newfiInFile.absoluteFilePath());
        m_pAnonymizer->setFileIn(m_fiInFileInfo.absoluteFilePath());

        generateDefaultOutputFileName();
        m_pWin->setLineEditInFile(m_fiInFileInfo.absoluteFilePath());
        m_pWin->setLineEditOutFile(m_fiOutFileInfo.absoluteFilePath());
    }
}

void SettingsControllerGui::fileOutChanged(const QString& strOutFile)
{
    QFileInfo newfiOutFile(strOutFile);
    if(m_fiOutFileInfo.isDir())
    {
        QString fileOutDefaultName(newfiOutFile.absolutePath() + m_fiInFileInfo.baseName() +
                        "_anonymized." + m_fiInFileInfo.completeSuffix());
        m_fiOutFileInfo.setFile(fileOutDefaultName);
        m_pWin->setLineEditOutFile(m_fiOutFileInfo.absoluteFilePath());
        return;
    }

    if(QString::compare(newfiOutFile.suffix(),QString("fif")) != 0)
    {
        m_pWin->statusMsg("The output file extension must be \".fif\" 0.");
        m_pWin->setLineEditOutFile(m_fiOutFileInfo.absoluteFilePath());
        return;
    }

    QFileInfo outDir(newfiOutFile.absolutePath());
    if(!outDir.isWritable())
    {
        m_pWin->winPopup("You might not have writing permissions to this folder");
        m_pWin->setLineEditOutFile(m_fiOutFileInfo.absoluteFilePath());
        return;
    }

    if(m_fiOutFileInfo != newfiOutFile)
    {
        m_fiOutFileInfo.setFile(strOutFile);
        m_pAnonymizer->setFileOut(m_fiOutFileInfo.absoluteFilePath());
    }
}

void SettingsControllerGui::setupCommunication()
{
    //view to controller
    QObject::connect(m_pWin.data(),&MainWindow::fileInChanged,
                     this,&SettingsControllerGui::fileInChanged);
    QObject::connect(m_pWin.data(),&MainWindow::fileOutChanged,
                     this,&SettingsControllerGui::fileOutChanged);
    QObject::connect(m_pWin.data(),&MainWindow::readInputDataButtonClicked,
                     this,&SettingsControllerGui::readData);

    //from view to model
    QObject::connect(m_pWin.data(),&MainWindow::bruteModeChanged,
                     m_pAnonymizer.data(),&FiffAnonymizer::setBruteMode);
    QObject::connect(m_pWin.data(),&MainWindow::measurementDateChanged,
                     m_pAnonymizer.data(),QOverload<const QDateTime&>::of(&FiffAnonymizer::setMeasurementDate));
    QObject::connect(m_pWin.data(),&MainWindow::useMeasurementOffset,
                     m_pAnonymizer.data(),&FiffAnonymizer::setUseMeasurementDateOffset);
    QObject::connect(m_pWin.data(),&MainWindow::measurementDateOffsetChanged,
                     m_pAnonymizer.data(),&FiffAnonymizer::setMeasurementDateOffset);
    QObject::connect(m_pWin.data(),&MainWindow::birthdayDateChanged,
                     m_pAnonymizer.data(),QOverload<const QDateTime&>::of(&FiffAnonymizer::setSubjectBirthday));
    QObject::connect(m_pWin.data(),&MainWindow::useBirthdayOffset,
                     m_pAnonymizer.data(),&FiffAnonymizer::setUseSubjectBirthdayOffset);
    QObject::connect(m_pWin.data(),&MainWindow::birthdayOffsetChanged,
                     m_pAnonymizer.data(),&FiffAnonymizer::setSubjectBirthdayOffset);
    QObject::connect(m_pWin.data(),&MainWindow::subjectHisIdChanged,
                     m_pAnonymizer.data(),&FiffAnonymizer::setSubjectHisId);

    //from model to view
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingIdFileVersion,
                     m_pWin.data(),&MainWindow::setLineEditIdFileVersion);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingIdMeasurementDate,
                     m_pWin.data(),&MainWindow::setLineEditIdMeasurementDate);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingIdMac,
                     m_pWin.data(),&MainWindow::setLineEditIdMacAddress);

    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingFileMeasurementDate,
                     m_pWin.data(),&MainWindow::setLineEditFileMeasurementDate);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingFileComment,
                     m_pWin.data(),&MainWindow::setLineEditFileComment);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingFileExperimenter,
                     m_pWin.data(),&MainWindow::setLineEditFileExperimenter);

    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectId,
                     m_pWin.data(),&MainWindow::setLineEditSubjectId);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectFirstName,
                     m_pWin.data(),&MainWindow::setLineEditSubjectFirstName);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectMiddleName,
                     m_pWin.data(),&MainWindow::setLineEditSubjectMiddleName);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectLastName,
                     m_pWin.data(),&MainWindow::setLineEditSubjectLastName);

    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectBirthday,
                     m_pWin.data(),&MainWindow::setLineEditSubjectBirthday);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectSex,
                     m_pWin.data(),&MainWindow::setComboBoxSubjectSex);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectHand,
                     m_pWin.data(),&MainWindow::setLineEditSubjectHand);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectWeight,
                     m_pWin.data(),&MainWindow::setLineEditSubjectHand);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectHeight,
                     m_pWin.data(),&MainWindow::setLineEditSubjectHeight);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectComment,
                     m_pWin.data(),&MainWindow::setLineEditSubjectComment);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectHisId,
                     m_pWin.data(),&MainWindow::setLineEditSubjectHisId);

    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingProjectId,
                     m_pWin.data(),&MainWindow::setLineEditProjectId);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingProjectName,
                     m_pWin.data(),&MainWindow::setLineEditProjectName);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingProjectAim,
                     m_pWin.data(),&MainWindow::setLineEditProjectAim);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingProjectPersons,
                     m_pWin.data(),&MainWindow::setLineEditProjectPersons);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingProjectComment,
                     m_pWin.data(),&MainWindow::setLineEditProjectComment);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::mriDataFoundInFile,
                     m_pWin.data(),&MainWindow::setLabelMriDataFoundVisible);
}

void SettingsControllerGui::initializeOptionsState()
{
    if(m_pAnonymizer->isFileInSet())
    {
        m_pWin->setLineEditInFile(m_fiInFileInfo.absoluteFilePath());
    }
    if(m_pAnonymizer->isFileOutSet())
    {
        m_pWin->setLineEditOutFile(m_fiOutFileInfo.absoluteFilePath());
    }

    m_pWin->setCheckBoxBruteMode(m_pAnonymizer->getBruteMode());
    m_pWin->setMeasurementDate(m_pAnonymizer->getMeasurementDate());
    m_pWin->setCheckBoxMeasurementDateOffset(m_pAnonymizer->getUseMeasurementDayOffset());
    m_pWin->setMeasurementDateOffset(m_pAnonymizer->getMeasurementDayOffset());
    m_pWin->setCheckBoxSubjectBirthdayOffset(m_pAnonymizer->getUseSubjectBirthdayOffset());
    m_pWin->setSubjectBirthdayOffset(m_pAnonymizer->getSubjectBirthdayOffset());
    if(m_bHisIdSpecified)
    {
        m_pWin->setSubjectHis(m_pAnonymizer->getSubjectHisID());
    }
}
<commit_msg>fix anonymize without input file specified<commit_after>//=============================================================================================================
/**
 * @file     settingscontrollergui.cpp
 * @author   Juan GPC <juangpc@gmail.com>
 * @since    0.1.0
 * @date     May, 2020
 *
 * @section  LICENSE
 *
 * Copyright (C) 2020, Juan GPC. 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 MNE-CPP authors 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.
 *
 *
 * @brief    SettingsControllerGUI class definition.
 *
 */

//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "settingscontrollergui.h"
#include "mainwindow.h"

//=============================================================================================================
// QT INCLUDES
//=============================================================================================================

#include <QDir>
#include <QStandardPaths>
#include <QDesktopServices>
#include <QDateTime>
#include <QtGlobal>

//=============================================================================================================
// EIGEN INCLUDES
//=============================================================================================================

//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace MNEANONYMIZE;

//=============================================================================================================
// DEFINE GLOBAL METHODS
//=============================================================================================================

//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================

SettingsControllerGui::SettingsControllerGui(const QStringList& arguments)
: m_pWin(QSharedPointer<MainWindow> (new MainWindow(this)))
{
    initParser();
    parseInputs(arguments);
    setupCommunication();

    initializeOptionsState();

    m_pWin->show();
//    m_bInputFileInformationVisible = m_pWin->getExtraInfoVisibility();

//    readData();
    QString msg("Mellow greetings!");
    m_pWin->statusMsg(msg,2000);
}

void SettingsControllerGui::executeAnonymizer()
{
    if(!m_pAnonymizer->isFileInSet())
    {
        m_pWin->winPopup("Please specify a valid input file first.");
        return;
    }
    if(!m_pAnonymizer->isFileOutSet())
    {
        m_pWin->winPopup("Please specify a valid output file first.");
        return;
    }
    m_pWin->statusMsg("Anonymizing the input file into the output file.",2000);
    m_pAnonymizer->anonymizeFile();
    m_pWin->statusMsg("Your file is ready!");
}

void SettingsControllerGui::readData()
{
    if(m_pAnonymizer->isFileInSet())
    {

        QString stringTempDir(QStandardPaths::writableLocation(QStandardPaths::TempLocation));
        QString fileOutStr(QDir(stringTempDir).filePath(generateRandomFileName()));
        m_pAnonymizer->setFileOut(fileOutStr);
        m_pWin->setDefaultStateExtraInfo();
        bool verboseMode(m_pAnonymizer->getVerboseMode());
        m_pAnonymizer->setVerboseMode(false);
        m_pWin->statusMsg("Reading input file information...",0);
        m_pAnonymizer->anonymizeFile();
        QFile fileOut(fileOutStr);
        fileOut.remove();
        m_pAnonymizer->setFileOut(m_fiOutFileInfo.absoluteFilePath());
        m_pAnonymizer->setVerboseMode(verboseMode);
        QString msg2("Input file information read correctly.");
        m_pWin->statusMsg(msg2,2000);
    } else {
        m_pWin->winPopup("Cannot read data. Please select a valid input file first.");
    }
}

void SettingsControllerGui::fileInChanged(const QString& strInFile)
{
    QFileInfo newfiInFile(strInFile);

    if(newfiInFile.isDir())
    {
        m_pWin->statusMsg("Invalid input file. That's a directory");
        m_pWin->setLineEditInFile(m_fiInFileInfo.absoluteFilePath());
        return;
    }
    if(QString::compare(newfiInFile.suffix(),QString("fif")) != 0)
    {
        m_pWin->statusMsg("The input file extension must be \".fif\" 0.");
        m_pWin->setLineEditOutFile(m_fiOutFileInfo.absoluteFilePath());
        return;
    }
    QFileInfo inDir(newfiInFile.absolutePath());
    if(!inDir.isReadable())
    {
        m_pWin->statusMsg("You might not have reading permissions to this folder");
        m_pWin->setLineEditInFile(m_fiInFileInfo.absoluteFilePath());
        return;
    }

    if( m_fiInFileInfo != newfiInFile )
    {
        m_fiInFileInfo.setFile(newfiInFile.absoluteFilePath());
        m_pAnonymizer->setFileIn(m_fiInFileInfo.absoluteFilePath());

        generateDefaultOutputFileName();
        m_pWin->setLineEditInFile(m_fiInFileInfo.absoluteFilePath());
        m_pWin->setLineEditOutFile(m_fiOutFileInfo.absoluteFilePath());
    }
}

void SettingsControllerGui::fileOutChanged(const QString& strOutFile)
{
    QFileInfo newfiOutFile(strOutFile);
    if(m_fiOutFileInfo.isDir())
    {
        QString fileOutDefaultName(newfiOutFile.absolutePath() + m_fiInFileInfo.baseName() +
                        "_anonymized." + m_fiInFileInfo.completeSuffix());
        m_fiOutFileInfo.setFile(fileOutDefaultName);
        m_pWin->setLineEditOutFile(m_fiOutFileInfo.absoluteFilePath());
        return;
    }

    if(QString::compare(newfiOutFile.suffix(),QString("fif")) != 0)
    {
        m_pWin->statusMsg("The output file extension must be \".fif\" 0.");
        m_pWin->setLineEditOutFile(m_fiOutFileInfo.absoluteFilePath());
        return;
    }

    QFileInfo outDir(newfiOutFile.absolutePath());
    if(!outDir.isWritable())
    {
        m_pWin->winPopup("You might not have writing permissions to this folder");
        m_pWin->setLineEditOutFile(m_fiOutFileInfo.absoluteFilePath());
        return;
    }

    if(m_fiOutFileInfo != newfiOutFile)
    {
        m_fiOutFileInfo.setFile(strOutFile);
        m_pAnonymizer->setFileOut(m_fiOutFileInfo.absoluteFilePath());
    }
}

void SettingsControllerGui::setupCommunication()
{
    //view to controller
    QObject::connect(m_pWin.data(),&MainWindow::fileInChanged,
                     this,&SettingsControllerGui::fileInChanged);
    QObject::connect(m_pWin.data(),&MainWindow::fileOutChanged,
                     this,&SettingsControllerGui::fileOutChanged);
    QObject::connect(m_pWin.data(),&MainWindow::readInputDataButtonClicked,
                     this,&SettingsControllerGui::readData);

    //from view to model
    QObject::connect(m_pWin.data(),&MainWindow::bruteModeChanged,
                     m_pAnonymizer.data(),&FiffAnonymizer::setBruteMode);
    QObject::connect(m_pWin.data(),&MainWindow::measurementDateChanged,
                     m_pAnonymizer.data(),QOverload<const QDateTime&>::of(&FiffAnonymizer::setMeasurementDate));
    QObject::connect(m_pWin.data(),&MainWindow::useMeasurementOffset,
                     m_pAnonymizer.data(),&FiffAnonymizer::setUseMeasurementDateOffset);
    QObject::connect(m_pWin.data(),&MainWindow::measurementDateOffsetChanged,
                     m_pAnonymizer.data(),&FiffAnonymizer::setMeasurementDateOffset);
    QObject::connect(m_pWin.data(),&MainWindow::birthdayDateChanged,
                     m_pAnonymizer.data(),QOverload<const QDateTime&>::of(&FiffAnonymizer::setSubjectBirthday));
    QObject::connect(m_pWin.data(),&MainWindow::useBirthdayOffset,
                     m_pAnonymizer.data(),&FiffAnonymizer::setUseSubjectBirthdayOffset);
    QObject::connect(m_pWin.data(),&MainWindow::birthdayOffsetChanged,
                     m_pAnonymizer.data(),&FiffAnonymizer::setSubjectBirthdayOffset);
    QObject::connect(m_pWin.data(),&MainWindow::subjectHisIdChanged,
                     m_pAnonymizer.data(),&FiffAnonymizer::setSubjectHisId);

    //from model to view
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingIdFileVersion,
                     m_pWin.data(),&MainWindow::setLineEditIdFileVersion);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingIdMeasurementDate,
                     m_pWin.data(),&MainWindow::setLineEditIdMeasurementDate);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingIdMac,
                     m_pWin.data(),&MainWindow::setLineEditIdMacAddress);

    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingFileMeasurementDate,
                     m_pWin.data(),&MainWindow::setLineEditFileMeasurementDate);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingFileComment,
                     m_pWin.data(),&MainWindow::setLineEditFileComment);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingFileExperimenter,
                     m_pWin.data(),&MainWindow::setLineEditFileExperimenter);

    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectId,
                     m_pWin.data(),&MainWindow::setLineEditSubjectId);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectFirstName,
                     m_pWin.data(),&MainWindow::setLineEditSubjectFirstName);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectMiddleName,
                     m_pWin.data(),&MainWindow::setLineEditSubjectMiddleName);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectLastName,
                     m_pWin.data(),&MainWindow::setLineEditSubjectLastName);

    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectBirthday,
                     m_pWin.data(),&MainWindow::setLineEditSubjectBirthday);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectSex,
                     m_pWin.data(),&MainWindow::setComboBoxSubjectSex);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectHand,
                     m_pWin.data(),&MainWindow::setLineEditSubjectHand);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectWeight,
                     m_pWin.data(),&MainWindow::setLineEditSubjectHand);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectHeight,
                     m_pWin.data(),&MainWindow::setLineEditSubjectHeight);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectComment,
                     m_pWin.data(),&MainWindow::setLineEditSubjectComment);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectHisId,
                     m_pWin.data(),&MainWindow::setLineEditSubjectHisId);

    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingProjectId,
                     m_pWin.data(),&MainWindow::setLineEditProjectId);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingProjectName,
                     m_pWin.data(),&MainWindow::setLineEditProjectName);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingProjectAim,
                     m_pWin.data(),&MainWindow::setLineEditProjectAim);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingProjectPersons,
                     m_pWin.data(),&MainWindow::setLineEditProjectPersons);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingProjectComment,
                     m_pWin.data(),&MainWindow::setLineEditProjectComment);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::mriDataFoundInFile,
                     m_pWin.data(),&MainWindow::setLabelMriDataFoundVisible);
}

void SettingsControllerGui::initializeOptionsState()
{
    if(m_pAnonymizer->isFileInSet())
    {
        m_pWin->setLineEditInFile(m_fiInFileInfo.absoluteFilePath());
    }
    if(m_pAnonymizer->isFileOutSet())
    {
        m_pWin->setLineEditOutFile(m_fiOutFileInfo.absoluteFilePath());
    }

    m_pWin->setCheckBoxBruteMode(m_pAnonymizer->getBruteMode());
    m_pWin->setMeasurementDate(m_pAnonymizer->getMeasurementDate());
    m_pWin->setCheckBoxMeasurementDateOffset(m_pAnonymizer->getUseMeasurementDayOffset());
    m_pWin->setMeasurementDateOffset(m_pAnonymizer->getMeasurementDayOffset());
    m_pWin->setCheckBoxSubjectBirthdayOffset(m_pAnonymizer->getUseSubjectBirthdayOffset());
    m_pWin->setSubjectBirthdayOffset(m_pAnonymizer->getSubjectBirthdayOffset());
    if(m_bHisIdSpecified)
    {
        m_pWin->setSubjectHis(m_pAnonymizer->getSubjectHisID());
    }
}
<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (C) 2004 by Stanislav Karchebny                             *
 *   Stanislav.Karchebny@kdemail.net                                       *
 *                                                                         *
 *   Licensed under GPL.                                                   *
 ***************************************************************************/
#include "feed.h"
#include "feedscollection.h"

#include <kurl.h>
#include <kdebug.h>

#include <qlistview.h>

using namespace Akregator;
using namespace RSS;

Feed::Feed(QListViewItem *i, FeedsCollection *coll)
    : FeedGroup(i, coll)
    , title()
    , xmlUrl()
    , htmlUrl()
    , description()
    , isLiveJournal(false)
    , ljUserName()
    , ljAuthMode(AuthNone)
    , ljLogin()
    , ljPassword()
    , updateTitle(false)
    , articles()
    , m_item(i)
    , m_collection(coll)
{
    updateView();
}

Feed::~Feed()
{
}

void Feed::destroy()
{
   m_collection->remove(m_item);
   delete this;
}

void Feed::updateView()
{
}

/*void Feed::open(QTextStream &ts)
{
}*/

QString Feed::ljAuthModeStr()
{
    if (ljAuthMode == AuthLocal)
        return "local";
    if (ljAuthMode == AuthGlobal)
        return "global";
    return "none";
}

/*static*/ Feed::LJAuthMode Feed::authModeFromString(const QString &mode)
{
    QString m = mode.lower();
    if (m == "local")
        return AuthLocal;
    if (m == "global")
        return AuthGlobal;
    return AuthNone;
}

void Feed::save(QTextStream &ts, int /*depth*/)
{
    ts << "<outline text=\"" << title << "\" "
                  "title=\"" << title << "\" "
                 "xmlUrl=\"" << xmlUrl << "\" "
                "htmlUrl=\"" << htmlUrl << "\" "
            "description=\"" << description << "\" "
          "isLiveJournal=\"" << isLiveJournal << "\" "
             "ljUserName=\"" << ljUserName << "\" "
             "ljAuthMode=\"" << ljAuthModeStr() << "\" "
                "ljLogin=\"" << ljLogin << "\" "
             "ljPassword=\"" << ljPassword << "\" "
            "updateTitle=\"" << updateTitle << "\" "
                   "type=\"akrss\" "
                "version=\"RSS\"/>" << endl;
}

void Feed::fetch()
{
    Loader *loader = Loader::create( this, SLOT(fetchCompleted(Loader *, Document, Status)) );
    loader->loadFrom( xmlUrl, new FileRetriever );
}

void Feed::fetchCompleted(Loader */*loader*/, Document doc, Status status)
{
    // Note that Loader::~Loader() is private, so you cannot delete Loader instances.
    // You don't need to do that anyway since Loader instances delete themselves.

    if (status != RSS::Success)
        return;

    kdDebug() << "Feed fetched successfully [" << doc.title() << "]" << endl;

    if (updateTitle || title.isEmpty()) title = doc.title();
    description = doc.description();
    htmlUrl = doc.link().url();
    articles = doc.articles();

    emit fetched(this);
}

#include "feed.moc"
<commit_msg>Be less verbose (silly)<commit_after>/***************************************************************************
 *   Copyright (C) 2004 by Stanislav Karchebny                             *
 *   Stanislav.Karchebny@kdemail.net                                       *
 *                                                                         *
 *   Licensed under GPL.                                                   *
 ***************************************************************************/
#include "feed.h"
#include "feedscollection.h"

#include <kurl.h>
#include <kdebug.h>

#include <qlistview.h>

using namespace Akregator;
using namespace RSS;

Feed::Feed(QListViewItem *i, FeedsCollection *coll)
    : FeedGroup(i, coll)
    , title()
    , xmlUrl()
    , htmlUrl()
    , description()
    , isLiveJournal(false)
    , ljUserName()
    , ljAuthMode(AuthNone)
    , ljLogin()
    , ljPassword()
    , updateTitle(false)
    , articles()
    , m_item(i)
    , m_collection(coll)
{
    updateView();
}

Feed::~Feed()
{
}

void Feed::destroy()
{
   m_collection->remove(m_item);
   delete this;
}

void Feed::updateView()
{
}

/*void Feed::open(QTextStream &ts)
{
}*/

QString Feed::ljAuthModeStr()
{
    if (ljAuthMode == AuthLocal)
        return "local";
    if (ljAuthMode == AuthGlobal)
        return "global";
    return "none";
}

/*static*/ Feed::LJAuthMode Feed::authModeFromString(const QString &mode)
{
    QString m = mode.lower();
    if (m == "local")
        return AuthLocal;
    if (m == "global")
        return AuthGlobal;
    return AuthNone;
}

void Feed::save(QTextStream &ts, int /*depth*/)
{
    ts << "<outline text=\"" << title << "\" "
                  "title=\"" << title << "\" "
                 "xmlUrl=\"" << xmlUrl << "\" "
                "htmlUrl=\"" << htmlUrl << "\" "
            "description=\"" << description << "\" "
          "isLiveJournal=\"" << isLiveJournal << "\" "
             "ljUserName=\"" << ljUserName << "\" "
             "ljAuthMode=\"" << ljAuthModeStr() << "\" "
                "ljLogin=\"" << ljLogin << "\" "
             "ljPassword=\"" << ljPassword << "\" "
            "updateTitle=\"" << updateTitle << "\" "
                   "type=\"akrss\" "
                "version=\"RSS\"/>" << endl;
}

void Feed::fetch()
{
    Loader *loader = Loader::create( this, SLOT(fetchCompleted(Loader *, Document, Status)) );
    loader->loadFrom( xmlUrl, new FileRetriever );
}

void Feed::fetchCompleted(Loader */*loader*/, Document doc, Status status)
{
    // Note that Loader::~Loader() is private, so you cannot delete Loader instances.
    // You don't need to do that anyway since Loader instances delete themselves.

    if (status != Success)
        return;

    kdDebug() << "Feed fetched successfully [" << doc.title() << "]" << endl;

    if (updateTitle || title.isEmpty()) title = doc.title();
    description = doc.description();
    htmlUrl = doc.link().url();
    articles = doc.articles();

    emit fetched(this);
}

#include "feed.moc"
<|endoftext|>


<commit_before>/*
 * MediaManager.cpp - Kurento Media Server
 *
 * Copyright (C) 2013 Kurento
 * Contact: Miguel París Díaz <mparisdiaz@gmail.com>
 * Contact: José Antonio Santos Cadenas <santoscadenas@kurento.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "MediaHandler.hpp"

namespace kurento
{

void
MediaHandler::sendEvent (MediaEvent &event)
{
  // TODO: Implement this trying to send the event to the possible addresses
}

}
<commit_msg>Send events to a random client<commit_after>/*
 * MediaManager.cpp - Kurento Media Server
 *
 * Copyright (C) 2013 Kurento
 * Contact: Miguel París Díaz <mparisdiaz@gmail.com>
 * Contact: José Antonio Santos Cadenas <santoscadenas@kurento.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "MediaHandler.hpp"

#include "thrift/transport/TSocket.h"
#include "thrift/transport/TBufferTransports.h"
#include "thrift/protocol/TBinaryProtocol.h"

#include "MediaHandlerService.h"

using namespace ::apache::thrift::transport;
using namespace ::apache::thrift::protocol;

namespace kurento
{

void
MediaHandler::sendEvent (MediaEvent &event)
{
  mutex.lock();
  std::list<std::shared_ptr<MediaHandlerAddress>>::iterator randIt = addresses.begin();
  std::advance (randIt, std::rand() % addresses.size() );
  std::shared_ptr<MediaHandlerAddress> addr = *randIt;
  mutex.unlock();

  boost::shared_ptr<TSocket> socket (new TSocket (addr->address, addr->port) );
  boost::shared_ptr<TTransport> transport (new TFramedTransport (socket) );
  boost::shared_ptr<TBinaryProtocol> protocol (new TBinaryProtocol (transport) );

  try {
    transport->open();

    MediaHandlerServiceClient client (protocol);

    client.onEvent (event);
    //TODO: Move the reply wating to a different thread to avoid locking main loop
    transport->close();
  } catch (...) {
    // TODO: Try to send event again or raise error;
  }
}

}
<|endoftext|>