<commit_before>
#include "numerics/чебышёв_series.hpp"

#include <algorithm>
#include <cmath>

#include "geometry/named_quantities.hpp"
#include "gtest/gtest.h"
#include "quantities/named_quantities.hpp"
#include "quantities/si.hpp"
#include "testing_utilities/numerics.hpp"

namespace principia {

using geometry::Instant;
using quantities::Length;
using quantities::Speed;
using si::Metre;
using si::Second;
using testing_utilities::AbsoluteError;

namespace numerics {

class ЧебышёвSeriesTest : public ::testing::Test {
 protected:
  ЧебышёвSeriesTest()
      : t_min_(-1 * Second),
        t_max_(3 * Second) {}

  Instant t_min_;
  Instant t_max_;
};

using ЧебышёвSeriesDeathTest = ЧебышёвSeriesTest;

TEST_F(ЧебышёвSeriesTest, ConstructionErrors) {
  EXPECT_DEATH({
    ЧебышёвSeries<double> p({}, t_min_, t_max_);
  }, "at least 0");
  EXPECT_DEATH({
    ЧебышёвSeries<double> p({1}, t_max_, t_min_);
  }, "not be empty");
}

TEST_F(ЧебышёвSeriesTest, EvaluationErrors) {
  EXPECT_DEATH({
    ЧебышёвSeries<double> p({1}, t_min_, t_max_);
    p.Evaluate(t_min_ - 10 * Second);
  }, ">= -1.1");
  EXPECT_DEATH({
    ЧебышёвSeries<double> p({1}, t_min_, t_max_);
    p.Evaluate(t_max_ + 10 * Second);
  }, "<= 1.1");
}

TEST_F(ЧебышёвSeriesTest, T0) {
  ЧебышёвSeries<double> t0({1}, t_min_, t_max_);
  EXPECT_EQ(1, t0.Evaluate(Instant(1 * Second)));
  EXPECT_EQ(1, t0.Evaluate(Instant(3 * Second)));
}

TEST_F(ЧебышёвSeriesTest, T1) {
  ЧебышёвSeries<double> t1({0, 1}, t_min_, t_max_);
  EXPECT_EQ(0, t1.Evaluate(Instant(1 * Second)));
  EXPECT_EQ(1, t1.Evaluate(Instant(3 * Second)));
}

TEST_F(ЧебышёвSeriesTest, T2) {
  ЧебышёвSeries<double> t2({0, 0, 1}, t_min_, t_max_);
  EXPECT_EQ(1, t2.Evaluate(Instant(-1 * Second)));
  EXPECT_EQ(-1, t2.Evaluate(Instant(1 * Second)));
  EXPECT_EQ(1, t2.Evaluate(Instant(3 * Second)));
}

TEST_F(ЧебышёвSeriesTest, T3) {
  ЧебышёвSeries<double> t3({0, 0, 0, 1}, t_min_, t_max_);
  EXPECT_EQ(-1, t3.Evaluate(Instant(-1 * Second)));
  EXPECT_EQ(0, t3.Evaluate(Instant(1 * Second)));
  EXPECT_EQ(-1, t3.Evaluate(Instant(2 * Second)));
  EXPECT_EQ(1, t3.Evaluate(Instant(3 * Second)));
}

TEST_F(ЧебышёвSeriesTest, X5) {
  ЧебышёвSeries<double> x5({0.0, 10.0 / 16.0, 0, 5.0 / 16.0, 0, 1.0 / 16.0},
                           t_min_, t_max_);
  EXPECT_EQ(-1, x5.Evaluate(Instant(-1 * Second)));
  EXPECT_EQ(0, x5.Evaluate(Instant(1 * Second)));
  EXPECT_EQ(1.0 / 1024.0, x5.Evaluate(Instant(1.5 * Second)));
  EXPECT_EQ(1.0 / 32.0, x5.Evaluate(Instant(2 * Second)));
  EXPECT_EQ(1, x5.Evaluate(Instant(3 * Second)));
}

TEST_F(ЧебышёвSeriesTest, X6) {
  ЧебышёвSeries<double> x6(
      {10.0 / 32.0, 0, 15.0 / 32.0, 0, 6.0 / 32.0, 0, 1.0 / 32.0},
      t_min_, t_max_);
  EXPECT_EQ(1, x6.Evaluate(Instant(-1 * Second)));
  EXPECT_EQ(0, x6.Evaluate(Instant(1 * Second)));
  EXPECT_EQ(1.0 / 4096.0, x6.Evaluate(Instant(1.5 * Second)));
  EXPECT_EQ(1.0 / 64.0, x6.Evaluate(Instant(2 * Second)));
  EXPECT_EQ(1, x6.Evaluate(Instant(3 * Second)));
}

TEST_F(ЧебышёвSeriesTest, T2Dimension) {
  ЧебышёвSeries<Length> t2({0 * Metre, 0 * Metre, 1 * Metre}, t_min_, t_max_);
  EXPECT_EQ(1 * Metre, t2.Evaluate(Instant(-1 * Second)));
  EXPECT_EQ(-1 * Metre, t2.Evaluate(Instant(1 * Second)));
  EXPECT_EQ(1 * Metre, t2.Evaluate(Instant(3 * Second)));
}

TEST_F(ЧебышёвSeriesDeathTest, SerializationError) {
  ЧебышёвSeries<Speed> v({1 * Metre / Second,
                          -2 * Metre / Second,
                          5 * Metre / Second},
                         t_min_, t_max_);
  ЧебышёвSeries<double> d({7, 8, -1}, t_min_, t_max_);

  EXPECT_DEATH({
    serialization::ЧебышёвSeries message;
    v.WriteToMessage(&message);
    ЧебышёвSeries<double>::ReadFromMessage(message);
  }, "has_double");
  EXPECT_DEATH({
    serialization::ЧебышёвSeries message;
    d.WriteToMessage(&message);
    ЧебышёвSeries<Speed>::ReadFromMessage(message);
  }, "has_quantity");
}

TEST_F(ЧебышёвSeriesTest, SerializationSuccess) {
  {
    serialization::ЧебышёвSeries message;
    ЧебышёвSeries<Speed> const v1({1 * Metre / Second,
                                   -2 * Metre / Second,
                                   5 * Metre / Second},
                                  t_min_, t_max_);
    v1.WriteToMessage(&message);
    EXPECT_EQ(3, message.coefficient_size());
    EXPECT_FALSE(message.coefficient(0).has_double_());
    EXPECT_TRUE(message.coefficient(0).has_quantity());
    EXPECT_EQ(0x7C01, message.coefficient(0).quantity().dimensions());
    EXPECT_EQ(1.0, message.coefficient(0).quantity().magnitude());
    EXPECT_TRUE(message.has_t_min());
    EXPECT_TRUE(message.t_min().has_scalar());
    EXPECT_TRUE(message.t_min().scalar().has_dimensions());
    EXPECT_TRUE(message.t_min().scalar().has_magnitude());
    EXPECT_EQ(-1.0, message.t_min().scalar().magnitude());
    EXPECT_TRUE(message.has_t_max());
    EXPECT_TRUE(message.t_max().has_scalar());
    EXPECT_TRUE(message.t_max().scalar().has_dimensions());
    EXPECT_TRUE(message.t_max().scalar().has_magnitude());
    EXPECT_EQ(3.0, message.t_max().scalar().magnitude());
    ЧебышёвSeries<Speed> const v2 =
        ЧебышёвSeries<Speed>::ReadFromMessage(message);
    EXPECT_EQ(v1, v2);
  }
  {
    serialization::ЧебышёвSeries message;
    ЧебышёвSeries<double> const d1({-1, 2, 5}, t_min_, t_max_);
    d1.WriteToMessage(&message);
    EXPECT_EQ(3, message.coefficient_size());
    EXPECT_TRUE(message.coefficient(0).has_double_());
    EXPECT_FALSE(message.coefficient(0).has_quantity());
    EXPECT_EQ(-1.0, message.coefficient(0).double_());
    EXPECT_TRUE(message.has_t_min());
    EXPECT_TRUE(message.t_min().has_scalar());
    EXPECT_TRUE(message.t_min().scalar().has_dimensions());
    EXPECT_TRUE(message.t_min().scalar().has_magnitude());
    EXPECT_EQ(-1.0, message.t_min().scalar().magnitude());
    EXPECT_TRUE(message.has_t_max());
    EXPECT_TRUE(message.t_max().has_scalar());
    EXPECT_TRUE(message.t_max().scalar().has_dimensions());
    EXPECT_TRUE(message.t_max().scalar().has_magnitude());
    EXPECT_EQ(3.0, message.t_max().scalar().magnitude());
    ЧебышёвSeries<double> const d2 =
        ЧебышёвSeries<double>::ReadFromMessage(message);
    EXPECT_EQ(d1, d2);
  }
}

TEST_F(ЧебышёвSeriesTest, NewhallApproximation) {
  std::vector<Length> lengths;
  std::vector<Speed> speeds;

  auto length_function = [this](Instant const t) -> Length {
    return 2 * Metre *
           std::sin((t - t_min_) / (0.3 * Second)) *
           std::exp((t - t_min_) / (1 * Second));
  };
  auto speed_function = [this](Instant const t) -> Speed {
    return ((2 * Metre) / (0.3 * Second) *
                 std::cos((t - t_min_) / (0.3 * Second)) +
            (2 * Metre / Second) *
                 std::sin((t - t_min_) / (0.3 * Second))) *
                     std::exp((t - t_min_) / (1 * Second));
  };

  for (Instant t = t_min_; t <= t_max_; t += 0.5 * Second) {
    lengths.push_back(length_function(t));
    speeds.push_back(speed_function(t));
  }

  for (int degree = 3; degree <= 17; ++degree) {
    ЧебышёвSeries<Length> const approximation =
        ЧебышёвSeries<Length>::NewhallApproximation(
            degree, lengths, speeds, t_min_, t_max_);
    Length absolute_error;
    for (Instant t = t_min_; t <= t_max_; t += 0.05 * Second) {
      Length const expected_length = length_function(t);
      Length const actual_length = approximation.Evaluate(t);
      absolute_error = std::max(absolute_error,
                                AbsoluteError(expected_length, actual_length));
    }
    LOG(ERROR)<<degree<<" "<<absolute_error;
  }
}

}  // namespace numerics
}  // namespace principia
<commit_msg>Accuracy testing.<commit_after>
#include "numerics/чебышёв_series.hpp"

#include <algorithm>
#include <cmath>

#include "geometry/named_quantities.hpp"
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "quantities/named_quantities.hpp"
#include "quantities/si.hpp"
#include "testing_utilities/numerics.hpp"

namespace principia {

using geometry::Instant;
using quantities::Length;
using quantities::Speed;
using si::Metre;
using si::Second;
using testing_utilities::AbsoluteError;
using ::testing::ElementsAre;
using ::testing::Lt;

namespace numerics {

class ЧебышёвSeriesTest : public ::testing::Test {
 protected:
  ЧебышёвSeriesTest()
      : t_min_(-1 * Second),
        t_max_(3 * Second) {}

  // TODO(phl): Support for evaluating the derivative.
  void NewhallApproximationErrors(
      std::function<Length(Instant const)> length_function,
      std::function<Speed(Instant const)> speed_function,
      not_null<std::vector<Length>*> const length_absolute_errors) {
    std::vector<Length> lengths;
    std::vector<Speed> speeds;
    for (Instant t = t_min_; t <= t_max_; t += 0.5 * Second) {
      lengths.push_back(length_function(t));
      speeds.push_back(speed_function(t));
    }

    length_absolute_errors->clear();
    for (int degree = 3; degree <= 17; ++degree) {
      ЧебышёвSeries<Length> const approximation =
          ЧебышёвSeries<Length>::NewhallApproximation(
              degree, lengths, speeds, t_min_, t_max_);
      Length absolute_error;
      for (Instant t = t_min_; t <= t_max_; t += 0.05 * Second) {
        Length const expected_length = length_function(t);
        Length const actual_length = approximation.Evaluate(t);
        absolute_error = std::max(absolute_error,
                                  AbsoluteError(expected_length, actual_length));
      }
      if (!length_absolute_errors->empty()) {
        //CHECK_LE(absolute_error, length_absolute_errors->back());
      }
      length_absolute_errors->push_back(absolute_error);
    }
  }

  // A helper that splits an array in two chunks and applies distinct matchers
  // to the chunks.  Necessary because ElementsAre only supports 10 elements and
  // ElementsAreArray does not support matches as arguments.
  template<typename Matcher1, typename Matcher2>
  void ExpectMultipart(std::vector<Length> const& v,
                       Matcher1 const& matcher1,
                       Matcher2 const& matcher2) {
    std::vector<Length> v_0_9(10);
    std::copy(v.begin(), v.begin() + 10, v_0_9.begin());
    EXPECT_THAT(v_0_9, matcher1);
    std::vector<Length> v_10_end(v.size() - 10);
    std::copy(v.begin() + 10, v.end(), v_10_end.begin());
    EXPECT_THAT(v_10_end, matcher2);
  }

  Instant t_min_;
  Instant t_max_;
};

using ЧебышёвSeriesDeathTest = ЧебышёвSeriesTest;

TEST_F(ЧебышёвSeriesTest, ConstructionErrors) {
  EXPECT_DEATH({
    ЧебышёвSeries<double> p({}, t_min_, t_max_);
  }, "at least 0");
  EXPECT_DEATH({
    ЧебышёвSeries<double> p({1}, t_max_, t_min_);
  }, "not be empty");
}

TEST_F(ЧебышёвSeriesTest, EvaluationErrors) {
  EXPECT_DEATH({
    ЧебышёвSeries<double> p({1}, t_min_, t_max_);
    p.Evaluate(t_min_ - 10 * Second);
  }, ">= -1.1");
  EXPECT_DEATH({
    ЧебышёвSeries<double> p({1}, t_min_, t_max_);
    p.Evaluate(t_max_ + 10 * Second);
  }, "<= 1.1");
}

TEST_F(ЧебышёвSeriesTest, T0) {
  ЧебышёвSeries<double> t0({1}, t_min_, t_max_);
  EXPECT_EQ(1, t0.Evaluate(Instant(1 * Second)));
  EXPECT_EQ(1, t0.Evaluate(Instant(3 * Second)));
}

TEST_F(ЧебышёвSeriesTest, T1) {
  ЧебышёвSeries<double> t1({0, 1}, t_min_, t_max_);
  EXPECT_EQ(0, t1.Evaluate(Instant(1 * Second)));
  EXPECT_EQ(1, t1.Evaluate(Instant(3 * Second)));
}

TEST_F(ЧебышёвSeriesTest, T2) {
  ЧебышёвSeries<double> t2({0, 0, 1}, t_min_, t_max_);
  EXPECT_EQ(1, t2.Evaluate(Instant(-1 * Second)));
  EXPECT_EQ(-1, t2.Evaluate(Instant(1 * Second)));
  EXPECT_EQ(1, t2.Evaluate(Instant(3 * Second)));
}

TEST_F(ЧебышёвSeriesTest, T3) {
  ЧебышёвSeries<double> t3({0, 0, 0, 1}, t_min_, t_max_);
  EXPECT_EQ(-1, t3.Evaluate(Instant(-1 * Second)));
  EXPECT_EQ(0, t3.Evaluate(Instant(1 * Second)));
  EXPECT_EQ(-1, t3.Evaluate(Instant(2 * Second)));
  EXPECT_EQ(1, t3.Evaluate(Instant(3 * Second)));
}

TEST_F(ЧебышёвSeriesTest, X5) {
  ЧебышёвSeries<double> x5({0.0, 10.0 / 16.0, 0, 5.0 / 16.0, 0, 1.0 / 16.0},
                           t_min_, t_max_);
  EXPECT_EQ(-1, x5.Evaluate(Instant(-1 * Second)));
  EXPECT_EQ(0, x5.Evaluate(Instant(1 * Second)));
  EXPECT_EQ(1.0 / 1024.0, x5.Evaluate(Instant(1.5 * Second)));
  EXPECT_EQ(1.0 / 32.0, x5.Evaluate(Instant(2 * Second)));
  EXPECT_EQ(1, x5.Evaluate(Instant(3 * Second)));
}

TEST_F(ЧебышёвSeriesTest, X6) {
  ЧебышёвSeries<double> x6(
      {10.0 / 32.0, 0, 15.0 / 32.0, 0, 6.0 / 32.0, 0, 1.0 / 32.0},
      t_min_, t_max_);
  EXPECT_EQ(1, x6.Evaluate(Instant(-1 * Second)));
  EXPECT_EQ(0, x6.Evaluate(Instant(1 * Second)));
  EXPECT_EQ(1.0 / 4096.0, x6.Evaluate(Instant(1.5 * Second)));
  EXPECT_EQ(1.0 / 64.0, x6.Evaluate(Instant(2 * Second)));
  EXPECT_EQ(1, x6.Evaluate(Instant(3 * Second)));
}

TEST_F(ЧебышёвSeriesTest, T2Dimension) {
  ЧебышёвSeries<Length> t2({0 * Metre, 0 * Metre, 1 * Metre}, t_min_, t_max_);
  EXPECT_EQ(1 * Metre, t2.Evaluate(Instant(-1 * Second)));
  EXPECT_EQ(-1 * Metre, t2.Evaluate(Instant(1 * Second)));
  EXPECT_EQ(1 * Metre, t2.Evaluate(Instant(3 * Second)));
}

TEST_F(ЧебышёвSeriesDeathTest, SerializationError) {
  ЧебышёвSeries<Speed> v({1 * Metre / Second,
                          -2 * Metre / Second,
                          5 * Metre / Second},
                         t_min_, t_max_);
  ЧебышёвSeries<double> d({7, 8, -1}, t_min_, t_max_);

  EXPECT_DEATH({
    serialization::ЧебышёвSeries message;
    v.WriteToMessage(&message);
    ЧебышёвSeries<double>::ReadFromMessage(message);
  }, "has_double");
  EXPECT_DEATH({
    serialization::ЧебышёвSeries message;
    d.WriteToMessage(&message);
    ЧебышёвSeries<Speed>::ReadFromMessage(message);
  }, "has_quantity");
}

TEST_F(ЧебышёвSeriesTest, SerializationSuccess) {
  {
    serialization::ЧебышёвSeries message;
    ЧебышёвSeries<Speed> const v1({1 * Metre / Second,
                                   -2 * Metre / Second,
                                   5 * Metre / Second},
                                  t_min_, t_max_);
    v1.WriteToMessage(&message);
    EXPECT_EQ(3, message.coefficient_size());
    EXPECT_FALSE(message.coefficient(0).has_double_());
    EXPECT_TRUE(message.coefficient(0).has_quantity());
    EXPECT_EQ(0x7C01, message.coefficient(0).quantity().dimensions());
    EXPECT_EQ(1.0, message.coefficient(0).quantity().magnitude());
    EXPECT_TRUE(message.has_t_min());
    EXPECT_TRUE(message.t_min().has_scalar());
    EXPECT_TRUE(message.t_min().scalar().has_dimensions());
    EXPECT_TRUE(message.t_min().scalar().has_magnitude());
    EXPECT_EQ(-1.0, message.t_min().scalar().magnitude());
    EXPECT_TRUE(message.has_t_max());
    EXPECT_TRUE(message.t_max().has_scalar());
    EXPECT_TRUE(message.t_max().scalar().has_dimensions());
    EXPECT_TRUE(message.t_max().scalar().has_magnitude());
    EXPECT_EQ(3.0, message.t_max().scalar().magnitude());
    ЧебышёвSeries<Speed> const v2 =
        ЧебышёвSeries<Speed>::ReadFromMessage(message);
    EXPECT_EQ(v1, v2);
  }
  {
    serialization::ЧебышёвSeries message;
    ЧебышёвSeries<double> const d1({-1, 2, 5}, t_min_, t_max_);
    d1.WriteToMessage(&message);
    EXPECT_EQ(3, message.coefficient_size());
    EXPECT_TRUE(message.coefficient(0).has_double_());
    EXPECT_FALSE(message.coefficient(0).has_quantity());
    EXPECT_EQ(-1.0, message.coefficient(0).double_());
    EXPECT_TRUE(message.has_t_min());
    EXPECT_TRUE(message.t_min().has_scalar());
    EXPECT_TRUE(message.t_min().scalar().has_dimensions());
    EXPECT_TRUE(message.t_min().scalar().has_magnitude());
    EXPECT_EQ(-1.0, message.t_min().scalar().magnitude());
    EXPECT_TRUE(message.has_t_max());
    EXPECT_TRUE(message.t_max().has_scalar());
    EXPECT_TRUE(message.t_max().scalar().has_dimensions());
    EXPECT_TRUE(message.t_max().scalar().has_magnitude());
    EXPECT_EQ(3.0, message.t_max().scalar().magnitude());
    ЧебышёвSeries<double> const d2 =
        ЧебышёвSeries<double>::ReadFromMessage(message);
    EXPECT_EQ(d1, d2);
  }
}

TEST_F(ЧебышёвSeriesTest, NewhallApproximation) {
  std::vector<Length> length_absolute_errors;

  auto length_function = [this](Instant const t) -> Length {
    return 2 * Metre *
           std::sin((t - t_min_) / (0.3 * Second)) *
           std::exp((t - t_min_) / (1 * Second));
  };
  auto speed_function = [this](Instant const t) -> Speed {
    return ((2 * Metre) / (0.3 * Second) *
                 std::cos((t - t_min_) / (0.3 * Second)) +
            (2 * Metre / Second) *
                 std::sin((t - t_min_) / (0.3 * Second))) *
                     std::exp((t - t_min_) / (1 * Second));
  };

  NewhallApproximationErrors(length_function,
                             speed_function,
                             &length_absolute_errors);

  ExpectMultipart(length_absolute_errors,
                  ElementsAre(Lt(1.7E2 * Metre),
                              Lt(4.7E1 * Metre),
                              Lt(4.3E1 * Metre),
                              Lt(3.8E1 * Metre),
                              Lt(1.5E1 * Metre),
                              Lt(6.3 * Metre),
                              Lt(4.9 * Metre),
                              Lt(6.5E-1 * Metre),
                              Lt(2.0E-1 * Metre),
                              Lt(7.9E-2 * Metre)),
                  ElementsAre(Lt(1.3E-2 * Metre),
                              Lt(1.6E-2 * Metre),
                              Lt(4.3E-3 * Metre),
                              Lt(1.7E-3 * Metre),
                              Lt(7.6E-4 * Metre)));
}

}  // namespace numerics
}  // namespace principia
<|endoftext|>


<commit_before>
#include <memory>
#include <vector>

namespace impl_fs_alloc {

	// One block
	template <size_t T_SIZE>
	struct Chunk
	{
		char data[T_SIZE];
		Chunk* next_chunk;
	};

	template <size_t T_SIZE, size_t ARRAY_SIZE>
	class Allocator
	{
		using chunk_t = Chunk<T_SIZE>;

		std::vector<std::unique_ptr<chunk_t[]>> chunks;
		chunk_t* pFreeChunk;
	public:
		static Allocator& instance() {
			static Allocator s_instance;
			return s_instance;
		}

		Allocator()
		{
			addChunks();
		}

		Allocator(const Allocator& clone) = delete;
		Allocator(Allocator&& clone) = delete;
		Allocator& operator=(const Allocator& clone) = delete;
		Allocator& operator=(Allocator&& clone) = delete;

		void addChunks()
		{
			chunk_t* array = new chunk_t[ARRAY_SIZE];
			chunks.emplace_back(array);

			for (auto i = 0; i < ARRAY_SIZE - 1; ++i)
				array[i].next_chunk = &array[i + 1];

			array[ARRAY_SIZE - 1].next_chunk = nullptr;
			pFreeChunk = array;
		}

		void* allocate()
		{
			if (pFreeChunk == nullptr)
				addChunks();

			chunk_t* pChunk = pFreeChunk;
			pFreeChunk = pChunk->next_chunk;

			return pChunk;
		}

		void deallocate(void* address)
		{
			auto pChunk = static_cast<chunk_t*>(address);

			pChunk->next_chunk = pFreeChunk;
			pFreeChunk = pChunk;
		}
	};
}

template<class T, size_t ARRAY_SIZE = 1024>
class FixedSizeAllocator {
public:
	typedef T value_type;
	typedef T* pointer;
	typedef const T* const_pointer;
	typedef T& reference;
	typedef const T& const_reference;
	typedef size_t size_type;
	typedef ptrdiff_t difference_type;

	template<typename U>
	struct rebind {
		typedef FixedSizeAllocator<U, ARRAY_SIZE> other;
	};
	using alloc_t = impl_fs_alloc::Allocator<sizeof(T), ARRAY_SIZE>;

	FixedSizeAllocator() = default;

	// allocation only for one block at the time

	pointer allocate(size_type nb) {

		if (nb == 1)
			return static_cast<pointer>(alloc_t::instance().allocate());
		else
			return std::allocator<T>().allocate(nb);
	}

	void deallocate(pointer pChunk, size_type nb) {

		if (nb == 1)
			alloc_t::instance().deallocate(static_cast<void*>(pChunk));
		else
			std::allocator<T>().deallocate(pChunk, nb);
	}

	void construct(pointer p) { new(p) T(); }
	void destroy(pointer p) { p->~T(); }
};

<commit_msg>fs_alloc style<commit_after>
/**
 *  Fixed size block allocator.
 *  Used to have fast allocation of continuous memory.
 *  If more than one block must be allocated, the standard allocator is called.
 */

#include <memory>
#include <vector>

namespace impl_fs_alloc {

	// One block
	template <size_t T_SIZE>
	struct Chunk
	{
		char data[T_SIZE];
		Chunk* pNext;
	};

	template <size_t T_SIZE, size_t ARRAY_SIZE>
	class Allocator
	{
		using chunk_t = Chunk<T_SIZE>;

		std::vector<std::unique_ptr<chunk_t[]>> chunks;
		chunk_t* pFreeChunk;
	public:
		static Allocator& instance() {
			static Allocator s_instance;
			return s_instance;
		}

		Allocator()
		{
			addChunks();
		}

		Allocator(const Allocator& clone) = delete;
		Allocator(Allocator&& clone) = delete;
		Allocator& operator=(const Allocator& clone) = delete;
		Allocator& operator=(Allocator&& clone) = delete;

		void addChunks()
		{
			chunk_t* array = new chunk_t[ARRAY_SIZE];
			chunks.emplace_back(array);

			for (auto i = 0; i < ARRAY_SIZE - 1; ++i)
				array[i].pNext = &array[i + 1];

			array[ARRAY_SIZE - 1].pNext = nullptr;
			pFreeChunk = array;
		}

		void* allocate()
		{
			if (pFreeChunk == nullptr)
				addChunks();

			chunk_t* pChunk = pFreeChunk;
			pFreeChunk = pChunk->pNext;

			return pChunk;
		}

		void deallocate(void* address)
		{
			auto pChunk = static_cast<chunk_t*>(address);

			pChunk->pNext = pFreeChunk;
			pFreeChunk = pChunk;
		}
	};
}

template<class T, size_t ARRAY_SIZE = 1024>
class fs_alloc {
public:
	typedef T value_type;
	typedef T* pointer;
	typedef const T* const_pointer;
	typedef T& reference;
	typedef const T& const_reference;
	typedef size_t size_type;
	typedef ptrdiff_t difference_type;

	template<typename U>
	struct rebind {
		typedef fs_alloc<U, ARRAY_SIZE> other;
	};
	using alloc_t = impl_fs_alloc::Allocator<sizeof(T), ARRAY_SIZE>;

	fs_alloc() = default;

	// allocation only for one block at the time

	pointer allocate(size_type nb) {

		if (nb == 1)
			return static_cast<pointer>(alloc_t::instance().allocate());
		else
			return std::allocator<T>().allocate(nb);
	}

	void deallocate(pointer pChunk, size_type nb) {

		if (nb == 1)
			alloc_t::instance().deallocate(static_cast<void*>(pChunk));
		else
			std::allocator<T>().deallocate(pChunk, nb);
	}

	void construct(pointer p) { new(p) T(); }
	void destroy(pointer p) { p->~T(); }
};

<|endoftext|>


<commit_before>#include "Halide.h"
#include <tiramisu/utils.h>
#include <cstdlib>
#include <iostream>
#include "benchmarks.h"

#include "baryon_wrapper.h"

#ifdef __cplusplus
extern "C" {
#endif

#ifdef __cplusplus
}  // extern "C"
#endif

#include "baryon_ref.cpp"

int main(int, char **)
{
    std::vector<std::chrono::duration<double,std::milli>> duration_vector_1;
    std::vector<std::chrono::duration<double,std::milli>> duration_vector_2;

    Halide::Buffer<float> buf_res2(1, "buf_res2");
    Halide::Buffer<float> buf_res2_ref(1, "buf_res2_ref");
    Halide::Buffer<float> buf_S(BARYON_P, BARYON_P, BARYON_P, BARYON_N, BARYON_N, BARYON_N, BARYON_P1, "buf_S");
    Halide::Buffer<float> buf_wp(BARYON_N, BARYON_P, BARYON_P, BARYON_P, BARYON_P1, BARYON_P1, BARYON_P1, "buf_wp");

    init_buffers((float (*)[BARYON_P][BARYON_P][BARYON_N][BARYON_N][BARYON_N][BARYON_P1]) buf_S.raw_buffer()->host, (float (*)[BARYON_P][BARYON_P][BARYON_P][BARYON_P1][BARYON_P1][BARYON_P1]) buf_wp.raw_buffer()->host, (float)5);

    for (int i = 0; i < NB_TESTS; i++)
    {
    	    init_buffer(buf_res2_ref, (float)0);
	    auto start2 = std::chrono::high_resolution_clock::now();
	    ref((float *) buf_res2_ref.raw_buffer()->host,
		(float (*)[BARYON_P][BARYON_P][BARYON_N][BARYON_N][BARYON_N][BARYON_P1]) buf_S.raw_buffer()->host,
		(float (*)[BARYON_P][BARYON_P][BARYON_P][BARYON_P1][BARYON_P1][BARYON_P1]) buf_wp.raw_buffer()->host);
	    auto end2 = std::chrono::high_resolution_clock::now();
	    std::chrono::duration<double,std::milli> duration2 = end2 - start2;
	    duration_vector_2.push_back(duration2);
    }

    for (int i = 0; i < NB_TESTS; i++)
    {
	    init_buffer(buf_res2, (float)0);
	    auto start1 = std::chrono::high_resolution_clock::now();
	    tiramisu_generated_code(buf_res2.raw_buffer(), buf_S.raw_buffer(), buf_wp.raw_buffer());
	    auto end1 = std::chrono::high_resolution_clock::now();
	    std::chrono::duration<double,std::milli> duration1 = end1 - start1;
	    duration_vector_1.push_back(duration1);
    }

    std::cout << std::endl << "Reference buffer : ";
    print_buffer(buf_res2_ref);

    std::cout << "Tiramisu buffer : ";
    print_buffer(buf_res2);

    compare_buffers("benchmark_" + std::string(TEST_NAME_STR), buf_res2, buf_res2_ref);

    print_time("performance_CPU.csv", "baryon",
               {"Ref", "Tiramisu"},
               {median(duration_vector_2), median(duration_vector_1)});

    return 0;
}
<commit_msg>Update baryon wrapper<commit_after>#include "Halide.h"
#include <tiramisu/utils.h>
#include <cstdlib>
#include <iostream>
#include "benchmarks.h"

#include "baryon_wrapper.h"

#ifdef __cplusplus
extern "C" {
#endif

#ifdef __cplusplus
}  // extern "C"
#endif

#include "baryon_ref.cpp"

int main(int, char **)
{
    std::vector<std::chrono::duration<double,std::milli>> duration_vector_1;
    std::vector<std::chrono::duration<double,std::milli>> duration_vector_2;

    Halide::Buffer<float> buf_res2(BT, "buf_res2");
    Halide::Buffer<float> buf_res2_ref(BT, "buf_res2_ref");
    Halide::Buffer<float> buf_S(BARYON_P1, BZ, BY, BX, BARYON_P, BARYON_P, BARYON_P, "buf_S");
    Halide::Buffer<float> buf_wp(BARYON_P, BARYON_P, BARYON_P, BARYON_N, "buf_wp");
    Halide::Buffer<int> fc1(BARYON_N, "buf_fc1");
    Halide::Buffer<int> fc2(BARYON_N, "buf_fc2");
    Halide::Buffer<int> fc3(BARYON_N, "buf_fc2");

    init_buffers((float (*)[BARYON_P][BARYON_P][BX][BY][BZ][BARYON_P1]) buf_S.raw_buffer()->host,
		 (float (*)[BARYON_P][BARYON_P][BARYON_P]) buf_wp.raw_buffer()->host,
		 (float) 5,
		 (int *) fc1.raw_buffer()->host,
		 (int *) fc2.raw_buffer()->host,
		 (int *) fc3.raw_buffer()->host);

    for (int i = 0; i < NB_TESTS; i++)
    {
    	    init_buffer(buf_res2_ref, (float)0);
	    auto start2 = std::chrono::high_resolution_clock::now();

	    ref((float *) buf_res2_ref.raw_buffer()->host,
		(float (*)[BARYON_P][BARYON_P][BX][BY][BZ][BARYON_P1]) buf_S.raw_buffer()->host,
		(float (*)[BARYON_P][BARYON_P][BARYON_P]) buf_wp.raw_buffer()->host,
		(int *) fc1.raw_buffer()->host,
		(int *) fc2.raw_buffer()->host,
		(int *) fc3.raw_buffer()->host);

	    auto end2 = std::chrono::high_resolution_clock::now();
	    std::chrono::duration<double,std::milli> duration2 = end2 - start2;
	    duration_vector_2.push_back(duration2);
    }

    for (int i = 0; i < NB_TESTS; i++)
    {
	    init_buffer(buf_res2, (float)0);
	    auto start1 = std::chrono::high_resolution_clock::now();
	    tiramisu_generated_code(buf_res2.raw_buffer(),
				    buf_S.raw_buffer(),
				    buf_wp.raw_buffer());
	    auto end1 = std::chrono::high_resolution_clock::now();
	    std::chrono::duration<double,std::milli> duration1 = end1 - start1;
	    duration_vector_1.push_back(duration1);
    }

    std::cout << std::endl << "Reference buffer : ";
    print_buffer(buf_res2_ref);

    std::cout << "Tiramisu buffer : ";
    print_buffer(buf_res2);

    compare_buffers("benchmark_" + std::string(TEST_NAME_STR), buf_res2, buf_res2_ref);

    print_time("performance_CPU.csv", "baryon",
               {"Ref", "Tiramisu"},
               {median(duration_vector_2), median(duration_vector_1)});

    return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

#include "core/framework/allocator.h"
#include "core/framework/allocatormgr.h"
#include <cstdlib>
#include <sstream>
#include <cstdlib>

namespace onnxruntime {

void* CPUAllocator::Alloc(size_t size) {
  if (size <= 0)
    return nullptr;
  //default align to 64;
  void* p;
#ifdef _WIN32
  size_t alignment = 32;
#else
  size_t alignment = 64;
#endif
#if _MSC_VER
  p = _aligned_malloc(size, alignment);
  if (p == nullptr) throw std::bad_alloc();
#elif defined(_LIBCPP_SGX_CONFIG)
  p = memalign(alignment, size);
  if (p == nullptr) throw std::bad_alloc();
#else
  int ret = posix_memalign(&p, alignment, size);
  if (ret != 0) throw std::bad_alloc();
#endif
  return p;
}

void CPUAllocator::Free(void* p) {
#if _MSC_VER
  _aligned_free(p);
#else
  free(p);
#endif
}

const OrtAllocatorInfo& CPUAllocator::Info() const {
  return *allocator_info_;
}
}  // namespace onnxruntime

std::ostream& operator<<(std::ostream& out, const OrtAllocatorInfo& info) {
  return (out << info.ToString());
}

ORT_API_STATUS_IMPL(OrtCreateAllocatorInfo, _In_ const char* name1, OrtAllocatorType type, int id1,
                    OrtMemType mem_type1, _Out_ OrtAllocatorInfo** out) {
  *out = new OrtAllocatorInfo(name1, type, id1, mem_type1);
  return nullptr;
}

ORT_API(void, OrtReleaseAllocatorInfo, _Frees_ptr_opt_ OrtAllocatorInfo* p) {
  delete p;
}

ORT_API_STATUS_IMPL(OrtAllocatorInfoGetName, _In_ OrtAllocatorInfo* ptr, _Out_ const char** out) {
  *out = ptr->name;
  return nullptr;
}

ORT_API_STATUS_IMPL(OrtAllocatorInfoGetId, _In_ OrtAllocatorInfo* ptr, _Out_ int* out) {
  *out = ptr->id;
  return nullptr;
}

ORT_API_STATUS_IMPL(OrtAllocatorInfoGetMemType, _In_ OrtAllocatorInfo* ptr, _Out_ OrtMemType* out) {
  *out = ptr->mem_type;
  return nullptr;
}

ORT_API_STATUS_IMPL(OrtAllocatorInfoGetType, _In_ OrtAllocatorInfo* ptr, _Out_ OrtAllocatorType* out) {
  *out = ptr->type;
  return nullptr;
}

ORT_API_STATUS_IMPL(OrtCompareAllocatorInfo, _In_ const OrtAllocatorInfo* info1, _In_ const OrtAllocatorInfo* info2, _Out_ int* out) {
  *out = (*info1 == *info2) ? 0 : -1;
  return nullptr;
}
<commit_msg>Change the memory alignment for default cpu provider (#1269)<commit_after>// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

#include "core/framework/allocator.h"
#include "core/framework/allocatormgr.h"
#include <cstdlib>
#include <sstream>

namespace onnxruntime {

void* CPUAllocator::Alloc(size_t size) {
  if (size <= 0)
    return nullptr;
  //default align to 64;
  void* p;
#if defined(__AVX512F__)
  size_t alignment = 64;
#elif defined(__AVX__)
  size_t alignment = 32;
#else
  size_t alignment = 32; //Indeed, the default one(8 or 16) should be enough
#endif
#if _MSC_VER
  p = _aligned_malloc(size, alignment);
  if (p == nullptr) throw std::bad_alloc();
#elif defined(_LIBCPP_SGX_CONFIG)
  p = memalign(alignment, size);
  if (p == nullptr) throw std::bad_alloc();
#else
  int ret = posix_memalign(&p, alignment, size);
  if (ret != 0) throw std::bad_alloc();
#endif
  return p;
}

void CPUAllocator::Free(void* p) {
#if _MSC_VER
  _aligned_free(p);
#else
  free(p);
#endif
}

const OrtAllocatorInfo& CPUAllocator::Info() const {
  return *allocator_info_;
}
}  // namespace onnxruntime

std::ostream& operator<<(std::ostream& out, const OrtAllocatorInfo& info) {
  return (out << info.ToString());
}

ORT_API_STATUS_IMPL(OrtCreateAllocatorInfo, _In_ const char* name1, OrtAllocatorType type, int id1,
                    OrtMemType mem_type1, _Out_ OrtAllocatorInfo** out) {
  *out = new OrtAllocatorInfo(name1, type, id1, mem_type1);
  return nullptr;
}

ORT_API(void, OrtReleaseAllocatorInfo, _Frees_ptr_opt_ OrtAllocatorInfo* p) {
  delete p;
}

ORT_API_STATUS_IMPL(OrtAllocatorInfoGetName, _In_ OrtAllocatorInfo* ptr, _Out_ const char** out) {
  *out = ptr->name;
  return nullptr;
}

ORT_API_STATUS_IMPL(OrtAllocatorInfoGetId, _In_ OrtAllocatorInfo* ptr, _Out_ int* out) {
  *out = ptr->id;
  return nullptr;
}

ORT_API_STATUS_IMPL(OrtAllocatorInfoGetMemType, _In_ OrtAllocatorInfo* ptr, _Out_ OrtMemType* out) {
  *out = ptr->mem_type;
  return nullptr;
}

ORT_API_STATUS_IMPL(OrtAllocatorInfoGetType, _In_ OrtAllocatorInfo* ptr, _Out_ OrtAllocatorType* out) {
  *out = ptr->type;
  return nullptr;
}

ORT_API_STATUS_IMPL(OrtCompareAllocatorInfo, _In_ const OrtAllocatorInfo* info1, _In_ const OrtAllocatorInfo* info2, _Out_ int* out) {
  *out = (*info1 == *info2) ? 0 : -1;
  return nullptr;
}
<|endoftext|>


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

#ifndef SD_RULER_HXX
#define SD_RULER_HXX

#ifndef _SVX_RULER_HXX
#include <svx/ruler.hxx>
#endif

namespace sd {

class DrawViewShell;
class RulerCtrlItem;
class View;
class Window;

/*************************************************************************
|*
|* das Fenster der Diashow leitet Mouse- und Key-Events an die SlideViewShell
|*
\************************************************************************/

class Ruler
    : public SvxRuler
{
public:
    Ruler (
        DrawViewShell& rViewSh,
        ::Window* pParent,
        ::sd::Window* pWin,
        USHORT nRulerFlags,
        SfxBindings& rBindings,
        WinBits nWinStyle);
    virtual ~Ruler (void);

    void SetNullOffset(const Point& rOffset);

    BOOL IsHorizontal() const { return bHorz; }

protected:
    ::sd::View* pSdView;
    ::sd::Window* pSdWin;
    DrawViewShell* pDrViewShell;
    RulerCtrlItem* pCtrlItem;
    BOOL bHorz;

    virtual void    MouseButtonDown(const MouseEvent& rMEvt);
    virtual void    MouseButtonUp(const MouseEvent& rMEvt);
    virtual void    MouseMove(const MouseEvent& rMEvt);
    virtual void    Command(const CommandEvent& rCEvt);
    virtual void    ExtraDown();
};

} // end of namespace sd

#endif
<commit_msg>INTEGRATION: CWS sdwarningsbegone (1.3.316); FILE MERGED 2006/11/27 13:48:06 cl 1.3.316.1: #i69285# warning free code changes for sd project<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: Ruler.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: kz $ $Date: 2006-12-12 17:37:16 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SD_RULER_HXX
#define SD_RULER_HXX

#ifndef _SVX_RULER_HXX
#include <svx/ruler.hxx>
#endif

namespace sd {

class DrawViewShell;
class RulerCtrlItem;
class View;
class Window;

/*************************************************************************
|*
|* das Fenster der Diashow leitet Mouse- und Key-Events an die SlideViewShell
|*
\************************************************************************/

class Ruler
    : public SvxRuler
{
public:
    Ruler (
        DrawViewShell& rViewSh,
        ::Window* pParent,
        ::sd::Window* pWin,
        USHORT nRulerFlags,
        SfxBindings& rBindings,
        WinBits nWinStyle);
    virtual ~Ruler (void);

    void SetNullOffset(const Point& rOffset);

    BOOL IsHorizontal() const { return bHorz; }

    using ::Ruler::SetNullOffset;
protected:
    ::sd::View* pSdView;
    ::sd::Window* pSdWin;
    DrawViewShell* pDrViewShell;
    RulerCtrlItem* pCtrlItem;
    BOOL bHorz;

    virtual void    MouseButtonDown(const MouseEvent& rMEvt);
    virtual void    MouseButtonUp(const MouseEvent& rMEvt);
    virtual void    MouseMove(const MouseEvent& rMEvt);
    virtual void    Command(const CommandEvent& rCEvt);
    virtual void    ExtraDown();
};

} // end of namespace sd

#endif
<|endoftext|>


<commit_before>/*
    This file is part of Akregator.

    Copyright (C) 2005 Frank Osterfeld <frank.osterfeld at kdemail.net>

    This program 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 2 of the License, or
    (at your option) any later version.

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

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include "listtabwidget.h"
#include "feedlistview.h"
#include "folder.h"
#include "treenode.h"

#include <kmultitabbar.h>

#include <qiconset.h>
#include <qlayout.h>
#include <qmap.h>
#include <qptrlist.h>
#include <qstring.h>
#include <qvaluelist.h>
#include <qwidgetstack.h>

#include <kdebug.h>

namespace Akregator {

class ListTabWidget::ListTabWidgetPrivate
{

public:
    int idCounter;
    KMultiTabBar* tabBar;
    QWidgetStack* stack;
    NodeListView* current;
    int currentID;
    QValueList<NodeListView*> views;
    QMap<int, NodeListView*> idToView;
    QGridLayout* layout;
    ViewMode viewMode;
    QMap<QWidget*, QString> captions;
};

void ListTabWidget::slotItemUp()
{
    if (d->current)
        d->current->slotItemUp();
}

void ListTabWidget::slotItemDown()
{
    if (d->current)
        d->current->slotItemDown();
}

void ListTabWidget::slotItemBegin()
{
    if (d->current)
        d->current->slotItemBegin();
}

void ListTabWidget::slotItemEnd()
{
    if (d->current)
        d->current->slotItemEnd();
}

void ListTabWidget::slotItemLeft()
{
    if (d->current)
        d->current->slotItemLeft();
}

void ListTabWidget::slotItemRight()
{
    if (d->current)
        d->current->slotItemRight();
}

void ListTabWidget::slotPrevFeed()
{
    if (d->current)
        d->current->slotPrevFeed();
}

void ListTabWidget::slotNextFeed()
{
    if (d->current)
        d->current->slotNextFeed();
}

void ListTabWidget::slotPrevUnreadFeed()
{
    if (d->current)
        d->current->slotPrevUnreadFeed();
}

void ListTabWidget::slotNextUnreadFeed()
{
    if (d->current)
        d->current->slotNextUnreadFeed();
}

void ListTabWidget::slotRootNodeChanged(NodeListView* view, TreeNode* node)
{
/*
    int unread = node->unread();
    if (unread > 0)
    {
        //uncomment this to append unread count
        //d->tabWidget->changeTab(view,  QString("<qt>%1 (%2)").arg(d->captions[view]).arg(node->unread()));
        d->tabWidget->changeTab(view, d->captions[view]);
    }
    else
    {
        d->tabWidget->changeTab(view, d->captions[view]);
    }
*/
}

void ListTabWidget::slotTabClicked(int id)
{
    NodeListView* view = d->idToView[id];
    if (view)
    {
        d->stack->raiseWidget(view);
        d->current = view;

        if (d->currentID >= 0)
            d->tabBar->setTab(d->currentID, false);
        d->currentID = id;
        d->tabBar->setTab(d->currentID, true);

        emit signalNodeSelected(d->current->selectedNode());
    }
}

ListTabWidget::ListTabWidget(QWidget* parent, const char* name) : QWidget(parent, name), d(new ListTabWidgetPrivate)
{
    d->idCounter = 0;
    d->current = 0;
    d->currentID = -1;
    d->viewMode = verticalTabs;
    d->layout = new QGridLayout(this, 1, 2);
    d->tabBar = new KMultiTabBar(KMultiTabBar::Vertical, this);
    d->tabBar->setStyle(KMultiTabBar::KDEV3ICON);
    //d->tabBar->setStyle(KMultiTabBar::KDEV3);
    d->tabBar->showActiveTabTexts(true);
    d->tabBar->setPosition(KMultiTabBar::Left);
    d->layout->addWidget(d->tabBar, 0, 0);

    d->stack = new QWidgetStack(this);
    d->layout->addWidget(d->stack, 0, 1);

//    connect(d->tabBar, SIGNAL(currentChanged(QWidget*)), this, SLOT(slotCurrentChanged(QWidget*)));
}

ListTabWidget::~ListTabWidget()
{
    delete d;
    d = 0;
}

/*
void ListTabWidget::setViewMode(ViewMode mode)
{
    if (mode == d->viewMode)
        return;

    // TODO
}*/

ListTabWidget::ViewMode ListTabWidget::viewMode() const
{
    return d->viewMode;
}

void ListTabWidget::addView(NodeListView* view, const QString& caption, const QPixmap& icon)
{
    d->captions[view] = caption;

    view->reparent(d->stack, QPoint(0,0));
    d->stack->addWidget(view);

    int tabId = d->idCounter++;
    d->tabBar->appendTab(icon, tabId, caption);
    d->idToView[tabId] = view;
    connect(d->tabBar->tab(tabId), SIGNAL(clicked(int)), this, SLOT(slotTabClicked(int)));

    connect(view, SIGNAL(signalNodeSelected(TreeNode*)), this, SIGNAL(signalNodeSelected(TreeNode*)));
    connect(view, SIGNAL(signalRootNodeChanged(NodeListView*, TreeNode*)), this, SLOT(slotRootNodeChanged(NodeListView*, TreeNode*)));

    if (tabId == 0) // first widget
    {
        d->current = view;
        d->currentID = 0;
        d->stack->raiseWidget(view);
    }
}

NodeListView* ListTabWidget::activeView() const
{
    return d->current;
}

}

#include "listtabwidget.h"

#include "listtabwidget.moc"
<commit_msg>initially activate the first tab added<commit_after>/*
    This file is part of Akregator.

    Copyright (C) 2005 Frank Osterfeld <frank.osterfeld at kdemail.net>

    This program 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 2 of the License, or
    (at your option) any later version.

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

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include "listtabwidget.h"
#include "feedlistview.h"
#include "folder.h"
#include "treenode.h"

#include <kmultitabbar.h>

#include <qiconset.h>
#include <qlayout.h>
#include <qmap.h>
#include <qptrlist.h>
#include <qstring.h>
#include <qvaluelist.h>
#include <qwidgetstack.h>

#include <kdebug.h>

namespace Akregator {

class ListTabWidget::ListTabWidgetPrivate
{

public:
    int idCounter;
    KMultiTabBar* tabBar;
    QWidgetStack* stack;
    NodeListView* current;
    int currentID;
    QValueList<NodeListView*> views;
    QMap<int, NodeListView*> idToView;
    QGridLayout* layout;
    ViewMode viewMode;
    QMap<QWidget*, QString> captions;
};

void ListTabWidget::slotItemUp()
{
    if (d->current)
        d->current->slotItemUp();
}

void ListTabWidget::slotItemDown()
{
    if (d->current)
        d->current->slotItemDown();
}

void ListTabWidget::slotItemBegin()
{
    if (d->current)
        d->current->slotItemBegin();
}

void ListTabWidget::slotItemEnd()
{
    if (d->current)
        d->current->slotItemEnd();
}

void ListTabWidget::slotItemLeft()
{
    if (d->current)
        d->current->slotItemLeft();
}

void ListTabWidget::slotItemRight()
{
    if (d->current)
        d->current->slotItemRight();
}

void ListTabWidget::slotPrevFeed()
{
    if (d->current)
        d->current->slotPrevFeed();
}

void ListTabWidget::slotNextFeed()
{
    if (d->current)
        d->current->slotNextFeed();
}

void ListTabWidget::slotPrevUnreadFeed()
{
    if (d->current)
        d->current->slotPrevUnreadFeed();
}

void ListTabWidget::slotNextUnreadFeed()
{
    if (d->current)
        d->current->slotNextUnreadFeed();
}

void ListTabWidget::slotRootNodeChanged(NodeListView* view, TreeNode* node)
{
/*
    int unread = node->unread();
    if (unread > 0)
    {
        //uncomment this to append unread count
        //d->tabWidget->changeTab(view,  QString("<qt>%1 (%2)").arg(d->captions[view]).arg(node->unread()));
        d->tabWidget->changeTab(view, d->captions[view]);
    }
    else
    {
        d->tabWidget->changeTab(view, d->captions[view]);
    }
*/
}

void ListTabWidget::slotTabClicked(int id)
{
    NodeListView* view = d->idToView[id];
    if (view)
    {
        d->stack->raiseWidget(view);
        d->current = view;

        if (d->currentID >= 0)
            d->tabBar->setTab(d->currentID, false);
        d->currentID = id;
        d->tabBar->setTab(d->currentID, true);

        emit signalNodeSelected(d->current->selectedNode());
    }
}

ListTabWidget::ListTabWidget(QWidget* parent, const char* name) : QWidget(parent, name), d(new ListTabWidgetPrivate)
{
    d->idCounter = 0;
    d->current = 0;
    d->currentID = -1;
    d->viewMode = verticalTabs;
    d->layout = new QGridLayout(this, 1, 2);
    d->tabBar = new KMultiTabBar(KMultiTabBar::Vertical, this);
    d->tabBar->setStyle(KMultiTabBar::KDEV3ICON);
    //d->tabBar->setStyle(KMultiTabBar::KDEV3);
    d->tabBar->showActiveTabTexts(true);
    d->tabBar->setPosition(KMultiTabBar::Left);
    d->layout->addWidget(d->tabBar, 0, 0);

    d->stack = new QWidgetStack(this);
    d->layout->addWidget(d->stack, 0, 1);

//    connect(d->tabBar, SIGNAL(currentChanged(QWidget*)), this, SLOT(slotCurrentChanged(QWidget*)));
}

ListTabWidget::~ListTabWidget()
{
    delete d;
    d = 0;
}

/*
void ListTabWidget::setViewMode(ViewMode mode)
{
    if (mode == d->viewMode)
        return;

    // TODO
}*/

ListTabWidget::ViewMode ListTabWidget::viewMode() const
{
    return d->viewMode;
}

void ListTabWidget::addView(NodeListView* view, const QString& caption, const QPixmap& icon)
{
    d->captions[view] = caption;

    view->reparent(d->stack, QPoint(0,0));
    d->stack->addWidget(view);

    int tabId = d->idCounter++;
    d->tabBar->appendTab(icon, tabId, caption);
    d->idToView[tabId] = view;
    connect(d->tabBar->tab(tabId), SIGNAL(clicked(int)), this, SLOT(slotTabClicked(int)));

    connect(view, SIGNAL(signalNodeSelected(TreeNode*)), this, SIGNAL(signalNodeSelected(TreeNode*)));
    connect(view, SIGNAL(signalRootNodeChanged(NodeListView*, TreeNode*)), this, SLOT(slotRootNodeChanged(NodeListView*, TreeNode*)));

    if (tabId == 0) // first widget
    {
        d->current = view;
        d->currentID = tabId;
        d->tabBar->setTab(d->currentID, true);
        d->stack->raiseWidget(view);
    }
}

NodeListView* ListTabWidget::activeView() const
{
    return d->current;
}

}

#include "listtabwidget.h"

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


<commit_before>/*
** Author(s):
**  - Cedric GESTES <gestes@aldebaran-robotics.com>
**  - Chris KILNER  <ckilner@aldebaran-robotics.com>
**
** Copyright (C) 2010 Aldebaran Robotics
*/

#ifndef   __QI_SERIALIZATION_SERIALIZEDDATA_HXX__
#define   __QI_SERIALIZATION_SERIALIZEDDATA_HXX__

#if 0
#define __QI_DEBUG_SERIALIZATION_W(x, extra) {                \
  std::string sig = qi::signature< x >::value();              \
  std::cout << "write(" << sig << ")" << extra << std::endl;  \
}

#define __QI_DEBUG_SERIALIZATION_R(x, extra) {                \
  std::string sig = qi::signature< x >::value();              \
  std::cout << "read (" << sig << ")" << extra << std::endl;  \
}

#define __QI_DEBUG_SERIALIZATION_CONTAINER_W(x, c) {                   \
  std::string sig = qi::signature< x >::value();                       \
  std::cout << "write(" << sig << ") size: " << c.size() << std::endl; \
}

#define __QI_DEBUG_SERIALIZATION_CONTAINER_R(x, c) {                  \
  std::string sig = qi::signature< x >::value();                      \
  std::cout << "read (" << sig << ") size: " << c.size() << std::endl; \
}
#else
# define __QI_DEBUG_SERIALIZATION_W(x, extra)
# define __QI_DEBUG_SERIALIZATION_R(x, extra)
# define __QI_DEBUG_SERIALIZATION_CONTAINER_W(x, c)
# define __QI_DEBUG_SERIALIZATION_CONTAINER_R(x, c)
#endif

#include <protobuf/message.h>
//#include <vector>

namespace qi {
  namespace serialization {

//Inline this function => they do nothing, they just call SerializedData method
//we keep vector/map not inlined at the moment because they take space.
#define QI_SIMPLE_SERIALIZER(Name, Type)                                 \
  template <>                                                         \
  struct serialize<Type>  {                                           \
    static inline void write(SerializedData &sd, const Type &val) {   \
      sd.write##Name(val);                                            \
    }                                                                 \
    static inline void read(SerializedData &sd, Type &val) {          \
      sd.read##Name(val);                                             \
    }                                                                 \
  };

    QI_SIMPLE_SERIALIZER(Bool, bool);
    QI_SIMPLE_SERIALIZER(Char, char);
    QI_SIMPLE_SERIALIZER(Int, int);
    QI_SIMPLE_SERIALIZER(Float, float);
    QI_SIMPLE_SERIALIZER(String, std::string);

    template <typename T>
    struct serialize<T&> {
      static inline void write(SerializedData &sd, const T &val) {
        __QI_DEBUG_SERIALIZATION_W(T, "&");
        serialize<T>::write(sd, val);
      }
      static inline void read(SerializedData &sd, T &val) {
        __QI_DEBUG_SERIALIZATION_R(T, "&");
        serialize<T>::read(sd, val);
      }
    };

    template <typename T>
    struct serialize<const T> {
      static inline void write(SerializedData &sd, const T &val) {
        __QI_DEBUG_SERIALIZATION_W(T, "Const");
        serialize<T>::write(sd, val);
      }
      static inline void read(SerializedData &sd, T &val) {
        __QI_DEBUG_SERIALIZATION_R(T, "Const");
        serialize<T>::read(sd, val);
      }
    };

    template <typename T>
    struct serialize<T, typename boost::enable_if< typename boost::is_base_of<google::protobuf::Message , T>::type >::type > {
      static void write(SerializedData &sd, const T &val) {
        __QI_DEBUG_SERIALIZATION_W(T, "Proto");
        std::string ser;
        val.SerializeToString(&ser);
        sd.writeString(ser);
      }

      static void read(SerializedData &sd, T &val) {
        __QI_DEBUG_SERIALIZATION_R(T, "Proto");
        std::string ser;
        sd.readString(ser);
        val.ParseFromString(ser);
      }
    };

    template<typename U>
    struct serialize< std::vector<U> >  {

      static void write(SerializedData &sd, const std::vector<U> &v) {
        sd.writeInt(v.size());
        if (v.size()) {
          // we should find out if the contents is a fixed size type
          // and directly assign the contents if we can
          typename std::vector<U>::const_iterator it = v.begin();
          typename std::vector<U>::const_iterator end = v.end();
          for (; it != end; ++it) {
            serialize<U>::write(*it);
          }
        }
        __QI_DEBUG_SERIALIZATION_CONTAINER_W(std::vector<U>, v);
      }

      static void read(SerializedData &sd, std::vector<U> &v) {
        int sz;
        sd.readInt(sz);
        v.clear();

        if (sz) {
          v.resize(sz);
          for(unsigned int i=0; i < sz; ++i) {
            serialize<U>::read(v[i]);
          }
        }
        __QI_DEBUG_SERIALIZATION_CONTAINER_R(std::vector<U>, v);
      }
    };

    template<typename K, typename V>
    struct serialize< std::map<K, V> >  {

      static void write(SerializedData &sd, const std::map<K, V> &m) {
        sd.writeInt(m.size());
        if (m.size()) {
          typename std::map<K, V>::const_iterator it = m.begin();
          typename std::map<K, V>::const_iterator end = m.end();
          for (; it != end; ++it) {
            serialize<K>::write(sd, it->first);
            serialize<V>::write(sd, it->second);
          }
        }
        typedef std::map<K, V> debugMap;
        __QI_DEBUG_SERIALIZATION_CONTAINER_W(debugMap, m);
      }

      static void read(SerializedData &sd, std::map<K, V>  &m) {
        int sz;
        sd.readInt(sz);
        m.clear();

        if (sz) {
          for(int i=0; i < sz; ++i) {
            K k;
            V v;
            serialize<K>::read(sd, k);
            serialize<V>::read(sd, v);
            m[k] = v;
          }
        }
        typedef std::map<K, V> debugMap;
        __QI_DEBUG_SERIALIZATION_CONTAINER_R(debugMap, m);
      }
    };

  }
}

#endif // __QI_SERIALIZATION_SERIALIZEDDATA_HXX__
<commit_msg>Serialized data: use iterator to fill vector<commit_after>/*
** Author(s):
**  - Cedric GESTES <gestes@aldebaran-robotics.com>
**  - Chris KILNER  <ckilner@aldebaran-robotics.com>
**
** Copyright (C) 2010 Aldebaran Robotics
*/

#ifndef   __QI_SERIALIZATION_SERIALIZEDDATA_HXX__
#define   __QI_SERIALIZATION_SERIALIZEDDATA_HXX__

#if 0
#define __QI_DEBUG_SERIALIZATION_W(x, extra) {                \
  std::string sig = qi::signature< x >::value();              \
  std::cout << "write(" << sig << ")" << extra << std::endl;  \
}

#define __QI_DEBUG_SERIALIZATION_R(x, extra) {                \
  std::string sig = qi::signature< x >::value();              \
  std::cout << "read (" << sig << ")" << extra << std::endl;  \
}

#define __QI_DEBUG_SERIALIZATION_CONTAINER_W(x, c) {                   \
  std::string sig = qi::signature< x >::value();                       \
  std::cout << "write(" << sig << ") size: " << c.size() << std::endl; \
}

#define __QI_DEBUG_SERIALIZATION_CONTAINER_R(x, c) {                  \
  std::string sig = qi::signature< x >::value();                      \
  std::cout << "read (" << sig << ") size: " << c.size() << std::endl; \
}
#else
# define __QI_DEBUG_SERIALIZATION_W(x, extra)
# define __QI_DEBUG_SERIALIZATION_R(x, extra)
# define __QI_DEBUG_SERIALIZATION_CONTAINER_W(x, c)
# define __QI_DEBUG_SERIALIZATION_CONTAINER_R(x, c)
#endif

#include <protobuf/message.h>
//#include <vector>

namespace qi {
  namespace serialization {

//Inline this function => they do nothing, they just call SerializedData method
//we keep vector/map not inlined at the moment because they take space.
#define QI_SIMPLE_SERIALIZER(Name, Type)                                 \
  template <>                                                         \
  struct serialize<Type>  {                                           \
    static inline void write(SerializedData &sd, const Type &val) {   \
      sd.write##Name(val);                                            \
    }                                                                 \
    static inline void read(SerializedData &sd, Type &val) {          \
      sd.read##Name(val);                                             \
    }                                                                 \
  };

    QI_SIMPLE_SERIALIZER(Bool, bool);
    QI_SIMPLE_SERIALIZER(Char, char);
    QI_SIMPLE_SERIALIZER(Int, int);
    QI_SIMPLE_SERIALIZER(Float, float);
    QI_SIMPLE_SERIALIZER(String, std::string);

    template <typename T>
    struct serialize<T&> {
      static inline void write(SerializedData &sd, const T &val) {
        __QI_DEBUG_SERIALIZATION_W(T, "&");
        serialize<T>::write(sd, val);
      }
      static inline void read(SerializedData &sd, T &val) {
        __QI_DEBUG_SERIALIZATION_R(T, "&");
        serialize<T>::read(sd, val);
      }
    };

    template <typename T>
    struct serialize<const T> {
      static inline void write(SerializedData &sd, const T &val) {
        __QI_DEBUG_SERIALIZATION_W(T, "Const");
        serialize<T>::write(sd, val);
      }
      static inline void read(SerializedData &sd, T &val) {
        __QI_DEBUG_SERIALIZATION_R(T, "Const");
        serialize<T>::read(sd, val);
      }
    };

    template <typename T>
    struct serialize<T, typename boost::enable_if< typename boost::is_base_of<google::protobuf::Message , T>::type >::type > {
      static void write(SerializedData &sd, const T &val) {
        __QI_DEBUG_SERIALIZATION_W(T, "Proto");
        std::string ser;
        val.SerializeToString(&ser);
        sd.writeString(ser);
      }

      static void read(SerializedData &sd, T &val) {
        __QI_DEBUG_SERIALIZATION_R(T, "Proto");
        std::string ser;
        sd.readString(ser);
        val.ParseFromString(ser);
      }
    };

    template<typename U>
    struct serialize< std::vector<U> >  {

      static void write(SerializedData &sd, const std::vector<U> &v) {
        sd.writeInt(v.size());
        if (v.size()) {
          // we should find out if the contents is a fixed size type
          // and directly assign the contents if we can
          typename std::vector<U>::const_iterator it = v.begin();
          typename std::vector<U>::const_iterator end = v.end();
          for (; it != end; ++it) {
            serialize<U>::write(*it);
          }
        }
        __QI_DEBUG_SERIALIZATION_CONTAINER_W(std::vector<U>, v);
      }

      static void read(SerializedData &sd, std::vector<U> &v) {
        int sz;
        sd.readInt(sz);
        v.clear();

        if (sz) {
          v.resize(sz);
          typename std::vector<U>::iterator it = v.begin();
          typename std::vector<U>::iterator end = v.end();
          for (; it != end; ++it) {
            serialize<U>::read(*it);
          }
        }
        __QI_DEBUG_SERIALIZATION_CONTAINER_R(std::vector<U>, v);
      }
    };

    template<typename K, typename V>
    struct serialize< std::map<K, V> >  {

      static void write(SerializedData &sd, const std::map<K, V> &m) {
        sd.writeInt(m.size());
        if (m.size()) {
          typename std::map<K, V>::const_iterator it = m.begin();
          typename std::map<K, V>::const_iterator end = m.end();
          for (; it != end; ++it) {
            serialize<K>::write(sd, it->first);
            serialize<V>::write(sd, it->second);
          }
        }
        typedef std::map<K, V> debugMap;
        __QI_DEBUG_SERIALIZATION_CONTAINER_W(debugMap, m);
      }

      static void read(SerializedData &sd, std::map<K, V>  &m) {
        int sz;
        sd.readInt(sz);
        m.clear();

        if (sz) {
          for(int i=0; i < sz; ++i) {
            K k;
            V v;
            serialize<K>::read(sd, k);
            serialize<V>::read(sd, v);
            m[k] = v;
          }
        }
        typedef std::map<K, V> debugMap;
        __QI_DEBUG_SERIALIZATION_CONTAINER_R(debugMap, m);
      }
    };

  }
}

#endif // __QI_SERIALIZATION_SERIALIZEDDATA_HXX__
<|endoftext|>


<commit_before>// Author: Valeriy Onuchin   25/08/2007
//
// This macro gives an example of how to set/change
// text entry attributes.
//
// To run it do either:
// .x textEntries.C
// .x textEntries.C++

#include <TGTextEntry.h>
#include <TGButtonGroup.h>
#include <TGLabel.h>
#include <TGComboBox.h>
#include <TApplication.h>

//////////// auxilary class ///////////////////////////////////////////////////
class GroupBox : public TGGroupFrame {
private:
   TGComboBox 	*fCombo;	// combo box
   TGTextEntry *fEntry;	// text entry

public:
   GroupBox(const TGWindow *p, const char *name, const char *title);
   TGTextEntry *GetEntry() const { return fEntry; }
   TGComboBox  *GetCombo() const { return fCombo; }

   ClassDef(GroupBox, 0)
};

//______________________________________________________________________________
GroupBox::GroupBox(const TGWindow *p, const char *name, const char *title) :
	TGGroupFrame(p, name)
{
	// group frame containing combobox and text entry

	TGHorizontalFrame *horz = new TGHorizontalFrame(this);
	AddFrame(horz, new TGLayoutHints(kLHintsExpandX | kLHintsCenterY));
   TGLabel *label = new TGLabel(horz, title);
	horz->AddFrame(label, new TGLayoutHints(kLHintsLeft | kLHintsCenterY));

	fCombo = new TGComboBox(horz);
	horz->AddFrame(fCombo, new TGLayoutHints(kLHintsRight | kLHintsExpandY,
						5, 0, 5, 5));
	fCombo->Resize(100, 20);

   fEntry = new TGTextEntry(this);
   AddFrame(fEntry, new TGLayoutHints(kLHintsExpandX | kLHintsCenterY));
}

////////////////////////////////////////////////////////////////////////////////
class TextEntryWindow {

protected:
   TGMainFrame *fMain;		// main frame
	GroupBox		*fEcho;		// echo mode (echo, password, no echo)
	GroupBox		*fAlign;		// alignment (left, right, center)
	GroupBox		*fAccess;	// read-only mode
	GroupBox		*fBorder;	// border mode

public:
   TextEntryWindow();
	virtual ~TextEntryWindow() { delete fMain; }

   ClassDef(TextEntryWindow, 0);
};

//______________________________________________________________________________
TextEntryWindow::TextEntryWindow()
{
   // Main test window.

	TGComboBox  *combo;
	TGTextEntry *entry;

	fMain = new TGMainFrame(0, 10, 10, kVerticalFrame);

	// recusively delete all subframes on exit
   fMain->SetCleanup(kDeepCleanup);

	fEcho = new GroupBox(fMain, "Echo", "Mode:");
	fMain->AddFrame(fEcho, new TGLayoutHints(kLHintsExpandX | kLHintsExpandY, 5, 5));
	combo = fEcho->GetCombo();
	entry = fEcho->GetEntry();
   // add entries
	combo->AddEntry("Normal", TGTextEntry::kNormal);
	combo->AddEntry("Password", TGTextEntry::kPassword);
	combo->AddEntry("No Echo", TGTextEntry::kNoEcho);
   // compact popup listbox
   combo->GetListBox()->Resize(combo->GetWidth(), combo->GetNumberOfEntries()*combo->GetHeight());

	combo->Connect("Selected(Int_t)", "TGTextEntry", entry, "SetEchoMode(Int_t)");
	combo->Select(TGTextEntry::kNormal);

	fAlign = new GroupBox(fMain, "Alignment", "Type:");
	fMain->AddFrame(fAlign, new TGLayoutHints(kLHintsExpandX | kLHintsExpandY, 5, 5));
	combo = fAlign->GetCombo();
	entry = fAlign->GetEntry();
   // add entries
	combo->Connect("Selected(Int_t)", "TGTextEntry", entry, "SetAlignment(Int_t)");
	combo->AddEntry("Left", kTextLeft);
	combo->AddEntry("Centered", kTextCenterX);
	combo->AddEntry("Right", kTextRight);
   // compact popup listbox
   combo->GetListBox()->Resize(combo->GetWidth(), combo->GetNumberOfEntries()*combo->GetHeight());
	combo->Select(kTextLeft);

	fAccess = new GroupBox(fMain, "Access", "Read-only:");
	fMain->AddFrame(fAccess, new TGLayoutHints(kLHintsExpandX | kLHintsExpandY, 5, 5));
	combo = fAccess->GetCombo();
	entry = fAccess->GetEntry();
	combo->Connect("Selected(Int_t)", "TGTextEntry", entry, "SetEnabled(Int_t)");
   // add entries
	combo->AddEntry("False", 1);
	combo->AddEntry("True", 0);
   // compact popup listbox
   combo->GetListBox()->Resize(combo->GetWidth(), combo->GetNumberOfEntries()*combo->GetHeight());
	combo->Select(1);

	fBorder = new GroupBox(fMain, "Border", "Drawn:");
	fMain->AddFrame(fBorder, new TGLayoutHints(kLHintsExpandX | kLHintsExpandY, 5, 5));
	combo = fBorder->GetCombo();
	entry = fBorder->GetEntry();
	combo->Connect("Selected(Int_t)", "TGTextEntry", entry, "SetFrameDrawn(Int_t)");
   // add entries
	combo->AddEntry("False", 0);
	combo->AddEntry("True", 1);
   // compact popup listbox
   combo->GetListBox()->Resize(combo->GetWidth(), combo->GetNumberOfEntries()*combo->GetHeight());
	combo->Select(1);

	// terminate ROOT session when window is closed
   fMain->Connect("CloseWindow()", "TApplication", gApplication, "Terminate()");
   fMain->DontCallClose();

   fMain->MapSubwindows();
   fMain->Resize();

	// set minimum width, height
   fMain->SetWMSizeHints(fMain->GetDefaultWidth(), fMain->GetDefaultHeight(),
								 1000, 1000, 0, 0);
   fMain->SetWindowName("Text Entries");
   fMain->MapRaised();
}

////////////////////////////////////////////////////////////////////////////////
void textEntries()
{
   // Main program.

   new TextEntryWindow();
}
<commit_msg>From Valeriy Onuchin: Taken advantage of TGComboBox::Layout() changes ++ removed many <TAB> from me<commit_after>// Author: Valeriy Onuchin   25/08/2007
//
// This macro gives an example of how to set/change
// text entry attributes.
//
// To run it do either:
// .x textEntries.C
// .x textEntries.C++

#include <TGTextEntry.h>
#include <TGButtonGroup.h>
#include <TGLabel.h>
#include <TGComboBox.h>
#include <TApplication.h>

//////////// auxilary class ///////////////////////////////////////////////////
class GroupBox : public TGGroupFrame {
private:
   TGComboBox 	*fCombo;	// combo box
   TGTextEntry *fEntry;	// text entry

public:
   GroupBox(const TGWindow *p, const char *name, const char *title);
   TGTextEntry *GetEntry() const { return fEntry; }
   TGComboBox  *GetCombo() const { return fCombo; }

   ClassDef(GroupBox, 0)
};

//______________________________________________________________________________
GroupBox::GroupBox(const TGWindow *p, const char *name, const char *title) :
   TGGroupFrame(p, name)
{
   // Group frame containing combobox and text entry.

   TGHorizontalFrame *horz = new TGHorizontalFrame(this);
   AddFrame(horz, new TGLayoutHints(kLHintsExpandX | kLHintsCenterY));
   TGLabel *label = new TGLabel(horz, title);
   horz->AddFrame(label, new TGLayoutHints(kLHintsLeft | kLHintsCenterY));

   fCombo = new TGComboBox(horz);
   horz->AddFrame(fCombo, new TGLayoutHints(kLHintsRight | kLHintsExpandY,
                                            5, 0, 5, 5));
   fCombo->Resize(100, 20);

   fEntry = new TGTextEntry(this);
   AddFrame(fEntry, new TGLayoutHints(kLHintsExpandX | kLHintsCenterY));
}

////////////////////////////////////////////////////////////////////////////////
class TextEntryWindow {

protected:
   TGMainFrame *fMain;		// main frame
   GroupBox		*fEcho;		// echo mode (echo, password, no echo)
   GroupBox		*fAlign;		// alignment (left, right, center)
   GroupBox		*fAccess;	// read-only mode
   GroupBox		*fBorder;	// border mode

public:
   TextEntryWindow();
   virtual ~TextEntryWindow() { delete fMain; }

   ClassDef(TextEntryWindow, 0);
};

//______________________________________________________________________________
TextEntryWindow::TextEntryWindow()
{
   // Main test window.

   TGComboBox  *combo;
   TGTextEntry *entry;

   fMain = new TGMainFrame(0, 10, 10, kVerticalFrame);

   // recusively delete all subframes on exit
   fMain->SetCleanup(kDeepCleanup);

   fEcho = new GroupBox(fMain, "Echo", "Mode:");
   fMain->AddFrame(fEcho, new TGLayoutHints(kLHintsExpandX | kLHintsExpandY, 5, 5));
   combo = fEcho->GetCombo();
   entry = fEcho->GetEntry();
   // add entries
   combo->AddEntry("Normal", TGTextEntry::kNormal);
   combo->AddEntry("Password", TGTextEntry::kPassword);
   combo->AddEntry("No Echo", TGTextEntry::kNoEcho);
   combo->Connect("Selected(Int_t)", "TGTextEntry", entry, "SetEchoMode(Int_t)");
   combo->Select(TGTextEntry::kNormal);

   fAlign = new GroupBox(fMain, "Alignment", "Type:");
   fMain->AddFrame(fAlign, new TGLayoutHints(kLHintsExpandX | kLHintsExpandY, 5, 5));
   combo = fAlign->GetCombo();
   entry = fAlign->GetEntry();
   // add entries
   combo->AddEntry("Left", kTextLeft);
   combo->AddEntry("Centered", kTextCenterX);
   combo->AddEntry("Right", kTextRight);
   combo->Connect("Selected(Int_t)", "TGTextEntry", entry, "SetAlignment(Int_t)");
   combo->Select(kTextLeft);

   fAccess = new GroupBox(fMain, "Access", "Read-only:");
   fMain->AddFrame(fAccess, new TGLayoutHints(kLHintsExpandX | kLHintsExpandY, 5, 5));
   combo = fAccess->GetCombo();
   entry = fAccess->GetEntry();
   // add entries
   combo->AddEntry("False", 1);
   combo->AddEntry("True", 0);
   combo->Connect("Selected(Int_t)", "TGTextEntry", entry, "SetEnabled(Int_t)");
   combo->Select(1);

   fBorder = new GroupBox(fMain, "Border", "Drawn:");
   fMain->AddFrame(fBorder, new TGLayoutHints(kLHintsExpandX | kLHintsExpandY, 5, 5));
   combo = fBorder->GetCombo();
   entry = fBorder->GetEntry();
   // add entries
   combo->AddEntry("False", 0);
   combo->AddEntry("True", 1);
   combo->Connect("Selected(Int_t)", "TGTextEntry", entry, "SetFrameDrawn(Int_t)");
   combo->Select(1);

   // terminate ROOT session when window is closed
   fMain->Connect("CloseWindow()", "TApplication", gApplication, "Terminate()");
   fMain->DontCallClose();

   fMain->MapSubwindows();
   fMain->Resize();

   // set minimum width, height
   fMain->SetWMSizeHints(fMain->GetDefaultWidth(), fMain->GetDefaultHeight(),
                         1000, 1000, 0, 0);
   fMain->SetWindowName("Text Entries");
   fMain->MapRaised();
}

////////////////////////////////////////////////////////////////////////////////
void textEntries()
{
   // Main program.

   new TextEntryWindow();
}
<|endoftext|>


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

#ifndef INCLUDED_TDOC_STORAGE_HXX
#define INCLUDED_TDOC_STORAGE_HXX

#include <map>

#include "osl/mutex.hxx"
#include "rtl/ref.hxx"
#include "salhelper/simplereferenceobject.hxx"

#include "com/sun/star/embed/XStorage.hpp"

namespace tdoc_ucp {

    enum StorageAccessMode
    {
        READ, // Note: might be writable as well
        READ_WRITE_NOCREATE,
        READ_WRITE_CREATE
    };

    class Storage;
    class OfficeDocumentsManager;

    class StorageElementFactory : public salhelper::SimpleReferenceObject
    {
    public:
        StorageElementFactory(
            const com::sun::star::uno::Reference<
                com::sun::star::lang::XMultiServiceFactory > & xSMgr,
            const rtl::Reference< OfficeDocumentsManager > & xDocsMgr );
        ~StorageElementFactory();

        com::sun::star::uno::Reference< com::sun::star::embed::XStorage >
        createTemporaryStorage()
            throw ( com::sun::star::uno::Exception,
                    com::sun::star::uno::RuntimeException );

        com::sun::star::uno::Reference< com::sun::star::embed::XStorage >
        createStorage( const rtl::OUString & rUri, StorageAccessMode eMode )
            throw ( com::sun::star::embed::InvalidStorageException,
                    com::sun::star::lang::IllegalArgumentException,
                    com::sun::star::io::IOException,
                    com::sun::star::embed::StorageWrappedTargetException,
                    com::sun::star::uno::RuntimeException );

        com::sun::star::uno::Reference< com::sun::star::io::XInputStream >
        createInputStream( const rtl::OUString & rUri,
                           const rtl::OUString & rPassword )
            throw ( com::sun::star::embed::InvalidStorageException,
                    com::sun::star::lang::IllegalArgumentException,
                    com::sun::star::io::IOException,
                    com::sun::star::embed::StorageWrappedTargetException,
                    com::sun::star::packages::WrongPasswordException,
                    com::sun::star::uno::RuntimeException );

        com::sun::star::uno::Reference< com::sun::star::io::XOutputStream >
        createOutputStream( const rtl::OUString & rUri,
                            const rtl::OUString & rPassword,
                            bool bTruncate )
            throw ( com::sun::star::embed::InvalidStorageException,
                    com::sun::star::lang::IllegalArgumentException,
                    com::sun::star::io::IOException,
                    com::sun::star::embed::StorageWrappedTargetException,
                    com::sun::star::packages::WrongPasswordException,
                    com::sun::star::uno::RuntimeException );

        com::sun::star::uno::Reference< com::sun::star::io::XStream >
        createStream( const rtl::OUString & rUri,
                      const rtl::OUString & rPassword,
                      bool bTruncate )
            throw ( com::sun::star::embed::InvalidStorageException,
                    com::sun::star::lang::IllegalArgumentException,
                    com::sun::star::io::IOException,
                    com::sun::star::embed::StorageWrappedTargetException,
                    com::sun::star::packages::WrongPasswordException,
                    com::sun::star::uno::RuntimeException );

    private:
        friend class Storage;

        void releaseElement( Storage * pElement ) SAL_THROW(());

        com::sun::star::uno::Reference< com::sun::star::embed::XStorage >
        queryParentStorage( const rtl::OUString & rUri,
                            StorageAccessMode eMode )
            throw ( com::sun::star::embed::InvalidStorageException,
                    com::sun::star::lang::IllegalArgumentException,
                    com::sun::star::io::IOException,
                    com::sun::star::embed::StorageWrappedTargetException,
                    com::sun::star::uno::RuntimeException );

        com::sun::star::uno::Reference< com::sun::star::embed::XStorage >
        queryStorage( const com::sun::star::uno::Reference<
                        com::sun::star::embed::XStorage > & xParentStorage,
                      const rtl::OUString & rUri,
                      StorageAccessMode eMode )
            throw ( com::sun::star::embed::InvalidStorageException,
                    com::sun::star::lang::IllegalArgumentException,
                    com::sun::star::io::IOException,
                    com::sun::star::embed::StorageWrappedTargetException,
                    com::sun::star::uno::RuntimeException );

        com::sun::star::uno::Reference< com::sun::star::io::XStream >
        queryStream( const com::sun::star::uno::Reference<
                        com::sun::star::embed::XStorage > & xParentStorage,
                     const rtl::OUString & rPassword,
                     const rtl::OUString & rUri,
                     StorageAccessMode eMode,
                     bool bTruncate /* ignored for read-only streams */ )
            throw ( com::sun::star::embed::InvalidStorageException,
                    com::sun::star::lang::IllegalArgumentException,
                    com::sun::star::io::IOException,
                    com::sun::star::embed::StorageWrappedTargetException,
                    com::sun::star::packages::WrongPasswordException,
                    com::sun::star::uno::RuntimeException );

        struct ltstrbool
        {
            bool operator()(
                const std::pair< rtl::OUString, bool > & s1,
                const std::pair< rtl::OUString, bool > & s2 ) const
            {
                if ( s1.first < s2.first )
                    return true;
                else if ( s1.first == s2.first )
                    return ( !s1.second && s2.second );
                else
                    return false;
            }
        };

        // key: pair< storageuri, iswritable >
        typedef std::map<
            std::pair< rtl::OUString, bool >, Storage *, ltstrbool > StorageMap;

        StorageMap m_aMap;
        osl::Mutex m_aMutex;
        rtl::Reference< OfficeDocumentsManager > m_xDocsMgr;
        com::sun::star::uno::Reference<
            com::sun::star::lang::XMultiServiceFactory > m_xSMgr;
    };

} // namespace tdoc_ucp

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

#ifndef INCLUDED_TDOC_STORAGE_HXX
#define INCLUDED_TDOC_STORAGE_HXX

#include <map>

#include "osl/mutex.hxx"
#include "rtl/ref.hxx"
#include "salhelper/simplereferenceobject.hxx"

#include "com/sun/star/embed/XStorage.hpp"

namespace tdoc_ucp {

    enum StorageAccessMode
    {
        READ, // Note: might be writable as well
        READ_WRITE_NOCREATE,
        READ_WRITE_CREATE
    };

    class Storage;
    class OfficeDocumentsManager;

    class StorageElementFactory : public salhelper::SimpleReferenceObject
    {
    public:
        StorageElementFactory(
            const com::sun::star::uno::Reference<
                com::sun::star::lang::XMultiServiceFactory > & xSMgr,
            const rtl::Reference< OfficeDocumentsManager > & xDocsMgr );
        ~StorageElementFactory();

        com::sun::star::uno::Reference< com::sun::star::embed::XStorage >
        createTemporaryStorage()
            throw ( com::sun::star::uno::Exception,
                    com::sun::star::uno::RuntimeException );

        com::sun::star::uno::Reference< com::sun::star::embed::XStorage >
        createStorage( const rtl::OUString & rUri, StorageAccessMode eMode )
            throw ( com::sun::star::embed::InvalidStorageException,
                    com::sun::star::lang::IllegalArgumentException,
                    com::sun::star::io::IOException,
                    com::sun::star::embed::StorageWrappedTargetException,
                    com::sun::star::uno::RuntimeException );

        com::sun::star::uno::Reference< com::sun::star::io::XInputStream >
        createInputStream( const rtl::OUString & rUri,
                           const rtl::OUString & rPassword )
            throw ( com::sun::star::embed::InvalidStorageException,
                    com::sun::star::lang::IllegalArgumentException,
                    com::sun::star::io::IOException,
                    com::sun::star::embed::StorageWrappedTargetException,
                    com::sun::star::packages::WrongPasswordException,
                    com::sun::star::uno::RuntimeException );

        com::sun::star::uno::Reference< com::sun::star::io::XOutputStream >
        createOutputStream( const rtl::OUString & rUri,
                            const rtl::OUString & rPassword,
                            bool bTruncate )
            throw ( com::sun::star::embed::InvalidStorageException,
                    com::sun::star::lang::IllegalArgumentException,
                    com::sun::star::io::IOException,
                    com::sun::star::embed::StorageWrappedTargetException,
                    com::sun::star::packages::WrongPasswordException,
                    com::sun::star::uno::RuntimeException );

        com::sun::star::uno::Reference< com::sun::star::io::XStream >
        createStream( const rtl::OUString & rUri,
                      const rtl::OUString & rPassword,
                      bool bTruncate )
            throw ( com::sun::star::embed::InvalidStorageException,
                    com::sun::star::lang::IllegalArgumentException,
                    com::sun::star::io::IOException,
                    com::sun::star::embed::StorageWrappedTargetException,
                    com::sun::star::packages::WrongPasswordException,
                    com::sun::star::uno::RuntimeException );

    private:
        friend class Storage;

        void releaseElement( Storage * pElement ) SAL_THROW(());

        com::sun::star::uno::Reference< com::sun::star::embed::XStorage >
        queryParentStorage( const rtl::OUString & rUri,
                            StorageAccessMode eMode )
            throw ( com::sun::star::embed::InvalidStorageException,
                    com::sun::star::lang::IllegalArgumentException,
                    com::sun::star::io::IOException,
                    com::sun::star::embed::StorageWrappedTargetException,
                    com::sun::star::uno::RuntimeException );

        com::sun::star::uno::Reference< com::sun::star::embed::XStorage >
        queryStorage( const com::sun::star::uno::Reference<
                        com::sun::star::embed::XStorage > & xParentStorage,
                      const rtl::OUString & rUri,
                      StorageAccessMode eMode )
            throw ( com::sun::star::embed::InvalidStorageException,
                    com::sun::star::lang::IllegalArgumentException,
                    com::sun::star::io::IOException,
                    com::sun::star::embed::StorageWrappedTargetException,
                    com::sun::star::uno::RuntimeException );

        com::sun::star::uno::Reference< com::sun::star::io::XStream >
        queryStream( const com::sun::star::uno::Reference<
                        com::sun::star::embed::XStorage > & xParentStorage,
                     const rtl::OUString & rPassword,
                     const rtl::OUString & rUri,
                     StorageAccessMode eMode,
                     bool bTruncate /* ignored for read-only streams */ )
            throw ( com::sun::star::embed::InvalidStorageException,
                    com::sun::star::lang::IllegalArgumentException,
                    com::sun::star::io::IOException,
                    com::sun::star::embed::StorageWrappedTargetException,
                    com::sun::star::packages::WrongPasswordException,
                    com::sun::star::uno::RuntimeException );

        struct ltstrbool
        {
            bool operator()(
                const std::pair< rtl::OUString, bool > & s1,
                const std::pair< rtl::OUString, bool > & s2 ) const
            {
                if ( s1.first < s2.first )
                    return true;
                else if ( s1.first == s2.first )
                    return ( !s1.second && s2.second );
                else
                    return false;
            }
        };

        // key: pair< storageuri, iswritable >
        typedef std::map<
            std::pair< rtl::OUString, bool >, Storage *, ltstrbool > StorageMap;

        StorageMap m_aMap;
        osl::Mutex m_aMutex;
        rtl::Reference< OfficeDocumentsManager > m_xDocsMgr;
        com::sun::star::uno::Reference<
            com::sun::star::lang::XMultiServiceFactory > m_xSMgr;
    };

} // namespace tdoc_ucp

#endif /* !INCLUDED_TDOC_STORAGE_HXX */
<|endoftext|>