<commit_before>#include "stdafx.h"
#include "SDL.h"
#include <limits.h>
#include <Windows.h>
#include "minmax.h"

#include "DreamPad.h"

static const Uint32 PAD_SUPPORT =
	PDD_DEV_SUPPORT_TA | PDD_DEV_SUPPORT_TB | PDD_DEV_SUPPORT_TX | PDD_DEV_SUPPORT_TY | PDD_DEV_SUPPORT_ST
	#ifdef EXTENDED_BUTTONS
	| PDD_DEV_SUPPORT_TC | PDD_DEV_SUPPORT_TD | PDD_DEV_SUPPORT_TZ
	#endif
	| PDD_DEV_SUPPORT_AR | PDD_DEV_SUPPORT_AL
	| PDD_DEV_SUPPORT_KU | PDD_DEV_SUPPORT_KD | PDD_DEV_SUPPORT_KL | PDD_DEV_SUPPORT_KR
	| PDD_DEV_SUPPORT_AX1 | PDD_DEV_SUPPORT_AY1 | PDD_DEV_SUPPORT_AX2 | PDD_DEV_SUPPORT_AY2;

DreamPad DreamPad::Controllers[GAMEPAD_COUNT];

DreamPad::DreamPad() : controller_id(-1), gamepad(nullptr), haptic(nullptr), effect({}), effect_id(-1),
	rumble_state(Motor::None), pad({}), normalized_L(0.0f), normalized_R(0.0f)
{
	// TODO: Properly detect supported rumble types
	effect.leftright.type = SDL_HAPTIC_LEFTRIGHT;
}
DreamPad::~DreamPad()
{
	Close();
}

bool DreamPad::Open(int id)
{
	if (connected)
	{
		Close();
	}

	gamepad = SDL_GameControllerOpen(id);

	if (gamepad == nullptr)
	{
		return (connected = false);
	}

	pad.Support = PAD_SUPPORT;

	SDL_Joystick* joystick = SDL_GameControllerGetJoystick(gamepad);

	if (joystick == nullptr)
	{
		return (connected = false);
	}

	controller_id = id;
	haptic = SDL_HapticOpenFromJoystick(joystick);

	if (haptic == nullptr)
	{
		return (connected = true);
	}

	if (SDL_HapticRumbleSupported(haptic))
	{
		effect_id = SDL_HapticNewEffect(haptic, &effect);
	}
	else
	{
		SDL_HapticClose(haptic);
		haptic = nullptr;
	}

	return (connected = true);
}

void DreamPad::Close()
{
	if (!connected)
	{
		return;
	}

	if (haptic != nullptr)
	{
		SDL_HapticDestroyEffect(haptic, effect_id);
		SDL_HapticClose(haptic);

		effect_id = -1;
		haptic = nullptr;
	}

	if (gamepad != nullptr)
	{
		SDL_GameControllerClose(gamepad);
		gamepad = nullptr;
	}

	controller_id = -1;
	connected = false;
}

void DreamPad::Poll()
{
	if (!connected && !settings.allow_keyboard)
	{
		return;
	}

	if (connected)
	{
		SDL_GameControllerUpdate();
	}

	bool allow_keyboard = settings.allow_keyboard;

	NJS_POINT2I axis;

	// TODO: keyboard/mouse toggle
	auto& kb = keyboard.DreamcastData();

	if (!connected || allow_keyboard && kb.LeftStickX)
	{
		axis.x = kb.LeftStickX;
	}
	else
	{
		axis.x = SDL_GameControllerGetAxis(gamepad, SDL_CONTROLLER_AXIS_LEFTX);
	}

	if (!connected || allow_keyboard && kb.LeftStickY)
	{
		axis.y = kb.LeftStickY;
	}
	else
	{
		axis.y = SDL_GameControllerGetAxis(gamepad, SDL_CONTROLLER_AXIS_LEFTY);
	}

	normalized_L = ConvertAxes((NJS_POINT2I*)&pad.LeftStickX, axis, settings.deadzoneL, settings.radialL);

	if (!connected || allow_keyboard && kb.RightStickX)
	{
		axis.x = kb.RightStickX;
	}
	else
	{
		axis.x = SDL_GameControllerGetAxis(gamepad, SDL_CONTROLLER_AXIS_RIGHTX);
	}

	if (!connected || allow_keyboard && kb.RightStickY)
	{
		axis.y = kb.RightStickY;
	}
	else
	{
		axis.y = SDL_GameControllerGetAxis(gamepad, SDL_CONTROLLER_AXIS_RIGHTY);
	}

	normalized_R = ConvertAxes((NJS_POINT2I*)&pad.RightStickX, axis, settings.deadzoneR, settings.radialR);

	short lt = (!connected || allow_keyboard && kb.LTriggerPressure) ? kb.LTriggerPressure : SDL_GameControllerGetAxis(gamepad, SDL_CONTROLLER_AXIS_TRIGGERLEFT);
	short rt = (!connected || allow_keyboard && kb.RTriggerPressure) ? kb.RTriggerPressure : SDL_GameControllerGetAxis(gamepad, SDL_CONTROLLER_AXIS_TRIGGERRIGHT);

	pad.LTriggerPressure = (short)(255.0f * ((float)lt / (float)SHRT_MAX));
	pad.RTriggerPressure = (short)(255.0f * ((float)rt / (float)SHRT_MAX));;

	Uint32 buttons = 0;

	buttons |= DigitalTrigger(pad.LTriggerPressure, settings.triggerThreshold, Buttons_L);
	buttons |= DigitalTrigger(pad.RTriggerPressure, settings.triggerThreshold, Buttons_R);

	if (connected)
	{
		if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_A))
		{
			buttons |= Buttons_A;
		}
		if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_B))
		{
			buttons |= Buttons_B;
		}
		if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_X))
		{
			buttons |= Buttons_X;
		}
		if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_Y))
		{
			buttons |= Buttons_Y;
		}

		if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_START))
		{
			buttons |= Buttons_Start;
		}

#ifdef EXTENDED_BUTTONS
		if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_LEFTSHOULDER))
		{
			buttons |= Buttons_C;
		}
		if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_BACK))
		{
			buttons |= Buttons_D;
		}
		if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER))
		{
			buttons |= Buttons_Z;
		}
#endif

		if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_DPAD_UP))
		{
			buttons |= Buttons_Up;
		}
		if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_DPAD_DOWN))
		{
			buttons |= Buttons_Down;
		}
		if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_DPAD_LEFT))
		{
			buttons |= Buttons_Left;
		}
		if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_DPAD_RIGHT))
		{
			buttons |= Buttons_Right;
		}
	}

	if (allow_keyboard)
	{
		buttons |= kb.HeldButtons;
	}

	UpdateButtons(pad, buttons);
}

void DreamPad::SetActiveMotor(Motor motor, bool enable)
{
	if (effect_id == -1 || haptic == nullptr)
	{
		return;
	}

	if (settings.megaRumble)
	{
		motor = Motor::Both;
	}

	const float f = settings.rumbleFactor;

	if (motor & Motor::Large)
	{
		effect.leftright.large_magnitude = enable ? (ushort)(USHRT_MAX * f) : 0;
		rumble_state = (Motor)(enable ? rumble_state | motor : rumble_state & ~Motor::Large);
	}

	if (motor & Motor::Small)
	{
		effect.leftright.small_magnitude = enable ? (ushort)(USHRT_MAX * f) : 0;
		rumble_state = (Motor)(enable ? rumble_state | motor : rumble_state & ~Motor::Small);
	}

	SDL_HapticUpdateEffect(haptic, effect_id, &effect);
	SDL_HapticRunEffect(haptic, effect_id, 1);
}

void DreamPad::Copy(ControllerData& dest) const
{
	dest = pad;
}

inline int DreamPad::DigitalTrigger(ushort trigger, ushort threshold, int button)
{
	return trigger > threshold ? button : 0;
}

float DreamPad::ConvertAxes(NJS_POINT2I* dest, const NJS_POINT2I& source, short deadzone, bool radial) const
{
	if (abs(source.x) < deadzone && abs(source.y) < deadzone)
	{
		*dest = {};
		return 0.0f;
	}

	// This is being intentionally limited to -32767 instead of -32768
	const float x = (float)clamp(source.x, (short)-SHRT_MAX, (short)SHRT_MAX);
	const float y = (float)-clamp(source.y, (short)-SHRT_MAX, (short)SHRT_MAX);

	const float m = sqrt(x * x + y * y);

	const float nx = (m < deadzone) ? 0 : x / m;	// Normalized (X)
	const float ny = (m < deadzone) ? 0 : y / m;	// Normalized (Y)
	const float n  = (min((float)SHRT_MAX, m) - deadzone) / ((float)SHRT_MAX - deadzone);

	// In my testing, multiplying -128 to 128 results in 127 instead, which is the desired value.
	dest->x = (radial || abs(source.x) >= deadzone) ? (short)clamp((short)(128 * (nx * n)), (short)-127, (short)127) : 0;
	dest->y = (radial || abs(source.y) >= deadzone) ? (short)clamp((short)(-128 * (ny * n)), (short)-127, (short)127) : 0;

	return n;
}

void DreamPad::UpdateButtons(ControllerData& pad, Uint32 buttons)
{
	pad.HeldButtons     = buttons;
	pad.NotHeldButtons  = ~buttons;
	pad.ReleasedButtons = pad.Old & (buttons ^ pad.Old);
	pad.PressedButtons  = buttons & (buttons ^ pad.Old);
	pad.Old             = pad.HeldButtons;
}

DreamPad::Settings::Settings()
{
	allow_keyboard   = false;
	deadzoneL        = GAMEPAD_LEFT_THUMB_DEADZONE;
	deadzoneR        = GAMEPAD_RIGHT_THUMB_DEADZONE;
	triggerThreshold = GAMEPAD_TRIGGER_THRESHOLD;
	radialL          = true;
	radialR          = false;
	rumbleFactor     = 1.0f;
	megaRumble       = false;
	rumbleMinTime    = 0;
}
void DreamPad::Settings::apply(short deadzoneL, short deadzoneR, bool radialL, bool radialR, uint8 triggerThreshold,
	float rumbleFactor, bool megaRumble, ushort rumbleMinTime)
{
	this->deadzoneL        = clamp(deadzoneL, (short)0, (short)SHRT_MAX);
	this->deadzoneR        = clamp(deadzoneR, (short)0, (short)SHRT_MAX);
	this->radialL          = radialL;
	this->radialR          = radialR;
	this->triggerThreshold = triggerThreshold;
	this->rumbleFactor     = rumbleFactor;
	this->megaRumble       = megaRumble;
	this->rumbleMinTime    = rumbleMinTime;
}
<commit_msg>Fixed keyboard diagonals<commit_after>#include "stdafx.h"
#include "SDL.h"
#include <limits.h>
#include <Windows.h>
#include "minmax.h"

#include "DreamPad.h"

static const Uint32 PAD_SUPPORT =
	PDD_DEV_SUPPORT_TA | PDD_DEV_SUPPORT_TB | PDD_DEV_SUPPORT_TX | PDD_DEV_SUPPORT_TY | PDD_DEV_SUPPORT_ST
	#ifdef EXTENDED_BUTTONS
	| PDD_DEV_SUPPORT_TC | PDD_DEV_SUPPORT_TD | PDD_DEV_SUPPORT_TZ
	#endif
	| PDD_DEV_SUPPORT_AR | PDD_DEV_SUPPORT_AL
	| PDD_DEV_SUPPORT_KU | PDD_DEV_SUPPORT_KD | PDD_DEV_SUPPORT_KL | PDD_DEV_SUPPORT_KR
	| PDD_DEV_SUPPORT_AX1 | PDD_DEV_SUPPORT_AY1 | PDD_DEV_SUPPORT_AX2 | PDD_DEV_SUPPORT_AY2;

DreamPad DreamPad::Controllers[GAMEPAD_COUNT];

DreamPad::DreamPad() : controller_id(-1), gamepad(nullptr), haptic(nullptr), effect({}), effect_id(-1),
	rumble_state(Motor::None), pad({}), normalized_L(0.0f), normalized_R(0.0f)
{
	// TODO: Properly detect supported rumble types
	effect.leftright.type = SDL_HAPTIC_LEFTRIGHT;
}
DreamPad::~DreamPad()
{
	Close();
}

bool DreamPad::Open(int id)
{
	if (connected)
	{
		Close();
	}

	gamepad = SDL_GameControllerOpen(id);

	if (gamepad == nullptr)
	{
		return (connected = false);
	}

	pad.Support = PAD_SUPPORT;

	SDL_Joystick* joystick = SDL_GameControllerGetJoystick(gamepad);

	if (joystick == nullptr)
	{
		return (connected = false);
	}

	controller_id = id;
	haptic = SDL_HapticOpenFromJoystick(joystick);

	if (haptic == nullptr)
	{
		return (connected = true);
	}

	if (SDL_HapticRumbleSupported(haptic))
	{
		effect_id = SDL_HapticNewEffect(haptic, &effect);
	}
	else
	{
		SDL_HapticClose(haptic);
		haptic = nullptr;
	}

	return (connected = true);
}

void DreamPad::Close()
{
	if (!connected)
	{
		return;
	}

	if (haptic != nullptr)
	{
		SDL_HapticDestroyEffect(haptic, effect_id);
		SDL_HapticClose(haptic);

		effect_id = -1;
		haptic = nullptr;
	}

	if (gamepad != nullptr)
	{
		SDL_GameControllerClose(gamepad);
		gamepad = nullptr;
	}

	controller_id = -1;
	connected = false;
}

void DreamPad::Poll()
{
	if (!connected && !settings.allow_keyboard)
	{
		return;
	}

	if (connected)
	{
		SDL_GameControllerUpdate();
	}

	bool allow_keyboard = settings.allow_keyboard;

	NJS_POINT2I axis;

	// TODO: keyboard/mouse toggle
	auto& kb = keyboard.DreamcastData();

	if (!connected || allow_keyboard && kb.LeftStickX)
	{
		axis.x = kb.LeftStickX;
	}
	else
	{
		axis.x = SDL_GameControllerGetAxis(gamepad, SDL_CONTROLLER_AXIS_LEFTX);
	}

	if (!connected || allow_keyboard && kb.LeftStickY)
	{
		axis.y = kb.LeftStickY;
	}
	else
	{
		axis.y = SDL_GameControllerGetAxis(gamepad, SDL_CONTROLLER_AXIS_LEFTY);
	}

	normalized_L = ConvertAxes((NJS_POINT2I*)&pad.LeftStickX, axis, settings.deadzoneL, settings.radialL);

	if (!connected || allow_keyboard && kb.RightStickX)
	{
		axis.x = kb.RightStickX;
	}
	else
	{
		axis.x = SDL_GameControllerGetAxis(gamepad, SDL_CONTROLLER_AXIS_RIGHTX);
	}

	if (!connected || allow_keyboard && kb.RightStickY)
	{
		axis.y = kb.RightStickY;
	}
	else
	{
		axis.y = SDL_GameControllerGetAxis(gamepad, SDL_CONTROLLER_AXIS_RIGHTY);
	}

	normalized_R = ConvertAxes((NJS_POINT2I*)&pad.RightStickX, axis, settings.deadzoneR, settings.radialR);

	short lt = (!connected || allow_keyboard && kb.LTriggerPressure) ? kb.LTriggerPressure : SDL_GameControllerGetAxis(gamepad, SDL_CONTROLLER_AXIS_TRIGGERLEFT);
	short rt = (!connected || allow_keyboard && kb.RTriggerPressure) ? kb.RTriggerPressure : SDL_GameControllerGetAxis(gamepad, SDL_CONTROLLER_AXIS_TRIGGERRIGHT);

	pad.LTriggerPressure = (short)(255.0f * ((float)lt / (float)SHRT_MAX));
	pad.RTriggerPressure = (short)(255.0f * ((float)rt / (float)SHRT_MAX));

	Uint32 buttons = 0;

	buttons |= DigitalTrigger(pad.LTriggerPressure, settings.triggerThreshold, Buttons_L);
	buttons |= DigitalTrigger(pad.RTriggerPressure, settings.triggerThreshold, Buttons_R);

	if (connected)
	{
		if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_A))
		{
			buttons |= Buttons_A;
		}
		if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_B))
		{
			buttons |= Buttons_B;
		}
		if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_X))
		{
			buttons |= Buttons_X;
		}
		if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_Y))
		{
			buttons |= Buttons_Y;
		}

		if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_START))
		{
			buttons |= Buttons_Start;
		}

#ifdef EXTENDED_BUTTONS
		if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_LEFTSHOULDER))
		{
			buttons |= Buttons_C;
		}
		if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_BACK))
		{
			buttons |= Buttons_D;
		}
		if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER))
		{
			buttons |= Buttons_Z;
		}
#endif

		if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_DPAD_UP))
		{
			buttons |= Buttons_Up;
		}
		if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_DPAD_DOWN))
		{
			buttons |= Buttons_Down;
		}
		if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_DPAD_LEFT))
		{
			buttons |= Buttons_Left;
		}
		if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_DPAD_RIGHT))
		{
			buttons |= Buttons_Right;
		}
	}

	if (allow_keyboard)
	{
		buttons |= kb.HeldButtons;
	}

	UpdateButtons(pad, buttons);
}

void DreamPad::SetActiveMotor(Motor motor, bool enable)
{
	if (effect_id == -1 || haptic == nullptr)
	{
		return;
	}

	if (settings.megaRumble)
	{
		motor = Motor::Both;
	}

	const float f = settings.rumbleFactor;

	if (motor & Motor::Large)
	{
		effect.leftright.large_magnitude = enable ? (ushort)(USHRT_MAX * f) : 0;
		rumble_state = (Motor)(enable ? rumble_state | motor : rumble_state & ~Motor::Large);
	}

	if (motor & Motor::Small)
	{
		effect.leftright.small_magnitude = enable ? (ushort)(USHRT_MAX * f) : 0;
		rumble_state = (Motor)(enable ? rumble_state | motor : rumble_state & ~Motor::Small);
	}

	SDL_HapticUpdateEffect(haptic, effect_id, &effect);
	SDL_HapticRunEffect(haptic, effect_id, 1);
}

void DreamPad::Copy(ControllerData& dest) const
{
	dest = pad;
}

inline int DreamPad::DigitalTrigger(ushort trigger, ushort threshold, int button)
{
	return trigger > threshold ? button : 0;
}

float DreamPad::ConvertAxes(NJS_POINT2I* dest, const NJS_POINT2I& source, short deadzone, bool radial) const
{
	if (abs(source.x) < deadzone && abs(source.y) < deadzone)
	{
		*dest = {};
		return 0.0f;
	}

	// This is being intentionally limited to -32767 instead of -32768
	const float x = (float)clamp(source.x, (short)-SHRT_MAX, (short)SHRT_MAX);
	const float y = (float)-clamp(source.y, (short)-SHRT_MAX, (short)SHRT_MAX);

	const float m = min(sqrt(x * x + y * y), (float)SHRT_MAX);

	const float nx = (m < deadzone) ? 0 : x / m; // Normalized (X)
	const float ny = (m < deadzone) ? 0 : y / m; // Normalized (Y)
	const float n  = (min((float)SHRT_MAX, m) - deadzone) / ((float)SHRT_MAX - deadzone);

	dest->x = (radial || abs(source.x) >= deadzone) ? (short)clamp((short)(128 * (nx * n)), (short)-127, (short)127) : 0;
	dest->y = (radial || abs(source.y) >= deadzone) ? (short)clamp((short)(-128 * (ny * n)), (short)-127, (short)127) : 0;

	return n;
}

void DreamPad::UpdateButtons(ControllerData& pad, Uint32 buttons)
{
	pad.HeldButtons     = buttons;
	pad.NotHeldButtons  = ~buttons;
	pad.ReleasedButtons = pad.Old & (buttons ^ pad.Old);
	pad.PressedButtons  = buttons & (buttons ^ pad.Old);
	pad.Old             = pad.HeldButtons;
}

DreamPad::Settings::Settings()
{
	allow_keyboard   = false;
	deadzoneL        = GAMEPAD_LEFT_THUMB_DEADZONE;
	deadzoneR        = GAMEPAD_RIGHT_THUMB_DEADZONE;
	triggerThreshold = GAMEPAD_TRIGGER_THRESHOLD;
	radialL          = true;
	radialR          = false;
	rumbleFactor     = 1.0f;
	megaRumble       = false;
	rumbleMinTime    = 0;
}
void DreamPad::Settings::apply(short deadzoneL, short deadzoneR, bool radialL, bool radialR, uint8 triggerThreshold,
	float rumbleFactor, bool megaRumble, ushort rumbleMinTime)
{
	this->deadzoneL        = clamp(deadzoneL, (short)0, (short)SHRT_MAX);
	this->deadzoneR        = clamp(deadzoneR, (short)0, (short)SHRT_MAX);
	this->radialL          = radialL;
	this->radialR          = radialR;
	this->triggerThreshold = triggerThreshold;
	this->rumbleFactor     = rumbleFactor;
	this->megaRumble       = megaRumble;
	this->rumbleMinTime    = rumbleMinTime;
}
<|endoftext|>


<commit_before><commit_msg>fix SFINAE detection of const char[N] for msvc<commit_after><|endoftext|>


<commit_before>#pragma once

#include <sal/config.hpp>
#if __sal_os_linux || __sal_os_darwin
  #include <netinet/ip.h>
  #include <arpa/inet.h>
#elif __sal_os_windows
  #include <ws2tcpip.h>
  #pragma comment(lib, "ws2_32")
#else
  #error Unsupported platform
#endif

__sal_begin

namespace net { namespace ip { namespace __bits {

#if __sal_os_windows
  using sa_family_t = ::ADDRESS_FAMILY;
#else
  using sa_family_t = ::sa_family_t;
#endif

inline bool ntop (const in_addr &src, char *dest, size_t size) noexcept
{
#if __sal_os_windows
  auto addr = src;
  return ::inet_ntop(AF_INET, &addr, dest, size) != nullptr;
#else
  return ::inet_ntop(AF_INET, &src, dest, size) != nullptr;
#endif
}

inline bool pton (const char *src, in_addr &dest) noexcept
{
  return ::inet_pton(AF_INET, src, &dest) == 1;
}

inline bool ntop (const in6_addr &src, char *dest, size_t size) noexcept
{
#if __sal_os_windows
  // depending on SDK version, it's API parameter is const or not
  // make it "void *" regardless
  auto addr = &const_cast<in6_addr &>(src);
  return ::inet_ntop(AF_INET6, addr, dest, size) != nullptr;
#else
  return ::inet_ntop(AF_INET6, &src, dest, size) != nullptr;
#endif
}

inline bool pton (const char *src, in6_addr &dest) noexcept
{
  return ::inet_pton(AF_INET6, src, &dest) == 1;
}

#if defined(_MSC_VER)
inline
#else
constexpr
#endif
uint64_t fnv_1a (const uint8_t *first, const uint8_t *last) noexcept
{
  auto h = 0xcbf29ce484222325ULL;
  while (first != last)
  {
    h ^= *first++;
    h += (h << 1) + (h << 4) + (h << 5) + (h << 7) + (h << 8) + (h << 40);
  }
  return h;
}

#if defined(_MSC_VER)
inline
#else
constexpr
#endif
uint64_t combine (uint64_t h, uint64_t l) noexcept
{
  constexpr uint64_t mul = 0x9ddfea08eb382d69ULL;
  uint64_t a = (l ^ h) * mul;
  a ^= (a >> 47);
  uint64_t b = (h ^ a) * mul;
  b ^= (b >> 47);
  return b * mul;
}

}}} // namespace net::ip::__bits

__sal_end
<commit_msg>Use inline for MSVC instead of constexpr for "complicated" function<commit_after>#pragma once

#include <sal/config.hpp>
#if __sal_os_linux || __sal_os_darwin
  #include <netinet/ip.h>
  #include <arpa/inet.h>
#elif __sal_os_windows
  #include <ws2tcpip.h>
  #pragma comment(lib, "ws2_32")
#else
  #error Unsupported platform
#endif

__sal_begin

namespace net { namespace ip { namespace __bits {

#if __sal_os_windows
  using sa_family_t = ::ADDRESS_FAMILY;
#else
  using sa_family_t = ::sa_family_t;
#endif

inline bool ntop (const in_addr &src, char *dest, size_t size) noexcept
{
#if __sal_os_windows
  auto addr = src;
  return ::inet_ntop(AF_INET, &addr, dest, size) != nullptr;
#else
  return ::inet_ntop(AF_INET, &src, dest, size) != nullptr;
#endif
}

inline bool pton (const char *src, in_addr &dest) noexcept
{
  return ::inet_pton(AF_INET, src, &dest) == 1;
}

inline bool ntop (const in6_addr &src, char *dest, size_t size) noexcept
{
#if __sal_os_windows
  // depending on SDK version, it's API parameter is const or not
  // make it "void *" regardless
  auto addr = &const_cast<in6_addr &>(src);
  return ::inet_ntop(AF_INET6, addr, dest, size) != nullptr;
#else
  return ::inet_ntop(AF_INET6, &src, dest, size) != nullptr;
#endif
}

inline bool pton (const char *src, in6_addr &dest) noexcept
{
  return ::inet_pton(AF_INET6, src, &dest) == 1;
}

#if defined(_MSC_VER)
  #define CONSTEXPR inline
#else
  #define CONSTEXPR constexpr
#endif

CONSTEXPR uint64_t fnv_1a (const uint8_t *first, const uint8_t *last) noexcept
{
  auto h = 0xcbf29ce484222325ULL;
  while (first != last)
  {
    h ^= *first++;
    h += (h << 1) + (h << 4) + (h << 5) + (h << 7) + (h << 8) + (h << 40);
  }
  return h;
}

CONSTEXPR uint64_t combine (uint64_t h, uint64_t l) noexcept
{
  constexpr uint64_t mul = 0x9ddfea08eb382d69ULL;
  uint64_t a = (l ^ h) * mul;
  a ^= (a >> 47);
  uint64_t b = (h ^ a) * mul;
  b ^= (b >> 47);
  return b * mul;
}

}}} // namespace net::ip::__bits

__sal_end
<|endoftext|>


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

#include "MRCWriter.h"

//-- C Includes
#include <stdio.h>

//-- C++ Includes
#include <iomanip>
#include <limits>

//-- MXA Includes
#include "MXA/MXA.h"
#include "MXA/Common/MXAEndian.h"
#include "MXA/Common/IO/MXAFileWriter64.h"

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
MRCWriter::MRCWriter() :
m_MRCHeader(NULL)
{
m_XDims[0] = 0;
m_XDims[1] = 0;
m_YDims[0] = 0;
m_YDims[1] = 0;
m_ZDims[0] = 0;
m_ZDims[1] = 0;
}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
MRCWriter::~MRCWriter()
{
}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void MRCWriter::execute()
{
    write();
}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
int MRCWriter::writeHeader()
{
  int err = -1;

  return err;
}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void MRCWriter::initializeMRCHeader(MRCHeader* header)
{

  header->nx = m_Geometry->N_x;
  header->ny = m_Geometry->N_y;
  header->nz = m_Geometry->N_z;

  header->mode = 2;

  header->nxstart = 0;
  header->nystart = 0;
  header->nzstart = 0;
  header->mx = m_Geometry->N_x;
  header->my = m_Geometry->N_y;
  header->mz = m_Geometry->N_z;

  header->xlen = m_Geometry->N_x;
  header->ylen = m_Geometry->N_y;
  header->zlen = m_Geometry->N_z;

  header->alpha = 90.0;
  header->beta = 90.0;
  header->gamma = 90.0;

  header->mapc = 1;
  header->mapr = 2;
  header->maps = 3;

  /* ** These need to be calculated from the data ** */
  header->amin = 0.0;
  header->amax = 0.0;
  header->amean = 0.0;

  header->ispg = 0;
  header->nsymbt = 0;
  /* ** Calculate the size of the extended header */
  header->next = sizeof(FEIHeader) * m_Geometry->N_z;
  header->creatid = 0;
  ::memset(&header->extra_data, 0, 30);

  header->nint = 0;
  header->nreal = 0;
  ::memset(&header->extra_data_2, 0, 20);
  header->imodStamp = 0;
  header->imodFlags = 0;
  header->idtype = 0;
  header->lens = 0;
  header->nd1 = 0;
  header->nd2 = 0;
  header->vd1 = 0;
  header->vd2 = 0;

  ::memset(&header->tiltangles, 0, 6 * sizeof(float));
  header->xorg = 0.0f;
  header->yorg = 0.0f;
  header->zorg = 0.0f;
  header->cmap[0] = 'M';
  header->cmap[1] = 'A';
  header->cmap[2] = 'P';
  header->cmap[3] = ' ';
#if defined (CMP_WORDS_BIGENDIAN)
  header->stamp[0] = 17;
  header->stamp[1] = 17;
#else
  header->stamp[0] = 68;
  header->stamp[1] = 65;
#endif
  header->stamp[2] = 0;
  header->stamp[3] = 0;
  header->rms = 0.0f;
  header->nLabels = 3;
  for(int i = 0; i < 10; ++i)
  {
    ::memset(header->labels[i], 0, 80);
  }
  snprintf(header->labels[0], 80, "Fei Company (C) Copyright 2003");
  snprintf(header->labels[1], 80, "Reconstruction by OpenMBIR");
  snprintf(header->labels[2], 80, "OpenMBIR code developed by Purdue University & BlueQuartz Software");

}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
int MRCWriter::write()
{
  int err = -1;
  std::stringstream ss;
 // std::cout << "MRC Output File: '" << m_OutputFile << "'" << std::endl;
  if (m_OutputFile.empty())
  {
      ss.str("");
      ss << "MRCWriter: Output File was Not Set";
      setErrorCondition(-1);
      setErrorMessage(ss.str());
      notify(getErrorMessage().c_str(), 0, UpdateErrorMessage);
      return err;
  }
  MXAFileWriter64 writer(m_OutputFile);
  bool success = writer.initWriter();

  if (false == success)
  {
      ss.str("");
      ss << "MRCWriter: Error opening output file for writing. '" <<
          m_OutputFile << "'";
      setErrorCondition(-1);
      setErrorMessage(ss.str());
      notify(getErrorMessage().c_str(), 0, UpdateErrorMessage);
      return err;
  }

//  std::cout << "Writing MRC File with Geometry of: " << std::endl;
//  std::cout << "  N_z: " << m_Geometry->N_z << std::endl;
//  std::cout << "  N_x: " << m_Geometry->N_x << std::endl;
//  std::cout << "  N_y: " << m_Geometry->N_y << std::endl;
  MRCHeader mrcHeader; // Put one on the stack in case the programmer supplied a NULL pointer
  ::memset(&mrcHeader, 0, 1024);
  bool detachHeaderReference = false;
  if (NULL == m_MRCHeader)
  {
    m_MRCHeader = &mrcHeader;
    initializeMRCHeader(m_MRCHeader);
    detachHeaderReference = true;
  }
  // Update the header with our Dimensions
  m_MRCHeader->nx = (m_XDims[1] - m_XDims[0]);
  m_MRCHeader->ny = (m_YDims[1] - m_YDims[0]);
  m_MRCHeader->nz = (m_ZDims[1] - m_ZDims[0]);
  m_MRCHeader->mx = m_MRCHeader->nx;
  m_MRCHeader->my = m_MRCHeader->ny;
  m_MRCHeader->mz = m_MRCHeader->nz;

  m_MRCHeader->xlen = m_MRCHeader->nx;
  m_MRCHeader->ylen = m_MRCHeader->ny;
  m_MRCHeader->zlen = m_MRCHeader->nz;
  m_MRCHeader->next = sizeof(FEIHeader) * m_MRCHeader->nz;

  // Write the header
  writer.write(reinterpret_cast<char*>(m_MRCHeader), 1024);
  for(uint16_t i = 0; i < m_Geometry->N_z; ++i)
  {
    FEIHeader fei;
    ::memset(&fei, 0, sizeof(FEIHeader));
    fei.pixelsize = static_cast<float>(m_Geometry->LengthX);
    writer.write(reinterpret_cast<char*>(&fei), sizeof(FEIHeader));
  }

  size_t dims[2] = {m_MRCHeader->nx, m_MRCHeader->ny};
  FloatImageType::Pointer sliceData = FloatImageType::New(dims, "temp slice data");
  float* slice = sliceData->getPointer(0);

  size_t index = 0;
  Real_t d = 0.0;
  size_t count = 0;

  float mean = 0.0;
  float dmax = std::numeric_limits<Real_t>::min();
  float dmin = std::numeric_limits<Real_t>::max();

  for (int z = m_ZDims[1]; z >= m_ZDims[0]; z--)
  {
    index = 0;
    for (int y = m_YDims[0]; y < m_YDims[1]; ++y)
    {
      for (int x = m_XDims[0]; x < m_XDims[1]; ++x)
      {
        //index = (x * m_Geometry->N_y) + y;
        d = m_Geometry->Object->getValue(z, x, y);
        slice[index] = static_cast<float>(d);
        mean += slice[index];
        count++;
        if(d > dmax) dmax = d;
        if(d < dmin) dmin = d;
        ++index;
      }
    }
    writer.write(reinterpret_cast<char*>(slice), sizeof(float) * dims[0] * dims[1]);
  }

  // Calculate the mean value
  mean = mean / count;
  // Update the values in the header of the file
  writer.setFilePointer64(76); // Set the position to the "amin" header entry
  writer.writeValue(&dmin);
  writer.writeValue(&dmax);
  writer.writeValue(&mean);

  if (detachHeaderReference == true)
  {
    m_MRCHeader = NULL;
  }

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

#include "MRCWriter.h"

//-- C Includes
#include <stdio.h>

//-- C++ Includes
#include <iomanip>
#include <limits>

//-- MXA Includes
#include "MXA/MXA.h"
#include "MXA/Common/MXAEndian.h"
#include "MXA/Common/IO/MXAFileWriter64.h"

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
MRCWriter::MRCWriter() :
m_MRCHeader(NULL)
{
m_XDims[0] = 0;
m_XDims[1] = 0;
m_YDims[0] = 0;
m_YDims[1] = 0;
m_ZDims[0] = 0;
m_ZDims[1] = 0;
}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
MRCWriter::~MRCWriter()
{
}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void MRCWriter::execute()
{
    write();
}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
int MRCWriter::writeHeader()
{
  int err = -1;

  return err;
}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void MRCWriter::initializeMRCHeader(MRCHeader* header)
{

  header->nx = m_Geometry->N_x;
  header->ny = m_Geometry->N_y;
  header->nz = m_Geometry->N_z;

  header->mode = 2;

  header->nxstart = 0;
  header->nystart = 0;
  header->nzstart = 0;
  header->mx = m_Geometry->N_x;
  header->my = m_Geometry->N_y;
  header->mz = m_Geometry->N_z;

  header->xlen = m_Geometry->N_x;
  header->ylen = m_Geometry->N_y;
  header->zlen = m_Geometry->N_z;

  header->alpha = 90.0;
  header->beta = 90.0;
  header->gamma = 90.0;

  header->mapc = 1;
  header->mapr = 2;
  header->maps = 3;

  /* ** These need to be calculated from the data ** */
  header->amin = 0.0;
  header->amax = 0.0;
  header->amean = 0.0;

  header->ispg = 0;
  header->nsymbt = 0;
  /* ** Calculate the size of the extended header */
  header->next = sizeof(FEIHeader) * m_Geometry->N_z;
  header->creatid = 0;
  ::memset(&header->extra_data, 0, 30);

  header->nint = 0;
  header->nreal = 0;
  ::memset(&header->extra_data_2, 0, 20);
  header->imodStamp = 0;
  header->imodFlags = 0;
  header->idtype = 0;
  header->lens = 0;
  header->nd1 = 0;
  header->nd2 = 0;
  header->vd1 = 0;
  header->vd2 = 0;

  ::memset(&header->tiltangles, 0, 6 * sizeof(float));
  header->xorg = 0.0f;
  header->yorg = 0.0f;
  header->zorg = 0.0f;
  header->cmap[0] = 'M';
  header->cmap[1] = 'A';
  header->cmap[2] = 'P';
  header->cmap[3] = ' ';
#if defined (CMP_WORDS_BIGENDIAN)
  header->stamp[0] = 17;
  header->stamp[1] = 17;
#else
  header->stamp[0] = 68;
  header->stamp[1] = 65;
#endif
  header->stamp[2] = 0;
  header->stamp[3] = 0;
  header->rms = 0.0f;
  header->nLabels = 3;
  for(int i = 0; i < 10; ++i)
  {
    ::memset(header->labels[i], 0, 80);
  }
  snprintf(header->labels[0], 80, "Fei Company (C) Copyright 2003");
  snprintf(header->labels[1], 80, "Reconstruction by OpenMBIR");
  snprintf(header->labels[2], 80, "OpenMBIR code developed by Purdue University & BlueQuartz Software");

}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
int MRCWriter::write()
{
  int err = -1;
  std::stringstream ss;
 // std::cout << "MRC Output File: '" << m_OutputFile << "'" << std::endl;
  if (m_OutputFile.empty())
  {
      ss.str("");
      ss << "MRCWriter: Output File was Not Set";
      setErrorCondition(-1);
      setErrorMessage(ss.str());
      notify(getErrorMessage().c_str(), 0, UpdateErrorMessage);
      return err;
  }
  MXAFileWriter64 writer(m_OutputFile);
  bool success = writer.initWriter();

  if (false == success)
  {
      ss.str("");
      ss << "MRCWriter: Error opening output file for writing. '" <<
          m_OutputFile << "'";
      setErrorCondition(-1);
      setErrorMessage(ss.str());
      notify(getErrorMessage().c_str(), 0, UpdateErrorMessage);
      return err;
  }

//  std::cout << "Writing MRC File with Geometry of: " << std::endl;
//  std::cout << "  N_z: " << m_Geometry->N_z << std::endl;
//  std::cout << "  N_x: " << m_Geometry->N_x << std::endl;
//  std::cout << "  N_y: " << m_Geometry->N_y << std::endl;
  MRCHeader mrcHeader; // Put one on the stack in case the programmer supplied a NULL pointer
  ::memset(&mrcHeader, 0, 1024);
  bool detachHeaderReference = false;
  if (NULL == m_MRCHeader)
  {
    m_MRCHeader = &mrcHeader;
    initializeMRCHeader(m_MRCHeader);
    detachHeaderReference = true;
  }
  // Update the header with our Dimensions
  m_MRCHeader->nx = (m_XDims[1] - m_XDims[0]);
  m_MRCHeader->ny = (m_YDims[1] - m_YDims[0]);
  m_MRCHeader->nz = (m_ZDims[1] - m_ZDims[0]);
  m_MRCHeader->mx = m_MRCHeader->nx;
  m_MRCHeader->my = m_MRCHeader->ny;
  m_MRCHeader->mz = m_MRCHeader->nz;

  m_MRCHeader->xlen = m_MRCHeader->nx;
  m_MRCHeader->ylen = m_MRCHeader->ny;
  m_MRCHeader->zlen = m_MRCHeader->nz;
  m_MRCHeader->next = sizeof(FEIHeader) * m_MRCHeader->nz;

  // Write the header
  writer.write(reinterpret_cast<char*>(m_MRCHeader), 1024);
  for(uint16_t i = 0; i < m_Geometry->N_z; ++i)
  {
    FEIHeader fei;
    ::memset(&fei, 0, sizeof(FEIHeader));
    fei.pixelsize = static_cast<float>(m_Geometry->LengthX);
    writer.write(reinterpret_cast<char*>(&fei), sizeof(FEIHeader));
  }

  size_t dims[2] = {m_MRCHeader->nx, m_MRCHeader->ny};
  FloatImageType::Pointer sliceData = FloatImageType::New(dims, "temp slice data");
  float* slice = sliceData->getPointer(0);

  size_t index = 0;
  Real_t d = 0.0;
  size_t count = 0;

  float mean = 0.0;
  float dmax = std::numeric_limits<Real_t>::min();
  float dmin = std::numeric_limits<Real_t>::max();

  for (int z = m_ZDims[1]; z >= m_ZDims[0]; z--)
  {
    index = 0;
    for (int y = m_YDims[0]; y < m_YDims[1]; ++y)
    {
      for (int x = m_XDims[0]; x < m_XDims[1]; ++x)
      {
        //index = (x * m_Geometry->N_y) + y;
        d = m_Geometry->Object->getValue(z, x, y);
        slice[index] = static_cast<float>(d);
        mean += slice[index];
        count++;
        if(d > dmax) dmax = d;
        if(d < dmin) dmin = d;
        ++index;
      }
    }
    writer.write(reinterpret_cast<char*>(slice), sizeof(float) * dims[0] * dims[1]);
  }

  // Calculate the mean value
  mean = mean / count;
  // Update the values in the header of the file
  writer.setFilePointer64(76); // Set the position to the "amin" header entry
  writer.writeValue(&dmin);
  writer.writeValue(&dmax);
  writer.writeValue(&mean);

  if (detachHeaderReference == true)
  {
    m_MRCHeader = NULL;
  }

  setErrorCondition(0);
  setErrorMessage("");
  notify("Done Writing the MRC Output File", 0, UpdateProgressMessage);
  err = 1;
  return err;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: datetime.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2005-04-13 12:25:14 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

//= conversions UNO3.TimeClass <-> Tools.TimeClass (Date/Time/DateTime)
#ifndef INCLUDED_UNOTOOLSDLLAPI_H
#include "unotools/unotoolsdllapi.h"
#endif

#ifndef _UNOTOOLS_DATETIME_HXX_
#define _UNOTOOLS_DATETIME_HXX_

#include <com/sun/star/util/Date.hpp>
#include <com/sun/star/util/Time.hpp>
#include <com/sun/star/util/DateTime.hpp>

class Date;
class Time;
class DateTime;

//.........................................................................
namespace utl
{
//.........................................................................

    namespace starutil = ::com::sun::star::util;

    UNOTOOLS_DLLPUBLIC void typeConvert(const Time& _rTime, starutil::Time& _rOut);
    UNOTOOLS_DLLPUBLIC void typeConvert(const starutil::Time& _rTime, Time& _rOut);

    UNOTOOLS_DLLPUBLIC void typeConvert(const Date& _rDate, starutil::Date& _rOut);
    UNOTOOLS_DLLPUBLIC void typeConvert(const starutil::Date& _rDate, Date& _rOut);

    UNOTOOLS_DLLPUBLIC void typeConvert(const DateTime& _rDateTime, starutil::DateTime& _rOut);
    UNOTOOLS_DLLPUBLIC void typeConvert(const starutil::DateTime& _rDateTime, DateTime& _rOut);

//.........................................................................
}   // namespace utl
//.........................................................................

#endif // _UNOTOOLS_DATETIME_HXX_

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

//= conversions UNO3.TimeClass <-> Tools.TimeClass (Date/Time/DateTime)
#ifndef INCLUDED_UNOTOOLSDLLAPI_H
#include "unotools/unotoolsdllapi.h"
#endif

#ifndef _UNOTOOLS_DATETIME_HXX_
#define _UNOTOOLS_DATETIME_HXX_

#include <com/sun/star/util/Date.hpp>
#include <com/sun/star/util/Time.hpp>
#include <com/sun/star/util/DateTime.hpp>

class Date;
class Time;
class DateTime;

//.........................................................................
namespace utl
{
//.........................................................................

    namespace starutil = ::com::sun::star::util;

    UNOTOOLS_DLLPUBLIC void typeConvert(const Time& _rTime, starutil::Time& _rOut);
    UNOTOOLS_DLLPUBLIC void typeConvert(const starutil::Time& _rTime, Time& _rOut);

    UNOTOOLS_DLLPUBLIC void typeConvert(const Date& _rDate, starutil::Date& _rOut);
    UNOTOOLS_DLLPUBLIC void typeConvert(const starutil::Date& _rDate, Date& _rOut);

    UNOTOOLS_DLLPUBLIC void typeConvert(const DateTime& _rDateTime, starutil::DateTime& _rOut);
    UNOTOOLS_DLLPUBLIC void typeConvert(const starutil::DateTime& _rDateTime, DateTime& _rOut);

//.........................................................................
}   // namespace utl
//.........................................................................

#endif // _UNOTOOLS_DATETIME_HXX_

<|endoftext|>


<commit_before>/*******************************************************************************
 * Copyright (c) 2009-04-24 Joacim Jacobsson.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Joacim Jacobsson - first implementation
 *******************************************************************************/

#include <stdlib.h>
#include <other/getopt.h>
#include <other/lookup3.h>

#include <btree/btree.h>
#include "generate/program.h"
#include "xgml_printer.h"

FILE* g_outputFile = 0x0;
char* g_inputFileName = 0x0;
char* g_outputFileName = "a.out";
bool g_swapEndian = false;
char* g_asmFileName = 0x0;
char* g_xgmlFileName = 0x0;
bool g_debug = false;

int g_allocs = 0;
int g_frees = 0;

struct ParsingInfo
{
  FILE* m_File;
  const char* m_Name;
};

int read_file( ParserContext pc, char* buffer, int maxsize )
{
  ParsingInfo* pi = (ParsingInfo*)ParserContextGetExtra( pc );
  if( !pi )
    return 0;
  if( feof( pi->m_File ) )
    return 0;
  return (int)fread( buffer, 1, maxsize, pi->m_File );
}

void parser_error( ParserContext pc, const char* msg )
{
  ParsingInfo* pi = (ParsingInfo*)ParserContextGetExtra( pc );
  if( pi )
  {
    printf( "%s(%d) : error : %s\n", pi->m_Name, ParserContextGetLineNo( pc ),
      msg );
  }
  else
  {
    printf( "%s: error : %s\n", g_inputFileName, msg );
  }
}

void parser_warning( ParserContext pc, const char* msg )
{
  ParsingInfo* pi = (ParsingInfo*)ParserContextGetExtra( pc );
  if( pi )
  {
    printf( "%s(%d): warning : %s\n", pi->m_Name,
      ParserContextGetLineNo( pc ), msg );
  }
  else
  {
    printf( "%s: warning : %s\n", g_inputFileName, msg );
  }
}

void* allocate_memory( mem_size_t size )
{
  g_allocs++;
  return malloc( size );
}

void free_memory( void* ptr )
{
  if( ptr )
  {
    g_frees++;
    free( ptr );
  }
}

const char* parser_translate_include( ParserContext pc, const char* include )
{
  ParsingInfo* pi = (ParsingInfo*)ParserContextGetExtra( pc );
  BehaviorTreeContext btc = ParserContextGetBehaviorTreeContext( pc );

  Allocator a;
  a.m_Alloc = &allocate_memory;
  a.m_Free = &free_memory;

  StringBuffer sb;
  StringBufferInit( a, &sb );

  if( pi->m_Name )
  {
    char backslash  = '\\';
    char frontslash = '/';

    int s = 0, last = -1;
    const char* p = pi->m_Name;
    while( p && *p )
    {
      if( *p == backslash || *p == frontslash )
        last = s;
      ++p;
      ++s;
    }
    if( last != -1 )
      StringBufferAppend( &sb, pi->m_Name, last + 1 );
  }

  StringBufferAppend( &sb, include );
  const char* ret = BehaviorTreeContextRegisterString( btc, sb.m_Str );
  StringBufferDestroy( &sb );

  return ret;
}

int main( int argc, char** argv )
{
  GetOptContext ctx;
  init_getopt_context( &ctx );
  char c;

  while( (c = getopt( argc, argv, "?i:o:a:de:x:", &ctx )) != -1 )
  {
    switch( c )
    {
    case 'i':
      g_inputFileName = ctx.optarg;
      break;
    case 'o':
      g_outputFileName = ctx.optarg;
      break;
    case 'e':
      if( strcmp( ctx.optarg, "big" ) == 0 )
        g_swapEndian = true;
      else if( strcmp( ctx.optarg, "little" ) == 0 )
        g_swapEndian = false;
      else
      {
        fprintf( stdout, "error: unknown argument for option -e: %s\n", ctx.optarg );
        return -1;
      }
      break;
    case 'a':
      g_asmFileName = ctx.optarg;
      break;
    case 'd':
      g_debug = true;
      break;
    case 'x':
      g_xgmlFileName = ctx.optarg;
      break;
    case '?':
      fprintf( stdout, "calltree compiler Version 0.1\n\n" );
      fprintf( stdout, "Options:\n" );
      fprintf( stdout, "\t-i\tInput file\n" );
      fprintf( stdout, "\t-o\tOutput file (defaults to \"a.out\")\n" );
      fprintf( stdout,
        "\t-a\tOutput text file of generated callback instructions. (optional)\n" );
      fprintf( stdout, "\t-x\tOutput a xgml file of the parsed tree\n" );
      fprintf( stdout, "\t-e\tSpecify endian, \"little\" or \"big\" as argument. Default is \"little\" (?).\n" );
      fprintf( stdout, "\t-d\tGenerate debug info\n" );
      fprintf( stdout, "\t-?\tPrint this message and exit.\n\n" );
      return 0;
      break;
    }
  }

  int returnCode = 0;

  if( !g_inputFileName )
  {
    returnCode = -1;
    printf( "error: No input file given.\n" );
  }

  if( returnCode == 0 )
  {
    Allocator a;
    a.m_Alloc = &allocate_memory;
    a.m_Free = &free_memory;
    BehaviorTreeContext btc = BehaviorTreeContextCreate( a );

    ParserContextFunctions pcf;
    pcf.m_Read = &read_file;
    pcf.m_Error = &parser_error;
    pcf.m_Warning = &parser_warning;
    pcf.m_Translate = &parser_translate_include;

    ParsingInfo pi;
    pi.m_Name = g_inputFileName;
    pi.m_File = fopen( pi.m_Name, "r" );
    if( !pi.m_File )
    {
      printf(
        "%s(0): error : unable to open input file \"%s\" for reading.\n",
        g_inputFileName, pi.m_Name );
      returnCode = -1;
    }

    if( returnCode == 0 )
    {
      ParserContext pc = ParserContextCreate( btc );
      ParserContextSetExtra( pc, &pi );
      ParserContextSetCurrent( pc, pi.m_Name );
      returnCode = Parse( pc, &pcf );
      ParserContextDestroy( pc );
    }

    if( pi.m_File )
      fclose( pi.m_File );

    Include* include = BehaviorTreeContextGetFirstInclude( btc );
    while( include )
    {
      pi.m_Name = include->m_Name;
      pi.m_File = fopen( pi.m_Name, "r" );
      if( !pi.m_File )
      {
        printf(
          "%s(%d): error : unable to open include file \"%s\" for reading.\n",
          include->m_Parent, include->m_LineNo, pi.m_Name );
        returnCode = -1;
        break;
      }

      ParserContext pc = ParserContextCreate( btc );
      ParserContextSetExtra( pc, &pi );
      ParserContextSetCurrent( pc, pi.m_Name );
      returnCode = Parse( pc, &pcf );
      ParserContextDestroy( pc );

      if( pi.m_File )
        fclose( pi.m_File );

      if( returnCode != 0 )
        break;

      include = include->m_Next;
    }

    NamedSymbol* main = BehaviorTreeContextFindSymbol( btc, hashlittle( "main" ) );
    if( !main || main->m_Type != E_ST_TREE
        || !main->m_Symbol.m_Tree->m_Declared )
    {
      printf( "%s(0): error: \"main\" tree has not been declared.\n",
        g_inputFileName );
      returnCode = -1;
    }

    if( returnCode == 0 )
    {
      Program p;
      p.m_I.SetGenerateDebugInfo( g_debug );

      setup_before_generate( main->m_Symbol.m_Tree->m_Root, &p );
      returnCode = generate_program( main->m_Symbol.m_Tree->m_Root, &p );
      teardown_after_generate( main->m_Symbol.m_Tree->m_Root, &p );

      if( returnCode != 0 )
      {
        printf( "%s(0): error: Internal compiler error.\n", g_inputFileName );
      }
      else
      {
        g_outputFile = fopen( g_outputFileName, "wb" );
        if( !g_outputFile )
        {
          printf( "error: Unable to open output file %s for writing.\n",
            g_outputFileName );
          returnCode = -2;
        }

        if( returnCode == 0 )
          returnCode = save_program( g_outputFile, g_swapEndian, &p );
        if( returnCode != 0 )
        {
          printf( "error: Failed to write output file %s.\n", g_outputFileName );
          returnCode = -5;
        }
      }

      if( returnCode == 0 && g_asmFileName )
      {
        FILE* asmFile = fopen( g_asmFileName, "w" );
        if( !asmFile )
        {
          printf( "warning: Unable to open assembly file %s for writing.\n",
            g_asmFileName );
        }
        else
        {
          print_program( asmFile, &p );
          fclose( asmFile );
        }
      }

    }
    if( returnCode == 0 && g_xgmlFileName )
    {

      XGMLPrinter xgml_printer;
      xgml_printer.Visit( main->m_Symbol.m_Tree->m_Root );
      xgml_printer.Layout();
      FILE* xgml_file = fopen( g_xgmlFileName, "w" );
      if( xgml_file )
      {
        xgml_printer.Print( xgml_file );
        fclose( xgml_file );
      }
      else
      {
        printf( "warning: Unable to open xgml file \"%s\" for writing.\n",
          g_xgmlFileName );
      }
    }

    BehaviorTreeContextDestroy( btc );
    if( g_allocs - g_frees != 0 )
      printf( "Allocs: %d\nFrees:  %d\nDelta:  %d\n", g_allocs, g_frees,
        g_allocs - g_frees );
  }

  if( g_outputFile )
    fclose( g_outputFile );

  return returnCode;
}
<commit_msg>Adding a "list include" option.<commit_after>/*******************************************************************************
 * Copyright (c) 2009-04-24 Joacim Jacobsson.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Joacim Jacobsson - first implementation
 *******************************************************************************/

#include <stdlib.h>
#include <other/getopt.h>
#include <other/lookup3.h>

#include <btree/btree.h>
#include "generate/program.h"
#include "xgml_printer.h"

FILE* g_outputFile = 0x0;
char* g_inputFileName = 0x0;
char* g_outputFileName = "a.out";
bool g_swapEndian = false;
bool g_printIncludes = false;
char* g_asmFileName = 0x0;
char* g_xgmlFileName = 0x0;
bool g_debug = false;

int g_allocs = 0;
int g_frees = 0;

struct ParsingInfo
{
  FILE* m_File;
  const char* m_Name;
};

int read_file( ParserContext pc, char* buffer, int maxsize )
{
  ParsingInfo* pi = (ParsingInfo*)ParserContextGetExtra( pc );
  if( !pi )
    return 0;
  if( feof( pi->m_File ) )
    return 0;
  return (int)fread( buffer, 1, maxsize, pi->m_File );
}

void parser_error( ParserContext pc, const char* msg )
{
  ParsingInfo* pi = (ParsingInfo*)ParserContextGetExtra( pc );
  if( pi )
  {
    printf( "%s(%d) : error : %s\n", pi->m_Name, ParserContextGetLineNo( pc ),
      msg );
  }
  else
  {
    printf( "%s: error : %s\n", g_inputFileName, msg );
  }
}

void parser_warning( ParserContext pc, const char* msg )
{
  ParsingInfo* pi = (ParsingInfo*)ParserContextGetExtra( pc );
  if( pi )
  {
    printf( "%s(%d): warning : %s\n", pi->m_Name,
      ParserContextGetLineNo( pc ), msg );
  }
  else
  {
    printf( "%s: warning : %s\n", g_inputFileName, msg );
  }
}

void* allocate_memory( mem_size_t size )
{
  g_allocs++;
  return malloc( size );
}

void free_memory( void* ptr )
{
  if( ptr )
  {
    g_frees++;
    free( ptr );
  }
}

const char* parser_translate_include( ParserContext pc, const char* include )
{
  ParsingInfo* pi = (ParsingInfo*)ParserContextGetExtra( pc );
  BehaviorTreeContext btc = ParserContextGetBehaviorTreeContext( pc );

  Allocator a;
  a.m_Alloc = &allocate_memory;
  a.m_Free = &free_memory;

  StringBuffer sb;
  StringBufferInit( a, &sb );

  if( pi->m_Name )
  {
    char backslash  = '\\';
    char frontslash = '/';

    int s = 0, last = -1;
    const char* p = pi->m_Name;
    while( p && *p )
    {
      if( *p == backslash || *p == frontslash )
        last = s;
      ++p;
      ++s;
    }
    if( last != -1 )
      StringBufferAppend( &sb, pi->m_Name, last + 1 );
  }

  StringBufferAppend( &sb, include );
  const char* ret = BehaviorTreeContextRegisterString( btc, sb.m_Str );
  StringBufferDestroy( &sb );

  return ret;
}

int main( int argc, char** argv )
{
  GetOptContext ctx;
  init_getopt_context( &ctx );
  char c;

  while( (c = getopt( argc, argv, "?i:o:a:de:x:lcr", &ctx )) != -1 )
  {
    switch( c )
    {
    case 'i':
      g_inputFileName = ctx.optarg;
      break;
    case 'o':
      g_outputFileName = ctx.optarg;
      break;
    case 'e':
      if( strcmp( ctx.optarg, "big" ) == 0 )
        g_swapEndian = true;
      else if( strcmp( ctx.optarg, "little" ) == 0 )
        g_swapEndian = false;
      else
      {
        fprintf( stdout, "error: unknown argument for option -e: %s\n", ctx.optarg );
        return -1;
      }
      break;
    case 'a':
      g_asmFileName = ctx.optarg;
      break;
    case 'd':
      g_debug = true;
      break;
    case 'x':
      g_xgmlFileName = ctx.optarg;
      break;
    case 'l':
      g_printIncludes = true;
      break;
    case 'c':
      /* don't ask. */
      break;
    case '?':
      fprintf( stdout, "calltree compiler Version 0.1\n\n" );
      fprintf( stdout, "Options:\n" );
      fprintf( stdout, "\t-i\tInput file\n" );
      fprintf( stdout, "\t-o\tOutput file (defaults to \"a.out\")\n" );
      fprintf( stdout,
        "\t-a\tOutput text file of generated callback instructions. (optional)\n" );
      fprintf( stdout, "\t-x\tOutput a xgml file of the parsed tree\n" );
      fprintf( stdout, "\t-e\tSpecify endian, \"little\" or \"big\" as argument. Default is \"little\" (?).\n" );
      fprintf( stdout, "\t-d\tGenerate debug info\n" );
      fprintf( stdout, "\t-l\tPrint a list of files included to stdout (non-recursive).\n");
      fprintf( stdout, "\t-?\tPrint this message and exit.\n\n" );
      return 0;
      break;
    }
  }

  int returnCode = 0;

  if( !g_inputFileName )
  {
    returnCode = -1;
    printf( "error: No input file given.\n" );
  }

  if( returnCode == 0 )
  {
    Allocator a;
    a.m_Alloc = &allocate_memory;
    a.m_Free = &free_memory;
    BehaviorTreeContext btc = BehaviorTreeContextCreate( a );

    ParserContextFunctions pcf;
    pcf.m_Read = &read_file;
    pcf.m_Error = &parser_error;
    pcf.m_Warning = &parser_warning;
    pcf.m_Translate = &parser_translate_include;

    ParsingInfo pi;
    pi.m_Name = g_inputFileName;
    pi.m_File = fopen( pi.m_Name, "r" );
    if( !pi.m_File )
    {
      printf(
        "%s(0): error : unable to open input file \"%s\" for reading.\n",
        g_inputFileName, pi.m_Name );
      returnCode = -1;
    }

    if( returnCode == 0 )
    {
      ParserContext pc = ParserContextCreate( btc );
      ParserContextSetExtra( pc, &pi );
      ParserContextSetCurrent( pc, pi.m_Name );
      returnCode = Parse( pc, &pcf );
      ParserContextDestroy( pc );
    }

    if( pi.m_File )
      fclose( pi.m_File );

    Include* include = BehaviorTreeContextGetFirstInclude( btc );

    while( returnCode == 0 && include && g_printIncludes )
    {
      fprintf( stdout, "%s\n", include->m_Name );
      include = include->m_Next;
    }

    include = BehaviorTreeContextGetFirstInclude( btc );
    while( returnCode == 0 && include )
    {
      pi.m_Name = include->m_Name;
      pi.m_File = fopen( pi.m_Name, "r" );
      if( !pi.m_File )
      {
        printf(
          "%s(%d): error : unable to open include file \"%s\" for reading.\n",
          include->m_Parent, include->m_LineNo, pi.m_Name );
        returnCode = -1;
        break;
      }

      ParserContext pc = ParserContextCreate( btc );
      ParserContextSetExtra( pc, &pi );
      ParserContextSetCurrent( pc, pi.m_Name );
      returnCode = Parse( pc, &pcf );
      ParserContextDestroy( pc );

      if( pi.m_File )
        fclose( pi.m_File );

      if( returnCode != 0 )
        break;

      include = include->m_Next;
    }

    NamedSymbol* main = BehaviorTreeContextFindSymbol( btc, hashlittle( "main" ) );
    if( !main || main->m_Type != E_ST_TREE
        || !main->m_Symbol.m_Tree->m_Declared )
    {
      printf( "%s(0): error: \"main\" tree has not been declared.\n",
        g_inputFileName );
      returnCode = -1;
    }

    if( returnCode == 0 )
    {
      Program p;
      p.m_I.SetGenerateDebugInfo( g_debug );

      setup_before_generate( main->m_Symbol.m_Tree->m_Root, &p );
      returnCode = generate_program( main->m_Symbol.m_Tree->m_Root, &p );
      teardown_after_generate( main->m_Symbol.m_Tree->m_Root, &p );

      if( returnCode != 0 )
      {
        printf( "%s(0): error: Internal compiler error.\n", g_inputFileName );
      }
      else
      {
        g_outputFile = fopen( g_outputFileName, "wb" );
        if( !g_outputFile )
        {
          printf( "error: Unable to open output file %s for writing.\n",
            g_outputFileName );
          returnCode = -2;
        }

        if( returnCode == 0 )
          returnCode = save_program( g_outputFile, g_swapEndian, &p );
        if( returnCode != 0 )
        {
          printf( "error: Failed to write output file %s.\n", g_outputFileName );
          returnCode = -5;
        }
      }

      if( returnCode == 0 && g_asmFileName )
      {
        FILE* asmFile = fopen( g_asmFileName, "w" );
        if( !asmFile )
        {
          printf( "warning: Unable to open assembly file %s for writing.\n",
            g_asmFileName );
        }
        else
        {
          print_program( asmFile, &p );
          fclose( asmFile );
        }
      }

    }
    if( returnCode == 0 && g_xgmlFileName )
    {

      XGMLPrinter xgml_printer;
      xgml_printer.Visit( main->m_Symbol.m_Tree->m_Root );
      xgml_printer.Layout();
      FILE* xgml_file = fopen( g_xgmlFileName, "w" );
      if( xgml_file )
      {
        xgml_printer.Print( xgml_file );
        fclose( xgml_file );
      }
      else
      {
        printf( "warning: Unable to open xgml file \"%s\" for writing.\n",
          g_xgmlFileName );
      }
    }

    BehaviorTreeContextDestroy( btc );
    if( g_allocs - g_frees != 0 )
      printf( "Allocs: %d\nFrees:  %d\nDelta:  %d\n", g_allocs, g_frees,
        g_allocs - g_frees );
  }

  if( g_outputFile )
    fclose( g_outputFile );

  return returnCode;
}
<|endoftext|>


<commit_before>//=============================================================================
//File Name: Disabled.cpp
//Description: This function runs when robot is in disabled state
//Author: FRC Team 3512, Spartatroniks
//=============================================================================

#include <Timer.h>
#include "OurRobot.hpp"

void OurRobot::Disabled() {
    mainCompressor.Stop();

    while ( IsDisabled() ) {
        DS_PrintOut();
        Wait( 0.1 );
    }
}
<commit_msg>Added joystick button toggling to Disabled.cpp so those button states would update on the DriverStationDisplay during Disabled mode<commit_after>//=============================================================================
//File Name: Disabled.cpp
//Description: This function runs when robot is in disabled state
//Author: FRC Team 3512, Spartatroniks
//=============================================================================

#include <Timer.h>
#include "OurRobot.hpp"
#include "ButtonTracker.hpp"

void OurRobot::Disabled() {
    mainCompressor.Stop();

    ButtonTracker driveStick1Buttons( 1 );
    ButtonTracker driveStick2Buttons( 2 );
    ButtonTracker turretStickButtons( 3 );

    while ( IsDisabled() ) {
        DS_PrintOut();

        // update "new" value of joystick buttons
       driveStick1Buttons.updateButtons();
       driveStick2Buttons.updateButtons();
       turretStickButtons.updateButtons();

       /* ===================== AutoAim ===================== */
       if ( turretStickButtons.releasedButton( 3 ) ) {
           isAutoAiming = !isAutoAiming; // toggles autoAim
       }
       /* =================================================== */

       /* ============== Toggle Shooter Motors ============== */
       // turns shooter on/off
       if ( turretStickButtons.releasedButton( 1 ) ) { // if released trigger
           isShooting = !isShooting;
       }

       // toggle manual RPM setting vs setting with encoder input
       if ( turretStickButtons.releasedButton( 2 ) ) {
           shooterIsManual = !shooterIsManual;
       }
       /* =================================================== */

        Wait( 0.1 );
    }
}
<|endoftext|>


<commit_before>#include "stdlib.h"
#include "PcapLiveDeviceList.h"
#include "SystemUtils.h"
/**
 * A struct for collecting packet statistics
 */
struct PacketStats
{
	int ethPacketCount;
	int ipv4PacketCount;
	int ipv6PacketCount;
	int tcpPacketCount;
	int udpPacketCount;
	int dnsPacketCount;
	int httpPacketCount;
	int sslPacketCount;

	/**
	 * Clear all stats
	 */
	void clear() { ethPacketCount = 0; ipv4PacketCount = 0; ipv6PacketCount = 0; tcpPacketCount = 0; udpPacketCount = 0; tcpPacketCount = 0; dnsPacketCount = 0; httpPacketCount = 0; sslPacketCount = 0; }

	/**
	 * C'tor
	 */
	PacketStats() { clear(); }

	/**
	 * Collect stats from a packet
	 */
	void consumePacket(pcpp::Packet& packet)
	{
		if (packet.isPacketOfType(pcpp::Ethernet))
			ethPacketCount++;
		if (packet.isPacketOfType(pcpp::IPv4))
			ipv4PacketCount++;
		if (packet.isPacketOfType(pcpp::IPv6))
			ipv6PacketCount++;
		if (packet.isPacketOfType(pcpp::TCP))
			tcpPacketCount++;
		if (packet.isPacketOfType(pcpp::UDP))
			udpPacketCount++;
		if (packet.isPacketOfType(pcpp::HTTP))
			httpPacketCount++;
		if (packet.isPacketOfType(pcpp::SSL))
			sslPacketCount++;
	}

	/**
	 * Print stats to console
	 */
	void printToConsole()
	{
		printf("Ethernet packet count: %d\n", ethPacketCount);
		printf("IPv4 packet count:     %d\n", ipv4PacketCount);
		printf("IPv6 packet count:     %d\n", ipv6PacketCount);
		printf("TCP packet count:      %d\n", tcpPacketCount);
		printf("UDP packet count:      %d\n", udpPacketCount);
		printf("DNS packet count:      %d\n", dnsPacketCount);
		printf("HTTP packet count:     %d\n", httpPacketCount);
		printf("SSL packet count:      %d\n", sslPacketCount);
	}
};

/**
 * A callback function for the async capture which is called each time a packet is captured
 */
static void onPacketArrives(pcpp::RawPacket* packet, pcpp::PcapLiveDevice* dev, void* cookie)
{
	// extract the stats object form the cookie
	PacketStats* stats = (PacketStats*)cookie;

	// parsed the raw packet
	pcpp::Packet parsedPacket(packet);

	// collect stats from packet
	stats->consumePacket(parsedPacket);
}

/**
 * a callback function for the blocking mode capture which is called each time a packet is captured
 */
static bool onPacketArrivesBlockingMode(pcpp::RawPacket* packet, pcpp::PcapLiveDevice* dev, void* cookie)
{
	// extract the stats object form the cookie
	PacketStats* stats = (PacketStats*)cookie;

	// parsed the raw packet
	pcpp::Packet parsedPacket(packet);

	// collect stats from packet
	stats->consumePacket(parsedPacket);

	// return false means we don't want to stop capturing after this callback
	return false;
}

/**
 * main method of the application
 */
int main(int argc, char* argv[])
{
	// IPv4 address of the interface we want to sniff
	std::string interfaceIPAddr = "10.0.0.1";

	// find the interface by IP address
	pcpp::PcapLiveDevice* dev = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIp(interfaceIPAddr.c_str());
	if (dev == NULL)
	{
		printf("Cannot find interface with IPv4 address of '%s'\n", interfaceIPAddr.c_str());
		exit(1);
	}

	// Get device info
	// ~~~~~~~~~~~~~~~

	// before capturing packets let's print some info about this interface
	printf("Interface info:\n");
	// get interface name
	printf("   Interface name:        %s\n", dev->getName());
	// get interface description
	printf("   Interface description: %s\n", dev->getDesc());
	// get interface MAC address
	printf("   MAC address:           %s\n", dev->getMacAddress().toString().c_str());
	// get default gateway for interface
	printf("   Default gateway:       %s\n", dev->getDefaultGateway().toString().c_str());
	// get interface MTU
	printf("   Interface MTU:         %d\n", dev->getMtu());
	// get DNS server if defined for this interface
	if (dev->getDnsServers().size() > 0)
		printf("   DNS server:            %s\n", dev->getDnsServers().at(0).toString().c_str());

	// open the device before start capturing/sending packets
	if (!dev->open())
	{
		printf("Cannot open device\n");
		exit(1);
	}

	// create the stats object
	PacketStats stats;

	// Async packet capture with a callback function
	// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

	printf("\nStarting async capture...\n");

	// start capture in async mode. Give a callback function to call to whenever a packet is captured and the stats object as the cookie
	dev->startCapture(onPacketArrives, &stats);

	// sleep for 10 seconds in main thread, in the meantime packets are captured in the async thread
	multiPlatformSleep(10);

	// stop capturing packets
	dev->stopCapture();

	// print results
	printf("Results:\n");
	stats.printToConsole();

	// clear stats
	stats.clear();

	// Capturing packets in a packet vector
	// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

	printf("\nStarting capture with packet vector...\n");

	// create an empty packet vector object
	pcpp::RawPacketVector packetVec;

	// start capturing packets. All packets will be added to the packet vector
	dev->startCapture(packetVec);

	// sleep for 10 seconds in main thread, in the meantime packets are captured in the async thread
	multiPlatformSleep(10);

	// stop capturing packets
	dev->stopCapture();

	// go over the packet vector and feed all packets to the stats object
	for (pcpp::RawPacketVector::ConstVectorIterator iter = packetVec.begin(); iter != packetVec.end(); iter++)
	{
		// parse raw packet
		pcpp::Packet parsedPacket(*iter);

		// feed packet to the stats object
		stats.consumePacket(parsedPacket);
	}

	// print results
	printf("Results:\n");
	stats.printToConsole();

	// clear stats
	stats.clear();

	// Capturing packets in blocking mode
	// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

	printf("\nStarting capture in blocking mode...\n");

	// start capturing in blocking mode. Give a callback function to call to whenever a packet is captured, the stats object as the cookie and a 10 seconds timeout
	dev->startCaptureBlockingMode(onPacketArrivesBlockingMode, &stats, 10);

	// thread is blocked until capture is finished

	// capture is finished, print results
	printf("Results:\n");
	stats.printToConsole();

	stats.clear();

	// Sending single packets
	// ~~~~~~~~~~~~~~~~~~~~~~

	printf("\nSending %d packets one by one...\n", (int)packetVec.size());

	// go over the vector of packets and send them one by one
	for (pcpp::RawPacketVector::ConstVectorIterator iter = packetVec.begin(); iter != packetVec.end(); iter++)
	{
		// send the packet. If fails exit the application
		if (!dev->sendPacket(**iter))
		{
			printf("Couldn't send packet\n");
			exit(1);
		}
	}
	printf("%d packets sent\n", (int)packetVec.size());

	// Sending batch of packets
	// ~~~~~~~~~~~~~~~~~~~~~~~~

	printf("\nSending %d packets...\n", (int)packetVec.size());

	// send all packets in the vector. The returned number shows how many packets were actually sent (expected to be equal to vector size)
	int packetsSent = dev->sendPackets(packetVec);

	printf("%d packets sent\n", packetsSent);

	// Using filters
	// ~~~~~~~~~~~~~

	// create a filter instance to capture only traffic on port 80
	pcpp::PortFilter portFilter(80, pcpp::SRC_OR_DST);

	// create a filter instance to capture only TCP traffic
	pcpp::ProtoFilter protocolFilter(pcpp::TCP);

	// create an AND filter to combine both filters - capture only TCP traffic on port 80
	pcpp::AndFilter andFilter;
	andFilter.addFilter(&portFilter);
	andFilter.addFilter(&protocolFilter);

	// set the filter on the device
	dev->setFilter(andFilter);

	printf("\nStarting packet capture with a filter in place...\n");

	// start capture in async mode. Give a callback function to call to whenever a packet is captured and the stats object as the cookie
	dev->startCapture(onPacketArrives, &stats);

	// sleep for 10 seconds in main thread, in the meantime packets are captured in the async thread
	multiPlatformSleep(10);

	// stop capturing packets
	dev->stopCapture();

	// print results - should capture only packets which match the filter (which is TCP port 80)
	printf("Results:\n");
	stats.printToConsole();

	// close the device before application ends
	dev->close();
}
<commit_msg>Few more small fixes<commit_after>#include "stdlib.h"
#include "PcapLiveDeviceList.h"
#include "SystemUtils.h"
/**
 * A struct for collecting packet statistics
 */
struct PacketStats
{
	int ethPacketCount;
	int ipv4PacketCount;
	int ipv6PacketCount;
	int tcpPacketCount;
	int udpPacketCount;
	int dnsPacketCount;
	int httpPacketCount;
	int sslPacketCount;

	/**
	 * Clear all stats
	 */
	void clear() { ethPacketCount = 0; ipv4PacketCount = 0; ipv6PacketCount = 0; tcpPacketCount = 0; udpPacketCount = 0; tcpPacketCount = 0; dnsPacketCount = 0; httpPacketCount = 0; sslPacketCount = 0; }

	/**
	 * C'tor
	 */
	PacketStats() { clear(); }

	/**
	 * Collect stats from a packet
	 */
	void consumePacket(pcpp::Packet& packet)
	{
		if (packet.isPacketOfType(pcpp::Ethernet))
			ethPacketCount++;
		if (packet.isPacketOfType(pcpp::IPv4))
			ipv4PacketCount++;
		if (packet.isPacketOfType(pcpp::IPv6))
			ipv6PacketCount++;
		if (packet.isPacketOfType(pcpp::TCP))
			tcpPacketCount++;
		if (packet.isPacketOfType(pcpp::UDP))
			udpPacketCount++;
		if (packet.isPacketOfType(pcpp::HTTP))
			httpPacketCount++;
		if (packet.isPacketOfType(pcpp::SSL))
			sslPacketCount++;
	}

	/**
	 * Print stats to console
	 */
	void printToConsole()
	{
		printf("Ethernet packet count: %d\n", ethPacketCount);
		printf("IPv4 packet count:     %d\n", ipv4PacketCount);
		printf("IPv6 packet count:     %d\n", ipv6PacketCount);
		printf("TCP packet count:      %d\n", tcpPacketCount);
		printf("UDP packet count:      %d\n", udpPacketCount);
		printf("DNS packet count:      %d\n", dnsPacketCount);
		printf("HTTP packet count:     %d\n", httpPacketCount);
		printf("SSL packet count:      %d\n", sslPacketCount);
	}
};

/**
 * A callback function for the async capture which is called each time a packet is captured
 */
static void onPacketArrives(pcpp::RawPacket* packet, pcpp::PcapLiveDevice* dev, void* cookie)
{
	// extract the stats object form the cookie
	PacketStats* stats = (PacketStats*)cookie;

	// parsed the raw packet
	pcpp::Packet parsedPacket(packet);

	// collect stats from packet
	stats->consumePacket(parsedPacket);
}

/**
 * a callback function for the blocking mode capture which is called each time a packet is captured
 */
static bool onPacketArrivesBlockingMode(pcpp::RawPacket* packet, pcpp::PcapLiveDevice* dev, void* cookie)
{
	// extract the stats object form the cookie
	PacketStats* stats = (PacketStats*)cookie;

	// parsed the raw packet
	pcpp::Packet parsedPacket(packet);

	// collect stats from packet
	stats->consumePacket(parsedPacket);

	// return false means we don't want to stop capturing after this callback
	return false;
}

/**
 * main method of the application
 */
int main(int argc, char* argv[])
{
	// IPv4 address of the interface we want to sniff
	std::string interfaceIPAddr = "10.0.0.1";

	// find the interface by IP address
	pcpp::PcapLiveDevice* dev = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIp(interfaceIPAddr.c_str());
	if (dev == NULL)
	{
		printf("Cannot find interface with IPv4 address of '%s'\n", interfaceIPAddr.c_str());
		exit(1);
	}

	// Get device info
	// ~~~~~~~~~~~~~~~

	// before capturing packets let's print some info about this interface
	printf("Interface info:\n");
	// get interface name
	printf("   Interface name:        %s\n", dev->getName());
	// get interface description
	printf("   Interface description: %s\n", dev->getDesc());
	// get interface MAC address
	printf("   MAC address:           %s\n", dev->getMacAddress().toString().c_str());
	// get default gateway for interface
	printf("   Default gateway:       %s\n", dev->getDefaultGateway().toString().c_str());
	// get interface MTU
	printf("   Interface MTU:         %d\n", dev->getMtu());
	// get DNS server if defined for this interface
	if (dev->getDnsServers().size() > 0)
		printf("   DNS server:            %s\n", dev->getDnsServers().at(0).toString().c_str());

	// open the device before start capturing/sending packets
	if (!dev->open())
	{
		printf("Cannot open device\n");
		exit(1);
	}

	// create the stats object
	PacketStats stats;

	// Async packet capture with a callback function
	// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

	printf("\nStarting async capture...\n");

	// start capture in async mode. Give a callback function to call to whenever a packet is captured and the stats object as the cookie
	dev->startCapture(onPacketArrives, &stats);

	// sleep for 10 seconds in main thread, in the meantime packets are captured in the async thread
	pcpp::multiPlatformSleep(10);

	// stop capturing packets
	dev->stopCapture();

	// print results
	printf("Results:\n");
	stats.printToConsole();

	// clear stats
	stats.clear();

	// Capturing packets in a packet vector
	// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

	printf("\nStarting capture with packet vector...\n");

	// create an empty packet vector object
	pcpp::RawPacketVector packetVec;

	// start capturing packets. All packets will be added to the packet vector
	dev->startCapture(packetVec);

	// sleep for 10 seconds in main thread, in the meantime packets are captured in the async thread
	pcpp::multiPlatformSleep(10);

	// stop capturing packets
	dev->stopCapture();

	// go over the packet vector and feed all packets to the stats object
	for (pcpp::RawPacketVector::ConstVectorIterator iter = packetVec.begin(); iter != packetVec.end(); iter++)
	{
		// parse raw packet
		pcpp::Packet parsedPacket(*iter);

		// feed packet to the stats object
		stats.consumePacket(parsedPacket);
	}

	// print results
	printf("Results:\n");
	stats.printToConsole();

	// clear stats
	stats.clear();

	// Capturing packets in blocking mode
	// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

	printf("\nStarting capture in blocking mode...\n");

	// start capturing in blocking mode. Give a callback function to call to whenever a packet is captured, the stats object as the cookie and a 10 seconds timeout
	dev->startCaptureBlockingMode(onPacketArrivesBlockingMode, &stats, 10);

	// thread is blocked until capture is finished

	// capture is finished, print results
	printf("Results:\n");
	stats.printToConsole();

	stats.clear();

	// Sending single packets
	// ~~~~~~~~~~~~~~~~~~~~~~

	printf("\nSending %d packets one by one...\n", (int)packetVec.size());

	// go over the vector of packets and send them one by one
	for (pcpp::RawPacketVector::ConstVectorIterator iter = packetVec.begin(); iter != packetVec.end(); iter++)
	{
		// send the packet. If fails exit the application
		if (!dev->sendPacket(**iter))
		{
			printf("Couldn't send packet\n");
			exit(1);
		}
	}
	printf("%d packets sent\n", (int)packetVec.size());

	// Sending batch of packets
	// ~~~~~~~~~~~~~~~~~~~~~~~~

	printf("\nSending %d packets...\n", (int)packetVec.size());

	// send all packets in the vector. The returned number shows how many packets were actually sent (expected to be equal to vector size)
	int packetsSent = dev->sendPackets(packetVec);

	printf("%d packets sent\n", packetsSent);

	// Using filters
	// ~~~~~~~~~~~~~

	// create a filter instance to capture only traffic on port 80
	pcpp::PortFilter portFilter(80, pcpp::SRC_OR_DST);

	// create a filter instance to capture only TCP traffic
	pcpp::ProtoFilter protocolFilter(pcpp::TCP);

	// create an AND filter to combine both filters - capture only TCP traffic on port 80
	pcpp::AndFilter andFilter;
	andFilter.addFilter(&portFilter);
	andFilter.addFilter(&protocolFilter);

	// set the filter on the device
	dev->setFilter(andFilter);

	printf("\nStarting packet capture with a filter in place...\n");

	// start capture in async mode. Give a callback function to call to whenever a packet is captured and the stats object as the cookie
	dev->startCapture(onPacketArrives, &stats);

	// sleep for 10 seconds in main thread, in the meantime packets are captured in the async thread
	pcpp::multiPlatformSleep(10);

	// stop capturing packets
	dev->stopCapture();

	// print results - should capture only packets which match the filter (which is TCP port 80)
	printf("Results:\n");
	stats.printToConsole();

	// close the device before application ends
	dev->close();
}
<|endoftext|>


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

#ifndef _CDATASECTION_HXX
#define _CDATASECTION_HXX

#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/uno/Exception.hpp>
#include <com/sun/star/xml/dom/XCDATASection.hpp>

#include "text.hxx"

using namespace rtl;
using namespace com::sun::star::uno;
using namespace com::sun::star::xml::dom;

namespace DOM
{
    class CCDATASection : public cppu::ImplInheritanceHelper1< CText, XCDATASection >
    {
        friend class CNode;
    protected:
        CCDATASection(const xmlNodePtr aNodePtr);

    public:
        virtual Reference< XText > SAL_CALL splitText(sal_Int32 offset)
             throw (RuntimeException)
        {
            return CText::splitText(offset);
        }

         // --- delegations for XCharacterData
        virtual void SAL_CALL appendData(const OUString& arg)
            throw (RuntimeException, DOMException)
        {
            CCharacterData::appendData(arg);
        }
        virtual void SAL_CALL deleteData(sal_Int32 offset, sal_Int32 count)
            throw (RuntimeException, DOMException)
        {
            CCharacterData::deleteData(offset, count);
        }
        virtual OUString SAL_CALL getData() throw (RuntimeException)
        {
            return CCharacterData::getData();
        }
        virtual sal_Int32 SAL_CALL getLength() throw (RuntimeException)
        {
            return CCharacterData::getLength();
        }
        virtual void SAL_CALL insertData(sal_Int32 offset, const OUString& arg)
            throw (RuntimeException, DOMException)
        {
            CCharacterData::insertData(offset, arg);
        }
        virtual void SAL_CALL replaceData(sal_Int32 offset, sal_Int32 count, const OUString& arg)
            throw (RuntimeException, DOMException)
        {
            CCharacterData::replaceData(offset, count, arg);
        }
        virtual void SAL_CALL setData(const OUString& data)
            throw (RuntimeException, DOMException)
        {
            CCharacterData::setData(data);
        }
        virtual OUString SAL_CALL subStringData(sal_Int32 offset, sal_Int32 count)
            throw (RuntimeException, DOMException)
        {
            return CCharacterData::subStringData(offset, count);
        }

         // --- overrides for XNode base
        virtual OUString SAL_CALL getNodeName()
            throw (RuntimeException);
        virtual OUString SAL_CALL getNodeValue()
            throw (RuntimeException);

    // --- delegation for XNde base.
    virtual Reference< XNode > SAL_CALL appendChild(const Reference< XNode >& newChild)
        throw (RuntimeException, DOMException)
    {
        return CNode::appendChild(newChild);
    }
    virtual Reference< XNode > SAL_CALL cloneNode(sal_Bool deep)
        throw (RuntimeException)
    {
        return CNode::cloneNode(deep);
    }
    virtual Reference< XNamedNodeMap > SAL_CALL getAttributes()
        throw (RuntimeException)
    {
        return CNode::getAttributes();
    }
    virtual Reference< XNodeList > SAL_CALL getChildNodes()
        throw (RuntimeException)
    {
        return CNode::getChildNodes();
    }
    virtual Reference< XNode > SAL_CALL getFirstChild()
        throw (RuntimeException)
    {
        return CNode::getFirstChild();
    }
    virtual Reference< XNode > SAL_CALL getLastChild()
        throw (RuntimeException)
    {
        return CNode::getLastChild();
    }
    virtual OUString SAL_CALL getLocalName()
        throw (RuntimeException)
    {
        return CNode::getLocalName();
    }
    virtual OUString SAL_CALL getNamespaceURI()
        throw (RuntimeException)
    {
        return CNode::getNamespaceURI();
    }
    virtual Reference< XNode > SAL_CALL getNextSibling()
        throw (RuntimeException)
    {
        return CNode::getNextSibling();
    }
    virtual NodeType SAL_CALL getNodeType()
        throw (RuntimeException)
    {
        return CNode::getNodeType();
    }
    virtual Reference< XDocument > SAL_CALL getOwnerDocument()
        throw (RuntimeException)
    {
        return CNode::getOwnerDocument();
    }
    virtual Reference< XNode > SAL_CALL getParentNode()
        throw (RuntimeException)
    {
        return CNode::getParentNode();
    }
    virtual OUString SAL_CALL getPrefix()
        throw (RuntimeException)
    {
        return CNode::getPrefix();
    }
    virtual Reference< XNode > SAL_CALL getPreviousSibling()
        throw (RuntimeException)
    {
        return CNode::getPreviousSibling();
    }
    virtual sal_Bool SAL_CALL hasAttributes()
        throw (RuntimeException)
    {
        return CNode::hasAttributes();
    }
    virtual sal_Bool SAL_CALL hasChildNodes()
        throw (RuntimeException)
    {
        return CNode::hasChildNodes();
    }
    virtual Reference< XNode > SAL_CALL insertBefore(
            const Reference< XNode >& newChild, const Reference< XNode >& refChild)
        throw (RuntimeException, DOMException)
    {
        return CNode::insertBefore(newChild, refChild);
    }
    virtual sal_Bool SAL_CALL isSupported(const OUString& feature, const OUString& ver)
        throw (RuntimeException)
    {
        return CNode::isSupported(feature, ver);
    }
    virtual void SAL_CALL normalize()
        throw (RuntimeException)
    {
        CNode::normalize();
    }
    virtual Reference< XNode > SAL_CALL removeChild(const Reference< XNode >& oldChild)
        throw (RuntimeException, DOMException)
    {
        return CNode::removeChild(oldChild);
    }
    virtual Reference< XNode > SAL_CALL replaceChild(
            const Reference< XNode >& newChild, const Reference< XNode >& oldChild)
        throw (RuntimeException, DOMException)
    {
        return CNode::replaceChild(newChild, oldChild);
    }
    virtual void SAL_CALL setNodeValue(const OUString& nodeValue)
        throw (RuntimeException, DOMException)
    {
        return CNode::setNodeValue(nodeValue);
    }
    virtual void SAL_CALL setPrefix(const OUString& prefix)
        throw (RuntimeException, DOMException)
    {
        return CNode::setPrefix(prefix);
    }

    };

}

#endif
<commit_msg>INTEGRATION: CWS custommeta (1.4.62); FILE MERGED 2008/02/01 10:36:11 mst 1.4.62.3: RESYNC: (1.5-1.6); FILE MERGED 2007/12/10 10:28:05 mst 1.4.62.2: RESYNC: (1.4-1.5); FILE MERGED 2007/12/07 14:05:56 mst 1.4.62.1: - unoxml/source/dom/document.{hxx,cxx}:   implement interface css::xml::sax::XSAXSerializable - unoxml/source/dom/*.{hxx,cxx}:   add virtual method saxify() on all subclasses of CNode   add missing implementations of getLocalName()<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: cdatasection.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: obo $ $Date: 2008-02-26 14:47:29 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _CDATASECTION_HXX
#define _CDATASECTION_HXX

#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/uno/Exception.hpp>
#include <com/sun/star/xml/dom/XCDATASection.hpp>

#include "text.hxx"

using namespace rtl;
using namespace com::sun::star::uno;
using namespace com::sun::star::xml::dom;

namespace DOM
{
    class CCDATASection : public cppu::ImplInheritanceHelper1< CText, XCDATASection >
    {
        friend class CNode;
    protected:
        CCDATASection(const xmlNodePtr aNodePtr);

    public:

        virtual void SAL_CALL saxify(
            const Reference< XDocumentHandler >& i_xHandler);

        virtual Reference< XText > SAL_CALL splitText(sal_Int32 offset)
             throw (RuntimeException)
        {
            return CText::splitText(offset);
        }

         // --- delegations for XCharacterData
        virtual void SAL_CALL appendData(const OUString& arg)
            throw (RuntimeException, DOMException)
        {
            CCharacterData::appendData(arg);
        }
        virtual void SAL_CALL deleteData(sal_Int32 offset, sal_Int32 count)
            throw (RuntimeException, DOMException)
        {
            CCharacterData::deleteData(offset, count);
        }
        virtual OUString SAL_CALL getData() throw (RuntimeException)
        {
            return CCharacterData::getData();
        }
        virtual sal_Int32 SAL_CALL getLength() throw (RuntimeException)
        {
            return CCharacterData::getLength();
        }
        virtual void SAL_CALL insertData(sal_Int32 offset, const OUString& arg)
            throw (RuntimeException, DOMException)
        {
            CCharacterData::insertData(offset, arg);
        }
        virtual void SAL_CALL replaceData(sal_Int32 offset, sal_Int32 count, const OUString& arg)
            throw (RuntimeException, DOMException)
        {
            CCharacterData::replaceData(offset, count, arg);
        }
        virtual void SAL_CALL setData(const OUString& data)
            throw (RuntimeException, DOMException)
        {
            CCharacterData::setData(data);
        }
        virtual OUString SAL_CALL subStringData(sal_Int32 offset, sal_Int32 count)
            throw (RuntimeException, DOMException)
        {
            return CCharacterData::subStringData(offset, count);
        }

         // --- overrides for XNode base
        virtual OUString SAL_CALL getNodeName()
            throw (RuntimeException);
        virtual OUString SAL_CALL getNodeValue()
            throw (RuntimeException);

    // --- delegation for XNde base.
    virtual Reference< XNode > SAL_CALL appendChild(const Reference< XNode >& newChild)
        throw (RuntimeException, DOMException)
    {
        return CNode::appendChild(newChild);
    }
    virtual Reference< XNode > SAL_CALL cloneNode(sal_Bool deep)
        throw (RuntimeException)
    {
        return CNode::cloneNode(deep);
    }
    virtual Reference< XNamedNodeMap > SAL_CALL getAttributes()
        throw (RuntimeException)
    {
        return CNode::getAttributes();
    }
    virtual Reference< XNodeList > SAL_CALL getChildNodes()
        throw (RuntimeException)
    {
        return CNode::getChildNodes();
    }
    virtual Reference< XNode > SAL_CALL getFirstChild()
        throw (RuntimeException)
    {
        return CNode::getFirstChild();
    }
    virtual Reference< XNode > SAL_CALL getLastChild()
        throw (RuntimeException)
    {
        return CNode::getLastChild();
    }
    virtual OUString SAL_CALL getLocalName()
        throw (RuntimeException)
    {
        return CNode::getLocalName();
    }
    virtual OUString SAL_CALL getNamespaceURI()
        throw (RuntimeException)
    {
        return CNode::getNamespaceURI();
    }
    virtual Reference< XNode > SAL_CALL getNextSibling()
        throw (RuntimeException)
    {
        return CNode::getNextSibling();
    }
    virtual NodeType SAL_CALL getNodeType()
        throw (RuntimeException)
    {
        return CNode::getNodeType();
    }
    virtual Reference< XDocument > SAL_CALL getOwnerDocument()
        throw (RuntimeException)
    {
        return CNode::getOwnerDocument();
    }
    virtual Reference< XNode > SAL_CALL getParentNode()
        throw (RuntimeException)
    {
        return CNode::getParentNode();
    }
    virtual OUString SAL_CALL getPrefix()
        throw (RuntimeException)
    {
        return CNode::getPrefix();
    }
    virtual Reference< XNode > SAL_CALL getPreviousSibling()
        throw (RuntimeException)
    {
        return CNode::getPreviousSibling();
    }
    virtual sal_Bool SAL_CALL hasAttributes()
        throw (RuntimeException)
    {
        return CNode::hasAttributes();
    }
    virtual sal_Bool SAL_CALL hasChildNodes()
        throw (RuntimeException)
    {
        return CNode::hasChildNodes();
    }
    virtual Reference< XNode > SAL_CALL insertBefore(
            const Reference< XNode >& newChild, const Reference< XNode >& refChild)
        throw (RuntimeException, DOMException)
    {
        return CNode::insertBefore(newChild, refChild);
    }
    virtual sal_Bool SAL_CALL isSupported(const OUString& feature, const OUString& ver)
        throw (RuntimeException)
    {
        return CNode::isSupported(feature, ver);
    }
    virtual void SAL_CALL normalize()
        throw (RuntimeException)
    {
        CNode::normalize();
    }
    virtual Reference< XNode > SAL_CALL removeChild(const Reference< XNode >& oldChild)
        throw (RuntimeException, DOMException)
    {
        return CNode::removeChild(oldChild);
    }
    virtual Reference< XNode > SAL_CALL replaceChild(
            const Reference< XNode >& newChild, const Reference< XNode >& oldChild)
        throw (RuntimeException, DOMException)
    {
        return CNode::replaceChild(newChild, oldChild);
    }
    virtual void SAL_CALL setNodeValue(const OUString& nodeValue)
        throw (RuntimeException, DOMException)
    {
        return CNode::setNodeValue(nodeValue);
    }
    virtual void SAL_CALL setPrefix(const OUString& prefix)
        throw (RuntimeException, DOMException)
    {
        return CNode::setPrefix(prefix);
    }

    };

}

#endif
<|endoftext|>