<commit_before>#include <nan.h>
#include <fstream>
#include "hive.h"

using namespace v8;

static uv_key_t isolate_cache_key;
static uv_key_t context_cache_key;
static uv_once_t key_guard;

static std::ifstream f("node_modules/babel-core/browser.js");
static std::string babel(
    (std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());

// Initialize libuv thread-local cache keys.
static void create_keys() {
  (void) uv_key_create(&isolate_cache_key);
  (void) uv_key_create(&context_cache_key);
}

// Returns an Isolate* from the thread-local cache, if it exists.
// Otherwise, creates and caches a new Isolate* before returning.
static Isolate* get_isolate() {
  Isolate* isolate = (Isolate *) uv_key_get(&isolate_cache_key);
  if (isolate == NULL) {
    isolate = Isolate::New();
    uv_key_set(&isolate_cache_key, isolate);
  }
  return isolate;
}

// Returns a Persistent<Context>* from the thread-local cache, if it exists.
// Otherwise, creates a new Persistent<Context>* in the given isolate, and
// evaluates the Babel bootstrap script to prepare the context for file
// transformation.
static Persistent<Context>* get_context(Isolate* isolate) {
  Persistent<Context>* context =
    (Persistent<Context> *) uv_key_get(&context_cache_key);

  if (context == NULL) {
    Local<Context> ctx = Context::New(isolate);
    context = new Persistent<Context>(isolate, ctx);

    Context::Scope context_scope(ctx);
    Local<Script> script = Script::Compile(
        String::NewFromUtf8(isolate, babel.c_str()));

    (void) script->Run();
    uv_key_set(&context_cache_key, context);
  }

  return context;
}

// Transforms the given file contents in a new v8 isolate on Node's default
// libuv thread pool, returning the result of the transformation on the main
// event loop.
class HiveWorker : public NanAsyncWorker {
 public:
  HiveWorker(NanCallback* callback, std::string path, std::string script)
    : NanAsyncWorker(callback), path(path), script(script) {}
  ~HiveWorker() {}

  // Executed inside the worker-thread.
  void Execute () {
    (void) uv_once(&key_guard, create_keys);
    Isolate* isolate = get_isolate();
    Isolate::Scope isolate_scope(isolate);

    NanLocker();
    NanScope();

    Persistent<Context>* context = get_context(isolate);
    Context::Scope context_scope(Local<Context>::New(isolate, *context));

    Local<Script> s = Script::Compile(NanNew<String>(script.c_str()));
    Local<Value> result = s->Run();

    res = result->IntegerValue();
    NanUnlocker();
  }

  // Executed when the async work is complete, inside the main thread.
  void HandleOKCallback () {
    NanScope();

    Local<Value> argv[] = {
        NanNull(),
        NanNew<Number>(res)
    };

    callback->Call(2, argv);
  }

 private:
  std::string path;
  std::string script;
  int64_t res;
};

NAN_METHOD(Take) {
  NanScope();

  String::Utf8Value p(args[0]->ToString());
  std::string path(*p);

  String::Utf8Value s(args[1]->ToString());
  std::string script(*s);

  NanCallback *callback = new NanCallback(args[2].As<Function>());
  NanAsyncQueueWorker(new HiveWorker(callback, path, script));
  NanReturnUndefined();
}
<commit_msg>Return string values from script eval<commit_after>#include <nan.h>
#include <fstream>
#include "hive.h"

using namespace v8;

static uv_key_t isolate_cache_key;
static uv_key_t context_cache_key;
static uv_once_t key_guard;

static std::ifstream f("node_modules/babel-core/browser.js");
static std::string babel(
    (std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());

// Initialize libuv thread-local cache keys.
static void create_keys() {
  (void) uv_key_create(&isolate_cache_key);
  (void) uv_key_create(&context_cache_key);
}

// Returns an Isolate* from the thread-local cache, if it exists.
// Otherwise, creates and caches a new Isolate* before returning.
static Isolate* get_isolate() {
  Isolate* isolate = (Isolate *) uv_key_get(&isolate_cache_key);
  if (isolate == NULL) {
    isolate = Isolate::New();
    uv_key_set(&isolate_cache_key, isolate);
  }
  return isolate;
}

// Returns a Persistent<Context>* from the thread-local cache, if it exists.
// Otherwise, creates a new Persistent<Context>* in the given isolate, and
// evaluates the Babel bootstrap script to prepare the context for file
// transformation.
static Persistent<Context>* get_context(Isolate* isolate) {
  Persistent<Context>* context =
    (Persistent<Context> *) uv_key_get(&context_cache_key);

  if (context == NULL) {
    Local<Context> ctx = Context::New(isolate);
    context = new Persistent<Context>(isolate, ctx);

    Context::Scope context_scope(ctx);
    Local<Script> script = Script::Compile(
        String::NewFromUtf8(isolate, babel.c_str()));

    (void) script->Run();
    uv_key_set(&context_cache_key, context);
  }

  return context;
}

// Transforms the given file contents in a new v8 isolate on Node's default
// libuv thread pool, returning the result of the transformation on the main
// event loop.
class HiveWorker : public NanAsyncWorker {
 public:
  HiveWorker(NanCallback* callback, std::string path, std::string script)
    : NanAsyncWorker(callback), path(path), script(script) {}
  ~HiveWorker() {}

  // Executed inside the worker-thread.
  void Execute () {
    (void) uv_once(&key_guard, create_keys);
    Isolate* isolate = get_isolate();
    Isolate::Scope isolate_scope(isolate);

    NanLocker();
    NanScope();

    Persistent<Context>* context = get_context(isolate);
    Context::Scope context_scope(Local<Context>::New(isolate, *context));

    Local<Script> s = Script::Compile(NanNew<String>(script.c_str()));
    Local<String> result = s->Run()->ToString();

    String::Utf8Value r(result);

    res = std::string(*r);
    NanUnlocker();
  }

  // Executed when the async work is complete, inside the main thread.
  void HandleOKCallback () {
    NanScope();

    Local<Value> argv[] = {
        NanNull(),
        NanNew<String>(res.c_str())
    };

    callback->Call(2, argv);
  }

 private:
  std::string path;
  std::string script;
  std::string res;
};

NAN_METHOD(Take) {
  NanScope();

  String::Utf8Value p(args[0]->ToString());
  std::string path(*p);

  String::Utf8Value s(args[1]->ToString());
  std::string script(*s);

  NanCallback *callback = new NanCallback(args[2].As<Function>());
  NanAsyncQueueWorker(new HiveWorker(callback, path, script));
  NanReturnUndefined();
}
<|endoftext|>


<commit_before>#include "S2_Sprite.h"
#include "S2_Symbol.h"
#include "OBB.h"
#include "RenderFilter.h"
#include "FilterFactory.h"

namespace s2
{

Sprite::Sprite()
	: m_sym(NULL)
	, m_position(0, 0)
	, m_angle(0)
	, m_scale(1, 1)
	, m_shear(0, 0)
	, m_visible(true)
{
	m_offset.MakeInvalid();

	m_bounding = new OBB();
	m_bounding_dirty = true;

	m_shader.filter = FilterFactory::Instance()->Create(FM_NULL);
}

Sprite::Sprite(const Sprite& spr)
	: m_sym(NULL)
	, m_position(spr.m_position)
	, m_angle(spr.m_angle)
	, m_scale(spr.m_scale)
	, m_shear(spr.m_shear)
	, m_offset(spr.m_offset)
	, m_color(spr.m_color)
	, m_shader(spr.m_shader)
	, m_camera(spr.m_camera)
	, m_visible(spr.m_visible)
{
	if (spr.m_sym) {
		spr.m_sym->AddReference();
		m_sym = spr.m_sym;
	}

	m_bounding = spr.m_bounding->Clone();
	m_bounding_dirty = true;

	FilterMode fm = FM_NULL;
	if (spr.Shader().filter) {
		fm = spr.Shader().filter->GetMode();
	}
	m_shader.filter = FilterFactory::Instance()->Create(fm);
}

Sprite::Sprite(Symbol* sym)
	: m_sym(NULL)
	, m_position(0, 0)
	, m_angle(0)
	, m_scale(1, 1)
	, m_shear(0, 0)
	, m_visible(true)
{
	m_offset.MakeInvalid();

	m_bounding = new OBB();
	SetSymbol(sym);

	m_shader.filter = FilterFactory::Instance()->Create(FM_NULL);
}

Sprite::~Sprite()
{
	if (m_sym) {
		m_sym->RemoveReference();
	}

	delete m_bounding;

	delete m_shader.filter;
}

void Sprite::Translate(const sm::vec2& offset)
{
	m_position += offset;
}

void Sprite::Rotate(float delta)
{
	m_angle += delta;
}

void Sprite::SetSymbol(Symbol* sym)
{
	cu::RefCountObjAssign(m_sym, sym);
	UpdateBounding();
}

const BoundingBox* Sprite::GetBounding() const
{
	if (m_bounding_dirty) {
		UpdateBounding();
	}
	return m_bounding;
}

// todo: m_sym->GetBounding too slow, should be cached
void Sprite::UpdateBounding() const
{
	if (!m_sym) {
		return;
	}

	sm::rect rect = m_sym->GetBounding(this);

	if (!m_offset.IsValid()) {
		m_offset = rect.Center();
	}

	m_bounding_dirty = false;
	m_bounding->Build(rect, m_position, m_angle, m_scale, m_shear, m_offset);
}

sm::vec2 Sprite::GetCenter() const
{
	sm::vec2 center_offset = sm::rotate_vector(-m_offset, m_angle) + m_offset;
	sm::vec2 center = m_position + center_offset;
	return center;
}

void Sprite::SetPosition(const sm::vec2& pos)
{
	m_position = pos;

// 	// immediately
// 	m_bounding->SetTransform(m_position, m_offset, m_angle);

	// lazy
	m_bounding_dirty = true;
}

void Sprite::SetAngle(float angle)
{
	m_angle = angle;

// 	// immediately
// 	m_bounding->SetTransform(m_position, m_offset, m_angle);

	// lazy
	m_bounding_dirty = true;
}

void Sprite::SetScale(const sm::vec2& scale)
{
	const sm::vec2& old_scale = m_scale;
	if (old_scale.x != 0 && old_scale.y != 0) {
		sm::vec2 dscale;
		dscale.x = scale.x / m_scale.x;
		dscale.y = scale.y / m_scale.y;

		sm::vec2 old_offset = m_offset;
		sm::vec2 new_offset(m_offset.x * dscale.x, m_offset.y * dscale.y);
		m_offset = new_offset;

		Translate(old_offset - new_offset);
	}

	m_scale = scale;

	// lazy
	m_bounding_dirty = true;
}

void Sprite::SetShear(const sm::vec2& shear)
{
	sm::mat4 mat_old, mat_new;
	mat_old.Shear(m_shear.x, m_shear.y);
	mat_new.Shear(shear.x, shear.y);

	sm::vec2 offset = mat_new * m_offset - mat_old * m_offset;
	m_offset += offset;
	Translate(-offset);

	m_shear = shear;

	// immediately
	m_bounding->SetTransform(m_position, m_offset, m_angle);

// 	// lazy
// 	m_bounding_dirty = true;
}

void Sprite::SetOffset(const sm::vec2& offset)
{
	// rotate + offset -> offset + rotate
	sm::vec2 old_center = GetCenter();
	m_offset = offset;
	sm::vec2 new_center = GetCenter();
	Translate(old_center - new_center);

	// immediately
	m_bounding->SetTransform(m_position, m_offset, m_angle);

// 	// lazy
// 	m_bounding_dirty = true;
}

sm::mat4 Sprite::GetTransMatrix() const
{
	sm::vec2 center = GetCenter();
	sm::mat4 mt;
	mt.SetTransformation(center.x, center.y, m_angle,
		m_scale.x, m_scale.y, 0, 0, m_shear.x, m_shear.y);
	return mt;
}

sm::mat4 Sprite::GetTransInvMatrix() const
{
	sm::mat4 mat;
	mat.RotateZ(-m_angle);
	mat.Shear(-m_shear.x, -m_shear.y);
	mat.Translate(-m_position.x/m_scale.x, -m_position.y/m_scale.y, 0);
	mat.Scale(1/m_scale.x, 1/m_scale.y, 1);
	return mat;
}

}<commit_msg>[FIXED] spr set sym in ctor<commit_after>#include "S2_Sprite.h"
#include "S2_Symbol.h"
#include "OBB.h"
#include "RenderFilter.h"
#include "FilterFactory.h"

namespace s2
{

Sprite::Sprite()
	: m_sym(NULL)
	, m_position(0, 0)
	, m_angle(0)
	, m_scale(1, 1)
	, m_shear(0, 0)
	, m_visible(true)
{
	m_offset.MakeInvalid();

	m_bounding = new OBB();
	m_bounding_dirty = true;

	m_shader.filter = FilterFactory::Instance()->Create(FM_NULL);
}

Sprite::Sprite(const Sprite& spr)
	: m_sym(NULL)
	, m_position(spr.m_position)
	, m_angle(spr.m_angle)
	, m_scale(spr.m_scale)
	, m_shear(spr.m_shear)
	, m_offset(spr.m_offset)
	, m_color(spr.m_color)
	, m_shader(spr.m_shader)
	, m_camera(spr.m_camera)
	, m_visible(spr.m_visible)
{
	if (spr.m_sym) {
		spr.m_sym->AddReference();
		m_sym = spr.m_sym;
	}

	m_bounding = spr.m_bounding->Clone();
	m_bounding_dirty = true;

	FilterMode fm = FM_NULL;
	if (spr.Shader().filter) {
		fm = spr.Shader().filter->GetMode();
	}
	m_shader.filter = FilterFactory::Instance()->Create(fm);
}

Sprite::Sprite(Symbol* sym)
	: m_sym(NULL)
	, m_position(0, 0)
	, m_angle(0)
	, m_scale(1, 1)
	, m_shear(0, 0)
	, m_visible(true)
{
	cu::RefCountObjAssign(m_sym, sym);

	m_offset.MakeInvalid();

	m_bounding = new OBB();
	m_bounding_dirty = true;

	m_shader.filter = FilterFactory::Instance()->Create(FM_NULL);
}

Sprite::~Sprite()
{
	if (m_sym) {
		m_sym->RemoveReference();
	}

	delete m_bounding;

	delete m_shader.filter;
}

void Sprite::Translate(const sm::vec2& offset)
{
	m_position += offset;
}

void Sprite::Rotate(float delta)
{
	m_angle += delta;
}

void Sprite::SetSymbol(Symbol* sym)
{
	cu::RefCountObjAssign(m_sym, sym);
	UpdateBounding();
}

const BoundingBox* Sprite::GetBounding() const
{
	if (m_bounding_dirty) {
		UpdateBounding();
	}
	return m_bounding;
}

// todo: m_sym->GetBounding too slow, should be cached
void Sprite::UpdateBounding() const
{
	if (!m_sym) {
		return;
	}

	sm::rect rect = m_sym->GetBounding(this);

	if (!m_offset.IsValid()) {
		m_offset = rect.Center();
	}

	m_bounding_dirty = false;
	m_bounding->Build(rect, m_position, m_angle, m_scale, m_shear, m_offset);
}

sm::vec2 Sprite::GetCenter() const
{
	sm::vec2 center_offset = sm::rotate_vector(-m_offset, m_angle) + m_offset;
	sm::vec2 center = m_position + center_offset;
	return center;
}

void Sprite::SetPosition(const sm::vec2& pos)
{
	m_position = pos;

// 	// immediately
// 	m_bounding->SetTransform(m_position, m_offset, m_angle);

	// lazy
	m_bounding_dirty = true;
}

void Sprite::SetAngle(float angle)
{
	m_angle = angle;

// 	// immediately
// 	m_bounding->SetTransform(m_position, m_offset, m_angle);

	// lazy
	m_bounding_dirty = true;
}

void Sprite::SetScale(const sm::vec2& scale)
{
	const sm::vec2& old_scale = m_scale;
	if (old_scale.x != 0 && old_scale.y != 0) {
		sm::vec2 dscale;
		dscale.x = scale.x / m_scale.x;
		dscale.y = scale.y / m_scale.y;

		sm::vec2 old_offset = m_offset;
		sm::vec2 new_offset(m_offset.x * dscale.x, m_offset.y * dscale.y);
		m_offset = new_offset;

		Translate(old_offset - new_offset);
	}

	m_scale = scale;

	// lazy
	m_bounding_dirty = true;
}

void Sprite::SetShear(const sm::vec2& shear)
{
	sm::mat4 mat_old, mat_new;
	mat_old.Shear(m_shear.x, m_shear.y);
	mat_new.Shear(shear.x, shear.y);

	sm::vec2 offset = mat_new * m_offset - mat_old * m_offset;
	m_offset += offset;
	Translate(-offset);

	m_shear = shear;

	// immediately
	m_bounding->SetTransform(m_position, m_offset, m_angle);

// 	// lazy
// 	m_bounding_dirty = true;
}

void Sprite::SetOffset(const sm::vec2& offset)
{
	// rotate + offset -> offset + rotate
	sm::vec2 old_center = GetCenter();
	m_offset = offset;
	sm::vec2 new_center = GetCenter();
	Translate(old_center - new_center);

	// immediately
	m_bounding->SetTransform(m_position, m_offset, m_angle);

// 	// lazy
// 	m_bounding_dirty = true;
}

sm::mat4 Sprite::GetTransMatrix() const
{
	sm::vec2 center = GetCenter();
	sm::mat4 mt;
	mt.SetTransformation(center.x, center.y, m_angle,
		m_scale.x, m_scale.y, 0, 0, m_shear.x, m_shear.y);
	return mt;
}

sm::mat4 Sprite::GetTransInvMatrix() const
{
	sm::mat4 mat;
	mat.RotateZ(-m_angle);
	mat.Shear(-m_shear.x, -m_shear.y);
	mat.Translate(-m_position.x/m_scale.x, -m_position.y/m_scale.y, 0);
	mat.Scale(1/m_scale.x, 1/m_scale.y, 1);
	return mat;
}

}<|endoftext|>


<commit_before>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
// Copyright (c) 2021 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef IOX_HOOFS_UNITS_DURATION_HPP
#define IOX_HOOFS_UNITS_DURATION_HPP

#include "iceoryx_hoofs/cxx/expected.hpp"
#include "iceoryx_hoofs/platform/time.hpp" // required for QNX

#include <chrono>
#include <cmath>
#include <iostream>
#include <numeric>

namespace iox
{
namespace units
{
enum class TimeSpecReference
{
    None,
    Epoch,
    Monotonic
};

class Duration;

inline namespace duration_literals
{
/// @brief Constructs a new Duration object from nanoseconds
constexpr Duration operator"" _ns(unsigned long long int) noexcept; // PRQA S 48

/// @brief Constructs a new Duration object from microseconds
constexpr Duration operator"" _us(unsigned long long int) noexcept; // PRQA S 48

/// @brief Constructs a new Duration object from milliseconds
constexpr Duration operator"" _ms(unsigned long long int) noexcept; // PRQA S 48

/// @brief Constructs a new Duration object from seconds
constexpr Duration operator"" _s(unsigned long long int) noexcept; // PRQA S 48

/// @brief Constructs a new Duration object from minutes
constexpr Duration operator"" _m(unsigned long long int) noexcept; // PRQA S 48

/// @brief Constructs a new Duration object from hours
constexpr Duration operator"" _h(unsigned long long int) noexcept; // PRQA S 48

/// @brief Constructs a new Duration object from days
constexpr Duration operator"" _d(unsigned long long int) noexcept; // PRQA S 48
} // namespace duration_literals

/// @code
///   #include <iostream>
///   // ...
///   using namespace units;
///   using namespace units::duration_literals;
///   auto someDays = 2 * 7_d + 5_ns;
///   auto someSeconds = 42_s + 500_ms;
///   std::cout << someDays << std::endl;
///   std::cout << someDays.nanoSeconds<uint64_t>() << " ns" << std::endl;
///   std::cout << someSeconds.milliSeconds<int64_t>() << " ms" << std::endl;
/// @endcode
class Duration
{
  public:
    // BEGIN CREATION FROM STATIC FUNCTIONS

    /// @brief Constructs a new Duration object from nanoseconds
    /// @tparam T is an integer type for the value
    /// @param[in] value as nanoseconds
    /// @return a new Duration object
    /// @attention Since negative durations are not allowed, the duration will be clamped to 0
    template <typename T>
    static constexpr Duration fromNanoseconds(const T value) noexcept;

    /// @brief Constructs a new Duration object from microseconds
    /// @tparam T is an integer type for the value
    /// @param[in] value as microseconds
    /// @return a new Duration object
    /// @attention Since negative durations are not allowed, the duration will be clamped to 0
    template <typename T>
    static constexpr Duration fromMicroseconds(const T value) noexcept;

    /// @brief Constructs a new Duration object from milliseconds
    /// @tparam T is an integer type for the value
    /// @param[in] value as milliseconds
    /// @return a new Duration object
    /// @attention Since negative durations are not allowed, the duration will be clamped to 0
    template <typename T>
    static constexpr Duration fromMilliseconds(const T value) noexcept;

    /// @brief Constructs a new Duration object from seconds
    /// @tparam T is an integer type for the value
    /// @param[in] value as seconds
    /// @return a new Duration object
    /// @attention Since negative durations are not allowed, the duration will be clamped to 0
    template <typename T>
    static constexpr Duration fromSeconds(const T value) noexcept;

    /// @brief Constructs a new Duration object from minutes
    /// @tparam T is an integer type for the value
    /// @param[in] value as minutes
    /// @return a new Duration object
    /// @attention Since negative durations are not allowed, the duration will be clamped to 0
    template <typename T>
    static constexpr Duration fromMinutes(const T value) noexcept;

    /// @brief Constructs a new Duration object from hours
    /// @tparam T is an integer type for the value
    /// @param[in] value as hours
    /// @return a new Duration object
    /// @attention Since negative durations are not allowed, the duration will be clamped to 0
    template <typename T>
    static constexpr Duration fromHours(const T value) noexcept;

    /// @brief Constructs a new Duration object from days
    /// @tparam T is an integer type for the value
    /// @param[in] value as days
    /// @return a new Duration object
    /// @attention Since negative durations are not allowed, the duration will be clamped to 0
    template <typename T>
    static constexpr Duration fromDays(const T value) noexcept;

    /// @brief Constructs a new Duration object of maximum allowed length. Useful for functions which should have an
    /// "infinite" timeout.
    static constexpr Duration max() noexcept;

    /// @brief Constructs a new Duration object with a duration of zero
    static constexpr Duration zero() noexcept;
    // END CREATION FROM STATIC FUNCTIONS

    // BEGIN CONSTRUCTORS AND ASSIGNMENT

    /// @brief Construct a Duration object from timeval
    /// @param[in] value as timeval
    constexpr explicit Duration(const struct timeval& value) noexcept;

    /// @brief Construct a Duration object from timespec
    /// @param[in] value as timespec
    constexpr explicit Duration(const struct timespec& value) noexcept;

    /// @brief Construct a Duration object from itimerspec
    /// @param[in] value as itimerspec
    /// @note only it_interval from the itimerspec is used
    constexpr explicit Duration(const struct itimerspec& value) noexcept;

    /// @brief Construct a Duration object from std::chrono::milliseconds
    /// @param[in] value as milliseconds
    /// @attention Since negative durations are not allowed, the duration will be clamped to 0
    constexpr explicit Duration(const std::chrono::milliseconds& value) noexcept;

    /// @brief Construct a Duration object from std::chrono::nanoseconds
    /// @param[in] value as nanoseconds
    /// @attention Since negative durations are not allowed, the duration will be clamped to 0
    constexpr explicit Duration(const std::chrono::nanoseconds& value) noexcept;

    /// @brief Assigns a std::chrono::milliseconds to an duration object
    /// @param[in] rhs is the right hand side of the assignment
    /// @return a reference to the Duration object with the assigned millisecond value
    /// @attention Since negative durations are not allowed, the duration will be clamped to 0
    Duration& operator=(const std::chrono::milliseconds& rhs) noexcept;

    // END CONSTRUCTORS AND ASSIGNMENT

    // BEGIN COMPARISON

    /// @brief Equal to operator
    /// @param[in] rhs is the right hand side of the comparison
    /// @return true if duration equal to rhs
    constexpr bool operator==(const Duration& rhs) const noexcept;

    /// @brief Not equal to operator
    /// @param[in] rhs is the right hand side of the comparison
    /// @return true if duration not equal to rhs
    constexpr bool operator!=(const Duration& rhs) const noexcept;

    /// @brief Less than operator
    /// @param[in] rhs is the right hand side of the comparison
    /// @return true if duration is less than rhs
    constexpr bool operator<(const Duration& rhs) const noexcept;

    /// @brief Less than or equal to operator
    /// @param[in] rhs is the right hand side of the comparison
    /// @return true if duration is less than or equal to rhs
    constexpr bool operator<=(const Duration& rhs) const noexcept;

    /// @brief Greater than operator
    /// @param[in] rhs is the right hand side of the comparison
    /// @return true if duration is greater than rhs
    constexpr bool operator>(const Duration& rhs) const noexcept;

    /// @brief Greater than or equal to operator
    /// @param[in] rhs is the right hand side of the comparison
    /// @return true if duration is greater than or equal to rhs
    constexpr bool operator>=(const Duration& rhs) const noexcept;

    // END COMPARISON

    // BEGIN ARITHMETIC

    /// @brief Creates Duration object by addition
    /// @param[in] rhs is the second summand
    /// @return a new Duration object
    constexpr Duration operator+(const Duration& rhs) const noexcept;

    /// @brief Creates Duration object by subtraction
    /// @param[in] rhs is the subtrahend
    /// @return a new Duration object
    /// @attention Since negative durations are not allowed, the duration will be clamped to 0
    constexpr Duration operator-(const Duration& rhs) const noexcept;

    /// @brief Creates Duration object by multiplication
    /// @tparam T is an arithmetic type for the multiplicator
    /// @param[in] rhs is the multiplicator
    /// @return a new Duration object
    /// @attention Since negative durations are not allowed, the duration will be clamped to 0
    /// @note A duration of 0 will always result in 0, no matter if multiplied with NaN or +Inf
    /// @note There is no explicit division operator! This can be achieved by multiplication with the inverse of the
    /// divisor.
    /// @note Multiplication of a non-zero duration with NaN and +Inf results in a saturated max duration
    template <typename T>
    constexpr Duration operator*(const T& rhs) const noexcept;

    // END ARITHMETIC

    // BEGIN CONVERSION

    /// @brief returns the duration in nanoseconds
    /// @note If the duration in nanoseconds is larger than an uint64_t can represent, it will be clamped to the
    /// uint64_t max value.
    constexpr uint64_t toNanoseconds() const noexcept;

    /// @brief returns the duration in microseconds
    /// @note If the duration in microseconds is larger than an uint64_t can represent, it will be clamped to the
    /// uint64_t max value.
    /// @note The remaining nanoseconds are truncated, similar to the casting behavior of a float to an int.
    constexpr uint64_t toMicroseconds() const noexcept;

    /// @brief returns the duration in milliseconds
    /// @note If the duration in milliseconds is larger than an uint64_t can represent, it will be clamped to the
    /// uint64_t max value.
    /// @note The remaining microseconds are truncated, similar to the casting behavior of a float to an int.
    constexpr uint64_t toMilliseconds() const noexcept;

    /// @brief returns the duration in seconds
    /// @note The remaining milliseconds are truncated, similar to the casting behavior of a float to an int.
    constexpr uint64_t toSeconds() const noexcept;

    /// @brief returns the duration in minutes
    /// @note The remaining seconds are truncated, similar to the casting behavior of a float to an int.
    constexpr uint64_t toMinutes() const noexcept;

    /// @brief returns the duration in hours
    /// @note The remaining minutes are truncated, similar to the casting behavior of a float to an int.
    constexpr uint64_t toHours() const noexcept;

    /// @brief returns the duration in days
    /// @note The remaining hours are truncated, similar to the casting behavior of a float to an int.
    constexpr uint64_t toDays() const noexcept;

    /// @brief converts duration in a timespec c struct
    struct timespec timespec(const TimeSpecReference& reference = TimeSpecReference::None) const noexcept;

    /// @brief converts duration in a timeval c struct
    ///     timeval::tv_sec = seconds since the Epoch (01.01.1970)
    ///     timeval::tv_usec = microseconds
    constexpr operator struct timeval() const noexcept;

    // END CONVERSION

    friend constexpr Duration duration_literals::operator"" _ns(unsigned long long int) noexcept; // PRQA S 48
    friend constexpr Duration duration_literals::operator"" _us(unsigned long long int) noexcept; // PRQA S 48
    friend constexpr Duration duration_literals::operator"" _ms(unsigned long long int) noexcept; // PRQA S 48
    friend constexpr Duration duration_literals::operator"" _s(unsigned long long int) noexcept;  // PRQA S 48
    friend constexpr Duration duration_literals::operator"" _m(unsigned long long int) noexcept;  // PRQA S 48
    friend constexpr Duration duration_literals::operator"" _h(unsigned long long int) noexcept;  // PRQA S 48
    friend constexpr Duration duration_literals::operator"" _d(unsigned long long int) noexcept;  // PRQA S 48

    template <typename T>
    friend constexpr Duration operator*(const T& lhs, const Duration& rhs) noexcept;

    friend std::ostream& operator<<(std::ostream& stream, const Duration& t) noexcept;

    static constexpr uint32_t SECS_PER_MINUTE{60U};
    static constexpr uint32_t SECS_PER_HOUR{3600U};
    static constexpr uint32_t HOURS_PER_DAY{24U};

    static constexpr uint32_t MILLISECS_PER_SEC{1000U};
    static constexpr uint32_t MICROSECS_PER_SEC{MILLISECS_PER_SEC * 1000U};

    static constexpr uint32_t NANOSECS_PER_MICROSEC{1000U};
    static constexpr uint32_t NANOSECS_PER_MILLISEC{NANOSECS_PER_MICROSEC * 1000U};
    static constexpr uint32_t NANOSECS_PER_SEC{NANOSECS_PER_MILLISEC * 1000U};

  protected:
    using Seconds_t = uint64_t;
    using Nanoseconds_t = uint32_t;

    /// @brief Constructs a Duration from seconds and nanoseconds
    /// @param[in] seconds portion of the duration
    /// @param[in] nanoseconds portion of the duration
    /// @note this is protected to be able to use it in unit tests
    constexpr Duration(const Seconds_t seconds, const Nanoseconds_t nanoseconds) noexcept;

    /// @note this is factory method is necessary to build with msvc due to issues calling a protected constexpr ctor
    /// from public methods
    static constexpr Duration createDuration(const Seconds_t seconds, const Nanoseconds_t nanoseconds) noexcept;

  private:
    template <typename T, typename String>
    static constexpr unsigned long long int positiveValueOrClampToZero(const T value, const String fromMethod) noexcept;

    template <typename T>
    constexpr Duration fromFloatingPointSeconds(const T floatingPointSeconds) const noexcept;
    template <typename From, typename To>
    constexpr bool wouldCastFromFloatingPointProbablyOverflow(const From floatingPoint) const noexcept;

    template <typename T>
    constexpr Duration multiplyWith(const std::enable_if_t<!std::is_floating_point<T>::value, T>& rhs) const noexcept;

    template <typename T>
    constexpr Duration multiplyWith(const std::enable_if_t<std::is_floating_point<T>::value, T>& rhs) const noexcept;

  private:
    Seconds_t m_seconds{0U};
    Nanoseconds_t m_nanoseconds{0U};
};

/// @brief creates Duration object by multiplying object T with a duration
/// @tparam T is an arithmetic type for the multiplicator
/// @param[in] lhs is the multiplicator
/// @param[in] rhs is the multiplicant
/// @return a new Duration object
/// @attention Since negative durations are not allowed, the duration will be clamped to 0
template <typename T>
constexpr Duration operator*(const T& lhs, const Duration& rhs) noexcept;

/// @brief stream operator for the Duration class
std::ostream& operator<<(std::ostream& stream, const Duration& t) noexcept;

} // namespace units
} // namespace iox

#include "iceoryx_hoofs/internal/units/duration.inl"

#endif // IOX_HOOFS_UNITS_DURATION_HPP
<commit_msg>iox-#1078 Make duration_literals a non inlined namespace<commit_after>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
// Copyright (c) 2021 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef IOX_HOOFS_UNITS_DURATION_HPP
#define IOX_HOOFS_UNITS_DURATION_HPP

#include "iceoryx_hoofs/cxx/expected.hpp"
#include "iceoryx_hoofs/platform/time.hpp" // required for QNX

#include <chrono>
#include <cmath>
#include <iostream>
#include <numeric>

namespace iox
{
namespace units
{
enum class TimeSpecReference
{
    None,
    Epoch,
    Monotonic
};

class Duration;

namespace duration_literals
{
/// @brief Constructs a new Duration object from nanoseconds
constexpr Duration operator"" _ns(unsigned long long int) noexcept; // PRQA S 48

/// @brief Constructs a new Duration object from microseconds
constexpr Duration operator"" _us(unsigned long long int) noexcept; // PRQA S 48

/// @brief Constructs a new Duration object from milliseconds
constexpr Duration operator"" _ms(unsigned long long int) noexcept; // PRQA S 48

/// @brief Constructs a new Duration object from seconds
constexpr Duration operator"" _s(unsigned long long int) noexcept; // PRQA S 48

/// @brief Constructs a new Duration object from minutes
constexpr Duration operator"" _m(unsigned long long int) noexcept; // PRQA S 48

/// @brief Constructs a new Duration object from hours
constexpr Duration operator"" _h(unsigned long long int) noexcept; // PRQA S 48

/// @brief Constructs a new Duration object from days
constexpr Duration operator"" _d(unsigned long long int) noexcept; // PRQA S 48
} // namespace duration_literals

/// @code
///   #include <iostream>
///   // ...
///   using namespace units;
///   using namespace units::duration_literals;
///   auto someDays = 2 * 7_d + 5_ns;
///   auto someSeconds = 42_s + 500_ms;
///   std::cout << someDays << std::endl;
///   std::cout << someDays.nanoSeconds<uint64_t>() << " ns" << std::endl;
///   std::cout << someSeconds.milliSeconds<int64_t>() << " ms" << std::endl;
/// @endcode
class Duration
{
  public:
    // BEGIN CREATION FROM STATIC FUNCTIONS

    /// @brief Constructs a new Duration object from nanoseconds
    /// @tparam T is an integer type for the value
    /// @param[in] value as nanoseconds
    /// @return a new Duration object
    /// @attention Since negative durations are not allowed, the duration will be clamped to 0
    template <typename T>
    static constexpr Duration fromNanoseconds(const T value) noexcept;

    /// @brief Constructs a new Duration object from microseconds
    /// @tparam T is an integer type for the value
    /// @param[in] value as microseconds
    /// @return a new Duration object
    /// @attention Since negative durations are not allowed, the duration will be clamped to 0
    template <typename T>
    static constexpr Duration fromMicroseconds(const T value) noexcept;

    /// @brief Constructs a new Duration object from milliseconds
    /// @tparam T is an integer type for the value
    /// @param[in] value as milliseconds
    /// @return a new Duration object
    /// @attention Since negative durations are not allowed, the duration will be clamped to 0
    template <typename T>
    static constexpr Duration fromMilliseconds(const T value) noexcept;

    /// @brief Constructs a new Duration object from seconds
    /// @tparam T is an integer type for the value
    /// @param[in] value as seconds
    /// @return a new Duration object
    /// @attention Since negative durations are not allowed, the duration will be clamped to 0
    template <typename T>
    static constexpr Duration fromSeconds(const T value) noexcept;

    /// @brief Constructs a new Duration object from minutes
    /// @tparam T is an integer type for the value
    /// @param[in] value as minutes
    /// @return a new Duration object
    /// @attention Since negative durations are not allowed, the duration will be clamped to 0
    template <typename T>
    static constexpr Duration fromMinutes(const T value) noexcept;

    /// @brief Constructs a new Duration object from hours
    /// @tparam T is an integer type for the value
    /// @param[in] value as hours
    /// @return a new Duration object
    /// @attention Since negative durations are not allowed, the duration will be clamped to 0
    template <typename T>
    static constexpr Duration fromHours(const T value) noexcept;

    /// @brief Constructs a new Duration object from days
    /// @tparam T is an integer type for the value
    /// @param[in] value as days
    /// @return a new Duration object
    /// @attention Since negative durations are not allowed, the duration will be clamped to 0
    template <typename T>
    static constexpr Duration fromDays(const T value) noexcept;

    /// @brief Constructs a new Duration object of maximum allowed length. Useful for functions which should have an
    /// "infinite" timeout.
    static constexpr Duration max() noexcept;

    /// @brief Constructs a new Duration object with a duration of zero
    static constexpr Duration zero() noexcept;
    // END CREATION FROM STATIC FUNCTIONS

    // BEGIN CONSTRUCTORS AND ASSIGNMENT

    /// @brief Construct a Duration object from timeval
    /// @param[in] value as timeval
    constexpr explicit Duration(const struct timeval& value) noexcept;

    /// @brief Construct a Duration object from timespec
    /// @param[in] value as timespec
    constexpr explicit Duration(const struct timespec& value) noexcept;

    /// @brief Construct a Duration object from itimerspec
    /// @param[in] value as itimerspec
    /// @note only it_interval from the itimerspec is used
    constexpr explicit Duration(const struct itimerspec& value) noexcept;

    /// @brief Construct a Duration object from std::chrono::milliseconds
    /// @param[in] value as milliseconds
    /// @attention Since negative durations are not allowed, the duration will be clamped to 0
    constexpr explicit Duration(const std::chrono::milliseconds& value) noexcept;

    /// @brief Construct a Duration object from std::chrono::nanoseconds
    /// @param[in] value as nanoseconds
    /// @attention Since negative durations are not allowed, the duration will be clamped to 0
    constexpr explicit Duration(const std::chrono::nanoseconds& value) noexcept;

    /// @brief Assigns a std::chrono::milliseconds to an duration object
    /// @param[in] rhs is the right hand side of the assignment
    /// @return a reference to the Duration object with the assigned millisecond value
    /// @attention Since negative durations are not allowed, the duration will be clamped to 0
    Duration& operator=(const std::chrono::milliseconds& rhs) noexcept;

    // END CONSTRUCTORS AND ASSIGNMENT

    // BEGIN COMPARISON

    /// @brief Equal to operator
    /// @param[in] rhs is the right hand side of the comparison
    /// @return true if duration equal to rhs
    constexpr bool operator==(const Duration& rhs) const noexcept;

    /// @brief Not equal to operator
    /// @param[in] rhs is the right hand side of the comparison
    /// @return true if duration not equal to rhs
    constexpr bool operator!=(const Duration& rhs) const noexcept;

    /// @brief Less than operator
    /// @param[in] rhs is the right hand side of the comparison
    /// @return true if duration is less than rhs
    constexpr bool operator<(const Duration& rhs) const noexcept;

    /// @brief Less than or equal to operator
    /// @param[in] rhs is the right hand side of the comparison
    /// @return true if duration is less than or equal to rhs
    constexpr bool operator<=(const Duration& rhs) const noexcept;

    /// @brief Greater than operator
    /// @param[in] rhs is the right hand side of the comparison
    /// @return true if duration is greater than rhs
    constexpr bool operator>(const Duration& rhs) const noexcept;

    /// @brief Greater than or equal to operator
    /// @param[in] rhs is the right hand side of the comparison
    /// @return true if duration is greater than or equal to rhs
    constexpr bool operator>=(const Duration& rhs) const noexcept;

    // END COMPARISON

    // BEGIN ARITHMETIC

    /// @brief Creates Duration object by addition
    /// @param[in] rhs is the second summand
    /// @return a new Duration object
    constexpr Duration operator+(const Duration& rhs) const noexcept;

    /// @brief Creates Duration object by subtraction
    /// @param[in] rhs is the subtrahend
    /// @return a new Duration object
    /// @attention Since negative durations are not allowed, the duration will be clamped to 0
    constexpr Duration operator-(const Duration& rhs) const noexcept;

    /// @brief Creates Duration object by multiplication
    /// @tparam T is an arithmetic type for the multiplicator
    /// @param[in] rhs is the multiplicator
    /// @return a new Duration object
    /// @attention Since negative durations are not allowed, the duration will be clamped to 0
    /// @note A duration of 0 will always result in 0, no matter if multiplied with NaN or +Inf
    /// @note There is no explicit division operator! This can be achieved by multiplication with the inverse of the
    /// divisor.
    /// @note Multiplication of a non-zero duration with NaN and +Inf results in a saturated max duration
    template <typename T>
    constexpr Duration operator*(const T& rhs) const noexcept;

    // END ARITHMETIC

    // BEGIN CONVERSION

    /// @brief returns the duration in nanoseconds
    /// @note If the duration in nanoseconds is larger than an uint64_t can represent, it will be clamped to the
    /// uint64_t max value.
    constexpr uint64_t toNanoseconds() const noexcept;

    /// @brief returns the duration in microseconds
    /// @note If the duration in microseconds is larger than an uint64_t can represent, it will be clamped to the
    /// uint64_t max value.
    /// @note The remaining nanoseconds are truncated, similar to the casting behavior of a float to an int.
    constexpr uint64_t toMicroseconds() const noexcept;

    /// @brief returns the duration in milliseconds
    /// @note If the duration in milliseconds is larger than an uint64_t can represent, it will be clamped to the
    /// uint64_t max value.
    /// @note The remaining microseconds are truncated, similar to the casting behavior of a float to an int.
    constexpr uint64_t toMilliseconds() const noexcept;

    /// @brief returns the duration in seconds
    /// @note The remaining milliseconds are truncated, similar to the casting behavior of a float to an int.
    constexpr uint64_t toSeconds() const noexcept;

    /// @brief returns the duration in minutes
    /// @note The remaining seconds are truncated, similar to the casting behavior of a float to an int.
    constexpr uint64_t toMinutes() const noexcept;

    /// @brief returns the duration in hours
    /// @note The remaining minutes are truncated, similar to the casting behavior of a float to an int.
    constexpr uint64_t toHours() const noexcept;

    /// @brief returns the duration in days
    /// @note The remaining hours are truncated, similar to the casting behavior of a float to an int.
    constexpr uint64_t toDays() const noexcept;

    /// @brief converts duration in a timespec c struct
    struct timespec timespec(const TimeSpecReference& reference = TimeSpecReference::None) const noexcept;

    /// @brief converts duration in a timeval c struct
    ///     timeval::tv_sec = seconds since the Epoch (01.01.1970)
    ///     timeval::tv_usec = microseconds
    constexpr operator struct timeval() const noexcept;

    // END CONVERSION

    friend constexpr Duration duration_literals::operator"" _ns(unsigned long long int) noexcept; // PRQA S 48
    friend constexpr Duration duration_literals::operator"" _us(unsigned long long int) noexcept; // PRQA S 48
    friend constexpr Duration duration_literals::operator"" _ms(unsigned long long int) noexcept; // PRQA S 48
    friend constexpr Duration duration_literals::operator"" _s(unsigned long long int) noexcept;  // PRQA S 48
    friend constexpr Duration duration_literals::operator"" _m(unsigned long long int) noexcept;  // PRQA S 48
    friend constexpr Duration duration_literals::operator"" _h(unsigned long long int) noexcept;  // PRQA S 48
    friend constexpr Duration duration_literals::operator"" _d(unsigned long long int) noexcept;  // PRQA S 48

    template <typename T>
    friend constexpr Duration operator*(const T& lhs, const Duration& rhs) noexcept;

    friend std::ostream& operator<<(std::ostream& stream, const Duration& t) noexcept;

    static constexpr uint32_t SECS_PER_MINUTE{60U};
    static constexpr uint32_t SECS_PER_HOUR{3600U};
    static constexpr uint32_t HOURS_PER_DAY{24U};

    static constexpr uint32_t MILLISECS_PER_SEC{1000U};
    static constexpr uint32_t MICROSECS_PER_SEC{MILLISECS_PER_SEC * 1000U};

    static constexpr uint32_t NANOSECS_PER_MICROSEC{1000U};
    static constexpr uint32_t NANOSECS_PER_MILLISEC{NANOSECS_PER_MICROSEC * 1000U};
    static constexpr uint32_t NANOSECS_PER_SEC{NANOSECS_PER_MILLISEC * 1000U};

  protected:
    using Seconds_t = uint64_t;
    using Nanoseconds_t = uint32_t;

    /// @brief Constructs a Duration from seconds and nanoseconds
    /// @param[in] seconds portion of the duration
    /// @param[in] nanoseconds portion of the duration
    /// @note this is protected to be able to use it in unit tests
    constexpr Duration(const Seconds_t seconds, const Nanoseconds_t nanoseconds) noexcept;

    /// @note this is factory method is necessary to build with msvc due to issues calling a protected constexpr ctor
    /// from public methods
    static constexpr Duration createDuration(const Seconds_t seconds, const Nanoseconds_t nanoseconds) noexcept;

  private:
    template <typename T, typename String>
    static constexpr unsigned long long int positiveValueOrClampToZero(const T value, const String fromMethod) noexcept;

    template <typename T>
    constexpr Duration fromFloatingPointSeconds(const T floatingPointSeconds) const noexcept;
    template <typename From, typename To>
    constexpr bool wouldCastFromFloatingPointProbablyOverflow(const From floatingPoint) const noexcept;

    template <typename T>
    constexpr Duration multiplyWith(const std::enable_if_t<!std::is_floating_point<T>::value, T>& rhs) const noexcept;

    template <typename T>
    constexpr Duration multiplyWith(const std::enable_if_t<std::is_floating_point<T>::value, T>& rhs) const noexcept;

  private:
    Seconds_t m_seconds{0U};
    Nanoseconds_t m_nanoseconds{0U};
};

/// @brief creates Duration object by multiplying object T with a duration
/// @tparam T is an arithmetic type for the multiplicator
/// @param[in] lhs is the multiplicator
/// @param[in] rhs is the multiplicant
/// @return a new Duration object
/// @attention Since negative durations are not allowed, the duration will be clamped to 0
template <typename T>
constexpr Duration operator*(const T& lhs, const Duration& rhs) noexcept;

/// @brief stream operator for the Duration class
std::ostream& operator<<(std::ostream& stream, const Duration& t) noexcept;

} // namespace units
} // namespace iox

#include "iceoryx_hoofs/internal/units/duration.inl"

#endif // IOX_HOOFS_UNITS_DURATION_HPP
<|endoftext|>


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

#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX
#include <svtools/pathoptions.hxx>
#endif
#ifndef _SVTOOLS_LANGUAGEOPTIONS_HXX
#include <svtools/languageoptions.hxx>
#endif
#ifndef _UNOTOOLS_UCBSTREAMHELPER_HXX
#include <unotools/ucbstreamhelper.hxx>
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _SV_VIRDEV_HXX
#include <vcl/virdev.hxx>
#endif
#ifndef _SFXAPP_HXX //autogen
#include <sfx2/app.hxx>
#endif
#ifndef _SV_STATUS_HXX //autogen
#include <vcl/status.hxx>
#endif
#ifndef _SFXINTITEM_HXX //autogen
#include <svtools/intitem.hxx>
#endif
#ifndef _SFXMSG_HXX //autogen
#include <sfx2/msg.hxx>
#endif
#ifndef _SFXOBJFACE_HXX //autogen
#include <sfx2/objface.hxx>
#endif
#ifndef _SFX_PRINTER_HXX
#include <sfx2/printer.hxx>
#endif
#ifndef _SVX_PSZCTRL_HXX //autogen
#include <svx/pszctrl.hxx>
#endif
#ifndef _SVX_ZOOMCTRL_HXX //autogen
#include <svx/zoomctrl.hxx>
#endif
#ifndef _SVX_MODCTRL_HXX //autogen
#include <svx/modctrl.hxx>
#endif
#ifndef _ZFORLIST_HXX
#include <svtools/zforlist.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#ifndef _EHDL_HXX
#include <svtools/ehdl.hxx>
#endif

#define ITEMID_SEARCH           SID_SEARCH_ITEM
#include <svx/svxids.hrc>
#include <offmgr/ofaids.hrc>
#include <svx/srchitem.hxx>

#pragma hdrstop

#define _SD_DLL                 // fuer SD_MOD()
#include "sderror.hxx"
#include "sdmod.hxx"
#include "sddll.hxx"
#include "sdresid.hxx"
#include "optsitem.hxx"
#include "docshell.hxx"
#include "drawdoc.hxx"
#include "app.hrc"
#include "glob.hrc"
#include "strings.hrc"
#include "res_bmp.hrc"
#include "cfgids.hxx"

TYPEINIT1( SdModuleDummy, SfxModule );
TYPEINIT1( SdModule, SdModuleDummy );

#define SdModule
#include "sdslots.hxx"

SFX_IMPL_INTERFACE(SdModule, SfxModule, SdResId(STR_APPLICATIONOBJECTBAR))
{
    SFX_STATUSBAR_REGISTRATION(RID_DRAW_STATUSBAR);
}

SFX_IMPL_MODULE_DLL(Sd)

/*************************************************************************
|*
|* Ctor
|*
\************************************************************************/

SdModule::SdModule(SvFactory* pDrawObjFact, SvFactory* pGraphicObjFact)
:   SdModuleDummy(SFX_APP()->CreateResManager("sd"), FALSE,
                  pDrawObjFact, pGraphicObjFact),
    bWaterCan(FALSE),
    pTransferClip(NULL),
    pTransferDrag(NULL),
    pTransferSelection(NULL),
    pImpressOptions(NULL),
    pDrawOptions(NULL),
    pSearchItem(NULL),
    pNumberFormatter( NULL )
{
    SetName( UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "StarDraw" ) ) );  // Nicht uebersetzen!
    pSearchItem = new SvxSearchItem(ITEMID_SEARCH);
    pSearchItem->SetAppFlag(SVX_SEARCHAPP_DRAW);
    StartListening( *SFX_APP() );

    mpErrorHdl = new SfxErrorHandler( RID_SD_ERRHDL,
                                         ERRCODE_AREA_SD,
                                         ERRCODE_AREA_SD_END,
                                         GetResMgr() );

    mpRefDevice = new VirtualDevice;
    mpRefDevice->SetMapMode( MAP_100TH_MM );
}

/*************************************************************************
|*
|* Dtor
|*
\************************************************************************/

SdModule::~SdModule()
{
    delete pSearchItem;

    if( pNumberFormatter )
        delete pNumberFormatter;

    delete mpErrorHdl;
    delete static_cast< VirtualDevice* >( mpRefDevice );
}

/*************************************************************************
|*
|* Statusbar erzeugen
|*
\************************************************************************/

#define AUTOSIZE_WIDTH  180
#define TEXT_WIDTH(s)   rStatusBar.GetTextWidth((s))

void SdModule::FillStatusBar(StatusBar& rStatusBar)
{
    // Hinweis
    rStatusBar.InsertItem( SID_CONTEXT, TEXT_WIDTH( String().Fill( 30, 'x' ) ), // vorher 52
                            SIB_IN | SIB_LEFT | SIB_AUTOSIZE );

    // Groesse und Position
    rStatusBar.InsertItem( SID_ATTR_SIZE, SvxPosSizeStatusBarControl::GetDefItemWidth(rStatusBar), // vorher 42
                            SIB_IN | SIB_USERDRAW );
                            // SIB_AUTOSIZE | SIB_LEFT | SIB_OWNERDRAW );

    // Massstab
    rStatusBar.InsertItem( SID_ATTR_ZOOM, SvxZoomStatusBarControl::GetDefItemWidth(rStatusBar), SIB_IN | SIB_CENTER );
/*
    // Einfuege- / Uberschreibmodus
    rStatusBar.InsertItem( SID_ATTR_INSERT, TEXT_WIDTH( "EINFG" ),
                            SIB_IN | SIB_CENTER );

    // Selektionsmodus
    rStatusBar.InsertItem( SID_STATUS_SELMODE, TEXT_WIDTH( "ERG" ),
                            SIB_IN | SIB_CENTER );
*/
    // Dokument geaendert
    rStatusBar.InsertItem( SID_DOC_MODIFIED, SvxModifyControl::GetDefItemWidth(rStatusBar) );

    // Seite
    rStatusBar.InsertItem( SID_STATUS_PAGE, TEXT_WIDTH( String().Fill( 24, 'X' ) ),
                            SIB_IN | SIB_LEFT );

    // Praesentationslayout
    rStatusBar.InsertItem( SID_STATUS_LAYOUT, TEXT_WIDTH( String().Fill( 10, 'X' ) ),
                            SIB_IN | SIB_LEFT | SIB_AUTOSIZE );
}

/*************************************************************************
|*
|* Modul laden (nur Attrappe fuer das Linken der DLL)
|*
\************************************************************************/

SfxModule* SdModuleDummy::Load()
{
    return (NULL);
}

/*************************************************************************
|*
|* Modul laden
|*
\************************************************************************/

SfxModule* SdModule::Load()
{
    return (this);
}

/*************************************************************************
|*
|* get notifications
|*
\************************************************************************/

void SdModule::Notify( SfxBroadcaster& rBC, const SfxHint& rHint )
{
    if( rHint.ISA( SfxSimpleHint ) &&
        ( (SfxSimpleHint&) rHint ).GetId() == SFX_HINT_DEINITIALIZING )
    {
        delete pImpressOptions, pImpressOptions = NULL;
        delete pDrawOptions, pDrawOptions = NULL;
    }
}

/*************************************************************************
|*
|* Modul freigeben
|*
\************************************************************************/

void SdModule::Free()
{
}

/*************************************************************************
|*
|* Optionen zurueckgeben
|*
\************************************************************************/

SdOptions* SdModule::GetSdOptions(DocumentType eDocType)
{
    SdOptions* pOptions = NULL;

    if (eDocType == DOCUMENT_TYPE_DRAW)
    {
        if (!pDrawOptions)
            pDrawOptions = new SdOptions( SDCFG_DRAW );

        pOptions = pDrawOptions;
    }
    else if (eDocType == DOCUMENT_TYPE_IMPRESS)
    {
        if (!pImpressOptions)
            pImpressOptions = new SdOptions( SDCFG_IMPRESS );

        pOptions = pImpressOptions;
    }
    if( pOptions )
    {
        UINT16 nMetric = pOptions->GetMetric();

        SdDrawDocShell* pDocSh = PTR_CAST( SdDrawDocShell, SfxObjectShell::Current() );
        SdDrawDocument* pDoc = NULL;
        if (pDocSh)
            pDoc = pDocSh->GetDoc();

        if( nMetric != 0xffff && pDoc && eDocType == pDoc->GetDocumentType() )
            PutItem( SfxUInt16Item( SID_ATTR_METRIC, nMetric ) );
    }

    return(pOptions);
}

/*************************************************************************
|*
|* Optionen-Stream fuer interne Options oeffnen und zurueckgeben;
|* falls der Stream zum Lesen geoeffnet wird, aber noch nicht
|* angelegt wurde, wird ein 'leeres' RefObject zurueckgegeben
|*
\************************************************************************/

SvStorageStreamRef SdModule::GetOptionStream( const String& rOptionName,
                                              SdOptionStreamMode eMode )
{
    SdDrawDocShell*     pDocSh = PTR_CAST( SdDrawDocShell, SfxObjectShell::Current() );
    SvStorageStreamRef  xStm;

    if( pDocSh )
    {
        DocumentType    eType = pDocSh->GetDoc()->GetDocumentType();
        String          aStmName;

        if( !xOptionStorage.Is() )
        {
            INetURLObject aURL( SvtPathOptions().GetUserConfigPath() );

            aURL.Append( UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "drawing.cfg" ) ) );

            SvStream* pStm = ::utl::UcbStreamHelper::CreateStream( aURL.GetMainURL( INetURLObject::NO_DECODE ), STREAM_READWRITE );

            if( pStm )
                xOptionStorage = new SvStorage( pStm, TRUE );
        }

        if( DOCUMENT_TYPE_DRAW == eType )
            aStmName.AssignAscii( RTL_CONSTASCII_STRINGPARAM( "Draw_" ) );
        else
            aStmName.AssignAscii( RTL_CONSTASCII_STRINGPARAM( "Impress_" ) );

        aStmName += rOptionName;

        if( SD_OPTION_STORE == eMode || xOptionStorage->IsContained( aStmName ) )
            xStm = xOptionStorage->OpenStream( aStmName );
    }

    return xStm;
}

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

SvNumberFormatter* SdModule::GetNumberFormatter()
{
    if( !pNumberFormatter )
        pNumberFormatter = new SvNumberFormatter( ::comphelper::getProcessServiceFactory(), LANGUAGE_SYSTEM );

    return pNumberFormatter;
}

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

OutputDevice* SdModule::GetRefDevice( SdDrawDocShell& rDocShell )
{
    return( IsPrinterRefDevice() ? rDocShell.GetPrinter( sal_True ) : mpRefDevice );
}

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

sal_Bool SdModule::IsPrinterRefDevice() const
{
    return sal_True;
}

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

::com::sun::star::text::WritingMode SdModule::GetDefaultWritingMode() const
{
/*
    const SvtLanguageOptions aLanguageOptions;

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

#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX
#include <svtools/pathoptions.hxx>
#endif
#ifndef _SVTOOLS_LANGUAGEOPTIONS_HXX
#include <svtools/languageoptions.hxx>
#endif
#ifndef _UNOTOOLS_UCBSTREAMHELPER_HXX
#include <unotools/ucbstreamhelper.hxx>
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _SV_VIRDEV_HXX
#include <vcl/virdev.hxx>
#endif
#ifndef _SFXAPP_HXX //autogen
#include <sfx2/app.hxx>
#endif
#ifndef _SV_STATUS_HXX //autogen
#include <vcl/status.hxx>
#endif
#ifndef _SFXINTITEM_HXX //autogen
#include <svtools/intitem.hxx>
#endif
#ifndef _SFXMSG_HXX //autogen
#include <sfx2/msg.hxx>
#endif
#ifndef _SFXOBJFACE_HXX //autogen
#include <sfx2/objface.hxx>
#endif
#ifndef _SFX_PRINTER_HXX
#include <sfx2/printer.hxx>
#endif
#ifndef _SVX_PSZCTRL_HXX //autogen
#include <svx/pszctrl.hxx>
#endif
#ifndef _SVX_ZOOMCTRL_HXX //autogen
#include <svx/zoomctrl.hxx>
#endif
#ifndef _SVX_MODCTRL_HXX //autogen
#include <svx/modctrl.hxx>
#endif
#ifndef _ZFORLIST_HXX
#include <svtools/zforlist.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#ifndef _EHDL_HXX
#include <svtools/ehdl.hxx>
#endif

#define ITEMID_SEARCH           SID_SEARCH_ITEM
#include <svx/svxids.hrc>
#include <offmgr/ofaids.hrc>
#include <svx/srchitem.hxx>

#pragma hdrstop

#define _SD_DLL                 // fuer SD_MOD()
#include "sderror.hxx"
#include "sdmod.hxx"
#include "sddll.hxx"
#include "sdresid.hxx"
#include "optsitem.hxx"
#include "docshell.hxx"
#include "drawdoc.hxx"
#include "app.hrc"
#include "glob.hrc"
#include "strings.hrc"
#include "res_bmp.hrc"
#include "cfgids.hxx"

TYPEINIT1( SdModuleDummy, SfxModule );
TYPEINIT1( SdModule, SdModuleDummy );

#define SdModule
#include "sdslots.hxx"

SFX_IMPL_INTERFACE(SdModule, SfxModule, SdResId(STR_APPLICATIONOBJECTBAR))
{
    SFX_STATUSBAR_REGISTRATION(RID_DRAW_STATUSBAR);
}

SFX_IMPL_MODULE_DLL(Sd)

/*************************************************************************
|*
|* Ctor
|*
\************************************************************************/

SdModule::SdModule(SvFactory* pDrawObjFact, SvFactory* pGraphicObjFact)
:   SdModuleDummy(SFX_APP()->CreateResManager("sd"), FALSE,
                  pDrawObjFact, pGraphicObjFact),
    bWaterCan(FALSE),
    pTransferClip(NULL),
    pTransferDrag(NULL),
    pTransferSelection(NULL),
    pImpressOptions(NULL),
    pDrawOptions(NULL),
    pSearchItem(NULL),
    pNumberFormatter( NULL )
{
    SetName( UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "StarDraw" ) ) );  // Nicht uebersetzen!
    pSearchItem = new SvxSearchItem(ITEMID_SEARCH);
    pSearchItem->SetAppFlag(SVX_SEARCHAPP_DRAW);
    StartListening( *SFX_APP() );

    mpErrorHdl = new SfxErrorHandler( RID_SD_ERRHDL,
                                         ERRCODE_AREA_SD,
                                         ERRCODE_AREA_SD_END,
                                         GetResMgr() );

    mpVirtualRefDevice = new VirtualDevice;
    mpVirtualRefDevice->SetMapMode( MAP_100TH_MM );
}

/*************************************************************************
|*
|* Dtor
|*
\************************************************************************/

SdModule::~SdModule()
{
    delete pSearchItem;

    if( pNumberFormatter )
        delete pNumberFormatter;

    delete mpErrorHdl;
    delete static_cast< VirtualDevice* >( mpVirtualRefDevice );
}

/*************************************************************************
|*
|* Statusbar erzeugen
|*
\************************************************************************/

#define AUTOSIZE_WIDTH  180
#define TEXT_WIDTH(s)   rStatusBar.GetTextWidth((s))

void SdModule::FillStatusBar(StatusBar& rStatusBar)
{
    // Hinweis
    rStatusBar.InsertItem( SID_CONTEXT, TEXT_WIDTH( String().Fill( 30, 'x' ) ), // vorher 52
                            SIB_IN | SIB_LEFT | SIB_AUTOSIZE );

    // Groesse und Position
    rStatusBar.InsertItem( SID_ATTR_SIZE, SvxPosSizeStatusBarControl::GetDefItemWidth(rStatusBar), // vorher 42
                            SIB_IN | SIB_USERDRAW );
                            // SIB_AUTOSIZE | SIB_LEFT | SIB_OWNERDRAW );

    // Massstab
    rStatusBar.InsertItem( SID_ATTR_ZOOM, SvxZoomStatusBarControl::GetDefItemWidth(rStatusBar), SIB_IN | SIB_CENTER );
/*
    // Einfuege- / Uberschreibmodus
    rStatusBar.InsertItem( SID_ATTR_INSERT, TEXT_WIDTH( "EINFG" ),
                            SIB_IN | SIB_CENTER );

    // Selektionsmodus
    rStatusBar.InsertItem( SID_STATUS_SELMODE, TEXT_WIDTH( "ERG" ),
                            SIB_IN | SIB_CENTER );
*/
    // Dokument geaendert
    rStatusBar.InsertItem( SID_DOC_MODIFIED, SvxModifyControl::GetDefItemWidth(rStatusBar) );

    // Seite
    rStatusBar.InsertItem( SID_STATUS_PAGE, TEXT_WIDTH( String().Fill( 24, 'X' ) ),
                            SIB_IN | SIB_LEFT );

    // Praesentationslayout
    rStatusBar.InsertItem( SID_STATUS_LAYOUT, TEXT_WIDTH( String().Fill( 10, 'X' ) ),
                            SIB_IN | SIB_LEFT | SIB_AUTOSIZE );
}

/*************************************************************************
|*
|* Modul laden (nur Attrappe fuer das Linken der DLL)
|*
\************************************************************************/

SfxModule* SdModuleDummy::Load()
{
    return (NULL);
}

/*************************************************************************
|*
|* Modul laden
|*
\************************************************************************/

SfxModule* SdModule::Load()
{
    return (this);
}

/*************************************************************************
|*
|* get notifications
|*
\************************************************************************/

void SdModule::Notify( SfxBroadcaster& rBC, const SfxHint& rHint )
{
    if( rHint.ISA( SfxSimpleHint ) &&
        ( (SfxSimpleHint&) rHint ).GetId() == SFX_HINT_DEINITIALIZING )
    {
        delete pImpressOptions, pImpressOptions = NULL;
        delete pDrawOptions, pDrawOptions = NULL;
    }
}

/*************************************************************************
|*
|* Modul freigeben
|*
\************************************************************************/

void SdModule::Free()
{
}

/*************************************************************************
|*
|* Optionen zurueckgeben
|*
\************************************************************************/

SdOptions* SdModule::GetSdOptions(DocumentType eDocType)
{
    SdOptions* pOptions = NULL;

    if (eDocType == DOCUMENT_TYPE_DRAW)
    {
        if (!pDrawOptions)
            pDrawOptions = new SdOptions( SDCFG_DRAW );

        pOptions = pDrawOptions;
    }
    else if (eDocType == DOCUMENT_TYPE_IMPRESS)
    {
        if (!pImpressOptions)
            pImpressOptions = new SdOptions( SDCFG_IMPRESS );

        pOptions = pImpressOptions;
    }
    if( pOptions )
    {
        UINT16 nMetric = pOptions->GetMetric();

        SdDrawDocShell* pDocSh = PTR_CAST( SdDrawDocShell, SfxObjectShell::Current() );
        SdDrawDocument* pDoc = NULL;
        if (pDocSh)
            pDoc = pDocSh->GetDoc();

        if( nMetric != 0xffff && pDoc && eDocType == pDoc->GetDocumentType() )
            PutItem( SfxUInt16Item( SID_ATTR_METRIC, nMetric ) );
    }

    return(pOptions);
}

/*************************************************************************
|*
|* Optionen-Stream fuer interne Options oeffnen und zurueckgeben;
|* falls der Stream zum Lesen geoeffnet wird, aber noch nicht
|* angelegt wurde, wird ein 'leeres' RefObject zurueckgegeben
|*
\************************************************************************/

SvStorageStreamRef SdModule::GetOptionStream( const String& rOptionName,
                                              SdOptionStreamMode eMode )
{
    SdDrawDocShell*     pDocSh = PTR_CAST( SdDrawDocShell, SfxObjectShell::Current() );
    SvStorageStreamRef  xStm;

    if( pDocSh )
    {
        DocumentType    eType = pDocSh->GetDoc()->GetDocumentType();
        String          aStmName;

        if( !xOptionStorage.Is() )
        {
            INetURLObject aURL( SvtPathOptions().GetUserConfigPath() );

            aURL.Append( UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "drawing.cfg" ) ) );

            SvStream* pStm = ::utl::UcbStreamHelper::CreateStream( aURL.GetMainURL( INetURLObject::NO_DECODE ), STREAM_READWRITE );

            if( pStm )
                xOptionStorage = new SvStorage( pStm, TRUE );
        }

        if( DOCUMENT_TYPE_DRAW == eType )
            aStmName.AssignAscii( RTL_CONSTASCII_STRINGPARAM( "Draw_" ) );
        else
            aStmName.AssignAscii( RTL_CONSTASCII_STRINGPARAM( "Impress_" ) );

        aStmName += rOptionName;

        if( SD_OPTION_STORE == eMode || xOptionStorage->IsContained( aStmName ) )
            xStm = xOptionStorage->OpenStream( aStmName );
    }

    return xStm;
}

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

SvNumberFormatter* SdModule::GetNumberFormatter()
{
    if( !pNumberFormatter )
        pNumberFormatter = new SvNumberFormatter( ::comphelper::getProcessServiceFactory(), LANGUAGE_SYSTEM );

    return pNumberFormatter;
}

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

OutputDevice* SdModule::GetVirtualRefDevice (void)
{
    return mpVirtualRefDevice;
}

/** This method is deprecated and only an alias to
    <member>GetVirtualRefDevice()</member>.  The given argument is ignored.
*/
OutputDevice* SdModule::GetRefDevice (SdDrawDocShell& rDocShell)
{
    return GetVirtualRefDevice();
}

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

::com::sun::star::text::WritingMode SdModule::GetDefaultWritingMode() const
{
/*
    const SvtLanguageOptions aLanguageOptions;

    return( aLanguageOptions.IsCTLFontEnabled() ?
            ::com::sun::star::text::WritingMode_RL_TB :
            ::com::sun::star::text::WritingMode_LR_TB );
*/
    return ::com::sun::star::text::WritingMode_LR_TB;
}
<|endoftext|>


<commit_before>// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <cassert>
// Boost
#include <boost/make_shared.hpp>
// StdAir
#include <stdair/basic/BasChronometer.hpp>
#include <stdair/basic/BasFileMgr.hpp>
#include <stdair/bom/BomManager.hpp>
#include <stdair/bom/BookingRequestStruct.hpp>
#include <stdair/factory/FacBomManager.hpp>
#include <stdair/service/Logger.hpp>
#include <stdair/STDAIR_Service.hpp>
// TravelCCM
#include <travelccm/factory/FacTRAVELCCMServiceContext.hpp>
#include <travelccm/command/ChoiceManager.hpp>
#include <travelccm/service/TRAVELCCM_ServiceContext.hpp>
#include <travelccm/TRAVELCCM_Service.hpp>

namespace TRAVELCCM {

  // ////////////////////////////////////////////////////////////////////
  TRAVELCCM_Service::TRAVELCCM_Service() : _travelccmServiceContext (NULL) {
    assert (false);
  }

  // ////////////////////////////////////////////////////////////////////
  TRAVELCCM_Service::TRAVELCCM_Service (const TRAVELCCM_Service& iService)
  : _travelccmServiceContext (NULL) {
    assert (false);
  }

  // ////////////////////////////////////////////////////////////////////
  TRAVELCCM_Service::TRAVELCCM_Service (const stdair::BasLogParams& iLogParams,
                                        const stdair::BasDBParams& iDBParams)
    : _travelccmServiceContext (NULL) {

    // Initialise the STDAIR service handler
    stdair::STDAIR_ServicePtr_T lSTDAIR_Service_ptr =
      initStdAirService (iLogParams, iDBParams);

    // Initialise the service context
    initServiceContext();

    // Add the StdAir service context to the AIRINV service context
    // \note AIRINV owns the STDAIR service resources here.
    const bool ownStdairService = true;
    addStdAirService (lSTDAIR_Service_ptr, ownStdairService);

    // Initialise the (remaining of the) context
    initTravelCCMService();
  }

  // ////////////////////////////////////////////////////////////////////
  TRAVELCCM_Service::TRAVELCCM_Service (const stdair::BasLogParams& iLogParams)
    : _travelccmServiceContext (NULL) {

    // Initialise the STDAIR service handler
    stdair::STDAIR_ServicePtr_T lSTDAIR_Service_ptr =
      initStdAirService (iLogParams);

    // Initialise the service context
    initServiceContext();

    // Add the StdAir service context to the AIRINV service context
    // \note AIRINV owns the STDAIR service resources here.
    const bool ownStdairService = true;
    addStdAirService (lSTDAIR_Service_ptr, ownStdairService);

    // Initialise the (remaining of the) context
    initTravelCCMService();
  }

  // ////////////////////////////////////////////////////////////////////
  TRAVELCCM_Service::
  TRAVELCCM_Service (stdair::STDAIR_ServicePtr_T ioSTDAIR_Service_ptr)
    : _travelccmServiceContext (NULL) {

    // Initialise the service context
    initServiceContext();

    // Store the STDAIR service object within the (AIRINV) service context
    // \note AirInv does not own the STDAIR service resources here.
    const bool doesNotOwnStdairService = false;
    addStdAirService (ioSTDAIR_Service_ptr, doesNotOwnStdairService);

    // Initialise the (remaining of the) context
    initTravelCCMService();
  }

  // ////////////////////////////////////////////////////////////////////
  void TRAVELCCM_Service::finalise () {

  // ////////////////////////////////////////////////////////////////////
  TRAVELCCM_Service::~TRAVELCCM_Service() {
    // Delete/Clean all the objects from memory
    finalise();
  }

  // ////////////////////////////////////////////////////////////////////
  void TRAVELCCM_Service::finalise() {
    assert (_travelccmServiceContext != NULL);
    // Reset the (Boost.)Smart pointer pointing on the STDAIR_Service object.
    _travelccmServiceContext->reset();
  }

  // ////////////////////////////////////////////////////////////////////
  void TRAVELCCM_Service::initServiceContext() {
    // Initialise the context
    TRAVELCCM_ServiceContext& lTRAVELCCM_ServiceContext =
      FacTRAVELCCMServiceContext::instance().create();
    _travelccmServiceContext = &lTRAVELCCM_ServiceContext;
  }

  // ////////////////////////////////////////////////////////////////////
  void TRAVELCCM_Service::
  addStdAirService (stdair::STDAIR_ServicePtr_T ioSTDAIR_Service_ptr,
                    const bool iOwnStdairService) {
    // Retrieve the Travelccm service context
    assert (_travelccmServiceContext != NULL);
    TRAVELCCM_ServiceContext& lTRAVELCCM_ServiceContext =
      *_travelccmServiceContext;

    // Store the STDAIR service object within the (TRAVELCCM) service context
    lTRAVELCCM_ServiceContext.setSTDAIR_Service (ioSTDAIR_Service_ptr,
                                                 iOwnStdairService);
  }

  // ////////////////////////////////////////////////////////////////////
  stdair::STDAIR_ServicePtr_T TRAVELCCM_Service::
  initStdAirService (const stdair::BasLogParams& iLogParams,
                     const stdair::BasDBParams& iDBParams) {

    /**
     * Initialise the STDAIR service handler.
     *
     * \note The track on the object memory is kept thanks to the Boost
     * Smart Pointers component.
     */
    stdair::STDAIR_ServicePtr_T oSTDAIR_Service_ptr =
      boost::make_shared<stdair::STDAIR_Service> (iLogParams, iDBParams);
    assert (oSTDAIR_Service_ptr != NULL);

    return oSTDAIR_Service_ptr;
  }

  // ////////////////////////////////////////////////////////////////////
  stdair::STDAIR_ServicePtr_T TRAVELCCM_Service::
  initStdAirService (const stdair::BasLogParams& iLogParams) {

    /**
     * Initialise the STDAIR service handler.
     *
     * \note The track on the object memory is kept thanks to the Boost
     * Smart Pointers component.
     */
    stdair::STDAIR_ServicePtr_T oSTDAIR_Service_ptr =
      boost::make_shared<stdair::STDAIR_Service> (iLogParams);
    assert (oSTDAIR_Service_ptr != NULL);

    return oSTDAIR_Service_ptr;
  }

  // ////////////////////////////////////////////////////////////////////
  void TRAVELCCM_Service::initTravelCCMService() {
    // Do nothing at this stage. A sample BOM tree may be built by
    // calling the buildSampleBom() method
  }

  // //////////////////////////////////////////////////////////////////////
  void TRAVELCCM_Service::buildSampleBom() {

    // Retrieve the TRAVELCCM service context
    if (_travelccmServiceContext == NULL) {
      throw stdair::NonInitialisedServiceException ("The Travelccm service has "
                                                    "not been initialised");
    }
    assert (_travelccmServiceContext != NULL);

    TRAVELCCM_ServiceContext& lTRAVELCCM_ServiceContext =
      *_travelccmServiceContext;

    // Retrieve the STDAIR service object from the (TRAVELCCM) service context
    stdair::STDAIR_Service& lSTDAIR_Service =
      lTRAVELCCM_ServiceContext.getSTDAIR_Service();

    // Delegate the BOM building to the dedicated service
    lSTDAIR_Service.buildSampleBom();
  }

  // //////////////////////////////////////////////////////////////////////
  void TRAVELCCM_Service::
  buildSampleTravelSolutions (stdair::TravelSolutionList_T& ioTSList) {

    // Retrieve the TRAVELCCM service context
    if (_travelccmServiceContext == NULL) {
      throw stdair::NonInitialisedServiceException ("The Travelccm service has "
                                                    "not been initialised");
    }
    assert (_travelccmServiceContext != NULL);

    TRAVELCCM_ServiceContext& lTRAVELCCM_ServiceContext =
      *_travelccmServiceContext;

    // Retrieve the STDAIR service object from the (TRAVELCCM) service context
    stdair::STDAIR_Service& lSTDAIR_Service =
      lTRAVELCCM_ServiceContext.getSTDAIR_Service();

    // Delegate the BOM building to the dedicated service
    lSTDAIR_Service.buildSampleTravelSolutions (ioTSList);
  }

  // //////////////////////////////////////////////////////////////////////
  stdair::BookingRequestStruct TRAVELCCM_Service::
  buildSampleBookingRequest (const bool isForCRS) {

    // Retrieve the TRAVELCCM service context
    if (_travelccmServiceContext == NULL) {
      throw stdair::NonInitialisedServiceException ("The Travelccm service has "
                                                    "not been initialised");
    }
    assert (_travelccmServiceContext != NULL);

    TRAVELCCM_ServiceContext& lTRAVELCCM_ServiceContext =
      *_travelccmServiceContext;

    // Retrieve the STDAIR service object from the (TRAVELCCM) service context
    stdair::STDAIR_Service& lSTDAIR_Service =
      lTRAVELCCM_ServiceContext.getSTDAIR_Service();

    // Delegate the BOM building to the dedicated service
    return lSTDAIR_Service.buildSampleBookingRequest (isForCRS);
  }

  // //////////////////////////////////////////////////////////////////////
  std::string TRAVELCCM_Service::csvDisplay() const {

    // Retrieve the TRAVELCCM service context
    if (_travelccmServiceContext == NULL) {
      throw stdair::NonInitialisedServiceException ("The TravelccmMaster service"
                                                    " has not been initialised");
    }
    assert (_travelccmServiceContext != NULL);

    TRAVELCCM_ServiceContext& lTRAVELCCM_ServiceContext =
      *_travelccmServiceContext;

    // Retrieve the STDAIR service object from the (TRAVELCCM) service context
    stdair::STDAIR_Service& lSTDAIR_Service =
      lTRAVELCCM_ServiceContext.getSTDAIR_Service();

    // Delegate the BOM building to the dedicated service
    return lSTDAIR_Service.csvDisplay();
  }

  // //////////////////////////////////////////////////////////////////////
  std::string TRAVELCCM_Service::
  csvDisplay (const stdair::TravelSolutionList_T& iTravelSolutionList) const {
    // Retrieve the TRAVELCCM service context
    if (_travelccmServiceContext == NULL) {
      throw stdair::NonInitialisedServiceException ("The TravelccmMaster service"
                                                    " has not been initialised");
    }
    assert (_travelccmServiceContext != NULL);

    TRAVELCCM_ServiceContext& lTRAVELCCM_ServiceContext =
      *_travelccmServiceContext;

    // Retrieve the STDAIR service object from the (TRAVELCCM) service context
    stdair::STDAIR_Service& lSTDAIR_Service =
      lTRAVELCCM_ServiceContext.getSTDAIR_Service();

    // Delegate the BOM building to the dedicated service
    return lSTDAIR_Service.csvDisplay (iTravelSolutionList);
  }

  // ////////////////////////////////////////////////////////////////////
  const stdair::TravelSolutionStruct* TRAVELCCM_Service::
  chooseTravelSolution (stdair::TravelSolutionList_T& ioTravelSolutionList,
                        const stdair::BookingRequestStruct& iBookingRequest) {

    const stdair::TravelSolutionStruct* oTravelSolution_ptr =
      ChoiceManager::chooseTravelSolution (ioTravelSolutionList,
                                           iBookingRequest);
    return oTravelSolution_ptr;
  }

}
<commit_msg>[TravelCCM] [Dev] Fixed a merge problem.<commit_after>// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <cassert>
// Boost
#include <boost/make_shared.hpp>
// StdAir
#include <stdair/basic/BasChronometer.hpp>
#include <stdair/basic/BasFileMgr.hpp>
#include <stdair/bom/BomManager.hpp>
#include <stdair/bom/BookingRequestStruct.hpp>
#include <stdair/factory/FacBomManager.hpp>
#include <stdair/service/Logger.hpp>
#include <stdair/STDAIR_Service.hpp>
// TravelCCM
#include <travelccm/factory/FacTRAVELCCMServiceContext.hpp>
#include <travelccm/command/ChoiceManager.hpp>
#include <travelccm/service/TRAVELCCM_ServiceContext.hpp>
#include <travelccm/TRAVELCCM_Service.hpp>

namespace TRAVELCCM {

  // ////////////////////////////////////////////////////////////////////
  TRAVELCCM_Service::TRAVELCCM_Service() : _travelccmServiceContext (NULL) {
    assert (false);
  }

  // ////////////////////////////////////////////////////////////////////
  TRAVELCCM_Service::TRAVELCCM_Service (const TRAVELCCM_Service& iService)
  : _travelccmServiceContext (NULL) {
    assert (false);
  }

  // ////////////////////////////////////////////////////////////////////
  TRAVELCCM_Service::TRAVELCCM_Service (const stdair::BasLogParams& iLogParams,
                                        const stdair::BasDBParams& iDBParams)
    : _travelccmServiceContext (NULL) {

    // Initialise the STDAIR service handler
    stdair::STDAIR_ServicePtr_T lSTDAIR_Service_ptr =
      initStdAirService (iLogParams, iDBParams);

    // Initialise the service context
    initServiceContext();

    // Add the StdAir service context to the AIRINV service context
    // \note AIRINV owns the STDAIR service resources here.
    const bool ownStdairService = true;
    addStdAirService (lSTDAIR_Service_ptr, ownStdairService);

    // Initialise the (remaining of the) context
    initTravelCCMService();
  }

  // ////////////////////////////////////////////////////////////////////
  TRAVELCCM_Service::TRAVELCCM_Service (const stdair::BasLogParams& iLogParams)
    : _travelccmServiceContext (NULL) {

    // Initialise the STDAIR service handler
    stdair::STDAIR_ServicePtr_T lSTDAIR_Service_ptr =
      initStdAirService (iLogParams);

    // Initialise the service context
    initServiceContext();

    // Add the StdAir service context to the AIRINV service context
    // \note AIRINV owns the STDAIR service resources here.
    const bool ownStdairService = true;
    addStdAirService (lSTDAIR_Service_ptr, ownStdairService);

    // Initialise the (remaining of the) context
    initTravelCCMService();
  }

  // ////////////////////////////////////////////////////////////////////
  TRAVELCCM_Service::
  TRAVELCCM_Service (stdair::STDAIR_ServicePtr_T ioSTDAIR_Service_ptr)
    : _travelccmServiceContext (NULL) {

    // Initialise the service context
    initServiceContext();

    // Store the STDAIR service object within the (AIRINV) service context
    // \note AirInv does not own the STDAIR service resources here.
    const bool doesNotOwnStdairService = false;
    addStdAirService (ioSTDAIR_Service_ptr, doesNotOwnStdairService);

    // Initialise the (remaining of the) context
    initTravelCCMService();
  }

  // ////////////////////////////////////////////////////////////////////
  TRAVELCCM_Service::~TRAVELCCM_Service() {
    // Delete/Clean all the objects from memory
    finalise();
  }

  // ////////////////////////////////////////////////////////////////////
  void TRAVELCCM_Service::finalise() {
    assert (_travelccmServiceContext != NULL);
    // Reset the (Boost.)Smart pointer pointing on the STDAIR_Service object.
    _travelccmServiceContext->reset();
  }

  // ////////////////////////////////////////////////////////////////////
  void TRAVELCCM_Service::initServiceContext() {
    // Initialise the context
    TRAVELCCM_ServiceContext& lTRAVELCCM_ServiceContext =
      FacTRAVELCCMServiceContext::instance().create();
    _travelccmServiceContext = &lTRAVELCCM_ServiceContext;
  }

  // ////////////////////////////////////////////////////////////////////
  void TRAVELCCM_Service::
  addStdAirService (stdair::STDAIR_ServicePtr_T ioSTDAIR_Service_ptr,
                    const bool iOwnStdairService) {
    // Retrieve the Travelccm service context
    assert (_travelccmServiceContext != NULL);
    TRAVELCCM_ServiceContext& lTRAVELCCM_ServiceContext =
      *_travelccmServiceContext;

    // Store the STDAIR service object within the (TRAVELCCM) service context
    lTRAVELCCM_ServiceContext.setSTDAIR_Service (ioSTDAIR_Service_ptr,
                                                 iOwnStdairService);
  }

  // ////////////////////////////////////////////////////////////////////
  stdair::STDAIR_ServicePtr_T TRAVELCCM_Service::
  initStdAirService (const stdair::BasLogParams& iLogParams,
                     const stdair::BasDBParams& iDBParams) {

    /**
     * Initialise the STDAIR service handler.
     *
     * \note The track on the object memory is kept thanks to the Boost
     * Smart Pointers component.
     */
    stdair::STDAIR_ServicePtr_T oSTDAIR_Service_ptr =
      boost::make_shared<stdair::STDAIR_Service> (iLogParams, iDBParams);
    assert (oSTDAIR_Service_ptr != NULL);

    return oSTDAIR_Service_ptr;
  }

  // ////////////////////////////////////////////////////////////////////
  stdair::STDAIR_ServicePtr_T TRAVELCCM_Service::
  initStdAirService (const stdair::BasLogParams& iLogParams) {

    /**
     * Initialise the STDAIR service handler.
     *
     * \note The track on the object memory is kept thanks to the Boost
     * Smart Pointers component.
     */
    stdair::STDAIR_ServicePtr_T oSTDAIR_Service_ptr =
      boost::make_shared<stdair::STDAIR_Service> (iLogParams);
    assert (oSTDAIR_Service_ptr != NULL);

    return oSTDAIR_Service_ptr;
  }

  // ////////////////////////////////////////////////////////////////////
  void TRAVELCCM_Service::initTravelCCMService() {
    // Do nothing at this stage. A sample BOM tree may be built by
    // calling the buildSampleBom() method
  }

  // //////////////////////////////////////////////////////////////////////
  void TRAVELCCM_Service::buildSampleBom() {

    // Retrieve the TRAVELCCM service context
    if (_travelccmServiceContext == NULL) {
      throw stdair::NonInitialisedServiceException ("The Travelccm service has "
                                                    "not been initialised");
    }
    assert (_travelccmServiceContext != NULL);

    TRAVELCCM_ServiceContext& lTRAVELCCM_ServiceContext =
      *_travelccmServiceContext;

    // Retrieve the STDAIR service object from the (TRAVELCCM) service context
    stdair::STDAIR_Service& lSTDAIR_Service =
      lTRAVELCCM_ServiceContext.getSTDAIR_Service();

    // Delegate the BOM building to the dedicated service
    lSTDAIR_Service.buildSampleBom();
  }

  // //////////////////////////////////////////////////////////////////////
  void TRAVELCCM_Service::
  buildSampleTravelSolutions (stdair::TravelSolutionList_T& ioTSList) {

    // Retrieve the TRAVELCCM service context
    if (_travelccmServiceContext == NULL) {
      throw stdair::NonInitialisedServiceException ("The Travelccm service has "
                                                    "not been initialised");
    }
    assert (_travelccmServiceContext != NULL);

    TRAVELCCM_ServiceContext& lTRAVELCCM_ServiceContext =
      *_travelccmServiceContext;

    // Retrieve the STDAIR service object from the (TRAVELCCM) service context
    stdair::STDAIR_Service& lSTDAIR_Service =
      lTRAVELCCM_ServiceContext.getSTDAIR_Service();

    // Delegate the BOM building to the dedicated service
    lSTDAIR_Service.buildSampleTravelSolutions (ioTSList);
  }

  // //////////////////////////////////////////////////////////////////////
  stdair::BookingRequestStruct TRAVELCCM_Service::
  buildSampleBookingRequest (const bool isForCRS) {

    // Retrieve the TRAVELCCM service context
    if (_travelccmServiceContext == NULL) {
      throw stdair::NonInitialisedServiceException ("The Travelccm service has "
                                                    "not been initialised");
    }
    assert (_travelccmServiceContext != NULL);

    TRAVELCCM_ServiceContext& lTRAVELCCM_ServiceContext =
      *_travelccmServiceContext;

    // Retrieve the STDAIR service object from the (TRAVELCCM) service context
    stdair::STDAIR_Service& lSTDAIR_Service =
      lTRAVELCCM_ServiceContext.getSTDAIR_Service();

    // Delegate the BOM building to the dedicated service
    return lSTDAIR_Service.buildSampleBookingRequest (isForCRS);
  }

  // //////////////////////////////////////////////////////////////////////
  std::string TRAVELCCM_Service::csvDisplay() const {

    // Retrieve the TRAVELCCM service context
    if (_travelccmServiceContext == NULL) {
      throw stdair::NonInitialisedServiceException ("The TravelccmMaster service"
                                                    " has not been initialised");
    }
    assert (_travelccmServiceContext != NULL);

    TRAVELCCM_ServiceContext& lTRAVELCCM_ServiceContext =
      *_travelccmServiceContext;

    // Retrieve the STDAIR service object from the (TRAVELCCM) service context
    stdair::STDAIR_Service& lSTDAIR_Service =
      lTRAVELCCM_ServiceContext.getSTDAIR_Service();

    // Delegate the BOM building to the dedicated service
    return lSTDAIR_Service.csvDisplay();
  }

  // //////////////////////////////////////////////////////////////////////
  std::string TRAVELCCM_Service::
  csvDisplay (const stdair::TravelSolutionList_T& iTravelSolutionList) const {
    // Retrieve the TRAVELCCM service context
    if (_travelccmServiceContext == NULL) {
      throw stdair::NonInitialisedServiceException ("The TravelccmMaster service"
                                                    " has not been initialised");
    }
    assert (_travelccmServiceContext != NULL);

    TRAVELCCM_ServiceContext& lTRAVELCCM_ServiceContext =
      *_travelccmServiceContext;

    // Retrieve the STDAIR service object from the (TRAVELCCM) service context
    stdair::STDAIR_Service& lSTDAIR_Service =
      lTRAVELCCM_ServiceContext.getSTDAIR_Service();

    // Delegate the BOM building to the dedicated service
    return lSTDAIR_Service.csvDisplay (iTravelSolutionList);
  }

  // ////////////////////////////////////////////////////////////////////
  const stdair::TravelSolutionStruct* TRAVELCCM_Service::
  chooseTravelSolution (stdair::TravelSolutionList_T& ioTravelSolutionList,
                        const stdair::BookingRequestStruct& iBookingRequest) {

    const stdair::TravelSolutionStruct* oTravelSolution_ptr =
      ChoiceManager::chooseTravelSolution (ioTravelSolutionList,
                                           iBookingRequest);
    return oTravelSolution_ptr;
  }

}
<|endoftext|>