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

#include "SurgSim/Devices/LabJack/linux/LabJackChecksums.h"

namespace SurgSim
{
namespace Device
{
namespace LabJackChecksums
{

unsigned char normalChecksum8(const std::array<unsigned char, LABJACK_MAXIMUM_BUFFER>& bytes, int count)
{
	uint16_t accumulator = 0;

	//Sums bytes 1 to n-1 unsigned to a 2 byte value. Sums quotient and
	//remainder of 256 division.  Again, sums quotient and remainder of
	//256 division.
	for (int i = 1; i < count; ++i)
	{
		accumulator += static_cast<uint16_t>(bytes.at(i));
	}

	uint16_t quotient = accumulator / 256;
	accumulator = (accumulator - 256 * quotient) + quotient;
	quotient = accumulator / 256;

	return static_cast<unsigned char>((accumulator - 256 * quotient) + quotient);
}

uint16_t extendedChecksum16(const std::array<unsigned char, LABJACK_MAXIMUM_BUFFER>& bytes, int count)
{
	int accumulator = 0;

	//Sums bytes 6 to n-1 to an unsigned 2 byte value
	for (int i = 6; i < count; ++i)
	{
		accumulator += static_cast<uint16_t>(bytes.at(i));
	}

	return accumulator;
}

unsigned char extendedChecksum8(const std::array<unsigned char, LABJACK_MAXIMUM_BUFFER>& bytes)
{
	return normalChecksum8(bytes, 6);
}

void normalChecksum(std::array<unsigned char, LABJACK_MAXIMUM_BUFFER>* bytes, int count)
{
	(*bytes)[0] = normalChecksum8(*bytes, count);
}

void extendedChecksum(std::array<unsigned char, LABJACK_MAXIMUM_BUFFER>* bytes, int count)
{
	uint16_t accumulator = extendedChecksum16(*bytes, count);
	(*bytes)[4] = static_cast<unsigned char>(accumulator & 0xff);
	(*bytes)[5] = static_cast<unsigned char>((accumulator / 256) & 0xff);
	(*bytes)[0] = extendedChecksum8(*bytes);
}

};  // namespace LabJackChecksums
};  // namespace Device
};  // namespace SurgSim<commit_msg>Fix variable type in LabJackChecksums.<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "SurgSim/Devices/LabJack/linux/LabJackChecksums.h"

namespace SurgSim
{
namespace Device
{
namespace LabJackChecksums
{

unsigned char normalChecksum8(const std::array<unsigned char, LABJACK_MAXIMUM_BUFFER>& bytes, int count)
{
	uint16_t accumulator = 0;

	//Sums bytes 1 to n-1 unsigned to a 2 byte value. Sums quotient and
	//remainder of 256 division.  Again, sums quotient and remainder of
	//256 division.
	for (int i = 1; i < count; ++i)
	{
		accumulator += static_cast<uint16_t>(bytes.at(i));
	}

	uint16_t quotient = accumulator / 256;
	accumulator = (accumulator - 256 * quotient) + quotient;
	quotient = accumulator / 256;

	return static_cast<unsigned char>((accumulator - 256 * quotient) + quotient);
}

uint16_t extendedChecksum16(const std::array<unsigned char, LABJACK_MAXIMUM_BUFFER>& bytes, int count)
{
	uint16_t accumulator = 0;

	//Sums bytes 6 to n-1 to an unsigned 2 byte value
	for (int i = 6; i < count; ++i)
	{
		accumulator += static_cast<uint16_t>(bytes.at(i));
	}

	return accumulator;
}

unsigned char extendedChecksum8(const std::array<unsigned char, LABJACK_MAXIMUM_BUFFER>& bytes)
{
	return normalChecksum8(bytes, 6);
}

void normalChecksum(std::array<unsigned char, LABJACK_MAXIMUM_BUFFER>* bytes, int count)
{
	(*bytes)[0] = normalChecksum8(*bytes, count);
}

void extendedChecksum(std::array<unsigned char, LABJACK_MAXIMUM_BUFFER>* bytes, int count)
{
	uint16_t accumulator = extendedChecksum16(*bytes, count);
	(*bytes)[4] = static_cast<unsigned char>(accumulator & 0xff);
	(*bytes)[5] = static_cast<unsigned char>((accumulator / 256) & 0xff);
	(*bytes)[0] = extendedChecksum8(*bytes);
}

};  // namespace LabJackChecksums
};  // namespace Device
};  // namespace SurgSim<|endoftext|>


<commit_before>#ifndef CONNECTOR_CPP
#define CONNECTOR_CPP

#include "Command.h"
#include "Connector.h"

using namespace std;
#include <iostream>
#include <vector>
#include <list>

//   VectorContainer(Sort* function):Container(function){};

class andConnector: public Connector
{
    private:

    public:

        andConnector(bool l, string s) : Connector(l,s)
        {
            // left = l;
            // right = s;
            self = false;
            if(l)
            {
                Command input(s);
                input.launch();
                self = (l && input.isValid() );
            }

            //input.getValidity()

        };

        bool getValidity()
        {
            return self;
        }
};

class orConnector: public Connector
{
    private:

    public:

        orConnector(bool l, string s) : Connector(l,s)
        {
            // left = l;
            // right = s;
            self = l;
            if(!l)
            {
                Command input(s);
                input.launch();
                self = (l || input.isValid() );
            }
            //input.getValidity()

        };

        bool getValidity()
        {
            return self;
        }
};

#endif <commit_msg>Delete Connector.cpp<commit_after><|endoftext|>


<commit_before>
// Copyright (c) 2015 Pierre MOULON.

// 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/.

#pragma once

#include "reconstructed_regions.hpp"
#include "LocalizationResult.hpp"

#include <openMVG/features/image_describer.hpp>
#include <openMVG/sfm/sfm_data.hpp>
#include <openMVG/sfm/pipelines/localization/SfM_Localizer.hpp>
#include <openMVG/stl/stlMap.hpp>
#include <openMVG/voctree/vocabulary_tree.hpp>
#include <openMVG/voctree/database.hpp>
#include <openMVG/matching/matcher_kdtree_flann.hpp>
#include <openMVG/matching/regions_matcher.hpp>
#include <flann/algorithms/dist.h>

namespace openMVG {
namespace localization {

//@fixme find a better place or maje the class template?
typedef openMVG::features::Descriptor<float, 128> DescriptorFloat;
typedef Reconstructed_Regions<features::SIOPointFeature, float, 128> Reconstructed_RegionsT;

class VoctreeLocalizer
{

public:
  enum Algorithm : int { FirstBest=0, BestResult=1, AllResults=2, Cluster=3};
  static Algorithm initFromString(const std::string &value);

public:
  struct Parameters
  {

    Parameters() :
      _useGuidedMatching(false),
      _refineIntrinsics(false),
      _algorithm(Algorithm::FirstBest),
      _numResults(4),
      _maxResults(10),
      _numCommonViews(3),
      _fDistRatio(0.6),
      _featurePreset(features::EDESCRIBER_PRESET::ULTRA_PRESET),
      _errorMax(std::numeric_limits<double>::max()) { }

    bool _useGuidedMatching;    //< Enable/disable guided matching when matching images
    bool _refineIntrinsics;     //< whether or not the Intrinsics of the query camera has to be refined
    Algorithm _algorithm;       //< algorithm to use for localization
    size_t _numResults;         //< number of best matching images to retrieve from the database
    size_t _maxResults;
    size_t _numCommonViews;     //< number minimum common images in which a point must be seen to be used in cluster tracking
    float _fDistRatio;          //< the ratio distance to use when matching feature with the ratio test
    features::EDESCRIBER_PRESET _featurePreset; //< the preset to use for feature extraction of the query image
    double _errorMax;
  };

public:
#ifdef HAVE_CCTAG
  VoctreeLocalizer(bool useSIFT_CCTAG = false);
#else
  VoctreeLocalizer();
#endif

  bool init(const std::string &sfmFilePath,
            const std::string &descriptorsFolder,
            const std::string &vocTreeFilepath,
            const std::string &weightsFilepath);

  // loadSfmData(const std::string & sfmDataPath)

  /**
   * @brief Load all the Descriptors who have contributed to the reconstruction.
   */
  bool loadReconstructionDescriptors(
    const sfm::SfM_Data & sfm_data,
    const std::string & feat_directory);

  /**
   * @brief Just a wrapper around the different localization algorithm, the algorith
   * used to localized is chosen using \p param._algorithm
   *
   * @param[in] imageGray The input greyscale image
   * @param[in] param The parameters for the localization
   * @param[in] useInputIntrinsics Uses the \p queryIntrinsics as known calibration
   * @param[in,out] queryIntrinsics Intrinsic parameters of the camera, they are used if the
   * flag useInputIntrinsics is set to true, otherwise they are estimated from the correspondences.
   * @param[out] pose The camera pose
   * @param[out] resection_data the 2D-3D correspondences used to compute the pose
   * @return true if the localization is successful
   */
  bool localize(const image::Image<unsigned char> & imageGrey,
                const Parameters &param,
                bool useInputIntrinsics,
                cameras::Pinhole_Intrinsic_Radial_K3 &queryIntrinsics,
                LocalizationResult &localizationResult);

  /**
   * @brief Try to localize an image in the database: it queries the database to
   * retrieve \p numResults matching images and it tries to localize the query image
   * wrt the retrieve images in order of their score taking the first best result.
   *
   * @param[in] imageGray The input greayscale image
   * @param[in] param The parameters for the localization
   * @param[in] useInputIntrinsics Uses the \p queryIntrinsics as known calibration
   * @param[in,out] queryIntrinsics Intrinsic parameters of the camera, they are used if the
   * flag useInputIntrinsics is set to true, otherwise they are estimated from the correspondences.
   * @param[out] pose The camera pose
   * @param[out] resection_data the 2D-3D correspondences used to compute the pose
   * @param[out] associationIDs the ids of the 2D-3D correspondences used to compute the pose
   * @return true if the localization is successful
   */
  bool localizeFirstBestResult(const image::Image<unsigned char> & imageGrey,
                const Parameters &param,
                bool useInputIntrinsics,
                cameras::Pinhole_Intrinsic_Radial_K3 &queryIntrinsics,
                LocalizationResult &localizationResult);

  /**
   * @brief Try to localize an image in the database: it queries the database to
   * retrieve \p numResults matching images and it tries to localize the query image
   * wrt the retrieve images in order of their score, collecting all the 2d-3d correspondences
   * and performing the resection with all these correspondences
   *
   * @param[in] imageGray The input greyscale image
   * @param[in] param The parameters for the localization
   * @param[in] useInputIntrinsics Uses the \p queryIntrinsics as known calibration
   * @param[in,out] queryIntrinsics Intrinsic parameters of the camera, they are used if the
   * flag useInputIntrinsics is set to true, otherwise they are estimated from the correspondences.
   * @param[out] pose The camera pose
   * @param[out] resection_data the 2D-3D correspondences used to compute the pose
   * @param[out] associationIDs the ids of the 2D-3D correspondences used to compute the pose
   * @return true if the localization is successful
   */
  bool localizeAllResults(const image::Image<unsigned char> & imageGrey,
                const Parameters &param,
                bool useInputIntrinsics,
                cameras::Pinhole_Intrinsic_Radial_K3 &queryIntrinsics,
                LocalizationResult &localizationResult);

  const sfm::SfM_Data& getSfMData() const {return _sfm_data; }

public:
  static bool refineSequence(cameras::Pinhole_Intrinsic_Radial_K3 *intrinsics,
                             std::vector<geometry::Pose3> & poses,
                             std::vector<sfm::Image_Localizer_Match_Data> & associations,
                             std::vector<std::vector<pair<IndexT, IndexT> > > &associationIDs);

private:
  /**
   * @brief Load the vocabulary tree.
   */
  bool initDatabase(const std::string & vocTreeFilepath,
                                    const std::string & weightsFilepath,
                                    const std::string & feat_directory);

  typedef flann::L2<float> MetricT;
  typedef matching::ArrayMatcher_Kdtree_Flann<float, MetricT> MatcherT;
  bool robustMatching(matching::RegionsMatcherT<MatcherT> & matcher,
                      const cameras::IntrinsicBase * queryIntrinsics,// the intrinsics of the image we are using as reference
                      const Reconstructed_RegionsT & regionsToMatch,
                      const cameras::IntrinsicBase * matchedIntrinsics,
                      const float fDistRatio,
                      const bool b_guided_matching,
                      const std::pair<size_t,size_t> & imageSizeI,     // size of the first image
                      const std::pair<size_t,size_t> & imageSizeJ,     // size of the first image
                      std::vector<matching::IndMatch> & vec_featureMatches) const;

public:

  // for each view index, it contains the features and descriptors that have an
  // associated 3D point
  Hash_Map<IndexT, Reconstructed_RegionsT > _regions_per_view;

  // contains the 3D reconstruction data
  sfm::SfM_Data _sfm_data;

  // the feature extractor
  // @fixme do we want a generic image describer?
//  features::SIFT_float_describer _image_describer;
  features::Image_describer* _image_describer;

  // the vocabulary tree used to generate the database and the visual images for
  // the query images
  voctree::VocabularyTree<DescriptorFloat> _voctree;

  // the database that stores the visual word representation of each image of
  // the original dataset
  voctree::Database _database;

};

/**
 * @brief Print the name of the algorithm
 */
std::ostream& operator<<(std::ostream& os, VoctreeLocalizer::Algorithm a);

/**
 * @brief Get the type of algorithm from an integer
 */
std::istream& operator>>(std::istream &in, VoctreeLocalizer::Algorithm &a);

} // localization
} // openMVG
<commit_msg>[localization] removed unused methods<commit_after>
// Copyright (c) 2015 Pierre MOULON.

// 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/.

#pragma once

#include "reconstructed_regions.hpp"
#include "LocalizationResult.hpp"

#include <openMVG/features/image_describer.hpp>
#include <openMVG/sfm/sfm_data.hpp>
#include <openMVG/sfm/pipelines/localization/SfM_Localizer.hpp>
#include <openMVG/stl/stlMap.hpp>
#include <openMVG/voctree/vocabulary_tree.hpp>
#include <openMVG/voctree/database.hpp>
#include <openMVG/matching/matcher_kdtree_flann.hpp>
#include <openMVG/matching/regions_matcher.hpp>
#include <flann/algorithms/dist.h>

namespace openMVG {
namespace localization {

//@fixme find a better place or maje the class template?
typedef openMVG::features::Descriptor<float, 128> DescriptorFloat;
typedef Reconstructed_Regions<features::SIOPointFeature, float, 128> Reconstructed_RegionsT;

class VoctreeLocalizer
{

public:
  enum Algorithm : int { FirstBest=0, BestResult=1, AllResults=2, Cluster=3};
  static Algorithm initFromString(const std::string &value);

public:
  struct Parameters
  {

    Parameters() :
      _useGuidedMatching(false),
      _refineIntrinsics(false),
      _algorithm(Algorithm::FirstBest),
      _numResults(4),
      _maxResults(10),
      _numCommonViews(3),
      _fDistRatio(0.6),
      _featurePreset(features::EDESCRIBER_PRESET::ULTRA_PRESET),
      _errorMax(std::numeric_limits<double>::max()) { }

    bool _useGuidedMatching;    //< Enable/disable guided matching when matching images
    bool _refineIntrinsics;     //< whether or not the Intrinsics of the query camera has to be refined
    Algorithm _algorithm;       //< algorithm to use for localization
    size_t _numResults;         //< number of best matching images to retrieve from the database
    size_t _maxResults;
    size_t _numCommonViews;     //< number minimum common images in which a point must be seen to be used in cluster tracking
    float _fDistRatio;          //< the ratio distance to use when matching feature with the ratio test
    features::EDESCRIBER_PRESET _featurePreset; //< the preset to use for feature extraction of the query image
    double _errorMax;
  };

public:
#ifdef HAVE_CCTAG
  VoctreeLocalizer(bool useSIFT_CCTAG = false);
#else
  VoctreeLocalizer();
#endif

  bool init(const std::string &sfmFilePath,
            const std::string &descriptorsFolder,
            const std::string &vocTreeFilepath,
            const std::string &weightsFilepath);

  /**
   * @brief Load all the Descriptors who have contributed to the reconstruction.
   */
  bool loadReconstructionDescriptors(
    const sfm::SfM_Data & sfm_data,
    const std::string & feat_directory);

  /**
   * @brief Just a wrapper around the different localization algorithm, the algorith
   * used to localized is chosen using \p param._algorithm
   *
   * @param[in] imageGray The input greyscale image
   * @param[in] param The parameters for the localization
   * @param[in] useInputIntrinsics Uses the \p queryIntrinsics as known calibration
   * @param[in,out] queryIntrinsics Intrinsic parameters of the camera, they are used if the
   * flag useInputIntrinsics is set to true, otherwise they are estimated from the correspondences.
   * @param[out] pose The camera pose
   * @param[out] resection_data the 2D-3D correspondences used to compute the pose
   * @return true if the localization is successful
   */
  bool localize(const image::Image<unsigned char> & imageGrey,
                const Parameters &param,
                bool useInputIntrinsics,
                cameras::Pinhole_Intrinsic_Radial_K3 &queryIntrinsics,
                LocalizationResult &localizationResult);

  /**
   * @brief Try to localize an image in the database: it queries the database to
   * retrieve \p numResults matching images and it tries to localize the query image
   * wrt the retrieve images in order of their score taking the first best result.
   *
   * @param[in] imageGray The input greayscale image
   * @param[in] param The parameters for the localization
   * @param[in] useInputIntrinsics Uses the \p queryIntrinsics as known calibration
   * @param[in,out] queryIntrinsics Intrinsic parameters of the camera, they are used if the
   * flag useInputIntrinsics is set to true, otherwise they are estimated from the correspondences.
   * @param[out] pose The camera pose
   * @param[out] resection_data the 2D-3D correspondences used to compute the pose
   * @param[out] associationIDs the ids of the 2D-3D correspondences used to compute the pose
   * @return true if the localization is successful
   */
  bool localizeFirstBestResult(const image::Image<unsigned char> & imageGrey,
                const Parameters &param,
                bool useInputIntrinsics,
                cameras::Pinhole_Intrinsic_Radial_K3 &queryIntrinsics,
                LocalizationResult &localizationResult);

  /**
   * @brief Try to localize an image in the database: it queries the database to
   * retrieve \p numResults matching images and it tries to localize the query image
   * wrt the retrieve images in order of their score, collecting all the 2d-3d correspondences
   * and performing the resection with all these correspondences
   *
   * @param[in] imageGray The input greyscale image
   * @param[in] param The parameters for the localization
   * @param[in] useInputIntrinsics Uses the \p queryIntrinsics as known calibration
   * @param[in,out] queryIntrinsics Intrinsic parameters of the camera, they are used if the
   * flag useInputIntrinsics is set to true, otherwise they are estimated from the correspondences.
   * @param[out] pose The camera pose
   * @param[out] resection_data the 2D-3D correspondences used to compute the pose
   * @param[out] associationIDs the ids of the 2D-3D correspondences used to compute the pose
   * @return true if the localization is successful
   */
  bool localizeAllResults(const image::Image<unsigned char> & imageGrey,
                const Parameters &param,
                bool useInputIntrinsics,
                cameras::Pinhole_Intrinsic_Radial_K3 &queryIntrinsics,
                LocalizationResult &localizationResult);

  const sfm::SfM_Data& getSfMData() const {return _sfm_data; }

private:
  /**
   * @brief Load the vocabulary tree.
   */
  bool initDatabase(const std::string & vocTreeFilepath,
                                    const std::string & weightsFilepath,
                                    const std::string & feat_directory);

  typedef flann::L2<float> MetricT;
  typedef matching::ArrayMatcher_Kdtree_Flann<float, MetricT> MatcherT;
  bool robustMatching(matching::RegionsMatcherT<MatcherT> & matcher,
                      const cameras::IntrinsicBase * queryIntrinsics,// the intrinsics of the image we are using as reference
                      const Reconstructed_RegionsT & regionsToMatch,
                      const cameras::IntrinsicBase * matchedIntrinsics,
                      const float fDistRatio,
                      const bool b_guided_matching,
                      const std::pair<size_t,size_t> & imageSizeI,     // size of the first image
                      const std::pair<size_t,size_t> & imageSizeJ,     // size of the first image
                      std::vector<matching::IndMatch> & vec_featureMatches) const;

public:

  // for each view index, it contains the features and descriptors that have an
  // associated 3D point
  Hash_Map<IndexT, Reconstructed_RegionsT > _regions_per_view;

  // contains the 3D reconstruction data
  sfm::SfM_Data _sfm_data;

  // the feature extractor
  // @fixme do we want a generic image describer?
//  features::SIFT_float_describer _image_describer;
  features::Image_describer* _image_describer;

  // the vocabulary tree used to generate the database and the visual images for
  // the query images
  voctree::VocabularyTree<DescriptorFloat> _voctree;

  // the database that stores the visual word representation of each image of
  // the original dataset
  voctree::Database _database;

};

/**
 * @brief Print the name of the algorithm
 */
std::ostream& operator<<(std::ostream& os, VoctreeLocalizer::Algorithm a);

/**
 * @brief Get the type of algorithm from an integer
 */
std::istream& operator>>(std::istream &in, VoctreeLocalizer::Algorithm &a);

} // localization
} // openMVG
<|endoftext|>


<commit_before>#ifndef ANIMATION_AUDIO_H_
#define ANIMATION_AUDIO_H_

#include "../../lib/Animation.hpp"
#include "../../conf/globals.h"
#include "../../dev/MSGEQ7.hpp"
#include "../../util/led.c"
#include "../../util/ledmath.c"

class Animation_Advanced : public Animation {
protected:
    Animation_Advanced() {}
    ~Animation_Advanced() {}

    void init();
};

class Animation_Advanced_Audio : public Animation_Advanced {
protected:
    Animation_Advanced_Audio() {}
    ~Animation_Advanced_Audio() {}

    void init();
};

class Animation_Advanced_Audio_BeatPulseWindow : public Animation_Advanced_Audio {
public:
    Animation_Advanced_Audio_BeatPulseWindow() {}
    ~Animation_Advanced_Audio_BeatPulseWindow() {}

	void init();
	void step();
	void clean();
private:
	MSGEQ7* left_eq;
};

class Animation_Advanced_Audio_BassPulseWindow : public Animation_Advanced_Audio {
public:
    Animation_Advanced_Audio_BassPulseWindow() {}
    ~Animation_Advanced_Audio_BassPulseWindow() {}

	void init();
	void step();
private:
	MSGEQ7* left_eq;
};

class Animation_Advanced_Audio_BassMidPulseWindow : public Animation_Advanced_Audio {
public:
    Animation_Advanced_Audio_BassMidPulseWindow() {}
    ~Animation_Advanced_Audio_BassMidPulseWindow() {}

	void init();
	void step();
private:
	MSGEQ7* left_eq;
};

class Animation_Advanced_Audio_EqualizerWindow : public Animation_Advanced_Audio {
public:
    Animation_Advanced_Audio_EqualizerWindow() {}
    ~Animation_Advanced_Audio_EqualizerWindow() {}

	void init();
	void step();
private:
	MSGEQ7* left_eq;
};

class Animation_Advanced_Audio_MaxEqualizerWindow : public Animation_Advanced_Audio {
public:
    Animation_Advanced_Audio_MaxEqualizerWindow() {}
    ~Animation_Advanced_Audio_MaxEqualizerWindow() {}

	void init();
	void step();
	void clean();
private:
	MSGEQ7* left_eq;
};

#endif
<commit_msg>put shared things in Animation_Advanced_Audio class<commit_after>#ifndef ANIMATION_AUDIO_H_
#define ANIMATION_AUDIO_H_

#include "../../lib/Animation.hpp"
#include "../../conf/globals.h"
#include "../../dev/MSGEQ7.hpp"
#include "../../util/led.c"
#include "../../util/ledmath.c"

class Animation_Advanced : public Animation {
protected:
    Animation_Advanced() {}
    ~Animation_Advanced() {}

    void init();
};

class Animation_Advanced_Audio : public Animation_Advanced {
protected:
    Animation_Advanced_Audio() {}
    ~Animation_Advanced_Audio() {}

    void init();

	MSGEQ7* left_eq;
	MSGEQ7* right_eq;
};

class Animation_Advanced_Audio_BeatPulseWindow : public Animation_Advanced_Audio {
public:
    Animation_Advanced_Audio_BeatPulseWindow() {}
    ~Animation_Advanced_Audio_BeatPulseWindow() {}

	void init();
	void step();
	void clean();
};

class Animation_Advanced_Audio_BassPulseWindow : public Animation_Advanced_Audio {
public:
    Animation_Advanced_Audio_BassPulseWindow() {}
    ~Animation_Advanced_Audio_BassPulseWindow() {}

	void init();
	void step();
};

class Animation_Advanced_Audio_BassMidPulseWindow : public Animation_Advanced_Audio {
public:
    Animation_Advanced_Audio_BassMidPulseWindow() {}
    ~Animation_Advanced_Audio_BassMidPulseWindow() {}

	void init();
	void step();
};

class Animation_Advanced_Audio_EqualizerWindow : public Animation_Advanced_Audio {
public:
    Animation_Advanced_Audio_EqualizerWindow() {}
    ~Animation_Advanced_Audio_EqualizerWindow() {}

	void init();
	void step();
};

class Animation_Advanced_Audio_MaxEqualizerWindow : public Animation_Advanced_Audio {
public:
    Animation_Advanced_Audio_MaxEqualizerWindow() {}
    ~Animation_Advanced_Audio_MaxEqualizerWindow() {}

	void init();
	void step();
	void clean();
};

#endif
<|endoftext|>


<commit_before>
// (c) COPYRIGHT URI/MIT 1997-1999
// Please read the full copyright statement in the file COPYRIGHT.
//
// Authors:
//      jhrg,jimg       James Gallagher (jgallagher@gso.uri.edu)

// Implementation of the DODSFilter class. This class is used to build dods
// filter programs which, along with a CGI program, comprise DODS servers.
// jhrg 8/26/97

// $Log: DODSFilter.cc,v $
// Revision 1.11  1999/05/19 23:56:57  jimg
// Changed the support address from @dods to @unidata
//
// Revision 1.10  1999/05/05 00:36:36  jimg
// Added the -V option. -v now is used to pass the version information from the
// CGI to the C++ software; -V triggers output of the version message. This
// allows the DODSFilter class to pass information about the server's version to
// the core software.
// All set_mime_*() functions are now passes the CGI version information so that
// all MIME headers contain information about the server's version.
// Added the get_cgi_version() member function so that clients of DODSFilter can
// find out the version number.
//
// Revision 1.9  1999/05/04 19:47:21  jimg
// Fixed copyright statements. Removed more of the GNU classes.
//
// Revision 1.8  1999/04/29 02:29:28  jimg
// Merge of no-gnu branch
//
// Revision 1.7  1999/02/22 22:59:07  jimg
// Added the get_accept_types() accessor.
// Changed the ctor so that the -t option is recognized.
//
// Revision 1.6  1998/12/16 19:10:53  jimg
// Added support for XDODS-Server MIME header. This fixes a problem where our
// use of Server clashed with Java.
//
// Revision 1.5  1998/11/10 01:04:42  jimg
// Added `ends' to strings made with ostrstream (fixes a bug found with
// purify).
// Added catch for throws from within the CE evaluation functions.
//
// Revision 1.4.2.2  1999/02/05 09:32:34  jimg
// Fixed __unused__ so that it not longer clashes with Red Hat 5.2 inlined
// math code.
//
// Revision 1.4.2.1  1999/02/02 21:56:57  jimg
// String to string version
//
// Revision 1.4  1998/08/06 16:12:30  jimg
// Added cache dir methods and stuff to ctor (from jeh)
//
// Revision 1.3  1998/03/19 23:34:21  jimg
// Fixed calls to set_mime_*().
// Removed the compression code (it is now in DDS::send().
// Removed old code (that was surrounded by #if 0 ... #endif).
//
// Revision 1.2  1998/02/11 22:00:46  jimg
// Added call to util.cc:deflate_exists() to send_data(). This means that
// send_data() will only try to start the compressor if an executable copy of
// deflate can be found. If, for any reason a copy of deflate cannot be found
// data is sent without trying to compress it.
//
// Revision 1.1  1997/08/28 20:39:02  jimg
// Created
//

#ifdef __GNUG__
#pragma "implemenation"
#endif

#include "config_dap.h"

static char rcsid[] not_used = {"$Id: DODSFilter.cc,v 1.11 1999/05/19 23:56:57 jimg Exp $"};

#include <iostream>
#ifdef __GNUG__
#include <strstream>
#else
#include <sstream>
#endif
#include <string>
#include <GetOpt.h>

#include "DAS.h"
#include "DDS.h"
#include "debug.h"
#include "cgi_util.h"
#include "DODSFilter.h"

DODSFilter::DODSFilter(int argc, char *argv[]) : comp(false), ver(false),
    bad_options(false), dataset(""), ce(""), cgi_ver(""),
    anc_dir(""), anc_file(""), cache_dir(""), accept_types("All")
{
    program_name = argv[0];

    int option_char;
    GetOpt getopt (argc, argv, "ce:v:Vd:f:r:t:");

    while ((option_char = getopt()) != EOF)
	switch (option_char) {
	  case 'c': comp = true; break;
	  case 'e': ce = getopt.optarg; break;
	  case 'v': cgi_ver = getopt.optarg; break;
	  case 'V': ver = true; break;
	  case 'd': anc_dir = getopt.optarg; break;
	  case 'f': anc_file = getopt.optarg; break;
	  case 'r': cache_dir = getopt.optarg; break;
	  case 't': accept_types = getopt.optarg; break;
	  default: bad_options = true; break;
	}

    int next_arg = getopt.optind;
    if(next_arg < argc)
	dataset = argv[next_arg];
    else
	bad_options = true;
}

DODSFilter::~DODSFilter()
{
}

bool
DODSFilter::OK()
{

    return !bad_options;
}

bool
DODSFilter::version()
{
    return ver;
}

string
DODSFilter::get_cgi_version()
{
    return cgi_ver;
}

string
DODSFilter::get_ce()
{
    return ce;
}

string
DODSFilter::get_dataset_name()
{
    return dataset;
}

string
DODSFilter::get_dataset_version()
{
    return "";
}

string
DODSFilter::get_cache_dir()
{
  return cache_dir;
}

string
DODSFilter::get_accept_types()
{
    return accept_types;
}

bool
DODSFilter::read_ancillary_das(DAS &das)
{
    string name = find_ancillary_file(dataset, "das", anc_dir, anc_file);
    FILE *in = fopen(name.c_str(), "r");

    if (in) {
	int status = das.parse(in);
	fclose(in);

	if(!status) {
	    string msg = "Parse error in external file " + dataset + ".das";

	    // server error message
	    ErrMsgT(msg);

	    // client error message
	    set_mime_text(cout, dods_error, cgi_ver);
	    Error e(malformed_expr, msg);
	    e.print(cout);

	    return false;
	}
    }

    return true;
}

bool
DODSFilter::read_ancillary_dds(DDS &dds)
{
    string name = find_ancillary_file(dataset, "dds", anc_dir, anc_file);
    FILE *in = fopen(name.c_str(), "r");

    if (in) {
	int status = dds.parse(in);
	fclose(in);

	if(!status) {
	    string msg = "Parse error in external file " + dataset + ".dds";

	    // server error message
	    ErrMsgT(msg);

	    // client error message
	    set_mime_text(cout, dods_error, cgi_ver);
	    Error e(malformed_expr, msg);
	    e.print(cout);

	    return false;
	}
    }

    return true;
}

static const char *emessage = \
"DODS internal server error. Please report this to the dataset maintainer, \
or to support@unidata.ucar.edu.";

void
DODSFilter::print_usage()
{
    // Write a message to the WWW server error log file.
    ostrstream oss;
    oss << "Usage: " << program_name
	<< " [-c] [-v <cgi version>] [-e <ce>]"
	<< " [-d <ancillary file directory>] [-f <ancillary file name>]"
	<< " <dataset>" << ends;
    ErrMsgT(oss.str());
    oss.rdbuf()->freeze(0);

    // Build an error object to return to the user.
    Error e(unknown_error, emessage);
    set_mime_text(cout, dods_error, cgi_ver);
    e.print(cout);
}

void
DODSFilter::send_version_info()
{
    cout << "HTTP/1.0 200 OK" << endl
	 << "XDODS-Server: " << cgi_ver << endl
	 << "Content-Type: text/plain" << endl
	 << endl;

    cout << "Core version: " << DVR << endl;

    if (cgi_ver != "")
	cout << "Server vision: " << cgi_ver << endl;

    string v = get_dataset_version();
    if (v != "")
	cout << "Dataset version: " << v << endl;
}

bool
DODSFilter::send_das(DAS &das)
{
    set_mime_text(cout, dods_das, cgi_ver);
    das.print(cout);

    return true;
}

bool
DODSFilter::send_dds(DDS &dds, bool constrained)
{
    if (constrained) {
	if (!dds.parse_constraint(ce, cout, true)) {
	    string m = program_name + ": parse error in constraint: "
		+  ce;
	    ErrMsgT(m);

	    set_mime_text(cout, dods_error, cgi_ver);
	    Error e(unknown_error, m);
	    e.print(cout);

	    return false;
	}
	set_mime_text(cout, dods_dds, cgi_ver);
	dds.print_constrained(cout);  // send constrained DDS
    }
    else {
	set_mime_text(cout, dods_dds, cgi_ver);
	dds.print(cout);
    }

    return true;
}

bool
DODSFilter::send_data(DDS &dds, FILE *data_stream)
{
    bool compress = comp && deflate_exists();

    // This catch is a quick & dirty hack for exceptions thrown by the new
    // (11/6/98) projection functions in CEs. I might add exceptions to other
    // parts of the CE parser and evaluator. Eventually, the C++ classes
    // should switch to exceptions. 11/6/98 jhrg
    try {
	if (!dds.send(dataset, ce, data_stream, compress, cgi_ver)) {
	    ErrMsgT((compress) ? "Could not send compressed data" :
		    "Could not send data");
	    return false;
	}
    }
    catch (Error &e) {
	set_mime_text(cout, dods_error, cgi_ver);
	e.print(cout);

	return false;
    }

    return true;
}

<commit_msg>Added instrumentation to the ctor. This simplifies debugging the interaction between the filter programs and the perl script.<commit_after>
// (c) COPYRIGHT URI/MIT 1997-1999
// Please read the full copyright statement in the file COPYRIGHT.
//
// Authors:
//      jhrg,jimg       James Gallagher (jgallagher@gso.uri.edu)

// Implementation of the DODSFilter class. This class is used to build dods
// filter programs which, along with a CGI program, comprise DODS servers.
// jhrg 8/26/97

// $Log: DODSFilter.cc,v $
// Revision 1.12  1999/05/21 17:15:46  jimg
// Added instrumentation to the ctor. This simplifies debugging the interaction
// between the filter programs and the perl script.
//
// Revision 1.11  1999/05/19 23:56:57  jimg
// Changed the support address from @dods to @unidata
//
// Revision 1.10  1999/05/05 00:36:36  jimg
// Added the -V option. -v now is used to pass the version information from the
// CGI to the C++ software; -V triggers output of the version message. This
// allows the DODSFilter class to pass information about the server's version to
// the core software.
// All set_mime_*() functions are now passes the CGI version information so that
// all MIME headers contain information about the server's version.
// Added the get_cgi_version() member function so that clients of DODSFilter can
// find out the version number.
//
// Revision 1.9  1999/05/04 19:47:21  jimg
// Fixed copyright statements. Removed more of the GNU classes.
//
// Revision 1.8  1999/04/29 02:29:28  jimg
// Merge of no-gnu branch
//
// Revision 1.7  1999/02/22 22:59:07  jimg
// Added the get_accept_types() accessor.
// Changed the ctor so that the -t option is recognized.
//
// Revision 1.6  1998/12/16 19:10:53  jimg
// Added support for XDODS-Server MIME header. This fixes a problem where our
// use of Server clashed with Java.
//
// Revision 1.5  1998/11/10 01:04:42  jimg
// Added `ends' to strings made with ostrstream (fixes a bug found with
// purify).
// Added catch for throws from within the CE evaluation functions.
//
// Revision 1.4.2.2  1999/02/05 09:32:34  jimg
// Fixed __unused__ so that it not longer clashes with Red Hat 5.2 inlined
// math code.
//
// Revision 1.4.2.1  1999/02/02 21:56:57  jimg
// String to string version
//
// Revision 1.4  1998/08/06 16:12:30  jimg
// Added cache dir methods and stuff to ctor (from jeh)
//
// Revision 1.3  1998/03/19 23:34:21  jimg
// Fixed calls to set_mime_*().
// Removed the compression code (it is now in DDS::send().
// Removed old code (that was surrounded by #if 0 ... #endif).
//
// Revision 1.2  1998/02/11 22:00:46  jimg
// Added call to util.cc:deflate_exists() to send_data(). This means that
// send_data() will only try to start the compressor if an executable copy of
// deflate can be found. If, for any reason a copy of deflate cannot be found
// data is sent without trying to compress it.
//
// Revision 1.1  1997/08/28 20:39:02  jimg
// Created
//

#ifdef __GNUG__
#pragma "implemenation"
#endif

#include "config_dap.h"

static char rcsid[] not_used = {"$Id: DODSFilter.cc,v 1.12 1999/05/21 17:15:46 jimg Exp $"};

#include <iostream>
#ifdef __GNUG__
#include <strstream>
#else
#include <sstream>
#endif
#include <string>
#include <GetOpt.h>

#include "DAS.h"
#include "DDS.h"
#include "debug.h"
#include "cgi_util.h"
#include "DODSFilter.h"

DODSFilter::DODSFilter(int argc, char *argv[]) : comp(false), ver(false),
    bad_options(false), dataset(""), ce(""), cgi_ver(""),
    anc_dir(""), anc_file(""), cache_dir(""), accept_types("All")
{
    program_name = argv[0];

    int option_char;
    GetOpt getopt (argc, argv, "ce:v:Vd:f:r:t:");

    while ((option_char = getopt()) != EOF)
	switch (option_char) {
	  case 'c': comp = true; break;
	  case 'e': ce = getopt.optarg; break;
	  case 'v': cgi_ver = getopt.optarg; break;
	  case 'V': ver = true; break;
	  case 'd': anc_dir = getopt.optarg; break;
	  case 'f': anc_file = getopt.optarg; break;
	  case 'r': cache_dir = getopt.optarg; break;
	  case 't': accept_types = getopt.optarg; break;
	  default: bad_options = true; break;
	}

    int next_arg = getopt.optind;
    if(next_arg < argc)
	dataset = argv[next_arg];
    else
	bad_options = true;

    DBG(cerr << "comp: " << comp << endl);
    DBG(cerr << "ce: " << ce << endl);
    DBG(cerr << "cgi_ver: " << cgi_ver << endl);
    DBG(cerr << "ver: " << ver << endl);
    DBG(cerr << "anc_dir: " << anc_dir << endl);
    DBG(cerr << "anc_file: " << anc_file << endl);
    DBG(cerr << "cache_dir: " << cache_dir << endl);
    DBG(cerr << "accept_types: " << accept_types << endl);
}

DODSFilter::~DODSFilter()
{
}

bool
DODSFilter::OK()
{

    return !bad_options;
}

bool
DODSFilter::version()
{
    return ver;
}

string
DODSFilter::get_cgi_version()
{
    return cgi_ver;
}

string
DODSFilter::get_ce()
{
    return ce;
}

string
DODSFilter::get_dataset_name()
{
    return dataset;
}

string
DODSFilter::get_dataset_version()
{
    return "";
}

string
DODSFilter::get_cache_dir()
{
  return cache_dir;
}

string
DODSFilter::get_accept_types()
{
    return accept_types;
}

bool
DODSFilter::read_ancillary_das(DAS &das)
{
    string name = find_ancillary_file(dataset, "das", anc_dir, anc_file);
    FILE *in = fopen(name.c_str(), "r");

    if (in) {
	int status = das.parse(in);
	fclose(in);

	if(!status) {
	    string msg = "Parse error in external file " + dataset + ".das";

	    // server error message
	    ErrMsgT(msg);

	    // client error message
	    set_mime_text(cout, dods_error, cgi_ver);
	    Error e(malformed_expr, msg);
	    e.print(cout);

	    return false;
	}
    }

    return true;
}

bool
DODSFilter::read_ancillary_dds(DDS &dds)
{
    string name = find_ancillary_file(dataset, "dds", anc_dir, anc_file);
    FILE *in = fopen(name.c_str(), "r");

    if (in) {
	int status = dds.parse(in);
	fclose(in);

	if(!status) {
	    string msg = "Parse error in external file " + dataset + ".dds";

	    // server error message
	    ErrMsgT(msg);

	    // client error message
	    set_mime_text(cout, dods_error, cgi_ver);
	    Error e(malformed_expr, msg);
	    e.print(cout);

	    return false;
	}
    }

    return true;
}

static const char *emessage = \
"DODS internal server error. Please report this to the dataset maintainer, \
or to support@unidata.ucar.edu.";

void
DODSFilter::print_usage()
{
    // Write a message to the WWW server error log file.
    ostrstream oss;
    oss << "Usage: " << program_name
	<< " [-c] [-v <cgi version>] [-e <ce>]"
	<< " [-d <ancillary file directory>] [-f <ancillary file name>]"
	<< " <dataset>" << ends;
    ErrMsgT(oss.str());
    oss.rdbuf()->freeze(0);

    // Build an error object to return to the user.
    Error e(unknown_error, emessage);
    set_mime_text(cout, dods_error, cgi_ver);
    e.print(cout);
}

void
DODSFilter::send_version_info()
{
    cout << "HTTP/1.0 200 OK" << endl
	 << "XDODS-Server: " << cgi_ver << endl
	 << "Content-Type: text/plain" << endl
	 << endl;

    cout << "Core version: " << DVR << endl;

    if (cgi_ver != "")
	cout << "Server vision: " << cgi_ver << endl;

    string v = get_dataset_version();
    if (v != "")
	cout << "Dataset version: " << v << endl;
}

bool
DODSFilter::send_das(DAS &das)
{
    set_mime_text(cout, dods_das, cgi_ver);
    das.print(cout);

    return true;
}

bool
DODSFilter::send_dds(DDS &dds, bool constrained)
{
    if (constrained) {
	if (!dds.parse_constraint(ce, cout, true)) {
	    string m = program_name + ": parse error in constraint: "
		+  ce;
	    ErrMsgT(m);

	    set_mime_text(cout, dods_error, cgi_ver);
	    Error e(unknown_error, m);
	    e.print(cout);

	    return false;
	}
	set_mime_text(cout, dods_dds, cgi_ver);
	dds.print_constrained(cout);  // send constrained DDS
    }
    else {
	set_mime_text(cout, dods_dds, cgi_ver);
	dds.print(cout);
    }

    return true;
}

bool
DODSFilter::send_data(DDS &dds, FILE *data_stream)
{
    bool compress = comp && deflate_exists();

    // This catch is a quick & dirty hack for exceptions thrown by the new
    // (11/6/98) projection functions in CEs. I might add exceptions to other
    // parts of the CE parser and evaluator. Eventually, the C++ classes
    // should switch to exceptions. 11/6/98 jhrg
    try {
	if (!dds.send(dataset, ce, data_stream, compress, cgi_ver)) {
	    ErrMsgT((compress) ? "Could not send compressed data" :
		    "Could not send data");
	    return false;
	}
    }
    catch (Error &e) {
	set_mime_text(cout, dods_error, cgi_ver);
	e.print(cout);

	return false;
    }

    return true;
}

<|endoftext|>


<commit_before>#include "catch.hpp"

#include <mapnik/parse_transform.hpp>
#include <mapnik/transform_expression.hpp>

namespace {

bool test_transform_expressions(std::string const& in, std::string const& out)
{
    auto tr_list = mapnik::parse_transform(in);
    return mapnik::to_expression_string(*tr_list) == out;
}

}

TEST_CASE("transform-expressions")
{
    // matrix
    CHECK(test_transform_expressions("matrix( 1,2,3,4,5, 6)", "matrix(1, 2, 3, 4, 5, 6)"));
    CHECK(test_transform_expressions("matrix(1 2 3 4 5  6)", "matrix(1, 2, 3, 4, 5, 6)"));
    CHECK(test_transform_expressions("matrix(1,2,3,4,5,4*2-1)", "matrix(1, 2, 3, 4, 5, (4*2-1))"));

    // translate
    CHECK(test_transform_expressions("translate(100)", "translate(100)"));
    CHECK(test_transform_expressions("translate([tx])", "translate([tx])"));
    CHECK(test_transform_expressions("translate(100 200)", "translate(100, 200)"));
    CHECK(test_transform_expressions("translate([tx],[ty])", "translate([tx], [ty])"));
    CHECK(test_transform_expressions("translate([tx],200)", "translate([tx], 200)"));
    CHECK(test_transform_expressions("translate(100,[ty])", "translate(100, [ty])"));

    // scale
    CHECK(test_transform_expressions("scale(1.5)", "scale(1.5)"));
    CHECK(test_transform_expressions("scale([sx])", "scale([sx])"));
    CHECK(test_transform_expressions("scale([sx],1.5)", "scale([sx], 1.5)"));
    CHECK(test_transform_expressions("scale(1.5,[sy])", "scale(1.5, [sy])"));
    CHECK(test_transform_expressions("scale([sx],[sy]/2)", "scale([sx], [sy]/2)"));

    // rotate
    CHECK(test_transform_expressions("rotate([a] -2)", "rotate(([a]-2))"));
    CHECK(test_transform_expressions("rotate([a] -2 -3)", "rotate((([a]-2)-3))"));
    CHECK(test_transform_expressions("rotate([a],-2,-3)", "rotate([a], -2, -3)"));
    CHECK(test_transform_expressions("rotate([a] -2 -3 -4)", "rotate(((([a]-2)-3)-4))"));
    CHECK(test_transform_expressions("rotate([a] -2, 3, 4)", "rotate(([a]-2), 3, 4)"));

    // skewX
    CHECK(test_transform_expressions("skewX(2)", "skewX(2)"));
    CHECK(test_transform_expressions("skewX(2*[x]+[y])", "skewX((2*[x]+[y]))"));

    // skewY
    CHECK(test_transform_expressions("skewY(2)", "skewY(2)"));
    CHECK(test_transform_expressions("skewY(2*[x]+[y])", "skewY((2*[x]+[y]))"));

    // compound
    CHECK(test_transform_expressions("translate([tx]) rotate([a])", "translate([tx]) rotate([a])"));
    CHECK(test_transform_expressions("rotate(30+[a]) scale(2*[sx],[sy])", "rotate((30+[a])) scale(2*[sx], [sy])"));
}
<commit_msg>transform_expressions_test - add global attribute tests ( e.g @value ) ref #3569<commit_after>#include "catch.hpp"

#include <mapnik/parse_transform.hpp>
#include <mapnik/transform_expression.hpp>

namespace {

bool test_transform_expressions(std::string const& in, std::string const& out)
{
    auto tr_list = mapnik::parse_transform(in);
    return mapnik::to_expression_string(*tr_list) == out;
}

}

TEST_CASE("transform-expressions")
{
    // matrix
    CHECK(test_transform_expressions("matrix( 1,2,3,4,5, 6)", "matrix(1, 2, 3, 4, 5, 6)"));
    CHECK(test_transform_expressions("matrix(1 2 3 4 5  6)", "matrix(1, 2, 3, 4, 5, 6)"));
    CHECK(test_transform_expressions("matrix(1,2,3,4,5,4*2-1)", "matrix(1, 2, 3, 4, 5, (4*2-1))"));
    CHECK(test_transform_expressions("matrix(1,2,3,4,5,[value])", "matrix(1, 2, 3, 4, 5, [value])"));
    CHECK(test_transform_expressions("matrix(1,2,@value,4,5,6)", "matrix(1, 2, @value, 4, 5, 6)"));
    CHECK(test_transform_expressions("matrix(1,2,3,4,5,@value)", "matrix(1, 2, 3, 4, 5, @value)"));

    // translate
    CHECK(test_transform_expressions("translate(100)", "translate(100)"));
    CHECK(test_transform_expressions("translate([tx])", "translate([tx])"));
    CHECK(test_transform_expressions("translate(100 200)", "translate(100, 200)"));
    CHECK(test_transform_expressions("translate([tx],[ty])", "translate([tx], [ty])"));
    CHECK(test_transform_expressions("translate([tx],200)", "translate([tx], 200)"));
    CHECK(test_transform_expressions("translate(100,[ty])", "translate(100, [ty])"));

    // scale
    CHECK(test_transform_expressions("scale(1.5)", "scale(1.5)"));
    CHECK(test_transform_expressions("scale([sx])", "scale([sx])"));
    CHECK(test_transform_expressions("scale([sx],1.5)", "scale([sx], 1.5)"));
    CHECK(test_transform_expressions("scale(1.5,[sy])", "scale(1.5, [sy])"));
    CHECK(test_transform_expressions("scale([sx],[sy]/2)", "scale([sx], [sy]/2)"));

    // rotate
    CHECK(test_transform_expressions("rotate([a] -2)", "rotate(([a]-2))"));
    CHECK(test_transform_expressions("rotate([a] -2 -3)", "rotate((([a]-2)-3))"));
    CHECK(test_transform_expressions("rotate([a],-2,-3)", "rotate([a], -2, -3)"));
    CHECK(test_transform_expressions("rotate([a] -2 -3 -4)", "rotate(((([a]-2)-3)-4))"));
    CHECK(test_transform_expressions("rotate([a] -2, 3, 4)", "rotate(([a]-2), 3, 4)"));

    // skewX
    CHECK(test_transform_expressions("skewX(2)", "skewX(2)"));
    CHECK(test_transform_expressions("skewX(2*[x]+[y])", "skewX((2*[x]+[y]))"));

    // skewY
    CHECK(test_transform_expressions("skewY(2)", "skewY(2)"));
    CHECK(test_transform_expressions("skewY(2*[x]+[y])", "skewY((2*[x]+[y]))"));

    // compound
    CHECK(test_transform_expressions("translate([tx]) rotate([a])", "translate([tx]) rotate([a])"));
    CHECK(test_transform_expressions("rotate(30+@value) scale(2*[sx],[sy])", "rotate((30+@value)) scale(2*[sx], [sy])"));
}
<|endoftext|>


<commit_before>//
// OpenFlight loader for OpenSceneGraph
//
//  Copyright (C) 2005-2006  Brede Johansen
//

#include <stdexcept>
#include <osg/Notify>
#include <osg/ProxyNode>
#include <osgDB/FileNameUtils>
#include <osgDB/FileUtils>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgDB/ReentrantMutex>
#include <osgUtil/Optimizer>

#include "Registry.h"
#include "Document.h"
#include "RecordInputStream.h"

#define SERIALIZER() OpenThreads::ScopedLock<osgDB::ReentrantMutex> lock(_serializerMutex)

using namespace flt;
using namespace osg;
using namespace osgDB;

class ReadExternalsVisitor : public osg::NodeVisitor
{
    osg::ref_ptr<ReaderWriter::Options> _options;

public:

    ReadExternalsVisitor(ReaderWriter::Options* options) :
        osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
        _options(options)
    {
    }

    virtual ~ReadExternalsVisitor() {}

    virtual void apply(ProxyNode& node)
    {
        // Transfer ownership of pools.
        _options->setUserData( node.getUserData() );
        node.setUserData(NULL);

        for (unsigned int pos=0; pos<node.getNumFileNames(); pos++)
        {
            std::string filename = node.getFileName(pos);

            // read external
            osg::Node* external = osgDB::readNodeFile(filename,_options.get());
            if (external)
                node.addChild(external);
        }
    }
};

class FLTReaderWriter : public ReaderWriter
{
    public:
        virtual const char* className() const { return "FLT Reader/Writer"; }

        virtual bool acceptsExtension(const std::string& extension) const
        {
            return equalCaseInsensitive(extension,"flt");
        }

        virtual ReadResult readObject(const std::string& file, const Options* options) const
        {
            return readNode(file, options);
        }

        virtual ReadResult readNode(const std::string& file, const Options* options) const
        {
            SERIALIZER();

            std::string ext = osgDB::getLowerCaseFileExtension(file);
            if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;

            std::string fileName = osgDB::findDataFile(file, options);
            if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;

            // in local cache?
            {
                osg::Node* node = flt::Registry::instance()->getFromLocalCache(fileName);
                if (node)
                    return ReadResult(node, ReaderWriter::ReadResult::FILE_LOADED_FROM_CACHE);
            }

            // setting up the database path so that internally referenced file are searched for on relative paths.
            osg::ref_ptr<Options> local_opt = options ? static_cast<Options*>(options->clone(osg::CopyOp::SHALLOW_COPY)) : new Options;
            local_opt->setDatabasePath(osgDB::getFilePath(fileName));

            ReadResult rr;

            // read file
            {
                std::ifstream istream;
                istream.imbue(std::locale::classic());
                istream.open(fileName.c_str(), std::ios::in | std::ios::binary);

                if (istream)
                {
                    rr = readNode(istream,local_opt.get());
                }
            }

            static int nestedExternalsLevel = 0;
            if (rr.success())
            {
                // add to local cache.
                flt::Registry::instance()->addToLocalCache(fileName,rr.getNode());

                bool keepExternalReferences = false;
                if (options)
                    keepExternalReferences = (options->getOptionString().find("keepExternalReferences")!=std::string::npos);

                if ( !keepExternalReferences )
                {
                    osg::notify(osg::DEBUG_INFO) << "keepExternalReferences not found, so externals will be re-readed"<<std::endl;
                    // read externals.
                    if (rr.getNode())
                    {
                        nestedExternalsLevel++;
                        ReadExternalsVisitor visitor(local_opt.get());
                        rr.getNode()->accept(visitor);
                        nestedExternalsLevel--;
                    }
                }
                else
                {
                    osg::notify(osg::DEBUG_INFO) << "keepExternalReferences found, so externals will be left as ProxyNodes"<<std::endl;
                }
            }

            // clear local cache.
            if (nestedExternalsLevel==0)
                flt::Registry::instance()->clearLocalCache();

            return rr;
        }

        virtual ReadResult readObject(std::istream& fin, const Options* options) const
        {
            return readNode(fin, options);
        }

        virtual ReadResult readNode(std::istream& fin, const Options* options) const
        {
            Document document;
            document.setOptions(options);

            // option string and parent pools
            if (options)
            {
                const char readerMsg[] = "flt reader option: ";

                document.setReplaceClampWithClampToEdge((options->getOptionString().find("clampToEdge")!=std::string::npos));
                osg::notify(osg::DEBUG_INFO) << readerMsg << "clampToEdge=" << document.getReplaceClampWithClampToEdge() << std::endl;

                document.setKeepExternalReferences((options->getOptionString().find("keepExternalReferences")!=std::string::npos));
                osg::notify(osg::DEBUG_INFO) << readerMsg << "keepExternalReferences=" << document.getKeepExternalReferences() << std::endl;

                document.setPreserveFace((options->getOptionString().find("preserveFace")!=std::string::npos));
                osg::notify(osg::DEBUG_INFO) << readerMsg << "preserveFace=" << document.getPreserveFace() << std::endl;

                document.setPreserveObject((options->getOptionString().find("preserveObject")!=std::string::npos));
                osg::notify(osg::DEBUG_INFO) << readerMsg << "preserveObject=" << document.getPreserveObject() << std::endl;

                document.setDefaultDOFAnimationState((options->getOptionString().find("dofAnimation")!=std::string::npos));
                osg::notify(osg::DEBUG_INFO) << readerMsg << "dofAnimation=" << document.getDefaultDOFAnimationState() << std::endl;

                document.setUseBillboardCenter((options->getOptionString().find("billboardCenter")!=std::string::npos));
                osg::notify(osg::DEBUG_INFO) << readerMsg << "billboardCenter=" << document.getUseBillboardCenter() << std::endl;

                document.setUseTextureAlphaForTransparancyBinning(options->getOptionString().find("noTextureAlphaForTransparancyBinning")==std::string::npos);
                osg::notify(osg::DEBUG_INFO) << readerMsg << "noTextureAlphaForTransparancyBinning=" << !document.getUseTextureAlphaForTransparancyBinning() << std::endl;

                document.setDoUnitsConversion((options->getOptionString().find("noUnitsConversion")==std::string::npos)); // default to true, unless noUnitsConversion is specified.
                osg::notify(osg::DEBUG_INFO) << readerMsg << "noUnitsConversion=" << !document.getDoUnitsConversion() << std::endl;

                if (document.getDoUnitsConversion())
                {
                    if (options->getOptionString().find("convertToFeet")!=std::string::npos)
                        document.setDesiredUnits(FEET);
                    else if (options->getOptionString().find("convertToInches")!=std::string::npos)
                        document.setDesiredUnits(INCHES);
                    else if (options->getOptionString().find("convertToMeters")!=std::string::npos)
                        document.setDesiredUnits(METERS);
                    else if (options->getOptionString().find("convertToKilometers")!=std::string::npos)
                        document.setDesiredUnits(KILOMETERS);
                    else if (options->getOptionString().find("convertToNauticalMiles")!=std::string::npos)
                        document.setDesiredUnits(NAUTICAL_MILES);
                }

                const ParentPools* pools = dynamic_cast<const ParentPools*>( options->getUserData() );
                if (pools)
                {
                    // This file is an external reference. The individual pools will
                    // be non-NULL if the parent is overriding the ext ref model's pools.
                    if (pools->getColorPool())
                        document.setColorPool( pools->getColorPool(), true );
                    if (pools->getTexturePool())
                        document.setTexturePool( pools->getTexturePool(), true );
                    if (pools->getMaterialPool())
                        document.setMaterialPool( pools->getMaterialPool(), true );
                    if (pools->getLPAppearancePool())
                        document.setLightPointAppearancePool( pools->getLPAppearancePool(), true );
                    if (pools->getShaderPool())
                        document.setShaderPool( pools->getShaderPool(), true );
                }
            }

            {
                // read records
                flt::RecordInputStream recordStream(fin.rdbuf());
                while (recordStream.good() && !document.done())
                {
                    recordStream.readRecord(document);
                }
            }

            if (!document.getHeaderNode())
                return ReadResult::ERROR_IN_READING_FILE;

            if (!document.getPreserveFace())
            {
                osgUtil::Optimizer optimizer;
                optimizer.optimize(document.getHeaderNode(),  osgUtil::Optimizer::SHARE_DUPLICATE_STATE | osgUtil::Optimizer::MERGE_GEOMETRY | osgUtil::Optimizer::MERGE_GEODES | osgUtil::Optimizer::TESSELATE_GEOMETRY );
            }

            return document.getHeaderNode();
        }

        virtual WriteResult writeObject(const Object& object,const std::string& fileName, const osgDB::ReaderWriter::Options* options) const
        {
            const Node* node = dynamic_cast<const Node*>(&object);
            if (node) return writeNode( *node, fileName, options );
            return WriteResult::FILE_NOT_HANDLED;
        }

        virtual WriteResult writeNode(const Node& /*node*/,const std::string& /*fileName*/, const osgDB::ReaderWriter::Options* /*options*/) const
        {
            return WriteResult::FILE_NOT_HANDLED;
        }

        virtual WriteResult writeObject(const Object& object,std::ostream& fout, const osgDB::ReaderWriter::Options* options) const
        {
            const Node* node = dynamic_cast<const Node*>(&object);
            if (node) return writeNode( *node, fout, options );
            return WriteResult::FILE_NOT_HANDLED;
        }

        virtual WriteResult writeNode(const Node& /*node*/,std::ostream& /*fout*/, const osgDB::ReaderWriter::Options* /*options*/) const
        {
            return WriteResult::FILE_NOT_HANDLED;
        }

    protected:

        mutable osgDB::ReentrantMutex _serializerMutex;
};

// now register with Registry to instantiate the above
// reader/writer.
RegisterReaderWriterProxy<FLTReaderWriter> g_FLTReaderWriterProxy;

<commit_msg>From Brede Johansen, "New option "cloneExternalReferences" for OpenFlight plugin"<commit_after>//
// OpenFlight loader for OpenSceneGraph
//
//  Copyright (C) 2005-2006  Brede Johansen
//

#include <stdexcept>
#include <osg/Notify>
#include <osg/ProxyNode>
#include <osgDB/FileNameUtils>
#include <osgDB/FileUtils>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgDB/ReentrantMutex>
#include <osgUtil/Optimizer>

#include "Registry.h"
#include "Document.h"
#include "RecordInputStream.h"

#define SERIALIZER() OpenThreads::ScopedLock<osgDB::ReentrantMutex> lock(_serializerMutex)

using namespace flt;
using namespace osg;
using namespace osgDB;

class ReadExternalsVisitor : public osg::NodeVisitor
{
    bool _cloneExternalReferences;
    osg::ref_ptr<ReaderWriter::Options> _options;

public:

    ReadExternalsVisitor(ReaderWriter::Options* options) :
        osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
        _options(options),
        _cloneExternalReferences(false)
    {
        if (options)
            _cloneExternalReferences = (options->getOptionString().find("cloneExternalReferences")!=std::string::npos);
    }

    virtual ~ReadExternalsVisitor() {}

    virtual void apply(ProxyNode& node)
    {
        // Transfer ownership of pools.
        _options->setUserData( node.getUserData() );
        node.setUserData(NULL);

        for (unsigned int pos=0; pos<node.getNumFileNames(); pos++)
        {
            std::string filename = node.getFileName(pos);

            // read external
            osg::ref_ptr<osg::Node> external = osgDB::readNodeFile(filename,_options.get());
            if (external.valid())
            {
                if (_cloneExternalReferences)
                    external = dynamic_cast<osg::Node*>(external->clone(osg::CopyOp(osg::CopyOp::DEEP_COPY_NODES)));

                node.addChild(external.get());
            }
        }
    }
};

class FLTReaderWriter : public ReaderWriter
{
    public:
        virtual const char* className() const { return "FLT Reader/Writer"; }

        virtual bool acceptsExtension(const std::string& extension) const
        {
            return equalCaseInsensitive(extension,"flt");
        }

        virtual ReadResult readObject(const std::string& file, const Options* options) const
        {
            return readNode(file, options);
        }

        virtual ReadResult readNode(const std::string& file, const Options* options) const
        {
            SERIALIZER();

            std::string ext = osgDB::getLowerCaseFileExtension(file);
            if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;

            std::string fileName = osgDB::findDataFile(file, options);
            if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;

            // in local cache?
            {
                osg::Node* node = flt::Registry::instance()->getFromLocalCache(fileName);
                if (node)
                    return ReadResult(node, ReaderWriter::ReadResult::FILE_LOADED_FROM_CACHE);
            }

            // setting up the database path so that internally referenced file are searched for on relative paths.
            osg::ref_ptr<Options> local_opt = options ? static_cast<Options*>(options->clone(osg::CopyOp::SHALLOW_COPY)) : new Options;
            local_opt->setDatabasePath(osgDB::getFilePath(fileName));

            ReadResult rr;

            // read file
            {
                std::ifstream istream;
                istream.imbue(std::locale::classic());
                istream.open(fileName.c_str(), std::ios::in | std::ios::binary);

                if (istream)
                {
                    rr = readNode(istream,local_opt.get());
                }
            }

            static int nestedExternalsLevel = 0;
            if (rr.success())
            {
                // add to local cache.
                flt::Registry::instance()->addToLocalCache(fileName,rr.getNode());

                bool keepExternalReferences = false;
                if (options)
                    keepExternalReferences = (options->getOptionString().find("keepExternalReferences")!=std::string::npos);

                if ( !keepExternalReferences )
                {
                    osg::notify(osg::DEBUG_INFO) << "keepExternalReferences not found, so externals will be re-readed"<<std::endl;
                    // read externals.
                    if (rr.getNode())
                    {
                        nestedExternalsLevel++;
                        ReadExternalsVisitor visitor(local_opt.get());
                        rr.getNode()->accept(visitor);
                        nestedExternalsLevel--;
                    }
                }
                else
                {
                    osg::notify(osg::DEBUG_INFO) << "keepExternalReferences found, so externals will be left as ProxyNodes"<<std::endl;
                }
            }

            // clear local cache.
            if (nestedExternalsLevel==0)
                flt::Registry::instance()->clearLocalCache();

            return rr;
        }

        virtual ReadResult readObject(std::istream& fin, const Options* options) const
        {
            return readNode(fin, options);
        }

        virtual ReadResult readNode(std::istream& fin, const Options* options) const
        {
            Document document;
            document.setOptions(options);

            // option string and parent pools
            if (options)
            {
                const char readerMsg[] = "flt reader option: ";

                document.setReplaceClampWithClampToEdge((options->getOptionString().find("clampToEdge")!=std::string::npos));
                osg::notify(osg::DEBUG_INFO) << readerMsg << "clampToEdge=" << document.getReplaceClampWithClampToEdge() << std::endl;

                document.setKeepExternalReferences((options->getOptionString().find("keepExternalReferences")!=std::string::npos));
                osg::notify(osg::DEBUG_INFO) << readerMsg << "keepExternalReferences=" << document.getKeepExternalReferences() << std::endl;

                document.setPreserveFace((options->getOptionString().find("preserveFace")!=std::string::npos));
                osg::notify(osg::DEBUG_INFO) << readerMsg << "preserveFace=" << document.getPreserveFace() << std::endl;

                document.setPreserveObject((options->getOptionString().find("preserveObject")!=std::string::npos));
                osg::notify(osg::DEBUG_INFO) << readerMsg << "preserveObject=" << document.getPreserveObject() << std::endl;

                document.setDefaultDOFAnimationState((options->getOptionString().find("dofAnimation")!=std::string::npos));
                osg::notify(osg::DEBUG_INFO) << readerMsg << "dofAnimation=" << document.getDefaultDOFAnimationState() << std::endl;

                document.setUseBillboardCenter((options->getOptionString().find("billboardCenter")!=std::string::npos));
                osg::notify(osg::DEBUG_INFO) << readerMsg << "billboardCenter=" << document.getUseBillboardCenter() << std::endl;

                document.setUseTextureAlphaForTransparancyBinning(options->getOptionString().find("noTextureAlphaForTransparancyBinning")==std::string::npos);
                osg::notify(osg::DEBUG_INFO) << readerMsg << "noTextureAlphaForTransparancyBinning=" << !document.getUseTextureAlphaForTransparancyBinning() << std::endl;

                document.setDoUnitsConversion((options->getOptionString().find("noUnitsConversion")==std::string::npos)); // default to true, unless noUnitsConversion is specified.
                osg::notify(osg::DEBUG_INFO) << readerMsg << "noUnitsConversion=" << !document.getDoUnitsConversion() << std::endl;

                if (document.getDoUnitsConversion())
                {
                    if (options->getOptionString().find("convertToFeet")!=std::string::npos)
                        document.setDesiredUnits(FEET);
                    else if (options->getOptionString().find("convertToInches")!=std::string::npos)
                        document.setDesiredUnits(INCHES);
                    else if (options->getOptionString().find("convertToMeters")!=std::string::npos)
                        document.setDesiredUnits(METERS);
                    else if (options->getOptionString().find("convertToKilometers")!=std::string::npos)
                        document.setDesiredUnits(KILOMETERS);
                    else if (options->getOptionString().find("convertToNauticalMiles")!=std::string::npos)
                        document.setDesiredUnits(NAUTICAL_MILES);
                }

                const ParentPools* pools = dynamic_cast<const ParentPools*>( options->getUserData() );
                if (pools)
                {
                    // This file is an external reference. The individual pools will
                    // be non-NULL if the parent is overriding the ext ref model's pools.
                    if (pools->getColorPool())
                        document.setColorPool( pools->getColorPool(), true );
                    if (pools->getTexturePool())
                        document.setTexturePool( pools->getTexturePool(), true );
                    if (pools->getMaterialPool())
                        document.setMaterialPool( pools->getMaterialPool(), true );
                    if (pools->getLPAppearancePool())
                        document.setLightPointAppearancePool( pools->getLPAppearancePool(), true );
                    if (pools->getShaderPool())
                        document.setShaderPool( pools->getShaderPool(), true );
                }
            }

            {
                // read records
                flt::RecordInputStream recordStream(fin.rdbuf());
                while (recordStream.good() && !document.done())
                {
                    recordStream.readRecord(document);
                }
            }

            if (!document.getHeaderNode())
                return ReadResult::ERROR_IN_READING_FILE;

            if (!document.getPreserveFace())
            {
                osgUtil::Optimizer optimizer;
                optimizer.optimize(document.getHeaderNode(),  osgUtil::Optimizer::SHARE_DUPLICATE_STATE | osgUtil::Optimizer::MERGE_GEOMETRY | osgUtil::Optimizer::MERGE_GEODES | osgUtil::Optimizer::TESSELATE_GEOMETRY );
            }

            return document.getHeaderNode();
        }

        virtual WriteResult writeObject(const Object& object,const std::string& fileName, const osgDB::ReaderWriter::Options* options) const
        {
            const Node* node = dynamic_cast<const Node*>(&object);
            if (node) return writeNode( *node, fileName, options );
            return WriteResult::FILE_NOT_HANDLED;
        }

        virtual WriteResult writeNode(const Node& /*node*/,const std::string& /*fileName*/, const osgDB::ReaderWriter::Options* /*options*/) const
        {
            return WriteResult::FILE_NOT_HANDLED;
        }

        virtual WriteResult writeObject(const Object& object,std::ostream& fout, const osgDB::ReaderWriter::Options* options) const
        {
            const Node* node = dynamic_cast<const Node*>(&object);
            if (node) return writeNode( *node, fout, options );
            return WriteResult::FILE_NOT_HANDLED;
        }

        virtual WriteResult writeNode(const Node& /*node*/,std::ostream& /*fout*/, const osgDB::ReaderWriter::Options* /*options*/) const
        {
            return WriteResult::FILE_NOT_HANDLED;
        }

    protected:

        mutable osgDB::ReentrantMutex _serializerMutex;
};

// now register with Registry to instantiate the above
// reader/writer.
RegisterReaderWriterProxy<FLTReaderWriter> g_FLTReaderWriterProxy;

<|endoftext|>


<commit_before>/* This file is part of the KDE libraries
    Copyright (C) 2004 Antonio Larrosa <larrosa@kde.org

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.
*/

#include "kpixmapregionselectorwidget.h"
#include <qpainter.h>
#include <qcolor.h>
#include <qimage.h>
#include <qlayout.h>
#include <kimageeffect.h>
#include <kdebug.h>
#include <stdlib.h>

using namespace KPIM;

KPixmapRegionSelectorWidget::KPixmapRegionSelectorWidget( QWidget *parent,
      const char *name) : QWidget( parent, name)
{
   QHBoxLayout * hboxLayout=new QHBoxLayout( this );

   hboxLayout->addStretch();
   QVBoxLayout * vboxLayout=new QVBoxLayout( this );

   vboxLayout->addStretch();
   m_label = new QLabel(this, "pixmapHolder");
   m_label->setBackgroundMode( Qt::NoBackground );
   m_label->installEventFilter( this );

   vboxLayout->addWidget(m_label);
   vboxLayout->addStretch();

   hboxLayout->addLayout(vboxLayout);
   hboxLayout->addStretch();

   m_forcedAspectRatio=0;

   m_zoomFactor=1.0;
}

KPixmapRegionSelectorWidget::~KPixmapRegionSelectorWidget()
{
}

void KPixmapRegionSelectorWidget::setPixmap( const QPixmap &pixmap )
{
   m_originalPixmap = pixmap;
   m_unzoomedPixmap = pixmap;
   m_label->setPixmap( pixmap );
   resetSelection();
}

void KPixmapRegionSelectorWidget::resetSelection()
{
   m_selectedRegion = m_originalPixmap.rect();
   updatePixmap();
}

QRect KPixmapRegionSelectorWidget::selectedRegion() const
{
     return m_selectedRegion;
}

void KPixmapRegionSelectorWidget::setSelectedRegion(const QRect &rect)
{
   if (!rect.isValid()) resetSelection();
   else
   {
      m_selectedRegion=rect;
      updatePixmap();

      QRect r=unzoomedSelectedRegion();
   }
}

void KPixmapRegionSelectorWidget::updatePixmap()
{
   if (m_selectedRegion.width()>m_originalPixmap.width()) m_selectedRegion.setWidth( m_originalPixmap.width() );
   if (m_selectedRegion.height()>m_originalPixmap.height()) m_selectedRegion.setHeight( m_originalPixmap.height() );

   QPainter painter;
   if (m_linedPixmap.isNull())
   {
     m_linedPixmap = m_originalPixmap;

     painter.begin(&m_linedPixmap);
     painter.setRasterOp( Qt::XorROP );
     painter.fillRect(0,0,m_linedPixmap.width(), m_linedPixmap.height(),
                  QBrush( QColor(255,255,255), Qt::BDiagPattern) );
     painter.end();

     QImage image=m_linedPixmap.convertToImage();
     image=KImageEffect::fade(image, 0.4, QColor(0,0,0));
     m_linedPixmap.convertFromImage(image);
   }

   QPixmap pixmap = m_linedPixmap;

   painter.begin(&pixmap);
   painter.drawPixmap( m_selectedRegion.topLeft(),
        m_originalPixmap, m_selectedRegion );

   painter.setPen( QColor(255,255,255) );
   painter.setRasterOp( Qt::XorROP );

   painter.drawRect( m_selectedRegion );

   painter.end();

   m_label->setPixmap(pixmap);
}

bool KPixmapRegionSelectorWidget::eventFilter(QObject *obj, QEvent *ev)
{
   if ( ev->type() == QEvent::MouseButtonPress )
   {
      QMouseEvent *mev= (QMouseEvent *)(ev);
      //kdDebug() << QString("click at  %1,%2").arg( mev->x() ).arg( mev->y() ) << endl;

      if ( m_selectedRegion.contains( mev->pos() )
          && m_selectedRegion!=m_originalPixmap.rect() )
         m_state=Moving;
      else
         m_state=Resizing;

      m_tempFirstClick=mev->pos();

      return TRUE;
   }

   if ( ev->type() == QEvent::MouseMove )
   {
      QMouseEvent *mev= (QMouseEvent *)(ev);

      //kdDebug() << QString("move to  %1,%2").arg( mev->x() ).arg( mev->y() ) << endl;

      if ( m_state == Resizing )
      {
         setSelectedRegion (
              calcSelectionRectangle( m_tempFirstClick, mev->pos() ) );
      }
      else if (m_state == Moving )
      {
         int mevx = mev->x();
         int mevy = mev->y();
         bool mouseOutside=false;
         if ( mevx < 0 )
         {
           m_selectedRegion.moveBy(-m_selectedRegion.x(),0);
           mouseOutside=true;
         }
         else if ( mevx > m_originalPixmap.width() )
         {
           m_selectedRegion.moveBy(m_originalPixmap.width()-m_selectedRegion.width()-m_selectedRegion.x(),0);
           mouseOutside=true;
         }
         if ( mevy < 0 )
         {
           m_selectedRegion.moveBy(0,-m_selectedRegion.y());
           mouseOutside=true;
         }
         else if ( mevy > m_originalPixmap.height() )
         {
           m_selectedRegion.moveBy(0,m_originalPixmap.height()-m_selectedRegion.height()-m_selectedRegion.y());
           mouseOutside=true;
         }
         if (mouseOutside) { updatePixmap(); return TRUE; };

         m_selectedRegion.moveBy( mev->x()-m_tempFirstClick.x(),
                                  mev->y()-m_tempFirstClick.y() );

         // Check that the region has not fallen outside the image
         if (m_selectedRegion.x() < 0)
            m_selectedRegion.moveBy(-m_selectedRegion.x(),0);
         else if (m_selectedRegion.right() > m_originalPixmap.width())
            m_selectedRegion.moveBy(-(m_selectedRegion.right()-m_originalPixmap.width()),0);

         if (m_selectedRegion.y() < 0)
            m_selectedRegion.moveBy(0,-m_selectedRegion.y());
         else if (m_selectedRegion.bottom() > m_originalPixmap.height())
            m_selectedRegion.moveBy(0,-(m_selectedRegion.bottom()-m_originalPixmap.height()));

         m_tempFirstClick=mev->pos();
         updatePixmap();
      }
      return TRUE;
   }

   if ( ev->type() == QEvent::MouseButtonRelease )
   {
      QMouseEvent *mev= (QMouseEvent *)(ev);

      if ( m_state == Resizing && mev->pos() == m_tempFirstClick)
         resetSelection();

      m_state=None;

      return TRUE;
   }

   QWidget::eventFilter(obj, ev);
   return FALSE;
}

QRect KPixmapRegionSelectorWidget::calcSelectionRectangle( const QPoint & startPoint, const QPoint & _endPoint )
{
   QPoint endPoint = _endPoint;
   if ( endPoint.x() < 0 ) endPoint.setX(0);
   else if ( endPoint.x() > m_originalPixmap.width() ) endPoint.setX(m_originalPixmap.width());
   if ( endPoint.y() < 0 ) endPoint.setY(0);
   else if ( endPoint.y() > m_originalPixmap.height() ) endPoint.setY(m_originalPixmap.height());
   int w=abs(startPoint.x()-endPoint.x());
   int h=abs(startPoint.y()-endPoint.y());

   if (m_forcedAspectRatio>0)
   {
      double aspectRatio=w/double(h);

      if (aspectRatio>m_forcedAspectRatio)
         h=(int)(w/m_forcedAspectRatio);
      else
         w=(int)(h*m_forcedAspectRatio);
   }

   int x,y;
   if ( startPoint.x() < endPoint.x() )
     x=startPoint.x();
   else
     x=startPoint.x()-w;
   if ( startPoint.y() < endPoint.y() )
     y=startPoint.y();
   else
     y=startPoint.y()-h;

   if (x<0)
   {
      w+=x;
      x=0;
      h=(int)(w/m_forcedAspectRatio);

      if ( startPoint.y() > endPoint.y() )
        y=startPoint.y()-h;
   }
   else if (x+w>m_originalPixmap.width())
   {
      w=m_originalPixmap.width()-x;
      h=(int)(w/m_forcedAspectRatio);

      if ( startPoint.y() > endPoint.y() )
        y=startPoint.y()-h;
   }
   if (y<0)
   {
      h+=y;
      y=0;
      w=(int)(h*m_forcedAspectRatio);

      if ( startPoint.x() > endPoint.x() )
        x=startPoint.x()-w;
   }
   else if (y+h>m_originalPixmap.height())
   {
      h=m_originalPixmap.height()-y;
      w=(int)(h*m_forcedAspectRatio);

      if ( startPoint.x() > endPoint.x() )
        x=startPoint.x()-w;
   }

   return QRect(x,y,w,h);
}

QRect KPixmapRegionSelectorWidget::unzoomedSelectedRegion() const
{
  return QRect((int)(m_selectedRegion.x()/m_zoomFactor),
               (int)(m_selectedRegion.y()/m_zoomFactor),
               (int)(m_selectedRegion.width()/m_zoomFactor),
               (int)(m_selectedRegion.height()/m_zoomFactor));
}

QImage KPixmapRegionSelectorWidget::selectedImage() const
{
   QImage origImage=m_unzoomedPixmap.convertToImage();
   return origImage.copy(unzoomedSelectedRegion());
}

void KPixmapRegionSelectorWidget::setSelectionAspectRatio(int width, int height)
{
   m_forcedAspectRatio=width/double(height);
}

void KPixmapRegionSelectorWidget::setFreeSelectionAspectRatio()
{
   m_forcedAspectRatio=0;
}

void KPixmapRegionSelectorWidget::setMaximumWidgetSize(int width, int height)
{
   m_maxWidth=width;
   m_maxHeight=height;

   m_originalPixmap=m_unzoomedPixmap;
   if (m_selectedRegion == m_originalPixmap.rect()) m_selectedRegion=QRect();

//   kdDebug() << QString(" original Pixmap :") << m_originalPixmap.rect() << endl;
//   kdDebug() << QString(" unzoomed Pixmap : %1 x %2 ").arg(m_unzoomedPixmap.width()).arg(m_unzoomedPixmap.height()) << endl;

   if ( !m_originalPixmap.isNull() &&
       ( m_originalPixmap.width() > m_maxWidth ||
         m_originalPixmap.height() > m_maxHeight ) )
   {
         /* We have to resize the pixmap to get it complete on the screen */
         QImage image=m_originalPixmap.convertToImage();
         m_originalPixmap.convertFromImage( image.smoothScale( width, height, QImage::ScaleMin ) );
         //m_originalPixmap.convertFromImage( KImageEffect::sample( image, width, height ) );
         double oldZoomFactor = m_zoomFactor;
         m_zoomFactor=m_originalPixmap.width()/(double)m_unzoomedPixmap.width();

         if (m_selectedRegion.isValid())
         {
            m_selectedRegion=
                  QRect((int)(m_selectedRegion.x()*m_zoomFactor/oldZoomFactor),
                        (int)(m_selectedRegion.y()*m_zoomFactor/oldZoomFactor),
                        (int)(m_selectedRegion.width()*m_zoomFactor/oldZoomFactor),
                        (int)(m_selectedRegion.height()*m_zoomFactor/oldZoomFactor) );
         }
   }

   if (!m_selectedRegion.isValid()) m_selectedRegion = m_originalPixmap.rect();

   m_linedPixmap=QPixmap();
   updatePixmap();
   resize(m_label->width(), m_label->height());
}

<commit_msg>fix the layout<commit_after>/* This file is part of the KDE libraries
    Copyright (C) 2004 Antonio Larrosa <larrosa@kde.org

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.
*/

#include "kpixmapregionselectorwidget.h"
#include <qpainter.h>
#include <qcolor.h>
#include <qimage.h>
#include <qlayout.h>
#include <kimageeffect.h>
#include <kdebug.h>
#include <stdlib.h>

using namespace KPIM;

KPixmapRegionSelectorWidget::KPixmapRegionSelectorWidget( QWidget *parent,
      const char *name) : QWidget( parent, name)
{
   QHBoxLayout * hboxLayout=new QHBoxLayout( this );

   hboxLayout->addStretch();
   QVBoxLayout * vboxLayout=new QVBoxLayout( hboxLayout );

   vboxLayout->addStretch();
   m_label = new QLabel(this, "pixmapHolder");
   m_label->setBackgroundMode( Qt::NoBackground );
   m_label->installEventFilter( this );

   vboxLayout->addWidget(m_label);
   vboxLayout->addStretch();

   hboxLayout->addStretch();

   m_forcedAspectRatio=0;

   m_zoomFactor=1.0;
}

KPixmapRegionSelectorWidget::~KPixmapRegionSelectorWidget()
{
}

void KPixmapRegionSelectorWidget::setPixmap( const QPixmap &pixmap )
{
   m_originalPixmap = pixmap;
   m_unzoomedPixmap = pixmap;
   m_label->setPixmap( pixmap );
   resetSelection();
}

void KPixmapRegionSelectorWidget::resetSelection()
{
   m_selectedRegion = m_originalPixmap.rect();
   updatePixmap();
}

QRect KPixmapRegionSelectorWidget::selectedRegion() const
{
     return m_selectedRegion;
}

void KPixmapRegionSelectorWidget::setSelectedRegion(const QRect &rect)
{
   if (!rect.isValid()) resetSelection();
   else
   {
      m_selectedRegion=rect;
      updatePixmap();

      QRect r=unzoomedSelectedRegion();
   }
}

void KPixmapRegionSelectorWidget::updatePixmap()
{
   if (m_selectedRegion.width()>m_originalPixmap.width()) m_selectedRegion.setWidth( m_originalPixmap.width() );
   if (m_selectedRegion.height()>m_originalPixmap.height()) m_selectedRegion.setHeight( m_originalPixmap.height() );

   QPainter painter;
   if (m_linedPixmap.isNull())
   {
     m_linedPixmap = m_originalPixmap;

     painter.begin(&m_linedPixmap);
     painter.setRasterOp( Qt::XorROP );
     painter.fillRect(0,0,m_linedPixmap.width(), m_linedPixmap.height(),
                  QBrush( QColor(255,255,255), Qt::BDiagPattern) );
     painter.end();

     QImage image=m_linedPixmap.convertToImage();
     image=KImageEffect::fade(image, 0.4, QColor(0,0,0));
     m_linedPixmap.convertFromImage(image);
   }

   QPixmap pixmap = m_linedPixmap;

   painter.begin(&pixmap);
   painter.drawPixmap( m_selectedRegion.topLeft(),
        m_originalPixmap, m_selectedRegion );

   painter.setPen( QColor(255,255,255) );
   painter.setRasterOp( Qt::XorROP );

   painter.drawRect( m_selectedRegion );

   painter.end();

   m_label->setPixmap(pixmap);
}

bool KPixmapRegionSelectorWidget::eventFilter(QObject *obj, QEvent *ev)
{
   if ( ev->type() == QEvent::MouseButtonPress )
   {
      QMouseEvent *mev= (QMouseEvent *)(ev);
      //kdDebug() << QString("click at  %1,%2").arg( mev->x() ).arg( mev->y() ) << endl;

      if ( m_selectedRegion.contains( mev->pos() )
          && m_selectedRegion!=m_originalPixmap.rect() )
         m_state=Moving;
      else
         m_state=Resizing;

      m_tempFirstClick=mev->pos();

      return TRUE;
   }

   if ( ev->type() == QEvent::MouseMove )
   {
      QMouseEvent *mev= (QMouseEvent *)(ev);

      //kdDebug() << QString("move to  %1,%2").arg( mev->x() ).arg( mev->y() ) << endl;

      if ( m_state == Resizing )
      {
         setSelectedRegion (
              calcSelectionRectangle( m_tempFirstClick, mev->pos() ) );
      }
      else if (m_state == Moving )
      {
         int mevx = mev->x();
         int mevy = mev->y();
         bool mouseOutside=false;
         if ( mevx < 0 )
         {
           m_selectedRegion.moveBy(-m_selectedRegion.x(),0);
           mouseOutside=true;
         }
         else if ( mevx > m_originalPixmap.width() )
         {
           m_selectedRegion.moveBy(m_originalPixmap.width()-m_selectedRegion.width()-m_selectedRegion.x(),0);
           mouseOutside=true;
         }
         if ( mevy < 0 )
         {
           m_selectedRegion.moveBy(0,-m_selectedRegion.y());
           mouseOutside=true;
         }
         else if ( mevy > m_originalPixmap.height() )
         {
           m_selectedRegion.moveBy(0,m_originalPixmap.height()-m_selectedRegion.height()-m_selectedRegion.y());
           mouseOutside=true;
         }
         if (mouseOutside) { updatePixmap(); return TRUE; };

         m_selectedRegion.moveBy( mev->x()-m_tempFirstClick.x(),
                                  mev->y()-m_tempFirstClick.y() );

         // Check that the region has not fallen outside the image
         if (m_selectedRegion.x() < 0)
            m_selectedRegion.moveBy(-m_selectedRegion.x(),0);
         else if (m_selectedRegion.right() > m_originalPixmap.width())
            m_selectedRegion.moveBy(-(m_selectedRegion.right()-m_originalPixmap.width()),0);

         if (m_selectedRegion.y() < 0)
            m_selectedRegion.moveBy(0,-m_selectedRegion.y());
         else if (m_selectedRegion.bottom() > m_originalPixmap.height())
            m_selectedRegion.moveBy(0,-(m_selectedRegion.bottom()-m_originalPixmap.height()));

         m_tempFirstClick=mev->pos();
         updatePixmap();
      }
      return TRUE;
   }

   if ( ev->type() == QEvent::MouseButtonRelease )
   {
      QMouseEvent *mev= (QMouseEvent *)(ev);

      if ( m_state == Resizing && mev->pos() == m_tempFirstClick)
         resetSelection();

      m_state=None;

      return TRUE;
   }

   QWidget::eventFilter(obj, ev);
   return FALSE;
}

QRect KPixmapRegionSelectorWidget::calcSelectionRectangle( const QPoint & startPoint, const QPoint & _endPoint )
{
   QPoint endPoint = _endPoint;
   if ( endPoint.x() < 0 ) endPoint.setX(0);
   else if ( endPoint.x() > m_originalPixmap.width() ) endPoint.setX(m_originalPixmap.width());
   if ( endPoint.y() < 0 ) endPoint.setY(0);
   else if ( endPoint.y() > m_originalPixmap.height() ) endPoint.setY(m_originalPixmap.height());
   int w=abs(startPoint.x()-endPoint.x());
   int h=abs(startPoint.y()-endPoint.y());

   if (m_forcedAspectRatio>0)
   {
      double aspectRatio=w/double(h);

      if (aspectRatio>m_forcedAspectRatio)
         h=(int)(w/m_forcedAspectRatio);
      else
         w=(int)(h*m_forcedAspectRatio);
   }

   int x,y;
   if ( startPoint.x() < endPoint.x() )
     x=startPoint.x();
   else
     x=startPoint.x()-w;
   if ( startPoint.y() < endPoint.y() )
     y=startPoint.y();
   else
     y=startPoint.y()-h;

   if (x<0)
   {
      w+=x;
      x=0;
      h=(int)(w/m_forcedAspectRatio);

      if ( startPoint.y() > endPoint.y() )
        y=startPoint.y()-h;
   }
   else if (x+w>m_originalPixmap.width())
   {
      w=m_originalPixmap.width()-x;
      h=(int)(w/m_forcedAspectRatio);

      if ( startPoint.y() > endPoint.y() )
        y=startPoint.y()-h;
   }
   if (y<0)
   {
      h+=y;
      y=0;
      w=(int)(h*m_forcedAspectRatio);

      if ( startPoint.x() > endPoint.x() )
        x=startPoint.x()-w;
   }
   else if (y+h>m_originalPixmap.height())
   {
      h=m_originalPixmap.height()-y;
      w=(int)(h*m_forcedAspectRatio);

      if ( startPoint.x() > endPoint.x() )
        x=startPoint.x()-w;
   }

   return QRect(x,y,w,h);
}

QRect KPixmapRegionSelectorWidget::unzoomedSelectedRegion() const
{
  return QRect((int)(m_selectedRegion.x()/m_zoomFactor),
               (int)(m_selectedRegion.y()/m_zoomFactor),
               (int)(m_selectedRegion.width()/m_zoomFactor),
               (int)(m_selectedRegion.height()/m_zoomFactor));
}

QImage KPixmapRegionSelectorWidget::selectedImage() const
{
   QImage origImage=m_unzoomedPixmap.convertToImage();
   return origImage.copy(unzoomedSelectedRegion());
}

void KPixmapRegionSelectorWidget::setSelectionAspectRatio(int width, int height)
{
   m_forcedAspectRatio=width/double(height);
}

void KPixmapRegionSelectorWidget::setFreeSelectionAspectRatio()
{
   m_forcedAspectRatio=0;
}

void KPixmapRegionSelectorWidget::setMaximumWidgetSize(int width, int height)
{
   m_maxWidth=width;
   m_maxHeight=height;

   m_originalPixmap=m_unzoomedPixmap;
   if (m_selectedRegion == m_originalPixmap.rect()) m_selectedRegion=QRect();

//   kdDebug() << QString(" original Pixmap :") << m_originalPixmap.rect() << endl;
//   kdDebug() << QString(" unzoomed Pixmap : %1 x %2 ").arg(m_unzoomedPixmap.width()).arg(m_unzoomedPixmap.height()) << endl;

   if ( !m_originalPixmap.isNull() &&
       ( m_originalPixmap.width() > m_maxWidth ||
         m_originalPixmap.height() > m_maxHeight ) )
   {
         /* We have to resize the pixmap to get it complete on the screen */
         QImage image=m_originalPixmap.convertToImage();
         m_originalPixmap.convertFromImage( image.smoothScale( width, height, QImage::ScaleMin ) );
         //m_originalPixmap.convertFromImage( KImageEffect::sample( image, width, height ) );
         double oldZoomFactor = m_zoomFactor;
         m_zoomFactor=m_originalPixmap.width()/(double)m_unzoomedPixmap.width();

         if (m_selectedRegion.isValid())
         {
            m_selectedRegion=
                  QRect((int)(m_selectedRegion.x()*m_zoomFactor/oldZoomFactor),
                        (int)(m_selectedRegion.y()*m_zoomFactor/oldZoomFactor),
                        (int)(m_selectedRegion.width()*m_zoomFactor/oldZoomFactor),
                        (int)(m_selectedRegion.height()*m_zoomFactor/oldZoomFactor) );
         }
   }

   if (!m_selectedRegion.isValid()) m_selectedRegion = m_originalPixmap.rect();

   m_linedPixmap=QPixmap();
   updatePixmap();
   resize(m_label->width(), m_label->height());
}

<|endoftext|>