<commit_before>#include "tests-base.hpp"

#include "../helpers/helpers-locale.hpp"
#include "../helpers/helpers-strings.hpp"

class Utf8ToTitleTurkish
	: public ::testing::Test
{

protected:

	void SetUp()
	{
		SET_LOCALE_TURKISH();
	}

	void TearDown()
	{
		RESET_LOCALE();
	}

};

TEST_F(Utf8ToTitleTurkish, SingleCapitalLetterI)
{
	// 0049
	// 0049

	const char* c = "I";
	const size_t s = 256;
	char b[s] = { 0 };
	int32_t errors = UTF8_ERR_NONE;

	EXPECT_EQ(1, utf8totitle(c, strlen(c), b, s - 1, &errors));
	EXPECT_UTF8EQ("I", b);
	EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}

TEST_F(Utf8ToTitleTurkish, SingleCapitalLetterIAndDotAbove)
{
	// 0049 0307
	// 0049 0307

	const char* c = "I\xCC\x87";
	const size_t s = 256;
	char b[s] = { 0 };
	int32_t errors = UTF8_ERR_NONE;

	EXPECT_EQ(3, utf8totitle(c, strlen(c), b, s - 1, &errors));
	EXPECT_UTF8EQ("I\xCC\x87", b);
	EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}

TEST_F(Utf8ToTitleTurkish, SingleCapitalLetterIWithDotAbove)
{
	// 0130
	// 0130

	const char* c = "\xC4\xB0";
	const size_t s = 256;
	char b[s] = { 0 };
	int32_t errors = UTF8_ERR_NONE;

	EXPECT_EQ(2, utf8totitle(c, strlen(c), b, s - 1, &errors));
	EXPECT_UTF8EQ("\xC4\xB0", b);
	EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}

TEST_F(Utf8ToTitleTurkish, SingleCapitalLetterIWithDotAboveAndDotAbove)
{
	// 0130 0307
	// 0130 0307

	const char* c = "\xC4\xB0\xCC\x87";
	const size_t s = 256;
	char b[s] = { 0 };
	int32_t errors = UTF8_ERR_NONE;

	EXPECT_EQ(4, utf8totitle(c, strlen(c), b, s - 1, &errors));
	EXPECT_UTF8EQ("\xC4\xB0\xCC\x87", b);
	EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}

TEST_F(Utf8ToTitleTurkish, SingleSmallLetterI)
{
	// 0069
	// 0130

	const char* c = "i";
	const size_t s = 256;
	char b[s] = { 0 };
	int32_t errors = UTF8_ERR_NONE;

	EXPECT_EQ(2, utf8totitle(c, strlen(c), b, s - 1, &errors));
	EXPECT_UTF8EQ("\xC4\xB0", b);
	EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}

TEST_F(Utf8ToTitleTurkish, SingleSmallLetterIWithDotAbove)
{
	// 0069 0307
	// 0130 0307

	const char* c = "i\xCC\x87";
	const size_t s = 256;
	char b[s] = { 0 };
	int32_t errors = UTF8_ERR_NONE;

	EXPECT_EQ(4, utf8totitle(c, strlen(c), b, s - 1, &errors));
	EXPECT_UTF8EQ("\xC4\xB0\xCC\x87", b);
	EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}

TEST_F(Utf8ToTitleTurkish, SingleSmallLetterDotlessI)
{
	// 0131
	// 0049

	const char* c = "\xC4\xB1";
	const size_t s = 256;
	char b[s] = { 0 };
	int32_t errors = UTF8_ERR_NONE;

	EXPECT_EQ(1, utf8totitle(c, strlen(c), b, s - 1, &errors));
	EXPECT_UTF8EQ("I", b);
	EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}

TEST_F(Utf8ToTitleTurkish, SingleSmallLetterDotlessIWithDotAbove)
{
	// 0131 0307
	// 0049 0307

	const char* c = "\xC4\xB1\xCC\x87";
	const size_t s = 256;
	char b[s] = { 0 };
	int32_t errors = UTF8_ERR_NONE;

	EXPECT_EQ(3, utf8totitle(c, strlen(c), b, s - 1, &errors));
	EXPECT_UTF8EQ("I\xCC\x87", b);
	EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}

TEST_F(Utf8ToTitleTurkish, WordCapitalLetterI)
{
	const char* c = "Imagine";
	const size_t s = 256;
	char b[s] = { 0 };
	int32_t errors = UTF8_ERR_NONE;

	EXPECT_EQ(7, utf8totitle(c, strlen(c), b, s - 1, &errors));
	EXPECT_UTF8EQ("Imagine", b);
	EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}<commit_msg>Add red tests for Turkish titlecase case mapping.<commit_after>#include "tests-base.hpp"

#include "../helpers/helpers-locale.hpp"
#include "../helpers/helpers-strings.hpp"

class Utf8ToTitleTurkish
	: public ::testing::Test
{

protected:

	void SetUp()
	{
		SET_LOCALE_TURKISH();
	}

	void TearDown()
	{
		RESET_LOCALE();
	}

};

TEST_F(Utf8ToTitleTurkish, SingleCapitalLetterI)
{
	// 0049
	// 0049

	const char* c = "I";
	const size_t s = 255;
	char b[256] = { 0 };
	int32_t errors = UTF8_ERR_NONE;

	EXPECT_EQ(1, utf8totitle(c, strlen(c), b, s, &errors));
	EXPECT_UTF8EQ("I", b);
	EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}

TEST_F(Utf8ToTitleTurkish, SingleCapitalLetterINotEnoughSpace)
{
	const char* c = "I";
	const size_t s = 0;
	char b[256] = { 0 };
	int32_t errors = UTF8_ERR_NONE;

	EXPECT_EQ(0, utf8totitle(c, strlen(c), b, s, &errors));
	EXPECT_UTF8EQ("", b);
	EXPECT_ERROREQ(UTF8_ERR_NOT_ENOUGH_SPACE, errors);
}

TEST_F(Utf8ToTitleTurkish, SingleCapitalLetterIAmountOfBytes)
{
	const char* c = "I";
	int32_t errors = UTF8_ERR_NONE;

	EXPECT_EQ(1, utf8totitle(c, strlen(c), nullptr, 0, &errors));
	EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}

TEST_F(Utf8ToTitleTurkish, SingleCapitalLetterIAndDotAbove)
{
	// 0049 0307
	// 0049 0307

	const char* c = "I\xCC\x87";
	const size_t s = 255;
	char b[256] = { 0 };
	int32_t errors = UTF8_ERR_NONE;

	EXPECT_EQ(3, utf8totitle(c, strlen(c), b, s, &errors));
	EXPECT_UTF8EQ("I\xCC\x87", b);
	EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}

TEST_F(Utf8ToTitleTurkish, SingleCapitalLetterIAndDotAboveNotEnoughSpace)
{
	const char* c = "I\xCC\x87";
	const size_t s = 2;
	char b[256] = { 0 };
	int32_t errors = UTF8_ERR_NONE;

	EXPECT_EQ(1, utf8totitle(c, strlen(c), b, s, &errors));
	EXPECT_UTF8EQ("I", b);
	EXPECT_ERROREQ(UTF8_ERR_NOT_ENOUGH_SPACE, errors);
}

TEST_F(Utf8ToTitleTurkish, SingleCapitalLetterIAndDotAboveAmountOfBytes)
{
	const char* c = "I\xCC\x87";
	int32_t errors = UTF8_ERR_NONE;

	EXPECT_EQ(3, utf8totitle(c, strlen(c), nullptr, 0, &errors));
	EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}

TEST_F(Utf8ToTitleTurkish, SingleCapitalLetterIWithDotAbove)
{
	// 0130
	// 0130

	const char* c = "\xC4\xB0";
	const size_t s = 255;
	char b[256] = { 0 };
	int32_t errors = UTF8_ERR_NONE;

	EXPECT_EQ(2, utf8totitle(c, strlen(c), b, s, &errors));
	EXPECT_UTF8EQ("\xC4\xB0", b);
	EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}

TEST_F(Utf8ToTitleTurkish, SingleCapitalLetterIWithDotAboveNotEnoughSpace)
{
	const char* c = "\xC4\xB0";
	const size_t s = 1;
	char b[256] = { 0 };
	int32_t errors = UTF8_ERR_NONE;

	EXPECT_EQ(0, utf8totitle(c, strlen(c), b, s, &errors));
	EXPECT_UTF8EQ("", b);
	EXPECT_ERROREQ(UTF8_ERR_NOT_ENOUGH_SPACE, errors);
}

TEST_F(Utf8ToTitleTurkish, SingleCapitalLetterIWithDotAboveAmountOfBytes)
{
	const char* c = "\xC4\xB0";
	int32_t errors = UTF8_ERR_NONE;

	EXPECT_EQ(2, utf8totitle(c, strlen(c), nullptr, 0, &errors));
	EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}

TEST_F(Utf8ToTitleTurkish, SingleCapitalLetterIWithDotAboveAndDotAbove)
{
	// 0130 0307
	// 0130 0307

	const char* c = "\xC4\xB0\xCC\x87";
	const size_t s = 255;
	char b[256] = { 0 };
	int32_t errors = UTF8_ERR_NONE;

	EXPECT_EQ(4, utf8totitle(c, strlen(c), b, s, &errors));
	EXPECT_UTF8EQ("\xC4\xB0\xCC\x87", b);
	EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}

TEST_F(Utf8ToTitleTurkish, SingleCapitalLetterIWithDotAboveAndDotAboveNotEnoughSpace)
{
	const char* c = "\xC4\xB0\xCC\x87";
	const size_t s = 3;
	char b[256] = { 0 };
	int32_t errors = UTF8_ERR_NONE;

	EXPECT_EQ(2, utf8totitle(c, strlen(c), b, s, &errors));
	EXPECT_UTF8EQ("\xC4\xB0", b);
	EXPECT_ERROREQ(UTF8_ERR_NOT_ENOUGH_SPACE, errors);
}

TEST_F(Utf8ToTitleTurkish, SingleCapitalLetterIWithDotAboveAndDotAboveAmountOfBytes)
{
	const char* c = "\xC4\xB0\xCC\x87";
	int32_t errors = UTF8_ERR_NONE;

	EXPECT_EQ(4, utf8totitle(c, strlen(c), nullptr, 0, &errors));
	EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}

TEST_F(Utf8ToTitleTurkish, SingleSmallLetterI)
{
	// 0069
	// 0130

	const char* c = "i";
	const size_t s = 255;
	char b[256] = { 0 };
	int32_t errors = UTF8_ERR_NONE;

	EXPECT_EQ(2, utf8totitle(c, strlen(c), b, s, &errors));
	EXPECT_UTF8EQ("\xC4\xB0", b);
	EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}

TEST_F(Utf8ToTitleTurkish, SingleSmallLetterINotEnoughSpace)
{
	const char* c = "i";
	const size_t s = 0;
	char b[256] = { 0 };
	int32_t errors = UTF8_ERR_NONE;

	EXPECT_EQ(0, utf8totitle(c, strlen(c), b, s, &errors));
	EXPECT_UTF8EQ("", b);
	EXPECT_ERROREQ(UTF8_ERR_NOT_ENOUGH_SPACE, errors);
}

TEST_F(Utf8ToTitleTurkish, SingleSmallLetterIAmountOfBytes)
{
	const char* c = "i";
	int32_t errors = UTF8_ERR_NONE;

	EXPECT_EQ(2, utf8totitle(c, strlen(c), nullptr, 0, &errors));
	EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}

TEST_F(Utf8ToTitleTurkish, SingleSmallLetterIWithDotAbove)
{
	// 0069 0307
	// 0130 0307

	const char* c = "i\xCC\x87";
	const size_t s = 255;
	char b[256] = { 0 };
	int32_t errors = UTF8_ERR_NONE;

	EXPECT_EQ(4, utf8totitle(c, strlen(c), b, s, &errors));
	EXPECT_UTF8EQ("\xC4\xB0\xCC\x87", b);
	EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}

TEST_F(Utf8ToTitleTurkish, SingleSmallLetterIWithDotAboveNotEnoughSpace)
{
	const char* c = "i\xCC\x87";
	const size_t s = 2;
	char b[256] = { 0 };
	int32_t errors = UTF8_ERR_NONE;

	EXPECT_EQ(2, utf8totitle(c, strlen(c), b, s, &errors));
	EXPECT_UTF8EQ("\xC4\xB0", b);
	EXPECT_ERROREQ(UTF8_ERR_NOT_ENOUGH_SPACE, errors);
}

TEST_F(Utf8ToTitleTurkish, SingleSmallLetterIWithDotAboveAmountOfBytes)
{
	const char* c = "i\xCC\x87";
	int32_t errors = UTF8_ERR_NONE;

	EXPECT_EQ(4, utf8totitle(c, strlen(c), nullptr, 0, &errors));
	EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}

TEST_F(Utf8ToTitleTurkish, SingleSmallLetterDotlessI)
{
	// 0131
	// 0049

	const char* c = "\xC4\xB1";
	const size_t s = 255;
	char b[256] = { 0 };
	int32_t errors = UTF8_ERR_NONE;

	EXPECT_EQ(1, utf8totitle(c, strlen(c), b, s, &errors));
	EXPECT_UTF8EQ("I", b);
	EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}

TEST_F(Utf8ToTitleTurkish, SingleSmallLetterDotlessINotEnoughSpace)
{
	const char* c = "\xC4\xB1";
	const size_t s = 0;
	char b[256] = { 0 };
	int32_t errors = UTF8_ERR_NONE;

	EXPECT_EQ(0, utf8totitle(c, strlen(c), b, s, &errors));
	EXPECT_UTF8EQ("", b);
	EXPECT_ERROREQ(UTF8_ERR_NOT_ENOUGH_SPACE, errors);
}

TEST_F(Utf8ToTitleTurkish, SingleSmallLetterDotlessIAmountOfBytes)
{
	const char* c = "\xC4\xB1";
	int32_t errors = UTF8_ERR_NONE;

	EXPECT_EQ(1, utf8totitle(c, strlen(c), nullptr, 0, &errors));
	EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}

TEST_F(Utf8ToTitleTurkish, SingleSmallLetterDotlessIWithDotAbove)
{
	// 0131 0307
	// 0049 0307

	const char* c = "\xC4\xB1\xCC\x87";
	const size_t s = 255;
	char b[256] = { 0 };
	int32_t errors = UTF8_ERR_NONE;

	EXPECT_EQ(3, utf8totitle(c, strlen(c), b, s, &errors));
	EXPECT_UTF8EQ("I\xCC\x87", b);
	EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}

TEST_F(Utf8ToTitleTurkish, SingleSmallLetterDotlessIWithDotAboveNotEnoughSpace)
{
	const char* c = "\xC4\xB1\xCC\x87";
	const size_t s = 2;
	char b[256] = { 0 };
	int32_t errors = UTF8_ERR_NONE;

	EXPECT_EQ(1, utf8totitle(c, strlen(c), b, s, &errors));
	EXPECT_UTF8EQ("I", b);
	EXPECT_ERROREQ(UTF8_ERR_NOT_ENOUGH_SPACE, errors);
}

TEST_F(Utf8ToTitleTurkish, SingleSmallLetterDotlessIWithDotAboveAmountOfBytes)
{
	const char* c = "\xC4\xB1\xCC\x87";
	int32_t errors = UTF8_ERR_NONE;

	EXPECT_EQ(3, utf8totitle(c, strlen(c), nullptr, 0, &errors));
	EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}<|endoftext|>


<commit_before>/*-------------------------------------------------------------------------
 *
 *   FILE
 *	pqxx/cursor.hxx
 *
 *   DESCRIPTION
 *      definition of the iterator/container-style cursor classes
 *   C++-style wrappers for SQL cursors
 *   DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx/pipeline instead.
 *
 * Copyright (c) 2004, Jeroen T. Vermeulen <jtv@xs4all.nl>
 *
 * See COPYING for copyright license.  If you did not receive a file called
 * COPYING with this source code, please notify the distributor of this mistake,
 * or contact the author.
 *
 *-------------------------------------------------------------------------
 */
#include "pqxx/libcompiler.h"

#include <limits>
#include <string>

#include "pqxx/result"

namespace pqxx
{
class transaction_base;

/// Common definitions for cursor types
/** @warning This code is experimental.  It is not fully covered by libpqxx'
 * regression tests, and may see considerable change before becoming part of a
 * stable release.  Use with care.
 */
class PQXX_LIBEXPORT cursor_base
{
public:
  typedef result::size_type size_type;

  operator void *() const { return m_done ? 0 : &s_dummy; }		//[t81]
  bool operator!() const { return m_done; }				//[t81]

  static size_type all() throw ();					//[t81]
  static size_type next() throw () { return 1; }			//[t81]
  static size_type prior() throw () { return -1; }			//[]
  static size_type backward_all() throw ();				//[]

  const PGSTD::string &name() const throw () { return m_name; }		//[t81]

protected:
  cursor_base(transaction_base *context, const PGSTD::string &cname) :
  	m_context(context), m_done(false), m_name(cname)
  {
    m_name += "_";
    m_name += to_string(get_unique_cursor_num());
  }

  transaction_base *m_context;
  bool m_done;

private:
  int get_unique_cursor_num();

  PGSTD::string m_name;

  /// Purely to give us a non-null pointer to return
  static unsigned char s_dummy;

  /// Not allowed
  cursor_base();
  /// Not allowed
  cursor_base(const cursor_base &);
  /// Not allowed
  cursor_base &operator=(const cursor_base &);
};

inline cursor_base::size_type cursor_base::all() throw ()
{
#ifdef _MSC_VER
  // Microsoft's compiler defines max() and min() macros!  Others may as well
  return INT_MAX;
#else
  return PGSTD::numeric_limits<size_type>::max();
#endif
}

inline cursor_base::size_type cursor_base::backward_all() throw ()
{
#ifdef _MSC_VER
  // Microsoft's compiler defines max() and min() macros!  Others may as well
  return INT_MIN + 1;
#else
  return PGSTD::numeric_limits<size_type>::min() + 1;
#endif
}

/// Simple read-only cursor represented as a stream of results
/** Data is fetched from the cursor as a sequence of result objects.  Each of
 * these will contain the number of rows defined as the stream's stride, except
 * of course the last block of data which may contain fewer rows.
 *
 * @warning This code is experimental.  It is not fully covered by libpqxx'
 * regression tests, and may see considerable change before becoming part of a
 * stable release.  Use with care.
 */
class PQXX_LIBEXPORT icursorstream : public cursor_base
{
public:
  /// Set up a read-only, forward-only cursor
  /** Roughly equivalent to a C++ Standard Library istream, this cursor type
   * supports only two operations: reading a block of rows while moving forward,
   * and moving forward without reading any data.
   *
   * @param context transaction context that this cursor will be active in
   * @param query SQL query whose results this cursor shall iterate
   * @param basename suggested name for the SQL cursor; a unique code will be
   * appended by the library to ensure its uniqueness
   * @param stride the number of rows to fetch per read operation; must be a
   * positive number
   */
  icursorstream(transaction_base &context,
      const PGSTD::string &query,
      const PGSTD::string &basename,
      size_type stride=1);						//[t81]

  /// Read new value into given result object; same as operator >>
  /** The result set may continue any number of rows from zero to the chosen
   * stride, inclusive.  An empty result will only be returned if there are no
   * more rows to retrieve.
   */
  icursorstream &get(result &res) { res = fetch(); return *this; }	//[]
  /// Read new value into given result object; same as get(result &)
  /** The result set may continue any number of rows from zero to the chosen
   * stride, inclusive.  An empty result will only be returned if there are no
   * more rows to retrieve.
   */
  icursorstream &operator>>(result &res) { return get(res); }		//[t81]
  /// Move given number of rows forward (ignoring stride) without reading data
  icursorstream &ignore(PGSTD::streamsize n=1);				//[]

  /// Change stride, i.e. the number of rows to fetch per read operation
  /**
   * @param stride must be a positive number
   */
  void set_stride(size_type stride);					//[t81]

private:
  void declare(const PGSTD::string &query);
  result fetch();

  size_type m_stride;
};

/// Approximate istream_iterator for icursorstream
/** A rough equivalent of the C++ Standard Library's istream_iterator or
 * input_iterator, this class supports only two basic operations: reading the
 * current element, and moving forward.  In addition to the minimal guarantees
 * for istream_iterators, this class supports multiple successive reads of the
 * same position (the current result set is cached in the iterator) even after
 * copying and even after new data have been read from the stream.
 *
 * The iterator has no concept of its own position, however.  Moving an iterator
 * forward moves the underlying stream forward and reads the data from the new
 * position, regardless of "where the iterator was" in the stream.  Comparison
 * of iterators is only supported for detecting the end of a stream.
 *
 * @warning This code is experimental.  It is not fully covered by libpqxx'
 * regression tests, and may see considerable change before becoming part of a
 * stable release.  Use with care.
 */
class PQXX_LIBEXPORT icursor_iterator :
  public PGSTD::iterator<PGSTD::input_iterator_tag,
  	result,
	cursor_base::size_type,
	const result *,
	const result &>
{
public:
  typedef icursorstream istream_type;
  typedef istream_type::size_type size_type;

  icursor_iterator() : m_stream(0), m_here(), m_fresh(true) {}		//[]
  icursor_iterator(istream_type &s) :					//[]
    m_stream(&s), m_here(), m_fresh(false) {}
  icursor_iterator(const icursor_iterator &rhs) : 			//[]
    m_stream(rhs.m_stream), m_here(rhs.m_here), m_fresh(rhs.m_fresh) {}

  const result &operator*() const { refresh(); return m_here; }		//[]
  const result *operator->() const { refresh(); return &m_here; }	//[]

  icursor_iterator &operator++() { read(); return *this; }		//[]

  icursor_iterator operator++(int)					//[]
  	{ icursor_iterator old(*this); read(); return old; }

  icursor_iterator &operator+=(size_type n)				//[]
  {
    m_stream->ignore(n);
    m_fresh = false;
    return *this;
  }

  icursor_iterator &operator=(const icursor_iterator &rhs)		//[]
  {
    m_here = rhs.m_here;	// (Already protected against self-assignment)
    m_stream = rhs.m_stream;	// (Does not throw, so we're exception-safe)
    m_fresh = rhs.m_fresh;
    return *this;
  }

  bool operator==(const icursor_iterator &rhs) const throw ()		//[]
  	{ return m_here.empty() && rhs.m_here.empty(); }
  bool operator!=(const icursor_iterator &rhs) const throw ()		//[]
  	{ return !operator==(rhs); }

private:
  void read() const
  {
    m_stream->get(m_here);
    m_fresh = true;
  }
  void refresh() const { if (!m_fresh) read(); }
  icursorstream *m_stream;
  mutable result m_here;
  mutable bool m_fresh;
};

} // namespace pqxx

<commit_msg>Updated warnings for experimental code<commit_after>/*-------------------------------------------------------------------------
 *
 *   FILE
 *	pqxx/cursor.hxx
 *
 *   DESCRIPTION
 *      definition of the iterator/container-style cursor classes
 *   C++-style wrappers for SQL cursors
 *   DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx/pipeline instead.
 *
 * Copyright (c) 2004, Jeroen T. Vermeulen <jtv@xs4all.nl>
 *
 * See COPYING for copyright license.  If you did not receive a file called
 * COPYING with this source code, please notify the distributor of this mistake,
 * or contact the author.
 *
 *-------------------------------------------------------------------------
 */
#include "pqxx/libcompiler.h"

#include <limits>
#include <string>

#include "pqxx/result"

namespace pqxx
{
class transaction_base;

/// Common definitions for cursor types
/** @warning This code is experimental.  It is not fully covered by libpqxx'
 * regression tests, and may see considerable change before becoming part of a
 * stable release.  Do not use except to test it.
 */
class PQXX_LIBEXPORT cursor_base
{
public:
  typedef result::size_type size_type;

  operator void *() const { return m_done ? 0 : &s_dummy; }		//[t81]
  bool operator!() const { return m_done; }				//[t81]

  static size_type all() throw ();					//[t81]
  static size_type next() throw () { return 1; }			//[t81]
  static size_type prior() throw () { return -1; }			//[]
  static size_type backward_all() throw ();				//[]

  const PGSTD::string &name() const throw () { return m_name; }		//[t81]

protected:
  cursor_base(transaction_base *context, const PGSTD::string &cname) :
  	m_context(context), m_done(false), m_name(cname)
  {
    m_name += "_";
    m_name += to_string(get_unique_cursor_num());
  }

  transaction_base *m_context;
  bool m_done;

private:
  int get_unique_cursor_num();

  PGSTD::string m_name;

  /// Purely to give us a non-null pointer to return
  static unsigned char s_dummy;

  /// Not allowed
  cursor_base();
  /// Not allowed
  cursor_base(const cursor_base &);
  /// Not allowed
  cursor_base &operator=(const cursor_base &);
};

inline cursor_base::size_type cursor_base::all() throw ()
{
#ifdef _MSC_VER
  // Microsoft's compiler defines max() and min() macros!  Others may as well
  return INT_MAX;
#else
  return PGSTD::numeric_limits<size_type>::max();
#endif
}

inline cursor_base::size_type cursor_base::backward_all() throw ()
{
#ifdef _MSC_VER
  // Microsoft's compiler defines max() and min() macros!  Others may as well
  return INT_MIN + 1;
#else
  return PGSTD::numeric_limits<size_type>::min() + 1;
#endif
}

/// Simple read-only cursor represented as a stream of results
/** Data is fetched from the cursor as a sequence of result objects.  Each of
 * these will contain the number of rows defined as the stream's stride, except
 * of course the last block of data which may contain fewer rows.
 *
 * @warning This code is experimental.  It is not fully covered by libpqxx'
 * regression tests, and may see considerable change before becoming part of a
 * stable release.  Do not use except to test it.
 */
class PQXX_LIBEXPORT icursorstream : public cursor_base
{
public:
  /// Set up a read-only, forward-only cursor
  /** Roughly equivalent to a C++ Standard Library istream, this cursor type
   * supports only two operations: reading a block of rows while moving forward,
   * and moving forward without reading any data.
   *
   * @param context transaction context that this cursor will be active in
   * @param query SQL query whose results this cursor shall iterate
   * @param basename suggested name for the SQL cursor; a unique code will be
   * appended by the library to ensure its uniqueness
   * @param stride the number of rows to fetch per read operation; must be a
   * positive number
   */
  icursorstream(transaction_base &context,
      const PGSTD::string &query,
      const PGSTD::string &basename,
      size_type stride=1);						//[t81]

  /// Read new value into given result object; same as operator >>
  /** The result set may continue any number of rows from zero to the chosen
   * stride, inclusive.  An empty result will only be returned if there are no
   * more rows to retrieve.
   */
  icursorstream &get(result &res) { res = fetch(); return *this; }	//[]
  /// Read new value into given result object; same as get(result &)
  /** The result set may continue any number of rows from zero to the chosen
   * stride, inclusive.  An empty result will only be returned if there are no
   * more rows to retrieve.
   */
  icursorstream &operator>>(result &res) { return get(res); }		//[t81]
  /// Move given number of rows forward (ignoring stride) without reading data
  icursorstream &ignore(PGSTD::streamsize n=1);				//[]

  /// Change stride, i.e. the number of rows to fetch per read operation
  /**
   * @param stride must be a positive number
   */
  void set_stride(size_type stride);					//[t81]

private:
  void declare(const PGSTD::string &query);
  result fetch();

  size_type m_stride;
};

/// Approximate istream_iterator for icursorstream
/** A rough equivalent of the C++ Standard Library's istream_iterator or
 * input_iterator, this class supports only two basic operations: reading the
 * current element, and moving forward.  In addition to the minimal guarantees
 * for istream_iterators, this class supports multiple successive reads of the
 * same position (the current result set is cached in the iterator) even after
 * copying and even after new data have been read from the stream.
 *
 * The iterator has no concept of its own position, however.  Moving an iterator
 * forward moves the underlying stream forward and reads the data from the new
 * position, regardless of "where the iterator was" in the stream.  Comparison
 * of iterators is only supported for detecting the end of a stream.
 *
 * @warning This code is experimental.  It is not fully covered by libpqxx'
 * regression tests, and may see considerable change before becoming part of a
 * stable release.  Do not use except to test it.
 */
class PQXX_LIBEXPORT icursor_iterator :
  public PGSTD::iterator<PGSTD::input_iterator_tag,
  	result,
	cursor_base::size_type,
	const result *,
	const result &>
{
public:
  typedef icursorstream istream_type;
  typedef istream_type::size_type size_type;

  icursor_iterator() : m_stream(0), m_here(), m_fresh(true) {}		//[]
  icursor_iterator(istream_type &s) :					//[]
    m_stream(&s), m_here(), m_fresh(false) {}
  icursor_iterator(const icursor_iterator &rhs) : 			//[]
    m_stream(rhs.m_stream), m_here(rhs.m_here), m_fresh(rhs.m_fresh) {}

  const result &operator*() const { refresh(); return m_here; }		//[]
  const result *operator->() const { refresh(); return &m_here; }	//[]

  icursor_iterator &operator++() { read(); return *this; }		//[]

  icursor_iterator operator++(int)					//[]
  	{ icursor_iterator old(*this); read(); return old; }

  icursor_iterator &operator+=(size_type n)				//[]
  {
    m_stream->ignore(n);
    m_fresh = false;
    return *this;
  }

  icursor_iterator &operator=(const icursor_iterator &rhs)		//[]
  {
    m_here = rhs.m_here;	// (Already protected against self-assignment)
    m_stream = rhs.m_stream;	// (Does not throw, so we're exception-safe)
    m_fresh = rhs.m_fresh;
    return *this;
  }

  bool operator==(const icursor_iterator &rhs) const throw ()		//[]
  	{ return m_here.empty() && rhs.m_here.empty(); }
  bool operator!=(const icursor_iterator &rhs) const throw ()		//[]
  	{ return !operator==(rhs); }

private:
  void read() const
  {
    m_stream->get(m_here);
    m_fresh = true;
  }
  void refresh() const { if (!m_fresh) read(); }
  icursorstream *m_stream;
  mutable result m_here;
  mutable bool m_fresh;
};

} // namespace pqxx

<|endoftext|>


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

#include "../PreFlightCheck.hpp"

#include <drivers/drv_hrt.h>
#include <systemlib/mavlink_log.h>
#include <lib/parameters/param.h>
#include <uORB/Subscription.hpp>
#include <uORB/topics/system_power.h>

using namespace time_literals;

unsigned int countSetBits(unsigned int n)
{
	unsigned int count = 0;

	while (n) {
		count += n & 1;
		n >>= 1;
	}

	return count;
}

bool PreFlightCheck::powerCheck(orb_advert_t *mavlink_log_pub, const vehicle_status_s &status, const bool report_fail,
				const bool prearm)
{
	bool success = true;

	if (!prearm) {
		// Ignore power check after arming.
		return true;
	}

	uORB::SubscriptionData<system_power_s> system_power_sub{ORB_ID(system_power)};
	system_power_sub.update();
	const system_power_s &system_power = system_power_sub.get();

	if (system_power.timestamp != 0) {
		int32_t required_power_module_count = 0;
		param_get(param_find("COM_POWER_COUNT"), &required_power_module_count);

		// Check avionics rail voltages (if USB isn't connected)
		if (!system_power.usb_connected) {
			float avionics_power_rail_voltage = system_power.voltage5v_v;

			if (avionics_power_rail_voltage < 4.5f) {
				success = false;

				if (report_fail) {
					mavlink_log_critical(mavlink_log_pub, "Preflight Fail: Avionics Power low: %6.2f Volt",
							     (double)avionics_power_rail_voltage);
				}

			} else if (avionics_power_rail_voltage < 4.8f) {
				if (report_fail) {
					mavlink_log_critical(mavlink_log_pub, "CAUTION: Avionics Power low: %6.2f Volt", (double)avionics_power_rail_voltage);
				}

			} else if (avionics_power_rail_voltage > 5.4f) {
				if (report_fail) {
					mavlink_log_critical(mavlink_log_pub, "CAUTION: Avionics Power high: %6.2f Volt", (double)avionics_power_rail_voltage);
				}
			}

			const int power_module_count = countSetBits(system_power.brick_valid);

			if (power_module_count < required_power_module_count) {
				success = false;

				if (report_fail) {
					mavlink_log_critical(mavlink_log_pub, "Power redundancy not met: %d instead of %d",
							     power_module_count, required_power_module_count);
				}
			}
		}

	} else {
		if (report_fail) {
			mavlink_log_critical(mavlink_log_pub, "system power unavailable");
		}

		success = false;
	}

	return success;
}
<commit_msg>commander: assume power is fine for HITL<commit_after>/****************************************************************************
 *
 *   Copyright (c) 2019-2020 PX4 Development Team. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

#include "../PreFlightCheck.hpp"

#include <drivers/drv_hrt.h>
#include <systemlib/mavlink_log.h>
#include <lib/parameters/param.h>
#include <uORB/Subscription.hpp>
#include <uORB/topics/system_power.h>

using namespace time_literals;

unsigned int countSetBits(unsigned int n)
{
	unsigned int count = 0;

	while (n) {
		count += n & 1;
		n >>= 1;
	}

	return count;
}

bool PreFlightCheck::powerCheck(orb_advert_t *mavlink_log_pub, const vehicle_status_s &status, const bool report_fail,
				const bool prearm)
{
	bool success = true;

	if (!prearm) {
		// Ignore power check after arming.
		return true;
	}

	if (status.hil_state == vehicle_status_s::HIL_STATE_ON) {
		// Ignore power check in HITL.
		return true;
	}

	uORB::SubscriptionData<system_power_s> system_power_sub{ORB_ID(system_power)};
	system_power_sub.update();
	const system_power_s &system_power = system_power_sub.get();

	if (system_power.timestamp != 0) {
		int32_t required_power_module_count = 0;
		param_get(param_find("COM_POWER_COUNT"), &required_power_module_count);

		// Check avionics rail voltages (if USB isn't connected)
		if (!system_power.usb_connected) {
			float avionics_power_rail_voltage = system_power.voltage5v_v;

			if (avionics_power_rail_voltage < 4.5f) {
				success = false;

				if (report_fail) {
					mavlink_log_critical(mavlink_log_pub, "Preflight Fail: Avionics Power low: %6.2f Volt",
							     (double)avionics_power_rail_voltage);
				}

			} else if (avionics_power_rail_voltage < 4.8f) {
				if (report_fail) {
					mavlink_log_critical(mavlink_log_pub, "CAUTION: Avionics Power low: %6.2f Volt", (double)avionics_power_rail_voltage);
				}

			} else if (avionics_power_rail_voltage > 5.4f) {
				if (report_fail) {
					mavlink_log_critical(mavlink_log_pub, "CAUTION: Avionics Power high: %6.2f Volt", (double)avionics_power_rail_voltage);
				}
			}

			const int power_module_count = countSetBits(system_power.brick_valid);

			if (power_module_count < required_power_module_count) {
				success = false;

				if (report_fail) {
					mavlink_log_critical(mavlink_log_pub, "Power redundancy not met: %d instead of %d",
							     power_module_count, required_power_module_count);
				}
			}
		}

	} else {
		if (report_fail) {
			mavlink_log_critical(mavlink_log_pub, "system power unavailable");
		}

		success = false;
	}

	return success;
}
<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// File MultiRegionsDemoTests.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// 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.
//
// Description: Run a series of tests on MultiRegions Demos
//
///////////////////////////////////////////////////////////////////////////////
#include "../../Auxiliary/RegressBase.h"
#include <cstdio>
#include <cstdlib>
#include <iostream>

void RunL2RegressionTest(std::string demo, std::string input, std::string info);
void MakeOkFile(std::string demo, std::string input, std::string info);

#ifdef MAKE_OK_FILE
#define Execute($1,$2,$3)  MakeOkFile($1,$2,$3)
#else
#define Execute($1,$2,$3)  RunL2RegressionTest($1,$2,$3)
#endif

int main(int argc, char* argv[])
{
    // 1D Demos
    Execute("Helmholtz1D", "helmholtz1D_8modes.xml","CG Helmholtz1D  modes=8");
    Execute("Helmholtz1D", "helmholtz1D_8modes_RBC.xml","CG Helmholtz1D  modes=8 with Robin BC");
    Execute("HDGHelmholtz1D", "helmholtz1D_8modes.xml","HDG Helmholtz1D  modes=8");
    Execute("HDGHelmholtz1D", "helmholtz1D_8modes_RBC.xml","HDG Helmholtz1D  modes=8 with Robin BC");

    // 2D Demos
    Execute("Helmholtz2D", "helmholtz2D_7modes.xml","CG Helmholtz2D  modes=7");
    Execute("Helmholtz2D", "helmholtz2D_7nodes.xml","CG Helmholtz2D  num nodes=7");
    Execute("Helmholtz2D", "helmholtz2D_7modes_AllBCs.xml","CG Helmholtz2D  modes=7 All BCs,  MultiLevel Static Condensation");
    Execute("Helmholtz2D", "helmholtz2D_7modes_AllBCs.xml","CG Helmholtz2D  modes=7 All BCs, Static Condensation");
    Execute("Helmholtz2D", "helmholtz2D_7modes_AllBCs.xml","CG Helmholtz2D  modes=7 All BCs, Full Matrix");
    Execute("HDGHelmholtz2D", "helmholtz2D_7modes.xml","HDG Helmholtz2D  modes=7");
    Execute("HDGHelmholtz2D", "helmholtz2D_7modes_AllBCs.xml","HDG Helmholtz2D  modes=7 All BCs,  MultiLevel Static Condensation");
    Execute("SteadyAdvectionDiffusionReaction2D", "linearadvdiffreact2D_7modes.xml","Steady Advection Diffusion Reaction 2D  modes=7");

    // 3D Demos
    Execute("Helmholtz3D", "helmholtz3D_hex.xml","CG Helmholtz3D hex");
    Execute("Helmholtz3D", "helmholtz3D_tet.xml","CG Helmholtz3D tets");

    return 0;
}

void RunL2RegressionTest(std::string Demo, std::string input, std::string info)
{
    RegressBase Test(NEKTAR_BIN_DIR,Demo,input,"Demos/MultiRegions/OkFiles/");
    int fail;

    // Copy input file to current location
    std::string syscommand = std::string("cp ") + REG_PATH + "Demos/MultiRegions/InputFiles/"+input +" .";
    int status = system(syscommand.c_str());
    if(status)
    {
        std::cerr << "Unable to copy file:" << input << " to current location" << std::endl;
        exit(2);
    }

    std::cout << Demo << ":  info = \"" << info <<"\""<<std::endl;
    if(fail = Test.TestL2()) // test failed
    {
        std::cout <<" status: FAILED" << std::endl;
        std::cout << "===========================================================\n";
        // Explain cause of error if available
        Test.PrintTestError(fail);
        std::cout << "===========================================================\n";
    }
    else
    {
        std:: cout <<" status: PASSED" << std::endl;
    }

    std::string cleanup = "rm -f *.xml *.fld";
    system(cleanup.c_str());
};

void MakeOkFile(std::string Demo, std::string input, std::string info)
{

    RegressBase Test(NEKTAR_BIN_DIR,Demo,input,"Demos/MultiRegions/OkFiles/");
    int fail;

    // Copy input file to current location
    std::string syscommand = std::string("cp ") + REG_PATH + "Demos/MultiRegions/InputFiles/"+input +" .";
    int status = system(syscommand.c_str());
    if(status)
    {
        std::cerr << "Unable to copy file:" << input << " to current location" << std::endl;
        exit(2);
    }

    if(fail = Test.MakeOkFile())
    {
        std::cout << "Failed to make OK file\n";
        // Explain cause of error if available
        std::cout << "===========================================================\n";
        Test.PrintTestError(fail);
        std::cout << "===========================================================\n";
}
}

<commit_msg>Added HDGHelmholtz3DHomo1D and Helmholtz3DHomo1D tests<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// File MultiRegionsDemoTests.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// 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.
//
// Description: Run a series of tests on MultiRegions Demos
//
///////////////////////////////////////////////////////////////////////////////
#include "../../Auxiliary/RegressBase.h"
#include <cstdio>
#include <cstdlib>
#include <iostream>

void RunL2RegressionTest(std::string demo, std::string input, std::string info);
void MakeOkFile(std::string demo, std::string input, std::string info);

#ifdef MAKE_OK_FILE
#define Execute($1,$2,$3)  MakeOkFile($1,$2,$3)
#else
#define Execute($1,$2,$3)  RunL2RegressionTest($1,$2,$3)
#endif

int main(int argc, char* argv[])
{
    // 1D Demos
    Execute("Helmholtz1D", "helmholtz1D_8modes.xml","CG Helmholtz1D  modes=8");
    Execute("Helmholtz1D", "helmholtz1D_8modes_RBC.xml","CG Helmholtz1D  modes=8 with Robin BC");
    Execute("HDGHelmholtz1D", "helmholtz1D_8modes.xml","HDG Helmholtz1D  modes=8");
    Execute("HDGHelmholtz1D", "helmholtz1D_8modes_RBC.xml","HDG Helmholtz1D  modes=8 with Robin BC");

    // 2D Demos
    Execute("Helmholtz2D", "helmholtz2D_7modes.xml","CG Helmholtz2D  modes=7");
    Execute("Helmholtz2D", "helmholtz2D_7nodes.xml","CG Helmholtz2D  num nodes=7");
    Execute("Helmholtz2D", "helmholtz2D_7modes_AllBCs.xml","CG Helmholtz2D  modes=7 All BCs,  MultiLevel Static Condensation");
    Execute("Helmholtz2D", "helmholtz2D_7modes_AllBCs.xml","CG Helmholtz2D  modes=7 All BCs, Static Condensation");
    Execute("Helmholtz2D", "helmholtz2D_7modes_AllBCs.xml","CG Helmholtz2D  modes=7 All BCs, Full Matrix");
    Execute("HDGHelmholtz2D", "helmholtz2D_7modes.xml","HDG Helmholtz2D  modes=7");
    Execute("HDGHelmholtz2D", "helmholtz2D_7modes_AllBCs.xml","HDG Helmholtz2D  modes=7 All BCs,  MultiLevel Static Condensation");
    Execute("SteadyAdvectionDiffusionReaction2D", "linearadvdiffreact2D_7modes.xml","Steady Advection Diffusion Reaction 2D  modes=7");

    // 3D Demos
    Execute("Helmholtz3D", "helmholtz3D_hex.xml","CG Helmholtz3D hex");
    Execute("Helmholtz3D", "helmholtz3D_tet.xml","CG Helmholtz3D tets");

    // 3D Demos Homogeneous1D

    Execute("Helmholtz3DHomo1D", "helmholtz3D_homo1D_7modes_8nz.xml","CG Helmholtz3D Homogeneous 1D");
    Execute("HDGHelmholtz3DHomo1D", "helmholtz3D_homo1D_7modes_8nz.xml","HDG Helmholtz3D Homogeneous 1D");

    return 0;
}

void RunL2RegressionTest(std::string Demo, std::string input, std::string info)
{
    RegressBase Test(NEKTAR_BIN_DIR,Demo,input,"Demos/MultiRegions/OkFiles/");
    int fail;

    // Copy input file to current location
    std::string syscommand = std::string("cp ") + REG_PATH + "Demos/MultiRegions/InputFiles/"+input +" .";
    int status = system(syscommand.c_str());
    if(status)
    {
        std::cerr << "Unable to copy file:" << input << " to current location" << std::endl;
        exit(2);
    }

    std::cout << Demo << ":  info = \"" << info <<"\""<<std::endl;
    if(fail = Test.TestL2()) // test failed
    {
        std::cout <<" status: FAILED" << std::endl;
        std::cout << "===========================================================\n";
        // Explain cause of error if available
        Test.PrintTestError(fail);
        std::cout << "===========================================================\n";
    }
    else
    {
        std:: cout <<" status: PASSED" << std::endl;
    }

    std::string cleanup = "rm -f *.xml *.fld";
    system(cleanup.c_str());
};

void MakeOkFile(std::string Demo, std::string input, std::string info)
{

    RegressBase Test(NEKTAR_BIN_DIR,Demo,input,"Demos/MultiRegions/OkFiles/");
    int fail;

    // Copy input file to current location
    std::string syscommand = std::string("cp ") + REG_PATH + "Demos/MultiRegions/InputFiles/"+input +" .";
    int status = system(syscommand.c_str());
    if(status)
    {
        std::cerr << "Unable to copy file:" << input << " to current location" << std::endl;
        exit(2);
    }

    if(fail = Test.MakeOkFile())
    {
        std::cout << "Failed to make OK file\n";
        // Explain cause of error if available
        std::cout << "===========================================================\n";
        Test.PrintTestError(fail);
        std::cout << "===========================================================\n";
}
}

<|endoftext|>


<commit_before>// Note to Visual Studio / Windows users: you must set the working directory manually on the project file
// to $(ProjectDir)../../ since these settings are not saved directly in project. The loader
// will be unable to find the example assets unless the proper working directory is set.

#if defined(_MSC_VER)
#pragma comment(lib, "dsound.lib")
#endif

#include "libnyquist/AudioDevice.h"
#include "libnyquist/AudioDecoder.h"
#include "libnyquist/WavEncoder.h"
#include "libnyquist/PostProcess.h"

#include <thread>

using namespace nqr;

int main(int argc, const char **argv) try
{
	AudioDevice::ListAudioDevices();

	int desiredSampleRate = 44100;
	AudioDevice myDevice(2, desiredSampleRate);
	myDevice.Open(myDevice.info.id);

	AudioData * fileData = new AudioData();

	NyquistIO loader;

    if (argc > 1)
    {
        std::string cli_arg = std::string(argv[1]);
        loader.Load(fileData, cli_arg);
    }
    else
    {
        // Circular libnyquist testing
        //loader.Load(fileData, "encoded.wav");

        // 1-channel wave
        loader.Load(fileData, "test_data/1ch/44100/8/test.wav");
        //loader.Load(fileData, "test_data/1ch/44100/16/test.wav");
        //loader.Load(fileData, "test_data/1ch/44100/24/test.wav");
        //loader.Load(fileData, "test_data/1ch/44100/32/test.wav");
        //loader.Load(fileData, "test_data/1ch/44100/64/test.wav");

        // 2-channel wave
        //loader.Load(fileData, "test_data/2ch/44100/8/test.wav");
        //loader.Load(fileData, "test_data/2ch/44100/16/test.wav");
        //loader.Load(fileData, "test_data/2ch/44100/24/test.wav");
        //loader.Load(fileData, "test_data/2ch/44100/32/test.wav");
        //loader.Load(fileData, "test_data/2ch/44100/64/test.wav");

        //loader.Load(fileData, "test_data/ad_hoc/TestBeat_44_16_mono-ima4-reaper.wav");
        //loader.Load(fileData, "test_data/ad_hoc/TestBeat_44_16_stereo-ima4-reaper.wav");

        // Multi-channel wave
        //loader.Load(fileData, "test_data/ad_hoc/6_channel_44k_16b.wav");

        // 1 + 2 channel ogg
        //loader.Load(fileData, "test_data/ad_hoc/LR_Stereo.ogg");
        //loader.Load(fileData, "test_data/ad_hoc/TestLaugh_44k.ogg");
        //loader.Load(fileData, "test_data/ad_hoc/TestBeat.ogg");
        //loader.Load(fileData, "test_data/ad_hoc/TestBeatMono.ogg");
        //loader.Load(fileData, "test_data/ad_hoc/BlockWoosh_Stereo.ogg");

        // 1 + 2 channel flac
        //loader.Load(fileData, "test_data/ad_hoc/KittyPurr8_Stereo_Dithered.flac");
        //loader.Load(fileData, "test_data/ad_hoc/KittyPurr16_Stereo.flac");
        //loader.Load(fileData, "test_data/ad_hoc/KittyPurr16_Mono.flac");
        //loader.Load(fileData, "test_data/ad_hoc/KittyPurr24_Stereo.flac");

        // 2-channel opus
        //loader.Load(fileData, "test_data/ad_hoc/detodos.opus"); // "Firefox: From All, To All"

        // 1 + 2 channel wavepack
        //loader.Load(fileData, "test_data/ad_hoc/TestBeat_Float32.wv");
        //loader.Load(fileData, "test_data/ad_hoc/TestBeat_Float32_Mono.wv");
        //loader.Load(fileData, "test_data/ad_hoc/TestBeat_Int16.wv");
        //loader.Load(fileData, "test_data/ad_hoc/TestBeat_Int24.wv");
        //loader.Load(fileData, "test_data/ad_hoc/TestBeat_Int32.wv");
        //loader.Load(fileData, "test_data/ad_hoc/TestBeat_Int24_Mono.wv");

        // 1 + 2 channel musepack
        //loader.Load(fileData, "test_data/ad_hoc/44_16_stereo.mpc");
        //loader.Load(fileData, "test_data/ad_hoc/44_16_mono.mpc");
    }

	// Libnyquist does not (currently) perform sample rate conversion
	if (fileData->sampleRate != desiredSampleRate)
	{
		std::cout << "[Warning - Sample Rate Mismatch] - file is sampled at " << fileData->sampleRate << " and output is " << desiredSampleRate << std::endl;
	}

	// Convert mono to stereo for testing playback
	if (fileData->channelCount == 1)
	{
		std::cout << "Playing MONO for: " << fileData->lengthSeconds << " seconds..." << std::endl;
		std::vector<float> stereoCopy(fileData->samples.size() * 2);
		MonoToStereo(fileData->samples.data(), stereoCopy.data(), fileData->samples.size());
		myDevice.Play(stereoCopy);
	}
	else
	{
		std::cout << "Playing for: " << fileData->lengthSeconds << " seconds..." << std::endl;
		myDevice.Play(fileData->samples);
	}

	int encoderStatus = WavEncoder::WriteFile({2, PCM_16, DITHER_NONE }, fileData, "encoded.wav");
    std::cout << "Encoder Status: " << encoderStatus << std::endl;

	return EXIT_SUCCESS;
}
catch (const UnsupportedExtensionEx & e)
{
	std::cerr << "Caught: " << e.what() << std::endl;
}
catch (const LoadPathNotImplEx & e)
{
	std::cerr << "Caught: " << e.what() << std::endl;
}
catch (const LoadBufferNotImplEx & e)
{
	std::cerr << "Caught: " << e.what() << std::endl;
}
catch (const std::exception & e)
{
	std::cerr << "Caught: " << e.what() << std::endl;
}
<commit_msg>fileData as a shared ptr<commit_after>// Note to Visual Studio / Windows users: you must set the working directory manually on the project file
// to $(ProjectDir)../../ since these settings are not saved directly in project. The loader
// will be unable to find the example assets unless the proper working directory is set.

#if defined(_MSC_VER)
#pragma comment(lib, "dsound.lib")
#endif

#include "libnyquist/AudioDevice.h"
#include "libnyquist/AudioDecoder.h"
#include "libnyquist/WavEncoder.h"
#include "libnyquist/PostProcess.h"

#include <thread>

using namespace nqr;

int main(int argc, const char **argv) try
{
	AudioDevice::ListAudioDevices();

	int desiredSampleRate = 44100;
	AudioDevice myDevice(2, desiredSampleRate);
	myDevice.Open(myDevice.info.id);

	std::shared_ptr<AudioData> fileData = std::make_shared<AudioData>();

	NyquistIO loader;

    if (argc > 1)
    {
        std::string cli_arg = std::string(argv[1]);
        loader.Load(fileData.get(), cli_arg);
    }
    else
    {
        // Circular libnyquist testing
        //loader.Load(fileData.get(), "encoded.wav");

        // 1-channel wave
        //loader.Load(fileData.get(), "test_data/1ch/44100/8/test.wav");
        //loader.Load(fileData.get(), "test_data/1ch/44100/16/test.wav");
        //loader.Load(fileData.get(), "test_data/1ch/44100/24/test.wav");
        //loader.Load(fileData.get(), "test_data/1ch/44100/32/test.wav");
        //loader.Load(fileData.get(), "test_data/1ch/44100/64/test.wav");

        // 2-channel wave
        //loader.Load(fileData.get(), "test_data/2ch/44100/8/test.wav");
        //loader.Load(fileData.get(), "test_data/2ch/44100/16/test.wav");
        //loader.Load(fileData.get(), "test_data/2ch/44100/24/test.wav");
        //loader.Load(fileData.get(), "test_data/2ch/44100/32/test.wav");
        //loader.Load(fileData.get(), "test_data/2ch/44100/64/test.wav");

        //loader.Load(fileData.get(), "test_data/ad_hoc/TestBeat_44_16_mono-ima4-reaper.wav");
        //loader.Load(fileData.get(), "test_data/ad_hoc/TestBeat_44_16_stereo-ima4-reaper.wav");

        // Multi-channel wave
        //loader.Load(fileData.get(), "test_data/ad_hoc/6_channel_44k_16b.wav");

        // 1 + 2 channel ogg
        //loader.Load(fileData.get(), "test_data/ad_hoc/LR_Stereo.ogg");
        //loader.Load(fileData.get(), "test_data/ad_hoc/TestLaugh_44k.ogg");
        //loader.Load(fileData.get(), "test_data/ad_hoc/TestBeat.ogg");
        //loader.Load(fileData.get(), "test_data/ad_hoc/TestBeatMono.ogg");
        //loader.Load(fileData.get(), "test_data/ad_hoc/BlockWoosh_Stereo.ogg");

        // 1 + 2 channel flac
        //loader.Load(fileData.get(), "test_data/ad_hoc/KittyPurr8_Stereo_Dithered.flac");
        //loader.Load(fileData.get(), "test_data/ad_hoc/KittyPurr16_Stereo.flac");
        //loader.Load(fileData.get(), "test_data/ad_hoc/KittyPurr16_Mono.flac");
        //loader.Load(fileData.get(), "test_data/ad_hoc/KittyPurr24_Stereo.flac");

        // 2-channel opus
        //loader.Load(fileData.get(), "test_data/ad_hoc/detodos.opus"); // "Firefox: From All, To All"

        // 1 + 2 channel wavepack
        //loader.Load(fileData.get(), "test_data/ad_hoc/TestBeat_Float32.wv");
        //loader.Load(fileData.get(), "test_data/ad_hoc/TestBeat_Float32_Mono.wv");
        //loader.Load(fileData.get(), "test_data/ad_hoc/TestBeat_Int16.wv");
        //loader.Load(fileData.get(), "test_data/ad_hoc/TestBeat_Int24.wv");
        //loader.Load(fileData.get(), "test_data/ad_hoc/TestBeat_Int32.wv");
        //loader.Load(fileData.get(), "test_data/ad_hoc/TestBeat_Int24_Mono.wv");

        // 1 + 2 channel musepack
        //loader.Load(fileData.get(), "test_data/ad_hoc/44_16_stereo.mpc");
        loader.Load(fileData.get(), "test_data/ad_hoc/44_16_mono.mpc");
    }

	// Libnyquist does not (currently) perform sample rate conversion
	if (fileData->sampleRate != desiredSampleRate)
	{
		std::cout << "[Warning - Sample Rate Mismatch] - file is sampled at " << fileData->sampleRate << " and output is " << desiredSampleRate << std::endl;
	}

	// Convert mono to stereo for testing playback
	if (fileData->channelCount == 1)
	{
		std::cout << "Playing MONO for: " << fileData->lengthSeconds << " seconds..." << std::endl;
		std::vector<float> stereoCopy(fileData->samples.size() * 2);
		MonoToStereo(fileData->samples.data(), stereoCopy.data(), fileData->samples.size());
		myDevice.Play(stereoCopy);
	}
	else
	{
		std::cout << "Playing for: " << fileData->lengthSeconds << " seconds..." << std::endl;
		myDevice.Play(fileData->samples);
	}

	int encoderStatus = WavEncoder::WriteFile({2, PCM_16, DITHER_NONE }, fileData.get(), "encoded.wav");
    std::cout << "Encoder Status: " << encoderStatus << std::endl;

	return EXIT_SUCCESS;
}
catch (const UnsupportedExtensionEx & e)
{
	std::cerr << "Caught: " << e.what() << std::endl;
}
catch (const LoadPathNotImplEx & e)
{
	std::cerr << "Caught: " << e.what() << std::endl;
}
catch (const LoadBufferNotImplEx & e)
{
	std::cerr << "Caught: " << e.what() << std::endl;
}
catch (const std::exception & e)
{
	std::cerr << "Caught: " << e.what() << std::endl;
}
<|endoftext|>


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

#include "chrome/browser/password_manager/login_database.h"

#include "base/utf_string_conversions.h"

// TODO: Actually encrypt passwords on Linux.

std::string LoginDatabase::EncryptedString(const string16& plain_text)
    const {
  return UTF16ToUTF8(plain_text);
}

string16 LoginDatabase::DecryptedString(const std::string& cipher_text)
    const {
  return ASCIIToUTF16(cipher_text);
}
<commit_msg>Linux: fix retrieving passwords with non-ASCII characters from the default password store. TEST=save a password containing a non-ASCII character, it should autofill correctly BUG=54065 Review URL: http://codereview.chromium.org/3316014<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/password_manager/login_database.h"

#include "base/utf_string_conversions.h"

// TODO: Actually encrypt passwords on Linux.

std::string LoginDatabase::EncryptedString(const string16& plain_text)
    const {
  return UTF16ToUTF8(plain_text);
}

string16 LoginDatabase::DecryptedString(const std::string& cipher_text)
    const {
  return UTF8ToUTF16(cipher_text);
}
<|endoftext|>


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

#pragma hdrstop

#include "fuzoom.hxx"

#include <svx/svxids.hrc>
#ifndef _SFX_BINDINGS_HXX //autogen
#include <sfx2/bindings.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX
#include <sfx2/viewfrm.hxx>
#endif
#include "app.hrc"

#ifndef _SVDPAGV_HXX //autogen
#include <svx/svdpagv.hxx>
#endif

#ifndef SD_FRAMW_VIEW_HXX
#include "FrameView.hxx"
#endif
#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef SD_WINDOW_SHELL_HXX
#include "Window.hxx"
#endif
#include "drawdoc.hxx"
#include "zoomlist.hxx"

namespace sd {

USHORT SidArrayZoom[] = {
                    SID_ATTR_ZOOM,
                    SID_ZOOM_OUT,
                    SID_ZOOM_IN,
                    0 };

TYPEINIT1( FuZoom, FuPoor );

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

FuZoom::FuZoom(
    ViewShell* pViewSh,
    ::sd::Window* pWin,
    ::sd::View* pView,
    SdDrawDocument* pDoc,
    SfxRequest& rReq)
    : FuPoor(pViewSh, pWin, pView, pDoc, rReq),
      bVisible(FALSE),
      bStartDrag(FALSE),
      bLineDraft(FALSE),
      bFillDraft(FALSE),
      bTextDraft(FALSE),
      bGrafDraft(FALSE)
{
}

/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/

FuZoom::~FuZoom()
{
    if (bVisible)
    {
        // Hide ZoomRect
        pViewShell->DrawMarkRect(aZoomRect);

        bVisible = FALSE;
        bStartDrag = FALSE;
    }
}

FunctionReference FuZoom::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )
{
    FunctionReference xFunc( new FuZoom( pViewSh, pWin, pView, pDoc, rReq ) );
    return xFunc;
}

/*************************************************************************
|*
|* MouseButtonDown-event
|*
\************************************************************************/

BOOL FuZoom::MouseButtonDown(const MouseEvent& rMEvt)
{
    // #95491# remember button state for creation of own MouseEvents
    SetMouseButtonCode(rMEvt.GetButtons());

    pWindow->CaptureMouse();
    bStartDrag = TRUE;

    aBeginPosPix = rMEvt.GetPosPixel();
    aBeginPos = pWindow->PixelToLogic(aBeginPosPix);

    if (nSlotId == SID_ZOOM_PANNING)
    {
        // Ersatzdarstellung merken
        FrameView* pFrameView = pViewShell->GetFrameView();
        bLineDraft = pFrameView->IsLineDraft();
        bFillDraft = pFrameView->IsFillDraft();
        bTextDraft = pFrameView->IsTextDraft();
        bGrafDraft = pFrameView->IsGrafDraft();

        // Ersatzdarstellungen einschalten
        pView->SetLineDraft(TRUE);
        pView->SetFillDraft(TRUE);
        pView->SetTextDraft(TRUE);
        pView->SetGrafDraft(TRUE);
    }

    return TRUE;
}

/*************************************************************************
|*
|* MouseMove-event
|*
\************************************************************************/

BOOL FuZoom::MouseMove(const MouseEvent& rMEvt)
{
    if (bStartDrag)
    {
        if (bVisible)
        {
            pViewShell->DrawMarkRect(aZoomRect);
        }

        Point aPosPix = rMEvt.GetPosPixel();
        ForceScroll(aPosPix);

        aEndPos = pWindow->PixelToLogic(aPosPix);
        aBeginPos = pWindow->PixelToLogic(aBeginPosPix);

        if (nSlotId == SID_ZOOM_PANNING)
        {
            // Panning

            Point aScroll = aBeginPos - aEndPos;

            // #i2237#
            // removed old stuff here which still forced zoom to be
            // %BRUSH_SIZE which is outdated now

            if (aScroll.X() != 0 || aScroll.Y() != 0)
            {
                Size aWorkSize = pView->GetWorkArea().GetSize();
                Size aPageSize = pView->GetPageViewPvNum(0)->GetPage()->GetSize();
                aScroll.X() /= aWorkSize.Width()  / aPageSize.Width();
                aScroll.Y() /= aWorkSize.Height() / aPageSize.Height();
                pViewShell->Scroll(aScroll.X(), aScroll.Y());
                aBeginPosPix = aPosPix;
            }
        }
        else
        {
            Rectangle aRect(aBeginPos, aEndPos);
            aZoomRect = aRect;
            aZoomRect.Justify();
            pViewShell->DrawMarkRect(aZoomRect);
        }

        bVisible = TRUE;
    }

    return bStartDrag;
}

/*************************************************************************
|*
|* MouseButtonUp-event
|*
\************************************************************************/

BOOL FuZoom::MouseButtonUp(const MouseEvent& rMEvt)
{
    // #95491# remember button state for creation of own MouseEvents
    SetMouseButtonCode(rMEvt.GetButtons());

    if (bVisible)
    {
        // Hide ZoomRect
        pViewShell->DrawMarkRect(aZoomRect);
        bVisible = FALSE;
    }

    Point aPosPix = rMEvt.GetPosPixel();

    if (nSlotId == SID_ZOOM_PANNING)
    {
        // Panning
        // Ersatzdarstellung restaurieren
        pView->SetLineDraft(bLineDraft);
        pView->SetFillDraft(bFillDraft);
        pView->SetTextDraft(bTextDraft);
        pView->SetGrafDraft(bGrafDraft);
    }
    else
    {
        // Zoom
        Size aZoomSizePixel = pWindow->LogicToPixel(aZoomRect).GetSize();
        ULONG nTol = DRGPIX + DRGPIX;

        if ( aZoomSizePixel.Width() < (long) nTol && aZoomSizePixel.Height() < (long) nTol )
        {
            // Klick auf der Stelle: Zoomfaktor verdoppeln
            Point aPos = pWindow->PixelToLogic(aPosPix);
            Size aSize = pWindow->PixelToLogic(pWindow->GetOutputSizePixel());
            aSize.Width() /= 2;
            aSize.Height() /= 2;
            aPos.X() -= aSize.Width() / 2;
            aPos.Y() -= aSize.Height() / 2;
            aZoomRect.SetPos(aPos);
            aZoomRect.SetSize(aSize);
        }

        pViewShell->SetZoomRect(aZoomRect);
    }

    Rectangle aVisAreaWin = pWindow->PixelToLogic(Rectangle(Point(0,0),
                                           pWindow->GetOutputSizePixel()));
    pViewShell->GetZoomList()->InsertZoomRect(aVisAreaWin);

    bStartDrag = FALSE;
    pWindow->ReleaseMouse();
    pViewShell->Cancel();

    return TRUE;
}

/*************************************************************************
|*
|* Function aktivieren
|*
\************************************************************************/

void FuZoom::Activate()
{
    aPtr = pWindow->GetPointer();

    if (nSlotId == SID_ZOOM_PANNING)
    {
        pWindow->SetPointer(Pointer(POINTER_HAND));
    }
    else
    {
        pWindow->SetPointer(Pointer(POINTER_MAGNIFY));
    }
}

/*************************************************************************
|*
|* Function deaktivieren
|*
\************************************************************************/

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

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

#include "fuzoom.hxx"

#include <svx/svxids.hrc>
#ifndef _SFX_BINDINGS_HXX //autogen
#include <sfx2/bindings.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX
#include <sfx2/viewfrm.hxx>
#endif
#include "app.hrc"

#ifndef _SVDPAGV_HXX //autogen
#include <svx/svdpagv.hxx>
#endif

#ifndef SD_FRAMW_VIEW_HXX
#include "FrameView.hxx"
#endif
#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef SD_WINDOW_SHELL_HXX
#include "Window.hxx"
#endif
#include "drawdoc.hxx"
#include "zoomlist.hxx"

namespace sd {

USHORT SidArrayZoom[] = {
                    SID_ATTR_ZOOM,
                    SID_ZOOM_OUT,
                    SID_ZOOM_IN,
                    0 };

TYPEINIT1( FuZoom, FuPoor );

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

FuZoom::FuZoom(
    ViewShell* pViewSh,
    ::sd::Window* pWin,
    ::sd::View* pView,
    SdDrawDocument* pDoc,
    SfxRequest& rReq)
    : FuPoor(pViewSh, pWin, pView, pDoc, rReq),
      bVisible(FALSE),
      bStartDrag(FALSE),
      bLineDraft(FALSE),
      bFillDraft(FALSE),
      bTextDraft(FALSE),
      bGrafDraft(FALSE)
{
}

/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/

FuZoom::~FuZoom()
{
    if (bVisible)
    {
        // Hide ZoomRect
        pViewShell->DrawMarkRect(aZoomRect);

        bVisible = FALSE;
        bStartDrag = FALSE;
    }
}

FunctionReference FuZoom::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )
{
    FunctionReference xFunc( new FuZoom( pViewSh, pWin, pView, pDoc, rReq ) );
    return xFunc;
}

/*************************************************************************
|*
|* MouseButtonDown-event
|*
\************************************************************************/

BOOL FuZoom::MouseButtonDown(const MouseEvent& rMEvt)
{
    // #95491# remember button state for creation of own MouseEvents
    SetMouseButtonCode(rMEvt.GetButtons());

    pWindow->CaptureMouse();
    bStartDrag = TRUE;

    aBeginPosPix = rMEvt.GetPosPixel();
    aBeginPos = pWindow->PixelToLogic(aBeginPosPix);

    if (nSlotId == SID_ZOOM_PANNING)
    {
        // Ersatzdarstellung merken
        FrameView* pFrameView = pViewShell->GetFrameView();
        bLineDraft = pFrameView->IsLineDraft();
        bFillDraft = pFrameView->IsFillDraft();
        bTextDraft = pFrameView->IsTextDraft();
        bGrafDraft = pFrameView->IsGrafDraft();

        // Ersatzdarstellungen einschalten
        pView->SetLineDraft(TRUE);
        pView->SetFillDraft(TRUE);
        pView->SetTextDraft(TRUE);
        pView->SetGrafDraft(TRUE);
    }

    return TRUE;
}

/*************************************************************************
|*
|* MouseMove-event
|*
\************************************************************************/

BOOL FuZoom::MouseMove(const MouseEvent& rMEvt)
{
    if (bStartDrag)
    {
        if (bVisible)
        {
            pViewShell->DrawMarkRect(aZoomRect);
        }

        Point aPosPix = rMEvt.GetPosPixel();
        ForceScroll(aPosPix);

        aEndPos = pWindow->PixelToLogic(aPosPix);
        aBeginPos = pWindow->PixelToLogic(aBeginPosPix);

        if (nSlotId == SID_ZOOM_PANNING)
        {
            // Panning

            Point aScroll = aBeginPos - aEndPos;

            // #i2237#
            // removed old stuff here which still forced zoom to be
            // %BRUSH_SIZE which is outdated now

            if (aScroll.X() != 0 || aScroll.Y() != 0)
            {
                Size aWorkSize = pView->GetWorkArea().GetSize();
                Size aPageSize = pView->GetPageViewPvNum(0)->GetPage()->GetSize();
                aScroll.X() /= aWorkSize.Width()  / aPageSize.Width();
                aScroll.Y() /= aWorkSize.Height() / aPageSize.Height();
                pViewShell->Scroll(aScroll.X(), aScroll.Y());
                aBeginPosPix = aPosPix;
            }
        }
        else
        {
            Rectangle aRect(aBeginPos, aEndPos);
            aZoomRect = aRect;
            aZoomRect.Justify();
            pViewShell->DrawMarkRect(aZoomRect);
        }

        bVisible = TRUE;
    }

    return bStartDrag;
}

/*************************************************************************
|*
|* MouseButtonUp-event
|*
\************************************************************************/

BOOL FuZoom::MouseButtonUp(const MouseEvent& rMEvt)
{
    // #95491# remember button state for creation of own MouseEvents
    SetMouseButtonCode(rMEvt.GetButtons());

    if (bVisible)
    {
        // Hide ZoomRect
        pViewShell->DrawMarkRect(aZoomRect);
        bVisible = FALSE;
    }

    Point aPosPix = rMEvt.GetPosPixel();

    if (nSlotId == SID_ZOOM_PANNING)
    {
        // Panning
        // Ersatzdarstellung restaurieren
        pView->SetLineDraft(bLineDraft);
        pView->SetFillDraft(bFillDraft);
        pView->SetTextDraft(bTextDraft);
        pView->SetGrafDraft(bGrafDraft);
    }
    else
    {
        // Zoom
        Size aZoomSizePixel = pWindow->LogicToPixel(aZoomRect).GetSize();
        ULONG nTol = DRGPIX + DRGPIX;

        if ( aZoomSizePixel.Width() < (long) nTol && aZoomSizePixel.Height() < (long) nTol )
        {
            // Klick auf der Stelle: Zoomfaktor verdoppeln
            Point aPos = pWindow->PixelToLogic(aPosPix);
            Size aSize = pWindow->PixelToLogic(pWindow->GetOutputSizePixel());
            aSize.Width() /= 2;
            aSize.Height() /= 2;
            aPos.X() -= aSize.Width() / 2;
            aPos.Y() -= aSize.Height() / 2;
            aZoomRect.SetPos(aPos);
            aZoomRect.SetSize(aSize);
        }

        pViewShell->SetZoomRect(aZoomRect);
    }

    Rectangle aVisAreaWin = pWindow->PixelToLogic(Rectangle(Point(0,0),
                                           pWindow->GetOutputSizePixel()));
    pViewShell->GetZoomList()->InsertZoomRect(aVisAreaWin);

    bStartDrag = FALSE;
    pWindow->ReleaseMouse();
    pViewShell->Cancel();

    return TRUE;
}

/*************************************************************************
|*
|* Function aktivieren
|*
\************************************************************************/

void FuZoom::Activate()
{
    aPtr = pWindow->GetPointer();

    if (nSlotId == SID_ZOOM_PANNING)
    {
        pWindow->SetPointer(Pointer(POINTER_HAND));
    }
    else
    {
        pWindow->SetPointer(Pointer(POINTER_MAGNIFY));
    }
}

/*************************************************************************
|*
|* Function deaktivieren
|*
\************************************************************************/

void FuZoom::Deactivate()
{
    pWindow->SetPointer( aPtr );
    pViewShell->GetViewFrame()->GetBindings().Invalidate( SidArrayZoom );
}
} // end of namespace sd
<|endoftext|>


<commit_before><commit_msg>Fixed a regression with Cloud Print notifications caused by a recent refactoring change.<commit_after><|endoftext|>