<commit_before>/*
 *  Copyright 2008-2010 NVIDIA Corporation
 *
 *  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 <thrust/random/uniform_real_distribution.h>
#include <math.h>

// XXX WAR missing definitions on MSVC
__host__ __device__
double nextafter(double, double);

__host__ __device__
float nextafterf(float, float);

namespace thrust
{

namespace random
{

template<typename RealType>
  uniform_real_distribution<RealType>
    ::uniform_real_distribution(RealType a, RealType b)
      :m_param(a,b)
{
} // end uniform_real_distribution::uniform_real_distribution()

template<typename RealType>
  uniform_real_distribution<RealType>
    ::uniform_real_distribution(const param_type &parm)
      :m_param(parm)
{
} // end uniform_real_distribution::uniform_real_distribution()

template<typename RealType>
  void uniform_real_distribution<RealType>
    ::reset(void)
{
} // end uniform_real_distribution::reset()

template<typename RealType>
  template<typename UniformRandomNumberGenerator>
    typename uniform_real_distribution<RealType>::result_type
      uniform_real_distribution<RealType>
        ::operator()(UniformRandomNumberGenerator &urng)
{
  return operator()(urng, m_param);
} // end uniform_real::operator()()

namespace detail
{

__host__ __device__ __inline__
double nextafter(double x, double y)
{
  return ::nextafter(x,y);
}

__host__ __device__ __inline__
float nextafter(float x, float y)
{
  return ::nextafterf(x,y);
}

}

template<typename RealType>
  template<typename UniformRandomNumberGenerator>
    typename uniform_real_distribution<RealType>::result_type
      uniform_real_distribution<RealType>
        ::operator()(UniformRandomNumberGenerator &urng,
                     const param_type &parm)
{
  // call the urng & map its result to [0,1]
  result_type result = static_cast<result_type>(urng() - UniformRandomNumberGenerator::min);
  result /= static_cast<result_type>(UniformRandomNumberGenerator::max - UniformRandomNumberGenerator::min);

  // do not include parm.second in the result
  // get the next value after parm.second in the direction of parm.first
  // we need to do this because the range is half-open at parm.second

  return (result * (detail::nextafter(parm.second,parm.first) - parm.first)) + parm.first;
} // end uniform_real::operator()()

template<typename RealType>
  typename uniform_real_distribution<RealType>::result_type
    uniform_real_distribution<RealType>
      ::a(void) const
{
  return m_param.first;
} // end uniform_real::a()

template<typename RealType>
  typename uniform_real_distribution<RealType>::result_type
    uniform_real_distribution<RealType>
      ::b(void) const
{
  return m_param.second;
} // end uniform_real_distribution::b()

template<typename RealType>
  typename uniform_real_distribution<RealType>::param_type
    uniform_real_distribution<RealType>
      ::param(void) const
{
  return m_param;;
} // end uniform_real_distribution::param()

template<typename RealType>
  void uniform_real_distribution<RealType>
    ::param(const param_type &parm)
{
  m_param = parm;
} // end uniform_real_distribution::param()

template<typename RealType>
  typename uniform_real_distribution<RealType>::result_type
    uniform_real_distribution<RealType>
      ::min(void) const
{
  return a();
} // end uniform_real_distribution::min()

template<typename RealType>
  typename uniform_real_distribution<RealType>::result_type
    uniform_real_distribution<RealType>
      ::max(void) const
{
  return b();
} // end uniform_real_distribution::max()

template<typename RealType>
  bool uniform_real_distribution<RealType>
    ::equal(const uniform_real_distribution &rhs) const
{
  return m_param == rhs.param();
}

template<typename RealType>
  template<typename CharT, typename Traits>
    std::basic_ostream<CharT,Traits>&
      uniform_real_distribution<RealType>
        ::stream_out(std::basic_ostream<CharT,Traits> &os) const
{
  typedef std::basic_ostream<CharT,Traits> ostream_type;
  typedef typename ostream_type::ios_base  ios_base;

  // save old flags and fill character
  const typename ios_base::fmtflags flags = os.flags();
  const CharT fill = os.fill();

  const CharT space = os.widen(' ');
  os.flags(ios_base::dec | ios_base::fixed | ios_base::left);
  os.fill(space);

  os << a() << space << b();

  // restore old flags and fill character
  os.flags(flags);
  os.fill(fill);
  return os;
}

template<typename RealType>
  template<typename CharT, typename Traits>
    std::basic_istream<CharT,Traits>&
      uniform_real_distribution<RealType>
        ::stream_in(std::basic_istream<CharT,Traits> &is)
{
  typedef std::basic_istream<CharT,Traits> istream_type;
  typedef typename istream_type::ios_base  ios_base;

  // save old flags
  const typename ios_base::fmtflags flags = is.flags();

  is.flags(ios_base::skipws);

  is >> m_param.first >> m_param.second;

  // restore old flags
  is.flags(flags);
  return is;
}

template<typename RealType>
bool operator==(const uniform_real_distribution<RealType> &lhs,
                const uniform_real_distribution<RealType> &rhs)
{
  return thrust::random::detail::random_core_access::equal(lhs,rhs);
}

template<typename RealType>
bool operator!=(const uniform_real_distribution<RealType> &lhs,
                const uniform_real_distribution<RealType> &rhs)
{
  return !(lhs == rhs);
}

template<typename RealType,
         typename CharT, typename Traits>
std::basic_ostream<CharT,Traits>&
operator<<(std::basic_ostream<CharT,Traits> &os,
           const uniform_real_distribution<RealType> &d)
{
  return thrust::random::detail::random_core_access::stream_out(os,d);
}

template<typename RealType,
         typename CharT, typename Traits>
std::basic_istream<CharT,Traits>&
operator>>(std::basic_istream<CharT,Traits> &is,
           uniform_real_distribution<RealType> &d)
{
  return thrust::random::detail::random_core_access::stream_in(is,d);
}

} // end random

} // end thrust

<commit_msg>Guard forward declarations of nextafter & nextafterf from compilers that aren't MSVC.<commit_after>/*
 *  Copyright 2008-2010 NVIDIA Corporation
 *
 *  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 <thrust/random/uniform_real_distribution.h>
#include <math.h>

#if THRUST_HOST_COMPILER == THRUST_HOST_COMPILER_MSVC
// XXX WAR missing definitions on MSVC
__host__ __device__
double nextafter(double, double);

__host__ __device__
float nextafterf(float, float);
#endif // THRUST_HOST_COMPILER_MSVC

namespace thrust
{

namespace random
{

template<typename RealType>
  uniform_real_distribution<RealType>
    ::uniform_real_distribution(RealType a, RealType b)
      :m_param(a,b)
{
} // end uniform_real_distribution::uniform_real_distribution()

template<typename RealType>
  uniform_real_distribution<RealType>
    ::uniform_real_distribution(const param_type &parm)
      :m_param(parm)
{
} // end uniform_real_distribution::uniform_real_distribution()

template<typename RealType>
  void uniform_real_distribution<RealType>
    ::reset(void)
{
} // end uniform_real_distribution::reset()

template<typename RealType>
  template<typename UniformRandomNumberGenerator>
    typename uniform_real_distribution<RealType>::result_type
      uniform_real_distribution<RealType>
        ::operator()(UniformRandomNumberGenerator &urng)
{
  return operator()(urng, m_param);
} // end uniform_real::operator()()

namespace detail
{

__host__ __device__ __inline__
double nextafter(double x, double y)
{
  return ::nextafter(x,y);
}

__host__ __device__ __inline__
float nextafter(float x, float y)
{
  return ::nextafterf(x,y);
}

}

template<typename RealType>
  template<typename UniformRandomNumberGenerator>
    typename uniform_real_distribution<RealType>::result_type
      uniform_real_distribution<RealType>
        ::operator()(UniformRandomNumberGenerator &urng,
                     const param_type &parm)
{
  // call the urng & map its result to [0,1]
  result_type result = static_cast<result_type>(urng() - UniformRandomNumberGenerator::min);
  result /= static_cast<result_type>(UniformRandomNumberGenerator::max - UniformRandomNumberGenerator::min);

  // do not include parm.second in the result
  // get the next value after parm.second in the direction of parm.first
  // we need to do this because the range is half-open at parm.second

  return (result * (detail::nextafter(parm.second,parm.first) - parm.first)) + parm.first;
} // end uniform_real::operator()()

template<typename RealType>
  typename uniform_real_distribution<RealType>::result_type
    uniform_real_distribution<RealType>
      ::a(void) const
{
  return m_param.first;
} // end uniform_real::a()

template<typename RealType>
  typename uniform_real_distribution<RealType>::result_type
    uniform_real_distribution<RealType>
      ::b(void) const
{
  return m_param.second;
} // end uniform_real_distribution::b()

template<typename RealType>
  typename uniform_real_distribution<RealType>::param_type
    uniform_real_distribution<RealType>
      ::param(void) const
{
  return m_param;;
} // end uniform_real_distribution::param()

template<typename RealType>
  void uniform_real_distribution<RealType>
    ::param(const param_type &parm)
{
  m_param = parm;
} // end uniform_real_distribution::param()

template<typename RealType>
  typename uniform_real_distribution<RealType>::result_type
    uniform_real_distribution<RealType>
      ::min(void) const
{
  return a();
} // end uniform_real_distribution::min()

template<typename RealType>
  typename uniform_real_distribution<RealType>::result_type
    uniform_real_distribution<RealType>
      ::max(void) const
{
  return b();
} // end uniform_real_distribution::max()

template<typename RealType>
  bool uniform_real_distribution<RealType>
    ::equal(const uniform_real_distribution &rhs) const
{
  return m_param == rhs.param();
}

template<typename RealType>
  template<typename CharT, typename Traits>
    std::basic_ostream<CharT,Traits>&
      uniform_real_distribution<RealType>
        ::stream_out(std::basic_ostream<CharT,Traits> &os) const
{
  typedef std::basic_ostream<CharT,Traits> ostream_type;
  typedef typename ostream_type::ios_base  ios_base;

  // save old flags and fill character
  const typename ios_base::fmtflags flags = os.flags();
  const CharT fill = os.fill();

  const CharT space = os.widen(' ');
  os.flags(ios_base::dec | ios_base::fixed | ios_base::left);
  os.fill(space);

  os << a() << space << b();

  // restore old flags and fill character
  os.flags(flags);
  os.fill(fill);
  return os;
}

template<typename RealType>
  template<typename CharT, typename Traits>
    std::basic_istream<CharT,Traits>&
      uniform_real_distribution<RealType>
        ::stream_in(std::basic_istream<CharT,Traits> &is)
{
  typedef std::basic_istream<CharT,Traits> istream_type;
  typedef typename istream_type::ios_base  ios_base;

  // save old flags
  const typename ios_base::fmtflags flags = is.flags();

  is.flags(ios_base::skipws);

  is >> m_param.first >> m_param.second;

  // restore old flags
  is.flags(flags);
  return is;
}

template<typename RealType>
bool operator==(const uniform_real_distribution<RealType> &lhs,
                const uniform_real_distribution<RealType> &rhs)
{
  return thrust::random::detail::random_core_access::equal(lhs,rhs);
}

template<typename RealType>
bool operator!=(const uniform_real_distribution<RealType> &lhs,
                const uniform_real_distribution<RealType> &rhs)
{
  return !(lhs == rhs);
}

template<typename RealType,
         typename CharT, typename Traits>
std::basic_ostream<CharT,Traits>&
operator<<(std::basic_ostream<CharT,Traits> &os,
           const uniform_real_distribution<RealType> &d)
{
  return thrust::random::detail::random_core_access::stream_out(os,d);
}

template<typename RealType,
         typename CharT, typename Traits>
std::basic_istream<CharT,Traits>&
operator>>(std::basic_istream<CharT,Traits> &is,
           uniform_real_distribution<RealType> &d)
{
  return thrust::random::detail::random_core_access::stream_in(is,d);
}

} // end random

} // end thrust

<|endoftext|>


<commit_before>/* StartingGateMission.cpp -- Implementation of StartingGateMission class

   Copyright (C) 2014 Tushar Pankaj

   This file is part of San Diego Robotics 101 Robosub.

   San Diego Robotics 101 Robosub is free software: you can redistribute it
   and/or modify it under the terms of the GNU General Public License as
   published by the Free Software Foundation, either version 3 of the License,
   or (at your option) any later version.

   San Diego Robotics 101 Robosub is distributed in the hope that it will be
   useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
   Public License for more details.

   You should have received a copy of the GNU General Public License
   along with San Diego Robotics 101 Robosub.  If not, see
   <http://www.gnu.org/licenses/>. */

#include <iostream>
#include <string>
#include <vector>
#include <opencv2/opencv.hpp>
#include "Robot.hpp"
#include "Logger.hpp"
#include "Contour.hpp"
#include "Circle.hpp"
#include "Rectangle.hpp"
#include "ContourDetector.hpp"
#include "Mission.hpp"
#include "StartingGateMission.hpp"

 StartingGateMission::StartingGateMission(Robot * robot_ptr):Mission(robot_ptr)
{
	mission_name = "Starting Gate Mission";
}

void StartingGateMission::run()
{
	robot->get_logger()->write("Running mission " + mission_name,
				   Logger::MESSAGE);
	//cv::Mat image = cv::imread("/tmp/starting_gate.png");
	cv::Mat image;
	while (true) {
		image = robot->get_forward_camera()->get_image();
		ContourDetector::Params detector_params;
		detector_params.filter_by_hue = true;
		detector_params.min_hue = 100;
		detector_params.max_hue = 150;
		detector_params.max_canny = 50;
		detector_params.filter_with_blur = false;
		ContourDetector detector(detector_params);
		std::vector < Contour > contours = detector.detect(image);
		if (contours.empty()) {
			robot->get_logger()->write("No contours found",
						   Logger::WARNING);
			continue;
		}
		std::vector < Rectangle > filtered_rectangles =
		    filter_rectangles(contours);
		if (filtered_rectangles.empty()) {
			robot->get_logger()->
			    write("No filtered rectangles found",
				  Logger::WARNING);
			continue;
		}
		std::vector < cv::Point2f > centroids =
		    find_centroids(filtered_rectangles);
		/*for (uint i = 0; i < centroids.size(); i++)
		   cv::circle(image, centroids.at(i), 5,
		   cv::Scalar(0, 0, 0)); */
		double angular_displacement = find_angular_displacement(centroids, cv::Point2f((float)image.rows / 2.0, (float)image.cols / 2.0));
		robot->get_serial()->get_tx_packet()->set_rot_z(angular_displacement);
		robot->get_logger()->write("StartingGateMission angular displacement is " + std::to_string(angular_displacement) + " degrees", Logger::VERBOSE);
	}
}

std::vector < Circle > StartingGateMission::contours_to_circles(std::vector <
								Contour >
								contours)
{
	std::vector < Circle > circles;
	for (uint i = 0; i < contours.size(); i++)
		circles.push_back(Circle(contours.at(i).get_points()));
	return circles;
}

std::vector < Rectangle >
    StartingGateMission::contours_to_rectangles(std::vector < Contour >
						contours)
{
	std::vector < Rectangle > rectangles;
	for (uint i = 0; i < contours.size(); i++)
		rectangles.push_back(Rectangle(contours.at(i).get_points()));
	return rectangles;
}

std::vector < Rectangle > StartingGateMission::filter_rectangles(std::vector <
								 Contour >
								 detected_contours)
{
	std::vector < Circle > detected_enclosing_circles =
	    contours_to_circles(detected_contours);
	std::vector < Rectangle > detected_bounding_rectangles =
	    contours_to_rectangles(detected_contours);
	std::vector < Rectangle > filtered_rectangles;
	for (uint i = 0; i < detected_contours.size(); i++)	// Filter out circular contours and filter on aspect ratio
	{
		if (detected_bounding_rectangles.at(i).get_area_ratio() <
		    detected_enclosing_circles.at(i).get_area_ratio()
		    && detected_bounding_rectangles.at(i).get_aspect_ratio() <
		    0.2)
			filtered_rectangles.push_back
			    (detected_bounding_rectangles.at(i));
	}
	return filtered_rectangles;
}

std::vector < cv::Point2f > StartingGateMission::find_centroids(std::vector <
								Rectangle >
								rectangles)
{
	cv::Mat data = cv::Mat::zeros(rectangles.size(), 2, CV_32F);
	for (uint i = 0; i < rectangles.size(); i++) {
		data.at < float >(i, 0) = rectangles.at(i).get_center().x;
		data.at < float >(i, 1) = rectangles.at(i).get_center().y;
	}
	int K = 2;
	cv::Mat best_labels;
	cv::TermCriteria criteria =
	    cv::TermCriteria(cv::TermCriteria::COUNT, 10, 1.0);
	int attempts = 3;
	int flags = cv::KMEANS_PP_CENTERS;
	cv::Mat centroids;
	cv::kmeans(data, K, best_labels, criteria, attempts, flags, centroids);
	std::vector < cv::Point2f > centroids_vector;
	for (int i = 0; i < centroids.rows; i++)
		centroids_vector.push_back(cv::Point2f
					   (centroids.at < float >(i, 0),
					    centroids.at < float >(i, 1)));
	return centroids_vector;
}

double StartingGateMission::find_angular_displacement(std::vector <
						      cv::Point2f > centroids, cv::Point2f image_center)
{
	cv::Point2f centroids_average = cv::Point2f(0.0, 0.0);
	for (uint i = 0; i < centroids.size(); i++)
		centroids_average += centroids.at(i);
	centroids_average.x /= centroids.size();
	centroids_average.y /= centroids.size();
	return robot->get_forward_camera()->pixels_to_angle((centroids_average = image_center).x);
}
<commit_msg>Fixed typo in angle calculation in StartingGateMission<commit_after>/* StartingGateMission.cpp -- Implementation of StartingGateMission class

   Copyright (C) 2014 Tushar Pankaj

   This file is part of San Diego Robotics 101 Robosub.

   San Diego Robotics 101 Robosub is free software: you can redistribute it
   and/or modify it under the terms of the GNU General Public License as
   published by the Free Software Foundation, either version 3 of the License,
   or (at your option) any later version.

   San Diego Robotics 101 Robosub is distributed in the hope that it will be
   useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
   Public License for more details.

   You should have received a copy of the GNU General Public License
   along with San Diego Robotics 101 Robosub.  If not, see
   <http://www.gnu.org/licenses/>. */

#include <iostream>
#include <string>
#include <vector>
#include <opencv2/opencv.hpp>
#include "Robot.hpp"
#include "Logger.hpp"
#include "Contour.hpp"
#include "Circle.hpp"
#include "Rectangle.hpp"
#include "ContourDetector.hpp"
#include "Mission.hpp"
#include "StartingGateMission.hpp"

 StartingGateMission::StartingGateMission(Robot * robot_ptr):Mission(robot_ptr)
{
	mission_name = "Starting Gate Mission";
}

void StartingGateMission::run()
{
	robot->get_logger()->write("Running mission " + mission_name,
				   Logger::MESSAGE);
	//cv::Mat image = cv::imread("/tmp/starting_gate.png");
	cv::Mat image;
	while (true) {
		image = robot->get_forward_camera()->get_image();
		ContourDetector::Params detector_params;
		detector_params.filter_by_hue = true;
		detector_params.min_hue = 100;
		detector_params.max_hue = 150;
		detector_params.max_canny = 50;
		detector_params.filter_with_blur = false;
		ContourDetector detector(detector_params);
		std::vector < Contour > contours = detector.detect(image);
		if (contours.empty()) {
			robot->get_logger()->write("No contours found",
						   Logger::WARNING);
			continue;
		}
		std::vector < Rectangle > filtered_rectangles =
		    filter_rectangles(contours);
		if (filtered_rectangles.empty()) {
			robot->get_logger()->
			    write("No filtered rectangles found",
				  Logger::WARNING);
			continue;
		}
		std::vector < cv::Point2f > centroids =
		    find_centroids(filtered_rectangles);
		/*for (uint i = 0; i < centroids.size(); i++)
		   cv::circle(image, centroids.at(i), 5,
		   cv::Scalar(0, 0, 0)); */
		double angular_displacement = find_angular_displacement(centroids, cv::Point2f((float)image.rows / 2.0, (float)image.cols / 2.0));
		robot->get_serial()->get_tx_packet()->set_rot_z(angular_displacement);
		robot->get_logger()->write("StartingGateMission angular displacement is " + std::to_string(angular_displacement) + " degrees", Logger::VERBOSE);
	}
}

std::vector < Circle > StartingGateMission::contours_to_circles(std::vector <
								Contour >
								contours)
{
	std::vector < Circle > circles;
	for (uint i = 0; i < contours.size(); i++)
		circles.push_back(Circle(contours.at(i).get_points()));
	return circles;
}

std::vector < Rectangle >
    StartingGateMission::contours_to_rectangles(std::vector < Contour >
						contours)
{
	std::vector < Rectangle > rectangles;
	for (uint i = 0; i < contours.size(); i++)
		rectangles.push_back(Rectangle(contours.at(i).get_points()));
	return rectangles;
}

std::vector < Rectangle > StartingGateMission::filter_rectangles(std::vector <
								 Contour >
								 detected_contours)
{
	std::vector < Circle > detected_enclosing_circles =
	    contours_to_circles(detected_contours);
	std::vector < Rectangle > detected_bounding_rectangles =
	    contours_to_rectangles(detected_contours);
	std::vector < Rectangle > filtered_rectangles;
	for (uint i = 0; i < detected_contours.size(); i++)	// Filter out circular contours and filter on aspect ratio
	{
		if (detected_bounding_rectangles.at(i).get_area_ratio() <
		    detected_enclosing_circles.at(i).get_area_ratio()
		    && detected_bounding_rectangles.at(i).get_aspect_ratio() <
		    0.2)
			filtered_rectangles.push_back
			    (detected_bounding_rectangles.at(i));
	}
	return filtered_rectangles;
}

std::vector < cv::Point2f > StartingGateMission::find_centroids(std::vector <
								Rectangle >
								rectangles)
{
	cv::Mat data = cv::Mat::zeros(rectangles.size(), 2, CV_32F);
	for (uint i = 0; i < rectangles.size(); i++) {
		data.at < float >(i, 0) = rectangles.at(i).get_center().x;
		data.at < float >(i, 1) = rectangles.at(i).get_center().y;
	}
	int K = 2;
	cv::Mat best_labels;
	cv::TermCriteria criteria =
	    cv::TermCriteria(cv::TermCriteria::COUNT, 10, 1.0);
	int attempts = 3;
	int flags = cv::KMEANS_PP_CENTERS;
	cv::Mat centroids;
	cv::kmeans(data, K, best_labels, criteria, attempts, flags, centroids);
	std::vector < cv::Point2f > centroids_vector;
	for (int i = 0; i < centroids.rows; i++)
		centroids_vector.push_back(cv::Point2f
					   (centroids.at < float >(i, 0),
					    centroids.at < float >(i, 1)));
	return centroids_vector;
}

double StartingGateMission::find_angular_displacement(std::vector <
						      cv::Point2f > centroids, cv::Point2f image_center)
{
	cv::Point2f centroids_average = cv::Point2f(0.0, 0.0);
	for (uint i = 0; i < centroids.size(); i++)
		centroids_average += centroids.at(i);
	centroids_average.x /= centroids.size();
	centroids_average.y /= centroids.size();
	return robot->get_forward_camera()->pixels_to_angle((centroids_average - image_center).x);
}
<|endoftext|>


<commit_before>/*
Used to calculate the m-dimension submatrices used in the Four Russians algorithm.
Each submatrix is calculated like a Wagner-Fischer edit matrix with cells as follows:
- (i-1, j-1) to (i, j) with 0 cost added if the characters at (i, j) match, replaceCost otherwise
- (i-1, j) to (i, j) with deleteCost added
- (i, j-1) to (i, j) with insertCost added

Notes:
The strings start with a space because the (0, x) and (x, 0) fields refer to one
string being empty.
The costs are not directly stored, they're converted to step vectors as per the
Four Russians algorithm.
*/

#include <cstdio>
#include <iostream>
#include <vector>
#include <map>
#include <cmath>
#include <string>
#include <cstdlib>
#include <ctime>
#include <numeric>

using namespace std;

class SubmatrixCalculator {

public:

    SubmatrixCalculator(int _dimension, string _alphabet, char _blankCharacter = '-', int _replaceCost = 2, int _deleteCost = 1,
                        int _insertCost = 1) {
        this->dimension = _dimension;
        this->alphabet = _alphabet;
        this->blankCharacter = _blankCharacter;
        this->replaceCost = _replaceCost;
        this->deleteCost = _deleteCost;
        this->insertCost = _insertCost;

        this->initialSteps.reserve(pow(3, _dimension));
        this->initialStrings.reserve(pow(_alphabet.size(), _dimension));

        int startTime = clock();
        this->resultIndex = new pair<string, string>[this->submatrixCountLimit];
        cout << "Allocation time: " << (clock()-startTime)/double(CLOCKS_PER_SEC) << "s" << endl;
    }

    void calculate() {
        printf("Clearing the submatrix data...\n");
        results.clear();

        generateInitialSteps(0, "1");
        generateInitialStrings(0, " ");

        //printDebug();

        // setting up temporary matrix storage
        lastSubH.reserve(this->dimension + 1);
        lastSubV.reserve(this->dimension + 1);
        vector<int> rowVec(this->dimension + 1, 0);
        for (int i = 0; i <= this->dimension; i++) {
            lastSubH.push_back(rowVec);
            lastSubV.push_back(rowVec);
        }

        // all possible initial steps and strings combinations
        int startTime = clock();
        for (int strA = 0; strA < initialStrings.size(); strA++) {
            for (int strB = 0; strB < initialStrings.size(); strB++) {
                for (int stepC = 0; stepC < initialSteps.size(); stepC++) {
                    for (int stepD = 0; stepD < initialSteps.size(); stepD++) {
                        string key = initialStrings[strA];
                        key += initialStrings[strB];
                        key += initialSteps[stepC];
                        key += initialSteps[stepD];
                        // storing the resulting final rows for future reference
                        resultIndex[hash(key)] = calculateFinalSteps(initialStrings[strA], initialStrings[strB],
                                                 initialSteps[stepC], initialSteps[stepD]);
                        //result[hash(key)] = calculateFinalSteps(initialStrings[strA], initialStrings[strB],
                        //                                  initialSteps[stepC], initialSteps[stepD]);
                    }
                }
            }
            //cout << strA + 1 << " / " << initialStrings.size() << " (submatrices: " << results.size() << " )" << endl;
            cout << strA + 1 << " / " << initialStrings.size() << " (submatrices: "
                 << (strA + 1) * initialStrings.size() * initialSteps.size() * initialSteps.size() << " )" << endl;
        }
        cout << "Submatrix calculation time: " << (clock()-startTime)/double(CLOCKS_PER_SEC) << "s" << endl;
    }

    pair<vector<int>, pair<pair<int, int>, pair<int, int> > > getSubmatrixPath(string strLeft, string strTop, string stepLeft,
            string stepTop, int finalRow, int finalCol) {

        calculateSubmatrix(strLeft, strTop, stepLeft, stepTop);

        int i = finalRow;
        int j = finalCol;
        vector<int> operations;
        while (i > 0 && j > 0){
            // TODO
        }

        pair<int, int> nextMatrix;
        pair<int, int> nextCell;
        if (i == 0 && j == 0){
            nextMatrix = make_pair(-1, -1);
            nextCell = make_pair(this->dimension, this->dimension);
        }
        else if (i == 0){
            nextMatrix = make_pair(-1, 0);
            nextCell = make_pair(this->dimension, j);
        }
        else {
            nextMatrix = make_pair(0, -1);
            nextCell = make_pair(i, this->dimension);
        }

        return make_pair(operations, make_pair(nextMatrix, nextCell));
    }

    /*
        Calculates the step-matrix determined by the two strings and two initial vectors provided.
        The step matrix has two parts, vertical and horizontal steps, stored in lastSubV and lastSubH.
    */
    inline void calculateSubmatrix(string strLeft, string strTop, string stepLeft, string stepTop) {
        /*
            TODO: CHECK: MIGHT BE WRONG AFTER TRANSPOSING
            have to transpose to keep cache functionality, huge speedup;
            old/new way commented
        */
        for (int i = 1; i <= this->dimension; i++) {
            //lastSubV[i][0] = stepLeft[i] - '1'; // old
            lastSubV[0][i] = stepLeft[i] - '1'; // new
            lastSubH[0][i] = stepTop[i] - '1';
        }

        for (int i = 1; i <= this->dimension; i++) {
            for (int j = 1; j <= this->dimension; j++) {
                int R = (strLeft[i] == strTop[j]) * this->replaceCost;
                //int lastV = lastSubV[i][j - 1]; // old
                int lastV = lastSubV[i - 1][j]; // new
                int lastH = lastSubH[i - 1][j];
                /*lastSubV[i][j] =
                    min(min(R - lastH,
                            this->deleteCost),
                            this->insertCost + lastV - lastH);
                lastSubH[i][j] =
                    min(min(R - lastV,
                            this->insertCost),
                            this->deleteCost + lastH - lastV);*/
                lastSubV[i][j] =
                    mmin(R - lastH, this->deleteCost, this->insertCost + lastV - lastH);
                lastSubH[i][j] =
                    mmin(R - lastV, this->insertCost, this->deleteCost + lastH - lastV);
            }
        }

        /*      // DEBUG
                cout << "left " << strLeft << " top " << strTop << " stepleft "
                << stepsToPrettyString(stepLeft) << " steptop " << stepsToPrettyString(stepTop) << endl;
                cout << "vertical:" << endl;
                for (int i = 0; i <= this->dimension; i++){
                    for (int j = 0; j <= this->dimension; j++)
                        cout << stepMatrixV[i][j] << " ";
                    cout << endl;
                }
                cout << "horizontal:" << endl;
                for (int i = 0; i <= this->dimension; i++){
                    for (int j = 0; j <= this->dimension; j++)
                        cout << stepMatrixH[i][j] << " ";
                    cout << endl;
                }
                system("pause");
        */
    }

    /*
        Calculates the final step vectors for a given initial submatrix description.
    */
    pair<string, string> calculateFinalSteps(string strLeft, string strTop, string stepLeft,
            string stepTop) {
        calculateSubmatrix(strLeft, strTop, stepLeft, stepTop);
        /*
            // WARNING: check calculateSubmatrix() comments
            // old
        vector<int> stepRight(this->dimension + 1, 0);
        for (int i = 1; i <= this->dimension; i++){
            //stepRight[i] = lastSubV[i][this->dimension];
        }
        */
        vector<int> stepRight = lastSubV[this->dimension];
        vector<int> stepBot = lastSubH[this->dimension];

        return make_pair(stepsToString(stepRight), stepsToString(stepBot));
    }

    /*
        Returns the precalculated final step vectors for a given initial submatrix description.
    */
    inline pair<string, string> getFinalSteps(string strLeft, string strTop, string stepLeft,
            string stepTop) {
        //return results[hash(strLeft + strTop + stepLeft + stepTop)];
        return resultIndex[hash(strLeft + strTop + stepLeft + stepTop)];
    }

    /*
        Returns the sum of the step values for a given step string.
    */
    inline int sumSteps(string steps) {
        vector<int> stepValues = stepsToVector(steps);
        return accumulate(stepValues.begin(), stepValues.end(), 0);
    }

    /*
        Transforms the step vector to a string. The string characters have no special meaning,
        strings are used for easier mapping.
    */
    static string stepsToString(vector<int> steps) {
        string ret = "";
        ret.reserve(steps.size());
        for (int i = 0; i < steps.size(); i++) {
            ret += steps[i] + '1';
        }
        return ret;
    }

    /*
        Transforms the string of steps (possibly a result of stepsToString()) to a vector of steps,
        where each step value is expected to be in {-1, 0, 1}. I.e., the steps string characters
        are expected to be in {'0', '1', '2'}.
    */
    static vector<int> stepsToVector(string steps) {
        vector<int> ret;
        ret.reserve(steps.size());
        for (int i = 0; i < steps.size(); i++) {
            ret.push_back(steps[i] - '1');
        }
        return ret;
    }

    /*
        Adds spaces and signs to the step string and transforms the values to real step values.
    */
    static string stepsToPrettyString(string steps) {
        string ret = "";
        for (int i = 0; i < steps.size(); i++) {
            if (steps[i] == '0') {
                ret += "-1 ";
            } else if (steps[i] == '2') {
                ret += "+1 ";
            } else {
                ret += "0 ";
            }
        }
        return ret;
    }

    void generateInitialSteps(int pos, string currStep) {
        if (pos == this->dimension) {
            initialSteps.push_back(currStep);
            return;
        }

        for (int i = -1; i <= 1; i++) {
            string tmp = currStep;
            tmp.push_back('1' + i);
            generateInitialSteps(pos + 1, tmp);
        }
    }

    void generateInitialStrings(int pos, string currString) {
        if (pos == this->dimension) {
            initialStrings.push_back(currString);
            return;
        }

        for (int i = 0; i < this->alphabet.size(); i++) {
            string tmp = currString;
            tmp.push_back(this->alphabet[i]);
            generateInitialStrings(pos + 1, tmp);
        }
    }

    // DEBUG
    void printDebug() {
        for (int i = 0; i < initialSteps.size(); i++)
            cout << stepsToPrettyString(initialSteps[i]) << endl;
        for (int i = 0; i < initialStrings.size(); i++)
            cout << initialStrings[i] << endl;
    }

    const long long HASH_BASE = 137;
    inline long long hash(string x) {
        long long ret = 0;
        for (int i = 0; i < x.size(); i++) {
            ret = (ret * HASH_BASE + x[i]);
        }
        ret &= this->submatrixCountLimit - 1; // fancy bit-work
        return ret;
    }

    inline int mmin(int x, int y, int z) {
        return x>y?(y<z?y:z):x<z?x:z;
    }

private:

    int dimension;
    int replaceCost;
    int deleteCost;
    int insertCost;
    // the actual maximum number of submatrices should be much lower
    // in order to decrease the possibility of hash collisions
    // when storing results
    const long long submatrixCountLimit = 16777216; // 2^24, coprime with hash base
    string alphabet;
    char blankCharacter;
    vector<string> initialSteps;
    vector<string> initialStrings;
    vector<vector<int> > lastSubH, lastSubV;
    map<long long, pair<string, string> > results;
    pair<string, string>* resultIndex;

};

int main() {
    SubmatrixCalculator calc(3, "ATGC");
    calc.calculate();

    return 0;
}
<commit_msg>Internal parameter modifications<commit_after>/*
Used to calculate the m-dimension submatrices used in the Four Russians algorithm.
Each submatrix is calculated like a Wagner-Fischer edit matrix with cells as follows:
- (i-1, j-1) to (i, j) with 0 cost added if the characters at (i, j) match, replaceCost otherwise
- (i-1, j) to (i, j) with deleteCost added
- (i, j-1) to (i, j) with insertCost added

Notes:
The strings start with a space because the (0, x) and (x, 0) fields refer to one
string being empty.
The costs are not directly stored, they're converted to step vectors as per the
Four Russians algorithm.
*/

#include <cstdio>
#include <iostream>
#include <vector>
#include <map>
#include <cmath>
#include <string>
#include <cstdlib>
#include <ctime>
#include <numeric>

using namespace std;

class SubmatrixCalculator {

public:

    SubmatrixCalculator(int _dimension, string _alphabet, char _blankCharacter = '-', int _replaceCost = 2,
                        int _deleteCost = 1,
                        int _insertCost = 1) {
        this->dimension = _dimension;
        this->alphabet = _alphabet;
        this->blankCharacter = _blankCharacter;
        this->replaceCost = _replaceCost;
        this->deleteCost = _deleteCost;
        this->insertCost = _insertCost;

        this->initialSteps.reserve(pow(3, _dimension));
        this->initialStrings.reserve(pow(_alphabet.size(), _dimension));

        int startTime = clock();
        this->resultIndex = new pair<string, string>[this->submatrixCountLimit];
        cout << "Allocation time: " << (clock()-startTime)/double(CLOCKS_PER_SEC) << "s" << endl;
    }

    void calculate() {
        printf("Clearing the submatrix data...\n");
        results.clear();

        generateInitialSteps(0, "");
        generateInitialStrings(0, "", false);

        //printDebug();

        // setting up temporary matrix storage
        lastSubH.reserve(this->dimension + 1);
        lastSubV.reserve(this->dimension + 1);
        vector<int> rowVec(this->dimension + 1, 0);
        for (int i = 0; i <= this->dimension; i++) {
            lastSubH.push_back(rowVec);
            lastSubV.push_back(rowVec);
        }

        // all possible initial steps and strings combinations
        int startTime = clock();
        for (int strA = 0; strA < initialStrings.size(); strA++) {
            for (int strB = 0; strB < initialStrings.size(); strB++) {
                for (int stepC = 0; stepC < initialSteps.size(); stepC++) {
                    for (int stepD = 0; stepD < initialSteps.size(); stepD++) {
                        string key = initialStrings[strA];
                        key += initialStrings[strB];
                        key += initialSteps[stepC];
                        key += initialSteps[stepD];
                        // storing the resulting final rows for future reference
                        resultIndex[hash(key)] = calculateFinalSteps(initialStrings[strA], initialStrings[strB],
                                                 initialSteps[stepC], initialSteps[stepD]);
                        //result[hash(key)] = calculateFinalSteps(initialStrings[strA], initialStrings[strB],
                        //                                  initialSteps[stepC], initialSteps[stepD]);
                    }
                }
            }
            //cout << strA + 1 << " / " << initialStrings.size() << " (submatrices: " << results.size() << " )" << endl;
            cout << strA + 1 << " / " << initialStrings.size() << " (submatrices: "
                 << (strA + 1) * initialStrings.size() * initialSteps.size() * initialSteps.size() << " )" << endl;
        }
        cout << "Submatrix calculation time: " << (clock()-startTime)/double(CLOCKS_PER_SEC) << "s" << endl;
    }

    pair<vector<int>, pair<pair<int, int>, pair<int, int> > > getSubmatrixPath(string strLeft, string strTop,
            string stepLeft,
            string stepTop, int finalRow, int finalCol) {

        calculateSubmatrix(strLeft, strTop, stepLeft, stepTop);

        int i = finalRow;
        int j = finalCol;
        vector<int> operations;
        while (i > 0 && j > 0) {
            // TODO
        }

        pair<int, int> nextMatrix;
        pair<int, int> nextCell;
        if (i == 0 && j == 0) {
            nextMatrix = make_pair(-1, -1);
            nextCell = make_pair(this->dimension, this->dimension);
        } else if (i == 0) {
            nextMatrix = make_pair(-1, 0);
            nextCell = make_pair(this->dimension, j);
        } else {
            nextMatrix = make_pair(0, -1);
            nextCell = make_pair(i, this->dimension);
        }

        return make_pair(operations, make_pair(nextMatrix, nextCell));
    }

    /*
        Calculates the step-matrix determined by the two strings and two initial vectors provided.
        The step matrix has two parts, vertical and horizontal steps, stored in lastSubV and lastSubH.
    */
    inline void calculateSubmatrix(string strLeft, string strTop, string stepLeft, string stepTop) {
        /*
            TODO: CHECK: MIGHT BE WRONG AFTER TRANSPOSING
            have to transpose to keep cache functionality, huge speedup;
            old/new way commented
        */
        for (int i = 1; i <= this->dimension; i++) {
            //lastSubV[i][0] = stepLeft[i] - '1'; // old
            lastSubV[0][i] = stepLeft[i - 1] - '1'; // new
            lastSubH[0][i] = stepTop[i - 1] - '1';
        }

        for (int i = 1; i <= this->dimension; i++) {
            for (int j = 1; j <= this->dimension; j++) {
                int R = (strLeft[i - 1] == strTop[j - 1]) * this->replaceCost;
                if (strLeft[i - 1] == blankCharacter or strTop[j - 1] == blankCharacter)
                    R = 0;
                //int lastV = lastSubV[i][j - 1]; // old
                int lastV = lastSubV[i - 1][j]; // new
                int lastH = lastSubH[i - 1][j];
                /*lastSubV[i][j] =
                    min(min(R - lastH,
                            this->deleteCost),
                            this->insertCost + lastV - lastH);
                lastSubH[i][j] =
                    min(min(R - lastV,
                            this->insertCost),
                            this->deleteCost + lastH - lastV);*/
                lastSubV[i][j] =
                    mmin(R - lastH, this->deleteCost, this->insertCost + lastV - lastH);
                lastSubH[i][j] =
                    mmin(R - lastV, this->insertCost, this->deleteCost + lastH - lastV);
            }
        }

        /*      // DEBUG
                cout << "left " << strLeft << " top " << strTop << " stepleft "
                << stepsToPrettyString(stepLeft) << " steptop " << stepsToPrettyString(stepTop) << endl;
                cout << "vertical:" << endl;
                for (int i = 0; i <= this->dimension; i++){
                    for (int j = 0; j <= this->dimension; j++)
                        cout << stepMatrixV[i][j] << " ";
                    cout << endl;
                }
                cout << "horizontal:" << endl;
                for (int i = 0; i <= this->dimension; i++){
                    for (int j = 0; j <= this->dimension; j++)
                        cout << stepMatrixH[i][j] << " ";
                    cout << endl;
                }
                system("pause");
        */
    }

    /*
        Calculates the final step vectors for a given initial submatrix description.
    */
    pair<string, string> calculateFinalSteps(string strLeft, string strTop, string stepLeft,
            string stepTop) {
        calculateSubmatrix(strLeft, strTop, stepLeft, stepTop);
        /*
            // WARNING: check calculateSubmatrix() comments
            // old
        vector<int> stepRight(this->dimension + 1, 0);
        for (int i = 1; i <= this->dimension; i++){
            //stepRight[i] = lastSubV[i][this->dimension];
        }
        */
        vector<int> stepRight = lastSubV[this->dimension];
        vector<int> stepBot = lastSubH[this->dimension];

        return make_pair(stepsToString(stepRight), stepsToString(stepBot));
    }

    /*
        Returns the precalculated final step vectors for a given initial submatrix description.
    */
    inline pair<string, string> getFinalSteps(string strLeft, string strTop, string stepLeft,
            string stepTop) {
        //return results[hash(strLeft + strTop + stepLeft + stepTop)];
        return resultIndex[hash(strLeft + strTop + stepLeft + stepTop)];
    }

    /*
        Returns the sum of the step values for a given step string.
    */
    inline int sumSteps(string steps) {
        vector<int> stepValues = stepsToVector(steps);
        return accumulate(stepValues.begin(), stepValues.end(), 0);
    }

    /*
        Transforms the step vector to a string. The string characters have no special meaning,
        strings are used for easier mapping. Check SubmatrixCalculator::stepsToVector comments.
    */
    static string stepsToString(vector<int> steps) {
        string ret = "";
        ret.reserve(steps.size());
        for (int i = 0; i < steps.size(); i++) {
            ret += steps[i] + '1';
        }
        return ret;
    }

    /*
        Transforms the string of steps (possibly a result of stepsToString()) to a vector of steps,
        where each step value is expected to be in {-1, 0, 1}. I.e., the steps string characters
        are expected to be in {'0', '1', '2'}.
    */
    static vector<int> stepsToVector(string steps) {
        vector<int> ret;
        ret.reserve(steps.size());
        for (int i = 0; i < steps.size(); i++) {
            ret.push_back(steps[i] - '1');
        }
        return ret;
    }

    /*
        Adds spaces and signs to the step string and transforms the values to real step values.
    */
    static string stepsToPrettyString(string steps) {
        string ret = "";
        for (int i = 0; i < steps.size(); i++) {
            if (steps[i] == '0') {
                ret += "-1 ";
            } else if (steps[i] == '2') {
                ret += "+1 ";
            } else {
                ret += "0 ";
            }
        }
        return ret;
    }

    void generateInitialSteps(int pos, string currStep) {
        if (pos == this->dimension) {
            initialSteps.push_back(currStep);
            return;
        }

        for (int i = -1; i <= 1; i++) {
            string tmp = currStep;
            tmp.push_back('1' + i);
            generateInitialSteps(pos + 1, tmp);
        }
    }

    void generateInitialStrings(int pos, string currString, bool blanks) {
        if (pos == this->dimension) {
            initialStrings.push_back(currString);
            return;
        }

        if (!blanks) {
            for (int i = 0; i < this->alphabet.size(); i++) {
                string tmp = currString;
                tmp.push_back(this->alphabet[i]);
                generateInitialStrings(pos + 1, tmp, false);
            }
        }

        string tmp = currString;
        tmp.push_back(blankCharacter);
        generateInitialStrings(pos + 1, tmp, true);
    }

    // DEBUG
    void printDebug() {
        for (int i = 0; i < initialSteps.size(); i++)
            cout << stepsToPrettyString(initialSteps[i]) << endl;
        for (int i = 0; i < initialStrings.size(); i++)
            cout << initialStrings[i] << endl;
    }

    const long long HASH_BASE = 137;
    inline long long hash(string x) {
        long long ret = 0;
        for (int i = 0; i < x.size(); i++) {
            ret = (ret * HASH_BASE + x[i]);
        }
        ret &= this->submatrixCountLimit - 1; // fancy bit-work
        return ret;
    }

    inline int mmin(int x, int y, int z) {
        return x>y?(y<z?y:z):x<z?x:z;
    }

private:

    int dimension;
    int replaceCost;
    int deleteCost;
    int insertCost;
    // the actual maximum number of submatrices should be much lower
    // in order to decrease the possibility of hash collisions
    // when storing results
    const long long submatrixCountLimit = 16777216; // 2^24, coprime with hash base
    string alphabet;
    char blankCharacter;
    vector<string> initialSteps;
    vector<string> initialStrings;
    vector<vector<int> > lastSubH, lastSubV;
    map<long long, pair<string, string> > results;
    pair<string, string>* resultIndex;

};

int main() {
    SubmatrixCalculator calc(3, "ATGC");
    calc.calculate();
    return 0;
}
<|endoftext|>


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

#define ITEMID_COLOR_TABLE      SID_COLOR_TABLE
#define ITEMID_GRADIENT_LIST    SID_GRADIENT_LIST
#define ITEMID_HATCH_LIST       SID_HATCH_LIST
#define ITEMID_BITMAP_LIST      SID_BITMAP_LIST

#ifndef _SVX_PAGE_HXX
#include <svx/page.hxx>
#endif
#ifndef _SVX_DIALOGS_HRC
#include <svx/dialogs.hrc>
#endif
#ifndef _SVX_TAB_AREA_HXX
#include <svx/tabarea.hxx>
#endif
#ifndef _SVX_DRAWITEM_HXX
#include <svx/drawitem.hxx>
#endif

#ifndef _SD_SDRESID_HXX
#include "sdresid.hxx"
#endif
#include "dlgpage.hxx"

#include "docshell.hxx"

/*************************************************************************
|*
|* Konstruktor des Tab-Dialogs: Fuegt die Seiten zum Dialog hinzu
|*
\************************************************************************/

SdPageDlg::SdPageDlg( SfxObjectShell* pDocSh, Window* pParent, const SfxItemSet* pAttr, BOOL bAreaPage ) :
        SfxTabDialog ( pParent, SdResId( TAB_PAGE ), pAttr ),
        rOutAttrs           ( *pAttr ),
        pDocShell           ( pDocSh )
{
    SvxColorTableItem aColorTableItem(*( (const SvxColorTableItem*)
        ( pDocShell->GetItem( SID_COLOR_TABLE ) ) ) );
    SvxGradientListItem aGradientListItem(*( (const SvxGradientListItem*)
        ( pDocShell->GetItem( SID_GRADIENT_LIST ) ) ) );
    SvxBitmapListItem aBitmapListItem(*( (const SvxBitmapListItem*)
        ( pDocShell->GetItem( SID_BITMAP_LIST ) ) ) );
    SvxHatchListItem aHatchListItem(*( (const SvxHatchListItem*)
        ( pDocShell->GetItem( SID_HATCH_LIST ) ) ) );

    pColorTab = aColorTableItem.GetColorTable();
    pGradientList = aGradientListItem.GetGradientList();
    pHatchingList = aHatchListItem.GetHatchList();
    pBitmapList = aBitmapListItem.GetBitmapList();

    FreeResource();

    AddTabPage( RID_SVXPAGE_PAGE, SvxPageDescPage::Create, 0);
    AddTabPage( RID_SVXPAGE_AREA, SvxAreaTabPage::Create, 0 );

    nDlgType = 1; // Vorlagen-Dialog
    nPageType = 0;
    nPos = 0;

    nColorTableState = CT_NONE;
    nBitmapListState = CT_NONE;
    nGradientListState = CT_NONE;
    nHatchingListState = CT_NONE;

    if(!bAreaPage)  // I have to add the page before I remove it !
        RemoveTabPage( RID_SVXPAGE_AREA );
}

/*************************************************************************
|*
|* Seite wird erzeugt
|*
\************************************************************************/

void SdPageDlg::PageCreated(USHORT nId, SfxTabPage& rPage)
{
    switch(nId)
    {
    case RID_SVXPAGE_PAGE:
        ( (SvxPageDescPage&) rPage).SetMode(SVX_PAGE_MODE_PRESENTATION);
        ( (SvxPageDescPage&) rPage).SetPaperFormatRanges( SVX_PAPER_A0, SVX_PAPER_E );
        break;
    case RID_SVXPAGE_AREA:
        ( (SvxAreaTabPage&) rPage ).SetColorTable( pColorTab );
        ( (SvxAreaTabPage&) rPage ).SetGradientList( pGradientList );
        ( (SvxAreaTabPage&) rPage ).SetHatchingList( pHatchingList );
        ( (SvxAreaTabPage&) rPage ).SetBitmapList( pBitmapList );
        ( (SvxAreaTabPage&) rPage ).SetPageType( &nPageType );
        ( (SvxAreaTabPage&) rPage ).SetDlgType( &nDlgType );
        ( (SvxAreaTabPage&) rPage ).SetPos( &nPos );
        ( (SvxAreaTabPage&) rPage ).SetGrdChgd( &nGradientListState );
        ( (SvxAreaTabPage&) rPage ).SetHtchChgd( &nHatchingListState );
        ( (SvxAreaTabPage&) rPage ).SetBmpChgd( &nBitmapListState );
        ( (SvxAreaTabPage&) rPage ).SetColorChgd( &nColorTableState );
        ( (SvxAreaTabPage&) rPage ).Construct();
        break;
    }
}

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

#define ITEMID_COLOR_TABLE      SID_COLOR_TABLE
#define ITEMID_GRADIENT_LIST    SID_GRADIENT_LIST
#define ITEMID_HATCH_LIST       SID_HATCH_LIST
#define ITEMID_BITMAP_LIST      SID_BITMAP_LIST

#ifndef _SVX_PAGE_HXX
#include <svx/page.hxx>
#endif
#ifndef _SVX_DIALOGS_HRC
#include <svx/dialogs.hrc>
#endif
#ifndef _SVX_TAB_AREA_HXX
#include <svx/tabarea.hxx>
#endif
#ifndef _SVX_DRAWITEM_HXX
#include <svx/drawitem.hxx>
#endif

#ifndef _SD_SDRESID_HXX
#include "sdresid.hxx"
#endif
#include "dlgpage.hxx"

#include "DrawDocShell.hxx"

/*************************************************************************
|*
|* Konstruktor des Tab-Dialogs: Fuegt die Seiten zum Dialog hinzu
|*
\************************************************************************/

SdPageDlg::SdPageDlg( SfxObjectShell* pDocSh, Window* pParent, const SfxItemSet* pAttr, BOOL bAreaPage ) :
        SfxTabDialog ( pParent, SdResId( TAB_PAGE ), pAttr ),
        rOutAttrs           ( *pAttr ),
        pDocShell           ( pDocSh )
{
    SvxColorTableItem aColorTableItem(*( (const SvxColorTableItem*)
        ( pDocShell->GetItem( SID_COLOR_TABLE ) ) ) );
    SvxGradientListItem aGradientListItem(*( (const SvxGradientListItem*)
        ( pDocShell->GetItem( SID_GRADIENT_LIST ) ) ) );
    SvxBitmapListItem aBitmapListItem(*( (const SvxBitmapListItem*)
        ( pDocShell->GetItem( SID_BITMAP_LIST ) ) ) );
    SvxHatchListItem aHatchListItem(*( (const SvxHatchListItem*)
        ( pDocShell->GetItem( SID_HATCH_LIST ) ) ) );

    pColorTab = aColorTableItem.GetColorTable();
    pGradientList = aGradientListItem.GetGradientList();
    pHatchingList = aHatchListItem.GetHatchList();
    pBitmapList = aBitmapListItem.GetBitmapList();

    FreeResource();

    AddTabPage( RID_SVXPAGE_PAGE, SvxPageDescPage::Create, 0);
    AddTabPage( RID_SVXPAGE_AREA, SvxAreaTabPage::Create, 0 );

    nDlgType = 1; // Vorlagen-Dialog
    nPageType = 0;
    nPos = 0;

    nColorTableState = CT_NONE;
    nBitmapListState = CT_NONE;
    nGradientListState = CT_NONE;
    nHatchingListState = CT_NONE;

    if(!bAreaPage)  // I have to add the page before I remove it !
        RemoveTabPage( RID_SVXPAGE_AREA );
}

/*************************************************************************
|*
|* Seite wird erzeugt
|*
\************************************************************************/

void SdPageDlg::PageCreated(USHORT nId, SfxTabPage& rPage)
{
    switch(nId)
    {
    case RID_SVXPAGE_PAGE:
        ( (SvxPageDescPage&) rPage).SetMode(SVX_PAGE_MODE_PRESENTATION);
        ( (SvxPageDescPage&) rPage).SetPaperFormatRanges( SVX_PAPER_A0, SVX_PAPER_E );
        break;
    case RID_SVXPAGE_AREA:
        ( (SvxAreaTabPage&) rPage ).SetColorTable( pColorTab );
        ( (SvxAreaTabPage&) rPage ).SetGradientList( pGradientList );
        ( (SvxAreaTabPage&) rPage ).SetHatchingList( pHatchingList );
        ( (SvxAreaTabPage&) rPage ).SetBitmapList( pBitmapList );
        ( (SvxAreaTabPage&) rPage ).SetPageType( &nPageType );
        ( (SvxAreaTabPage&) rPage ).SetDlgType( &nDlgType );
        ( (SvxAreaTabPage&) rPage ).SetPos( &nPos );
        ( (SvxAreaTabPage&) rPage ).SetGrdChgd( &nGradientListState );
        ( (SvxAreaTabPage&) rPage ).SetHtchChgd( &nHatchingListState );
        ( (SvxAreaTabPage&) rPage ).SetBmpChgd( &nBitmapListState );
        ( (SvxAreaTabPage&) rPage ).SetColorChgd( &nColorTableState );
        ( (SvxAreaTabPage&) rPage ).Construct();
        break;
    }
}

<|endoftext|>


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

#pragma hdrstop

#include <tools/pstm.hxx>
#include <svx/outliner.hxx>
#include <offmgr/osplcfg.hxx>
#ifndef _OFF_APP_HXX //autogen
#include <offmgr/app.hxx>
#endif
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SVDOBJ_HXX //autogen
#include <svx/svdobj.hxx>
#endif
#ifndef _SVDOTEXT_HXX //autogen
#include <svx/svdotext.hxx>
#endif
#ifndef _COM_SUN_STAR_LINGUISTIC2_XLINGUSERVICEMANAGER_HPP_
#include <com/sun/star/linguistic2/XLinguServiceManager.hpp>
#endif

#define ITEMID_LANGUAGE         SID_ATTR_CHAR_LANGUAGE
#include <svx/dialogs.hrc>
#include <svx/svxerr.hxx>
#include <svx/dialmgr.hxx>

#ifndef _UNO_LINGU_HXX
#include <svx/unolingu.hxx>
#endif
#include <unotools/processfactory.hxx>

#include "app.hrc"
#include "strings.hrc"
#include "drawdoc.hxx"
#include "app.hxx"
#include "futhes.hxx"
#include "sdview.hxx"
#include "sdoutl.hxx"
#include "drviewsh.hxx"
#include "outlnvsh.hxx"
#include "sdwindow.hxx"
#include "sdresid.hxx"

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::linguistic2;

class SfxRequest;

TYPEINIT1( FuThesaurus, FuPoor );

/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/

FuThesaurus::FuThesaurus( SdViewShell* pViewSh, SdWindow* pWin, SdView* pView,
                  SdDrawDocument* pDoc, SfxRequest& rReq )
       : FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
    SfxErrorContext aContext(ERRCTX_SVX_LINGU_THESAURUS, String(),
                             pWin, RID_SVXERRCTX, DIALOG_MGR() );

    if ( pViewShell->ISA(SdDrawViewShell) )
    {
        SdrTextObj* pTextObj = NULL;

        if ( pView->HasMarkedObj() )
        {
            const SdrMarkList& rMarkList = pView->GetMarkList();

            if ( rMarkList.GetMarkCount() == 1 )
            {
                SdrMark* pMark = rMarkList.GetMark(0);
                SdrObject* pObj = pMark->GetObj();

                if ( pObj->ISA(SdrTextObj) )
                {
                    pTextObj = (SdrTextObj*) pObj;
                }
            }
        }

        Outliner* pOutliner = pView->GetTextEditOutliner();
        const OutlinerView* pOutlView = pView->GetTextEditOutlinerView();

        if ( pTextObj && pOutliner && pOutlView )
        {
            if ( !pOutliner->GetSpeller().is() )
            {
                Reference< XMultiServiceFactory > xMgr( ::utl::getProcessServiceFactory() );
                Reference< XLinguServiceManager > xLinguServiceManager( xMgr->createInstance(
                    OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.linguistic2.LinguServiceManager" ))),
                                                                    uno::UNO_QUERY );

                if ( xLinguServiceManager.is() )
                {
                    Reference< XSpellChecker1 > xSpellChecker( xLinguServiceManager->getSpellChecker(), UNO_QUERY );
                    if ( xSpellChecker.is() )
                        pOutliner->SetSpeller( xSpellChecker );

                    Reference< XHyphenator > xHyphenator( xLinguServiceManager->getHyphenator(), UNO_QUERY );
                    if( xHyphenator.is() )
                        pOutliner->SetHyphenator( xHyphenator );
                }

                pOutliner->SetDefaultLanguage( pDoc->GetLanguage() );
            }

            EESpellState eState = ( (OutlinerView*) pOutlView)
                                  ->StartThesaurus( pDoc->GetLanguage() );

            DBG_ASSERT(eState != EE_SPELL_NOSPELLER, "No SpellChecker");

            if (eState == EE_SPELL_NOLANGUAGE)
            {
                ErrorBox(pWindow, WB_OK, String(SdResId(STR_NOLANGUAGE))).Execute();
            }
        }
    }
    else if ( pViewShell->ISA(SdOutlineViewShell) )
    {
        Outliner* pOutliner = pDoc->GetOutliner();
        OutlinerView* pOutlView = pOutliner->GetView(0);

        if ( !pOutliner->GetSpeller().is() )
        {
            Reference< XMultiServiceFactory > xMgr( ::utl::getProcessServiceFactory() );
            Reference< XLinguServiceManager > xLinguServiceManager( xMgr->createInstance(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.linguistic2.LinguServiceManager" ))),
                                                                uno::UNO_QUERY );

            if ( xLinguServiceManager.is() )
            {
                Reference< XSpellChecker1 > xSpellChecker( xLinguServiceManager->getSpellChecker(), UNO_QUERY );
                if ( xSpellChecker.is() )
                    pOutliner->SetSpeller( xSpellChecker );

                Reference< XHyphenator1 > xHyphenator( xLinguServiceManager->getHyphenator(), UNO_QUERY );
                if( xHyphenator.is() )
                    pOutliner->SetHyphenator( xHyphenator );
            }

            pOutliner->SetDefaultLanguage( pDoc->GetLanguage() );
        }

        EESpellState eState = pOutlView->StartThesaurus( pDoc->GetLanguage() );

        DBG_ASSERT(eState != EE_SPELL_NOSPELLER, "No SpellChecker");

        if (eState == EE_SPELL_NOLANGUAGE)
        {
            ErrorBox(pWindow, WB_OK, String(SdResId(STR_NOLANGUAGE))).Execute();
        }
    }
}

/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/
FuThesaurus::~FuThesaurus()
{
}

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

#pragma hdrstop

#include <tools/pstm.hxx>
#include <svx/outliner.hxx>
#include <offmgr/osplcfg.hxx>
#ifndef _OFF_APP_HXX //autogen
#include <offmgr/app.hxx>
#endif
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SVDOBJ_HXX //autogen
#include <svx/svdobj.hxx>
#endif
#ifndef _SVDOTEXT_HXX //autogen
#include <svx/svdotext.hxx>
#endif
#ifndef _COM_SUN_STAR_LINGUISTIC2_XLINGUSERVICEMANAGER_HPP_
#include <com/sun/star/linguistic2/XLinguServiceManager.hpp>
#endif

#define ITEMID_LANGUAGE         SID_ATTR_CHAR_LANGUAGE
#include <svx/dialogs.hrc>
#include <svx/svxerr.hxx>
#include <svx/dialmgr.hxx>

#ifndef _UNO_LINGU_HXX
#include <svx/unolingu.hxx>
#endif
#include <unotools/processfactory.hxx>

#include "app.hrc"
#include "strings.hrc"
#include "drawdoc.hxx"
#include "app.hxx"
#include "futhes.hxx"
#include "sdview.hxx"
#include "sdoutl.hxx"
#include "drviewsh.hxx"
#include "outlnvsh.hxx"
#include "sdwindow.hxx"
#include "sdresid.hxx"

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::linguistic2;

class SfxRequest;

TYPEINIT1( FuThesaurus, FuPoor );

/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/

FuThesaurus::FuThesaurus( SdViewShell* pViewSh, SdWindow* pWin, SdView* pView,
                  SdDrawDocument* pDoc, SfxRequest& rReq )
       : FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
    SfxErrorContext aContext(ERRCTX_SVX_LINGU_THESAURUS, String(),
                             pWin, RID_SVXERRCTX, DIALOG_MGR() );

    if ( pViewShell->ISA(SdDrawViewShell) )
    {
        SdrTextObj* pTextObj = NULL;

        if ( pView->HasMarkedObj() )
        {
            const SdrMarkList& rMarkList = pView->GetMarkList();

            if ( rMarkList.GetMarkCount() == 1 )
            {
                SdrMark* pMark = rMarkList.GetMark(0);
                SdrObject* pObj = pMark->GetObj();

                if ( pObj->ISA(SdrTextObj) )
                {
                    pTextObj = (SdrTextObj*) pObj;
                }
            }
        }

        Outliner* pOutliner = pView->GetTextEditOutliner();
        const OutlinerView* pOutlView = pView->GetTextEditOutlinerView();

        if ( pTextObj && pOutliner && pOutlView )
        {
            if ( !pOutliner->GetSpeller().is() )
            {
                Reference< XMultiServiceFactory > xMgr( ::utl::getProcessServiceFactory() );
                Reference< XLinguServiceManager > xLinguServiceManager( xMgr->createInstance(
                    OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.linguistic2.LinguServiceManager" ))),
                                                                    uno::UNO_QUERY );

                if ( xLinguServiceManager.is() )
                {
                    Reference< XSpellChecker1 > xSpellChecker( xLinguServiceManager->getSpellChecker(), UNO_QUERY );
                    if ( xSpellChecker.is() )
                        pOutliner->SetSpeller( xSpellChecker );

                    Reference< XHyphenator > xHyphenator( xLinguServiceManager->getHyphenator(), UNO_QUERY );
                    if( xHyphenator.is() )
                        pOutliner->SetHyphenator( xHyphenator );
                }

                pOutliner->SetDefaultLanguage( pDoc->GetLanguage() );
            }

            EESpellState eState = ( (OutlinerView*) pOutlView)
                                  ->StartThesaurus( pDoc->GetLanguage() );

            DBG_ASSERT(eState != EE_SPELL_NOSPELLER, "No SpellChecker");

            if (eState == EE_SPELL_NOLANGUAGE)
            {
                ErrorBox(pWindow, WB_OK, String(SdResId(STR_NOLANGUAGE))).Execute();
            }
        }
    }
    else if ( pViewShell->ISA(SdOutlineViewShell) )
    {
        Outliner* pOutliner = pDoc->GetOutliner();
        OutlinerView* pOutlView = pOutliner->GetView(0);

        if ( !pOutliner->GetSpeller().is() )
        {
            Reference< XMultiServiceFactory > xMgr( ::utl::getProcessServiceFactory() );
            Reference< XLinguServiceManager > xLinguServiceManager( xMgr->createInstance(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.linguistic2.LinguServiceManager" ))),
                                                                uno::UNO_QUERY );

            if ( xLinguServiceManager.is() )
            {
                Reference< XSpellChecker1 > xSpellChecker( xLinguServiceManager->getSpellChecker(), UNO_QUERY );
                if ( xSpellChecker.is() )
                    pOutliner->SetSpeller( xSpellChecker );

                Reference< XHyphenator > xHyphenator( xLinguServiceManager->getHyphenator(), UNO_QUERY );
                if( xHyphenator.is() )
                    pOutliner->SetHyphenator( xHyphenator );
            }

            pOutliner->SetDefaultLanguage( pDoc->GetLanguage() );
        }

        EESpellState eState = pOutlView->StartThesaurus( pDoc->GetLanguage() );

        DBG_ASSERT(eState != EE_SPELL_NOSPELLER, "No SpellChecker");

        if (eState == EE_SPELL_NOLANGUAGE)
        {
            ErrorBox(pWindow, WB_OK, String(SdResId(STR_NOLANGUAGE))).Execute();
        }
    }
}

/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/
FuThesaurus::~FuThesaurus()
{
}

<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <limits>
#include <stdexcept>
#include <math.h>
#include "supercubic.h"

using namespace std;

Supercubic::Supercubic():dimen(0),n(nullptr),L(0) {}

Supercubic::Supercubic(int Dc, const int* Nc)
{
    dimen=Dc;
    n=new int[dimen]; std::copy(Nc,Nc+dimen,n);
    L=1; for(int i=0; i<dimen; i++) L*=n[i];
}

Supercubic::Supercubic(string filename)
{
    n=nullptr;  //We first initial n, since read_param function assume n is either nullptr or allocated.
    read_param(filename); //read dimen and *n, allocate n
    L=1; for(int i=0; i<dimen; i++) L*=n[i];
}

Supercubic::Supercubic(const Supercubic& x)
{
    dimen=x.dimen;L=x.L;
    n=new int[dimen]; std::copy(x.n,x.n+dimen,n);
}

Supercubic::Supercubic(Supercubic&& x)
{
    dimen=x.dimen;L=x.L;
    n=x.n; x.n=nullptr;
}

Supercubic::~Supercubic() {if(n) delete[] n;}

Supercubic& Supercubic::operator  = (const Supercubic& x)
{
    dimen=x.dimen;L=x.L;
    if(n) delete[] n; n=new int[dimen]; std::copy(x.n,x.n+dimen,n);
    return *this;
}

Supercubic& Supercubic::operator  = (Supercubic&& x)
{
    dimen=x.dimen;L=x.L;
    int* ntmp=n; n=x.n; x.n=ntmp; //swap
    return *this;
}

vector<int> Supercubic::coor(int lattice_index) const
{
    vector<int> coordinate(dimen); int den=L;
    for(int i=dimen-1; i>=0; i--)
    {
        den/=n[i];
        coordinate[i]=lattice_index/den;
        lattice_index%=den;
    }
    return coordinate;
}

int Supercubic::index(const vector<int>& lattice_coor) const
{
    int size=lattice_coor.size();
    if(size!=dimen)
    {
        std::cout<<"Input for index in Supercubic error! Size of lattice_coor !=dimen \n";
        exit(1);
    }

    int lattice_index=0; int den=1;
    for(int i=0; i<dimen; i++)
    {
        lattice_index+=(lattice_coor[i]*den);
        den*=n[i];
    }
    return lattice_index;
}

int Supercubic::bound(const int i, const int i_max) const
{
    int i_bound = (i>=0) ? i%i_max : i%i_max+i_max;
    if(i_bound==i_max) i_bound=0;
    return i_bound;
}

//return coor_j-coor_i
vector<int> Supercubic::coor_relat(const vector<int>& coor_i, const vector<int>& coor_j) const
{
    int size_i=coor_i.size(); int size_j=coor_j.size();
    if(size_i!=dimen||size_j!=dimen)
    {
        std::cout<<"Input for coor_relat in Supercubic error! Size of coor_i or coor_j !=dimen \n";
        exit(1);
    }

    vector<int> dist(dimen);
    for(int i=0; i<dimen; i++) dist[i]=this->bound(coor_j[i]-coor_i[i], n[i]);
    return dist;
}

//return the inverse point of lattice_index with zero point
int Supercubic::inverse(int lattice_index) const
{
    vector<int> coordinate=this->coor(lattice_index);
    for(int i=0; i<dimen; i++) coordinate[i]=this->bound(-coordinate[i],n[i]);
    return this->index(coordinate);
}

//Read the parameters from "filename"
//Read dimen and *n, allocate n
void Supercubic::read_param(string filename)
{
    int rank=0;
#ifdef MPI_HAO
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
#endif

    if(rank==0)
    {
       ifstream latt_file;
       latt_file.open(filename, ios::in);
       if ( ! latt_file.is_open() ) {cout << "Error opening file!!!"; exit(1);}
       latt_file>>dimen; latt_file.ignore(numeric_limits<streamsize>::max(),'\n');
       if(n) delete[] n; n=new int[dimen];
       for(int i=0; i<dimen; i++) {latt_file>>n[i];} latt_file.ignore(numeric_limits<streamsize>::max(),'\n');
       latt_file.close();
    }

#ifdef MPI_HAO
    MPI_Bcast(&dimen, 1, MPI_INT, 0, MPI_COMM_WORLD);
    if(rank!=0) { if(n) delete[] n; n=new int[dimen]; }
    MPI_Bcast(n, dimen, MPI_INT, 0, MPI_COMM_WORLD);
    MPI_Barrier(MPI_COMM_WORLD);
#endif
}
<commit_msg>Remove latt_file.ignore(numeric_limits<streamsize>::max(),'\n').<commit_after>#include <iostream>
#include <fstream>
#include <limits>
#include <stdexcept>
#include <math.h>
#include "supercubic.h"

using namespace std;

Supercubic::Supercubic():dimen(0),n(nullptr),L(0) {}

Supercubic::Supercubic(int Dc, const int* Nc)
{
    dimen=Dc;
    n=new int[dimen]; std::copy(Nc,Nc+dimen,n);
    L=1; for(int i=0; i<dimen; i++) L*=n[i];
}

Supercubic::Supercubic(string filename)
{
    n=nullptr;  //We first initial n, since read_param function assume n is either nullptr or allocated.
    read_param(filename); //read dimen and *n, allocate n
    L=1; for(int i=0; i<dimen; i++) L*=n[i];
}

Supercubic::Supercubic(const Supercubic& x)
{
    dimen=x.dimen;L=x.L;
    n=new int[dimen]; std::copy(x.n,x.n+dimen,n);
}

Supercubic::Supercubic(Supercubic&& x)
{
    dimen=x.dimen;L=x.L;
    n=x.n; x.n=nullptr;
}

Supercubic::~Supercubic() {if(n) delete[] n;}

Supercubic& Supercubic::operator  = (const Supercubic& x)
{
    dimen=x.dimen;L=x.L;
    if(n) delete[] n; n=new int[dimen]; std::copy(x.n,x.n+dimen,n);
    return *this;
}

Supercubic& Supercubic::operator  = (Supercubic&& x)
{
    dimen=x.dimen;L=x.L;
    int* ntmp=n; n=x.n; x.n=ntmp; //swap
    return *this;
}

vector<int> Supercubic::coor(int lattice_index) const
{
    vector<int> coordinate(dimen); int den=L;
    for(int i=dimen-1; i>=0; i--)
    {
        den/=n[i];
        coordinate[i]=lattice_index/den;
        lattice_index%=den;
    }
    return coordinate;
}

int Supercubic::index(const vector<int>& lattice_coor) const
{
    int size=lattice_coor.size();
    if(size!=dimen)
    {
        std::cout<<"Input for index in Supercubic error! Size of lattice_coor !=dimen \n";
        exit(1);
    }

    int lattice_index=0; int den=1;
    for(int i=0; i<dimen; i++)
    {
        lattice_index+=(lattice_coor[i]*den);
        den*=n[i];
    }
    return lattice_index;
}

int Supercubic::bound(const int i, const int i_max) const
{
    int i_bound = (i>=0) ? i%i_max : i%i_max+i_max;
    if(i_bound==i_max) i_bound=0;
    return i_bound;
}

//return coor_j-coor_i
vector<int> Supercubic::coor_relat(const vector<int>& coor_i, const vector<int>& coor_j) const
{
    int size_i=coor_i.size(); int size_j=coor_j.size();
    if(size_i!=dimen||size_j!=dimen)
    {
        std::cout<<"Input for coor_relat in Supercubic error! Size of coor_i or coor_j !=dimen \n";
        exit(1);
    }

    vector<int> dist(dimen);
    for(int i=0; i<dimen; i++) dist[i]=this->bound(coor_j[i]-coor_i[i], n[i]);
    return dist;
}

//return the inverse point of lattice_index with zero point
int Supercubic::inverse(int lattice_index) const
{
    vector<int> coordinate=this->coor(lattice_index);
    for(int i=0; i<dimen; i++) coordinate[i]=this->bound(-coordinate[i],n[i]);
    return this->index(coordinate);
}

//Read the parameters from "filename"
//Read dimen and *n, allocate n
void Supercubic::read_param(string filename)
{
    int rank=0;
#ifdef MPI_HAO
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
#endif

    if(rank==0)
    {
       ifstream latt_file;
       latt_file.open(filename, ios::in);
       if ( ! latt_file.is_open() ) {cout << "Error opening file!!!"; exit(1);}
       latt_file>>dimen;  //latt_file.ignore(numeric_limits<streamsize>::max(),'\n');
       if(n) delete[] n; n=new int[dimen];
       for(int i=0; i<dimen; i++) latt_file>>n[i];;
       latt_file.close();
    }

#ifdef MPI_HAO
    MPI_Bcast(&dimen, 1, MPI_INT, 0, MPI_COMM_WORLD);
    if(rank!=0) { if(n) delete[] n; n=new int[dimen]; }
    MPI_Bcast(n, dimen, MPI_INT, 0, MPI_COMM_WORLD);
    MPI_Barrier(MPI_COMM_WORLD);
#endif
}
<|endoftext|>


<commit_before>#include "WProgram.h"

#define encoderPinA 4
#define encoderPinB 6
#define encoderOutputI 5

int counter=0;
int stateA;
int stateB;
int lastStateA=LOW;
int lastStateB=LOW;

void loopTest();

int main()
{
init();
pinMode(encoderPinA,INPUT);
pinMode(encoderPinB,INPUT);
loopTest();
return 0;
}

void loopTest()
{
while(true)
{
stateA=digitalRead(encoderPinA);
stateB=digitalRead(encoderPinB);
if(stateA=!lastStateA && encoderPinB!=lastStateB)
{
counter++;
lastStateA=stateA;
lastStateB=stateB;
}

printf("%d\n",counter);
}
}
<commit_msg>Added freaking tabs<commit_after>#include "WProgram.h"

#define encoderPinA 4
#define encoderPinB 6
#define encoderOutputI 5

int counter=0;
int stateA;
int stateB;
int lastStateA=LOW;
int lastStateB=LOW;

void loopTest();

int main()
{
	init();
	pinMode(encoderPinA,INPUT);
	pinMode(encoderPinB,INPUT);
	loopTest();
	return 0;
}

void loopTest()
{
	while(true)
	{
		stateA=digitalRead(encoderPinA);
		stateB=digitalRead(encoderPinB);
		if(stateA=!lastStateA && encoderPinB!=lastStateB)
		{
			counter++;
			lastStateA=stateA;
			lastStateB=stateB;
		}

		printf("%d\n",counter);
	}
}
<|endoftext|>


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

#include "lcds.h"
#include "bitop.h"

#include <util/delay.h>
#include <avr/pgmspace.h>

avr_cpp_lib::LCDS::LCDS(OutputPin rs, OutputPin e, OutputPin d4, OutputPin d5, OutputPin d6, OutputPin d7)
	: rs(rs), e(e), d4(d4), d5(d5), d6(d6), d7(d7) {
	d7.clear();
	d6.clear();
	d5.set();
	d4.set();
	rs.clear();

	// one (8 bit mode)
	enableToggle();

	// two (8 bit mode)
	enableToggle();

	// three (4 bit mode)
	d4.clear();
	enableToggle();

	// dual line, 4 bit mode
	command(0b00101000);

	// turn display on, cursor off
	command(DISPLAY_ON);
}

void avr_cpp_lib::LCDS::enableToggle() {
	e.set();
	_delay_ms(1);
	e.clear();
	_delay_ms(1);
}

void avr_cpp_lib::LCDS::command(uint8_t c) {
	rs.clear();
	send(c);
	_delay_ms(2);
}

void avr_cpp_lib::LCDS::character(uint8_t c) {
	rs.set();
	send(c);
}

void avr_cpp_lib::LCDS::send(uint8_t c) {
	if (BITSET(c, 7)) {
		d7.set();
	} else {
		d7.clear();
	}
	if (BITSET(c, 6)) {
		d6.set();
	} else {
		d6.clear();
	}
	if (BITSET(c, 5)) {
		d5.set();
	} else {
		d5.clear();
	}
	if (BITSET(c, 4)) {
		d4.set();
	} else {
		d4.clear();
	}
	enableToggle();
	if (BITSET(c, 3)) {
		d7.set();
	} else {
		d7.clear();
	}
	if (BITSET(c, 2)) {
		d6.set();
	} else {
		d6.clear();
	}
	if (BITSET(c, 1)) {
		d5.set();
	} else {
		d5.clear();
	}
	if (BITSET(c, 0)) {
		d4.set();
	} else {
		d4.clear();
	}
	enableToggle();
}

void avr_cpp_lib::LCDS::gotoXY(uint8_t x, uint8_t y) {
	uint8_t tmp;
	switch (y) {
	case 0:
		tmp = x;
		break;
	case 1:
		tmp = 0x40 + x;
		break;
	case 2:
		tmp = 0x14 + x;
		break;
	default:
		tmp = 0x54 + x;
	}
	command(1<<7 | tmp);
}

void avr_cpp_lib::LCDS::write(uint32_t i, uint8_t l, uint8_t m) {
	char buf[l + 1];
	buf[l] = '\0';
	for (; l > 0; l--) {
		uint8_t c = i % m;
		if (c < 10) {
			buf[l-1] = 0x30 + c;
		} else {
			buf[l-1] = 0x41 + c - 10;
		}
		i = i / m;
	}
	write(buf);
}

void avr_cpp_lib::LCDS::write(const char * s) {
	while (*s != '\0') {
		character(*s);
		s++;
	}
}

void avr_cpp_lib::LCDS::writeFlash(const char * s) {
	uint8_t c = pgm_read_byte(s);
	while (c != '\0') {
		character(c);
		s++;
		c = pgm_read_byte(s);
	}
}
<commit_msg>Some more pause and additional clear<commit_after>/* File: lcds.cpp
 * Synchronous lcd hd44780 interface.
 */
/* Copyright (c) 2012-2013 Domen Ipavec (domen.ipavec@z-v.si)
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation files
 * (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge,
 * publish, distribute, sublicense, and/or sell copies of the Software,
 * and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include "lcds.h"
#include "bitop.h"

#include <util/delay.h>
#include <avr/pgmspace.h>

avr_cpp_lib::LCDS::LCDS(OutputPin rs, OutputPin e, OutputPin d4, OutputPin d5, OutputPin d6, OutputPin d7)
	: rs(rs), e(e), d4(d4), d5(d5), d6(d6), d7(d7) {
	d7.clear();
	d6.clear();
	d5.set();
	d4.set();
	rs.clear();

	// one (8 bit mode)
	enableToggle();

	// two (8 bit mode)
	enableToggle();

	// three (4 bit mode)
	d4.clear();
	enableToggle();

	// dual line, 4 bit mode
	command(0b00101000);

	// turn display on, cursor off
	command(DISPLAY_ON);

	// clear display
	command(CLEAR);
}

void avr_cpp_lib::LCDS::enableToggle() {
	e.set();
	_delay_ms(1);
	e.clear();
	_delay_ms(1);
}

void avr_cpp_lib::LCDS::command(uint8_t c) {
	rs.clear();
	send(c);
	_delay_ms(5);
}

void avr_cpp_lib::LCDS::character(uint8_t c) {
	rs.set();
	send(c);
}

void avr_cpp_lib::LCDS::send(uint8_t c) {
	if (BITSET(c, 7)) {
		d7.set();
	} else {
		d7.clear();
	}
	if (BITSET(c, 6)) {
		d6.set();
	} else {
		d6.clear();
	}
	if (BITSET(c, 5)) {
		d5.set();
	} else {
		d5.clear();
	}
	if (BITSET(c, 4)) {
		d4.set();
	} else {
		d4.clear();
	}
	enableToggle();
	if (BITSET(c, 3)) {
		d7.set();
	} else {
		d7.clear();
	}
	if (BITSET(c, 2)) {
		d6.set();
	} else {
		d6.clear();
	}
	if (BITSET(c, 1)) {
		d5.set();
	} else {
		d5.clear();
	}
	if (BITSET(c, 0)) {
		d4.set();
	} else {
		d4.clear();
	}
	enableToggle();
}

void avr_cpp_lib::LCDS::gotoXY(uint8_t x, uint8_t y) {
	uint8_t tmp;
	switch (y) {
	case 0:
		tmp = x;
		break;
	case 1:
		tmp = 0x40 + x;
		break;
	case 2:
		tmp = 0x14 + x;
		break;
	default:
		tmp = 0x54 + x;
	}
	command(1<<7 | tmp);
}

void avr_cpp_lib::LCDS::write(uint32_t i, uint8_t l, uint8_t m) {
	char buf[l + 1];
	buf[l] = '\0';
	for (; l > 0; l--) {
		uint8_t c = i % m;
		if (c < 10) {
			buf[l-1] = 0x30 + c;
		} else {
			buf[l-1] = 0x41 + c - 10;
		}
		i = i / m;
	}
	write(buf);
}

void avr_cpp_lib::LCDS::write(const char * s) {
	while (*s != '\0') {
		character(*s);
		s++;
	}
}

void avr_cpp_lib::LCDS::writeFlash(const char * s) {
	uint8_t c = pgm_read_byte(s);
	while (c != '\0') {
		character(c);
		s++;
		c = pgm_read_byte(s);
	}
}
<|endoftext|>