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

/**
 * @file mixer_multirotor.cpp
 *
 * Multi-rotor mixers.
 */
#include <px4_config.h>
#include <sys/types.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <poll.h>
#include <errno.h>
#include <stdio.h>
#include <math.h>
#include <unistd.h>
#include <math.h>

#include <px4iofirmware/protocol.h>

#include "mixer.h"

// This file is generated by the multi_tables script which is invoked during the build process
#include "mixer_multirotor.generated.h"

#define debug(fmt, args...)	do { } while(0)
//#define debug(fmt, args...)	do { printf("[mixer] " fmt "\n", ##args); } while(0)
//#include <debug.h>
//#define debug(fmt, args...)	lowsyslog(fmt "\n", ##args)

/*
 * Clockwise: 1
 * Counter-clockwise: -1
 */

namespace
{

float constrain(float val, float min, float max)
{
	return (val < min) ? min : ((val > max) ? max : val);
}

} // anonymous namespace

MultirotorMixer::MultirotorMixer(ControlCallback control_cb,
				 uintptr_t cb_handle,
				 MultirotorGeometry geometry,
				 float roll_scale,
				 float pitch_scale,
				 float yaw_scale,
				 float idle_speed) :
	Mixer(control_cb, cb_handle),
	_roll_scale(roll_scale),
	_pitch_scale(pitch_scale),
	_yaw_scale(yaw_scale),
	_idle_speed(-1.0f + idle_speed * 2.0f),	/* shift to output range here to avoid runtime calculation */
	_limits_pub(),
	_rotor_count(_config_rotor_count[(MultirotorGeometryUnderlyingType)geometry]),
	_rotors(_config_index[(MultirotorGeometryUnderlyingType)geometry])
{
}

MultirotorMixer::~MultirotorMixer()
{
}

MultirotorMixer *
MultirotorMixer::from_text(Mixer::ControlCallback control_cb, uintptr_t cb_handle, const char *buf, unsigned &buflen)
{
	MultirotorGeometry geometry;
	char geomname[8];
	int s[4];
	int used;

	/* enforce that the mixer ends with space or a new line */
	for (int i = buflen - 1; i >= 0; i--) {
		if (buf[i] == '\0')
			continue;

		/* require a space or newline at the end of the buffer, fail on printable chars */
		if (buf[i] == ' ' || buf[i] == '\n' || buf[i] == '\r') {
			/* found a line ending or space, so no split symbols / numbers. good. */
			break;
		} else {
			debug("simple parser rejected: No newline / space at end of buf. (#%d/%d: 0x%02x)", i, buflen-1, buf[i]);
			return nullptr;
		}

	}

	if (sscanf(buf, "R: %s %d %d %d %d%n", geomname, &s[0], &s[1], &s[2], &s[3], &used) != 5) {
		debug("multirotor parse failed on '%s'", buf);
		return nullptr;
	}

	if (used > (int)buflen) {
		debug("OVERFLOW: multirotor spec used %d of %u", used, buflen);
		return nullptr;
	}

	buf = skipline(buf, buflen);
	if (buf == nullptr) {
		debug("no line ending, line is incomplete");
		return nullptr;
	}

	debug("remaining in buf: %d, first char: %c", buflen, buf[0]);

	if (!strcmp(geomname, "4+")) {
		geometry = MultirotorGeometry::QUAD_PLUS;

	} else if (!strcmp(geomname, "4x")) {
		geometry = MultirotorGeometry::QUAD_X;

	} else if (!strcmp(geomname, "4v")) {
		geometry = MultirotorGeometry::QUAD_V;

	} else if (!strcmp(geomname, "4w")) {
		geometry = MultirotorGeometry::QUAD_WIDE;

	} else if (!strcmp(geomname, "4dc")) {
		geometry = MultirotorGeometry::QUAD_DEADCAT;

	} else if (!strcmp(geomname, "6+")) {
		geometry = MultirotorGeometry::HEX_PLUS;

	} else if (!strcmp(geomname, "6x")) {
		geometry = MultirotorGeometry::HEX_X;

	} else if (!strcmp(geomname, "6c")) {
		geometry = MultirotorGeometry::HEX_COX;

	} else if (!strcmp(geomname, "8+")) {
		geometry = MultirotorGeometry::OCTA_PLUS;

	} else if (!strcmp(geomname, "8x")) {
		geometry = MultirotorGeometry::OCTA_X;

	} else if (!strcmp(geomname, "8c")) {
		geometry = MultirotorGeometry::OCTA_COX;

	} else if (!strcmp(geomname, "2-")) {
		geometry = MultirotorGeometry::TWIN_ENGINE;

	} else if (!strcmp(geomname, "3y")) {
		geometry = MultirotorGeometry::TRI_Y;

	} else {
		debug("unrecognised geometry '%s'", geomname);
		return nullptr;
	}

	debug("adding multirotor mixer '%s'", geomname);

	return new MultirotorMixer(
		       control_cb,
		       cb_handle,
		       geometry,
		       s[0] / 10000.0f,
		       s[1] / 10000.0f,
		       s[2] / 10000.0f,
		       s[3] / 10000.0f);
}

unsigned
MultirotorMixer::mix(float *outputs, unsigned space, uint16_t *status_reg)
{
	/* Summary of mixing strategy:
	1) mix roll, pitch and thrust without yaw.
	2) if some outputs violate range [0,1] then try to shift all outputs to minimize violation ->
		increase or decrease total thrust (boost). The total increase or decrease of thrust is limited
		(max_thrust_diff). If after the shift some outputs still violate the bounds then scale roll & pitch.
		In case there is violation at the lower and upper bound then try to shift such that violation is equal
		on both sides.
	3) mix in yaw and scale if it leads to limit violation.
	4) scale all outputs to range [idle_speed,1]
	*/

	float		roll    = constrain(get_control(0, 0) * _roll_scale, -1.0f, 1.0f);
	float		pitch   = constrain(get_control(0, 1) * _pitch_scale, -1.0f, 1.0f);
	float		yaw     = constrain(get_control(0, 2) * _yaw_scale, -1.0f, 1.0f);
	float		thrust  = constrain(get_control(0, 3), 0.0f, 1.0f);
	float		min_out = 0.0f;
	float		max_out = 0.0f;

	// clean register for saturation status flags
	if (status_reg != NULL) {
		(*status_reg) = 0;
	}
	// thrust boost parameters
	float thrust_increase_factor = 1.5f;
	float thrust_decrease_factor = 0.6f;

	/* perform initial mix pass yielding unbounded outputs, ignore yaw */
	for (unsigned i = 0; i < _rotor_count; i++) {
		float out = roll * _rotors[i].roll_scale +
			    pitch * _rotors[i].pitch_scale +
			    thrust;

		out *= _rotors[i].out_scale;

		/* calculate min and max output values */
		if (out < min_out) {
			min_out = out;
		}
		if (out > max_out) {
			max_out = out;
		}

		outputs[i] = out;
	}

	float boost = 0.0f;				// value added to demanded thrust (can also be negative)
	float roll_pitch_scale = 1.0f;	// scale for demanded roll and pitch

	if(min_out < 0.0f && max_out < 1.0f && -min_out <= 1.0f - max_out) {
		float max_thrust_diff = thrust * thrust_increase_factor - thrust;
		if(max_thrust_diff >= -min_out) {
			boost = -min_out;
		}
		else {
			boost = max_thrust_diff;
			roll_pitch_scale = (thrust + boost)/(thrust - min_out);
		}
	}
	else if (max_out > 1.0f && min_out > 0.0f && min_out >= max_out - 1.0f) {
		float max_thrust_diff = thrust - thrust_decrease_factor*thrust;
		if(max_thrust_diff >= max_out - 1.0f) {
			boost = -(max_out - 1.0f);
		} else {
			boost = -max_thrust_diff;
			roll_pitch_scale = (1 - (thrust + boost))/(max_out - thrust);
		}
	}
	else if (min_out < 0.0f && max_out < 1.0f && -min_out > 1.0f - max_out) {
		float max_thrust_diff = thrust * thrust_increase_factor - thrust;
		boost = constrain(-min_out - (1.0f - max_out)/2.0f,0.0f, max_thrust_diff);
		roll_pitch_scale = (thrust + boost)/(thrust - min_out);
	}
	else if (max_out > 1.0f && min_out > 0.0f && min_out < max_out - 1.0f ) {
		float max_thrust_diff = thrust - thrust_decrease_factor*thrust;
		boost = constrain(-(max_out - 1.0f - min_out)/2.0f, -max_thrust_diff, 0.0f);
		roll_pitch_scale = (1 - (thrust + boost))/(max_out - thrust);
	}
	else if (min_out < 0.0f && max_out > 1.0f) {
		boost = constrain(-(max_out - 1.0f + min_out)/2.0f, thrust_decrease_factor*thrust - thrust, thrust_increase_factor*thrust - thrust);
		roll_pitch_scale = (thrust + boost)/(thrust - min_out);
	}

	// notify if saturation has occurred
	if(min_out < 0.0f) {
		if(status_reg != NULL) {
			(*status_reg) |= PX4IO_P_STATUS_MIXER_LOWER_LIMIT;
		}
	}
	if(max_out > 0.0f) {
		if(status_reg != NULL) {
			(*status_reg) |= PX4IO_P_STATUS_MIXER_UPPER_LIMIT;
		}
	}

	// mix again but now with thrust boost, scale roll/pitch and also add yaw
	for(unsigned i = 0; i < _rotor_count; i++) {
		float out = (roll * _rotors[i].roll_scale +
			    pitch * _rotors[i].pitch_scale) * roll_pitch_scale +
				yaw * _rotors[i].yaw_scale +
			    thrust + boost;

		out *= _rotors[i].out_scale;

		// scale yaw if it violates limits. inform about yaw limit reached
		if(out < 0.0f) {
			yaw = -((roll * _rotors[i].roll_scale + pitch * _rotors[i].pitch_scale) *
				roll_pitch_scale + thrust + boost)/_rotors[i].yaw_scale;
			if(status_reg != NULL) {
				(*status_reg) |= PX4IO_P_STATUS_MIXER_YAW_LIMIT;
			}
		}
		else if(out > 1.0f) {
			yaw = (1.0f - ((roll * _rotors[i].roll_scale + pitch * _rotors[i].pitch_scale) *
				roll_pitch_scale + thrust + boost))/_rotors[i].yaw_scale;
			if(status_reg != NULL) {
				(*status_reg) |= PX4IO_P_STATUS_MIXER_YAW_LIMIT;
			}
		}
	}

	/* last mix, add yaw and scale outputs to range idle_speed...1 */
	for (unsigned i = 0; i < _rotor_count; i++) {
		outputs[i] = (roll * _rotors[i].roll_scale +
			    pitch * _rotors[i].pitch_scale) * roll_pitch_scale +
				yaw * _rotors[i].yaw_scale +
			    thrust + boost;

		outputs[i] = constrain(_idle_speed + (outputs[i] * (1.0f - _idle_speed)), _idle_speed, 1.0f);
	}

	return _rotor_count;
}

void
MultirotorMixer::groups_required(uint32_t &groups)
{
	/* XXX for now, hardcoded to indexes 0-3 in control group zero */
	groups |= (1 << 0);
}

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

/**
 * @file mixer_multirotor.cpp
 *
 * Multi-rotor mixers.
 */
#include <px4_config.h>
#include <sys/types.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <poll.h>
#include <errno.h>
#include <stdio.h>
#include <math.h>
#include <unistd.h>
#include <math.h>

#include <px4iofirmware/protocol.h>

#include "mixer.h"

// This file is generated by the multi_tables script which is invoked during the build process
#include "mixer_multirotor.generated.h"

#define debug(fmt, args...)	do { } while(0)
//#define debug(fmt, args...)	do { printf("[mixer] " fmt "\n", ##args); } while(0)
//#include <debug.h>
//#define debug(fmt, args...)	lowsyslog(fmt "\n", ##args)

/*
 * Clockwise: 1
 * Counter-clockwise: -1
 */

namespace
{

float constrain(float val, float min, float max)
{
	return (val < min) ? min : ((val > max) ? max : val);
}

} // anonymous namespace

MultirotorMixer::MultirotorMixer(ControlCallback control_cb,
				 uintptr_t cb_handle,
				 MultirotorGeometry geometry,
				 float roll_scale,
				 float pitch_scale,
				 float yaw_scale,
				 float idle_speed) :
	Mixer(control_cb, cb_handle),
	_roll_scale(roll_scale),
	_pitch_scale(pitch_scale),
	_yaw_scale(yaw_scale),
	_idle_speed(-1.0f + idle_speed * 2.0f),	/* shift to output range here to avoid runtime calculation */
	_limits_pub(),
	_rotor_count(_config_rotor_count[(MultirotorGeometryUnderlyingType)geometry]),
	_rotors(_config_index[(MultirotorGeometryUnderlyingType)geometry])
{
}

MultirotorMixer::~MultirotorMixer()
{
}

MultirotorMixer *
MultirotorMixer::from_text(Mixer::ControlCallback control_cb, uintptr_t cb_handle, const char *buf, unsigned &buflen)
{
	MultirotorGeometry geometry;
	char geomname[8];
	int s[4];
	int used;

	/* enforce that the mixer ends with space or a new line */
	for (int i = buflen - 1; i >= 0; i--) {
		if (buf[i] == '\0')
			continue;

		/* require a space or newline at the end of the buffer, fail on printable chars */
		if (buf[i] == ' ' || buf[i] == '\n' || buf[i] == '\r') {
			/* found a line ending or space, so no split symbols / numbers. good. */
			break;
		} else {
			debug("simple parser rejected: No newline / space at end of buf. (#%d/%d: 0x%02x)", i, buflen-1, buf[i]);
			return nullptr;
		}

	}

	if (sscanf(buf, "R: %s %d %d %d %d%n", geomname, &s[0], &s[1], &s[2], &s[3], &used) != 5) {
		debug("multirotor parse failed on '%s'", buf);
		return nullptr;
	}

	if (used > (int)buflen) {
		debug("OVERFLOW: multirotor spec used %d of %u", used, buflen);
		return nullptr;
	}

	buf = skipline(buf, buflen);
	if (buf == nullptr) {
		debug("no line ending, line is incomplete");
		return nullptr;
	}

	debug("remaining in buf: %d, first char: %c", buflen, buf[0]);

	if (!strcmp(geomname, "4+")) {
		geometry = MultirotorGeometry::QUAD_PLUS;

	} else if (!strcmp(geomname, "4x")) {
		geometry = MultirotorGeometry::QUAD_X;

	} else if (!strcmp(geomname, "4v")) {
		geometry = MultirotorGeometry::QUAD_V;

	} else if (!strcmp(geomname, "4w")) {
		geometry = MultirotorGeometry::QUAD_WIDE;

	} else if (!strcmp(geomname, "4dc")) {
		geometry = MultirotorGeometry::QUAD_DEADCAT;

	} else if (!strcmp(geomname, "6+")) {
		geometry = MultirotorGeometry::HEX_PLUS;

	} else if (!strcmp(geomname, "6x")) {
		geometry = MultirotorGeometry::HEX_X;

	} else if (!strcmp(geomname, "6c")) {
		geometry = MultirotorGeometry::HEX_COX;

	} else if (!strcmp(geomname, "8+")) {
		geometry = MultirotorGeometry::OCTA_PLUS;

	} else if (!strcmp(geomname, "8x")) {
		geometry = MultirotorGeometry::OCTA_X;

	} else if (!strcmp(geomname, "8c")) {
		geometry = MultirotorGeometry::OCTA_COX;

	} else if (!strcmp(geomname, "2-")) {
		geometry = MultirotorGeometry::TWIN_ENGINE;

	} else if (!strcmp(geomname, "3y")) {
		geometry = MultirotorGeometry::TRI_Y;

	} else {
		debug("unrecognised geometry '%s'", geomname);
		return nullptr;
	}

	debug("adding multirotor mixer '%s'", geomname);

	return new MultirotorMixer(
		       control_cb,
		       cb_handle,
		       geometry,
		       s[0] / 10000.0f,
		       s[1] / 10000.0f,
		       s[2] / 10000.0f,
		       s[3] / 10000.0f);
}

unsigned
MultirotorMixer::mix(float *outputs, unsigned space, uint16_t *status_reg)
{
	/* Summary of mixing strategy:
	1) mix roll, pitch and thrust without yaw.
	2) if some outputs violate range [0,1] then try to shift all outputs to minimize violation ->
		increase or decrease total thrust (boost). The total increase or decrease of thrust is limited
		(max_thrust_diff). If after the shift some outputs still violate the bounds then scale roll & pitch.
		In case there is violation at the lower and upper bound then try to shift such that violation is equal
		on both sides.
	3) mix in yaw and scale if it leads to limit violation.
	4) scale all outputs to range [idle_speed,1]
	*/

	float		roll    = constrain(get_control(0, 0) * _roll_scale, -1.0f, 1.0f);
	float		pitch   = constrain(get_control(0, 1) * _pitch_scale, -1.0f, 1.0f);
	float		yaw     = constrain(get_control(0, 2) * _yaw_scale, -1.0f, 1.0f);
	float		thrust  = constrain(get_control(0, 3), 0.0f, 1.0f);
	float		min_out = 0.0f;
	float		max_out = 0.0f;

	// clean register for saturation status flags
	if (status_reg != NULL) {
		(*status_reg) = 0;
	}
	// thrust boost parameters
	float thrust_increase_factor = 1.5f;
	float thrust_decrease_factor = 0.6f;

	/* perform initial mix pass yielding unbounded outputs, ignore yaw */
	for (unsigned i = 0; i < _rotor_count; i++) {
		float out = roll * _rotors[i].roll_scale +
			    pitch * _rotors[i].pitch_scale +
			    thrust;

		out *= _rotors[i].out_scale;

		/* calculate min and max output values */
		if (out < min_out) {
			min_out = out;
		}
		if (out > max_out) {
			max_out = out;
		}

		outputs[i] = out;
	}

	float boost = 0.0f;				// value added to demanded thrust (can also be negative)
	float roll_pitch_scale = 1.0f;	// scale for demanded roll and pitch

	if(min_out < 0.0f && max_out < 1.0f && -min_out <= 1.0f - max_out) {
		float max_thrust_diff = thrust * thrust_increase_factor - thrust;
		if(max_thrust_diff >= -min_out) {
			boost = -min_out;
		}
		else {
			boost = max_thrust_diff;
			roll_pitch_scale = (thrust + boost)/(thrust - min_out);
		}
	}
	else if (max_out > 1.0f && min_out > 0.0f && min_out >= max_out - 1.0f) {
		float max_thrust_diff = thrust - thrust_decrease_factor*thrust;
		if(max_thrust_diff >= max_out - 1.0f) {
			boost = -(max_out - 1.0f);
		} else {
			boost = -max_thrust_diff;
			roll_pitch_scale = (1 - (thrust + boost))/(max_out - thrust);
		}
	}
	else if (min_out < 0.0f && max_out < 1.0f && -min_out > 1.0f - max_out) {
		float max_thrust_diff = thrust * thrust_increase_factor - thrust;
		boost = constrain(-min_out - (1.0f - max_out)/2.0f,0.0f, max_thrust_diff);
		roll_pitch_scale = (thrust + boost)/(thrust - min_out);
	}
	else if (max_out > 1.0f && min_out > 0.0f && min_out < max_out - 1.0f ) {
		float max_thrust_diff = thrust - thrust_decrease_factor*thrust;
		boost = constrain(-(max_out - 1.0f - min_out)/2.0f, -max_thrust_diff, 0.0f);
		roll_pitch_scale = (1 - (thrust + boost))/(max_out - thrust);
	}
	else if (min_out < 0.0f && max_out > 1.0f) {
		boost = constrain(-(max_out - 1.0f + min_out)/2.0f, thrust_decrease_factor*thrust - thrust, thrust_increase_factor*thrust - thrust);
		roll_pitch_scale = (thrust + boost)/(thrust - min_out);
	}

	// notify if saturation has occurred
	if(min_out < 0.0f) {
		if(status_reg != NULL) {
			(*status_reg) |= PX4IO_P_STATUS_MIXER_LOWER_LIMIT;
		}
	}
	if(max_out > 0.0f) {
		if(status_reg != NULL) {
			(*status_reg) |= PX4IO_P_STATUS_MIXER_UPPER_LIMIT;
		}
	}

	// mix again but now with thrust boost, scale roll/pitch and also add yaw
	for(unsigned i = 0; i < _rotor_count; i++) {
		float out = (roll * _rotors[i].roll_scale +
			    pitch * _rotors[i].pitch_scale) * roll_pitch_scale +
				yaw * _rotors[i].yaw_scale +
			    thrust + boost;

		out *= _rotors[i].out_scale;

		// scale yaw if it violates limits. inform about yaw limit reached
		if(out < 0.0f) {
			yaw = -((roll * _rotors[i].roll_scale + pitch * _rotors[i].pitch_scale) *
				roll_pitch_scale + thrust + boost)/_rotors[i].yaw_scale;
			if(status_reg != NULL) {
				(*status_reg) |= PX4IO_P_STATUS_MIXER_YAW_LIMIT;
			}
		}
		else if(out > 1.0f) {
			// allow to reduce thrust to get some yaw response
			float thrust_reduction = fminf(0.15f, out - 1.0f);
			thrust -= thrust_reduction;
			yaw = (1.0f - ((roll * _rotors[i].roll_scale + pitch * _rotors[i].pitch_scale) *
				roll_pitch_scale + thrust + boost))/_rotors[i].yaw_scale;
			if(status_reg != NULL) {
				(*status_reg) |= PX4IO_P_STATUS_MIXER_YAW_LIMIT;
			}
		}
	}

	/* last mix, add yaw and scale outputs to range idle_speed...1 */
	for (unsigned i = 0; i < _rotor_count; i++) {
		outputs[i] = (roll * _rotors[i].roll_scale +
			    pitch * _rotors[i].pitch_scale) * roll_pitch_scale +
				yaw * _rotors[i].yaw_scale +
			    thrust + boost;

		outputs[i] = constrain(_idle_speed + (outputs[i] * (1.0f - _idle_speed)), _idle_speed, 1.0f);
	}

	return _rotor_count;
}

void
MultirotorMixer::groups_required(uint32_t &groups)
{
	/* XXX for now, hardcoded to indexes 0-3 in control group zero */
	groups |= (1 << 0);
}

<|endoftext|>


<commit_before>/*!
 * \file cpp_api_example.cc
 *
 * \brief This file is a small example of using the IEGenLib C++ API.
 *
 * To compile, execute the following command from the root of the project:
 *     cd ..
 *     make install     // or change the iegen/ subdir below to iegen-MACOSX/
 *                      //                                  or iegen-LINUX64/
 *     cd src
 *     g++ -o cpp_api_example -I../iegen/include/iegenlib -L../iegen/lib -liegenlib cpp_api_example.cc
 *
 * \date Date Started: 3/11/11
 *
 * \authors Alan LaMielle, Michelle Strout, Cathie Olschanowsky
 *
 * Copyright (c) 2011-2013, Colorado State University

 * Copyright (c) 2015, University of Arizona

 * All rights reserved.

 * See COPYING for details.

 */

#include <iostream>
#include <iegenlib.h>

using iegenlib::Set;

int main(int ac, char **av)
{
//  iegenlib::Set* set = new iegenlib::Set("{[a]: a=10}");
  Set* set = new Set("{[a]:0<a}");

  std::cout << set->prettyPrintString() << std::endl;

  return 0;
}
<commit_msg>Edited usage instructions for cpp_api_example.cc<commit_after>/*!
 * \file cpp_api_example.cc
 *
 * \brief This file is a small example of using the IEGenLib C++ API.
 *
 * To compile, execute the following command from the root of the project:
 *     cd ..
 *     make install VERBOSE=1   // NOTE the compiler being used, <C++COMP>
 *     cd src
 *     <C++COMP> -o cpp_api_example -I../iegen/include/iegenlib -L../iegen/lib -liegenlib -L../lib/installed/lib  -lisl -lgmp cpp_api_example.cc
 *
 * \date Date Started: 3/11/11
 *
 * \authors Alan LaMielle, Michelle Strout, Cathie Olschanowsky
 *
 * Copyright (c) 2011-2013, Colorado State University

 * Copyright (c) 2015, University of Arizona

 * All rights reserved.

 * See COPYING for details.

 */

#include <iostream>
#include <iegenlib.h>

using iegenlib::Set;

int main(int ac, char **av)
{
//  iegenlib::Set* set = new iegenlib::Set("{[a]: a=10}");
  Set* set = new Set("{[a]:0<a}");

  std::cout << set->prettyPrintString() << std::endl;

  return 0;
}
<|endoftext|>


<commit_before>// FOVE Data Example
// This shows how to fetch and output data from the FOVE service in a console program

#include "FoveAPI.h"
#include "Util.h"
#include <chrono>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <thread>

// Use std namespace for convenience
using namespace std;

// Helper function to check error responses from the FOVE API
bool checkError(const Fove::ErrorCode errorCode)
{
	// Check for error
	switch (errorCode) {
	case Fove::ErrorCode::None:
		return true;

	case Fove::ErrorCode::Connect_NotConnected:
		// This happens when the service is off, or we haven't finished connecting to it
		cerr << "Not connected to service" << endl;
		break;

	case Fove::ErrorCode::Data_NoUpdate:
		// This happens after we connect to the service, but before the first frame of data comes in
		cerr << "No update" << endl;
		break;

	case Fove::ErrorCode::Data_Unreliable:
		// This happens when the user is not present, closes the eye or the headset is not properly positioned
		// => here we just ignore the data
		break;

	case Fove::ErrorCode::Data_LowAccuracy:
		// This happens when the user is looking at extreme positions or closing the eyes
		// Depending of the application you may want to ignore this data
		// => here we just print it the same way as reliable data
		return true;

	default:
		// Less common errors are simply logged with their numeric value
		cerr << "Error #" << EnumToUnderlyingValue(errorCode) << endl;
		break;
	}

	return false;
}

int main() try {
	// Create the Headset object, taking the capabilities we need in our program
	// Different capabilities may enable different hardware or software, so use only the capabilities that are needed
	Fove::Headset headset = Fove::Headset::create(Fove::ClientCapabilities::EyeTracking).getValue();

	// Loop indefinitely
	while (true) {
		// Wait for the next eye frame
		// The current thread will sleep until a new frame comes in
		// This allows us to capture data at the full frame rate of eye tracking and not use too much CPU
		const auto waitResult = headset.waitAndFetchNextEyeTrackingData();
		if (!checkError(waitResult.getError())) {
			// Sleep for a second in the event of failure
			// If the wait function fails, it might have returned immediately, and we may eat up 100% of a CPU core if we don't sleep manually
			this_thread::sleep_for(chrono::seconds { 1 }); // Can use 1s in C++14 and later

			continue; // Skip getting the gaze vectors
		}

		// Below we print data
		// Feel free to mess around and call other data query functions,
		// but remember to add the capabilities as needed

		// Left gaze vector
		const auto leftGaze = headset.getGazeVector(Fove::Eye::Left);
		cout << "Gaze vectors:   L(" << fixed << setprecision(3);
		if (leftGaze.isValid()) {
			cout
			    << setw(5) << leftGaze.getValue().x << ", "
			    << setw(5) << leftGaze.getValue().y << ", "
			    << setw(5) << leftGaze.getValue().z;
		} else {
			cout << "error: " << static_cast<int>(leftGaze.getError());
		}

		// Right gaze vector
		const auto rightGaze = headset.getGazeVector(Fove::Eye::Right);
		cout << ")   R(";
		if (rightGaze.isValid()) {
			cout
			    << setw(5) << rightGaze.getValue().x << ", "
			    << setw(5) << rightGaze.getValue().y << ", "
			    << setw(5) << rightGaze.getValue().z << ')' << endl;
		} else {
			cout << "error: " << static_cast<int>(rightGaze.getError()) << ')' << endl;
		}
	}
} catch (...) {

	// If an exception is thrown for any reason, log it and exit
	// The FOVE api is designed not to throw externally, but the standard library can
	cerr << "Error: " << currentExceptionMessage() << endl;
	return EXIT_FAILURE;
}
<commit_msg>Data Example: Use combined gaze vector instead of stereo<commit_after>// FOVE Data Example
// This shows how to fetch and output data from the FOVE service in a console program

#include "FoveAPI.h"
#include "Util.h"
#include <chrono>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <thread>

// Use std namespace for convenience
using namespace std;

// Helper function to check error responses from the FOVE API
bool checkError(const Fove::ErrorCode errorCode)
{
	// Check for error
	switch (errorCode) {
	case Fove::ErrorCode::None:
		return true;

	case Fove::ErrorCode::Connect_NotConnected:
		// This happens when the service is off, or we haven't finished connecting to it
		cerr << "Not connected to service" << endl;
		break;

	case Fove::ErrorCode::Data_NoUpdate:
		// This happens after we connect to the service, but before the first frame of data comes in
		cerr << "No update" << endl;
		break;

	case Fove::ErrorCode::Data_Unreliable:
		// This happens when the user is not present, closes the eye or the headset is not properly positioned
		// => here we just ignore the data
		break;

	case Fove::ErrorCode::Data_LowAccuracy:
		// This happens when the user is looking at extreme positions or closing the eyes
		// Depending of the application you may want to ignore this data
		// => here we just print it the same way as reliable data
		return true;

	default:
		// Less common errors are simply logged with their numeric value
		cerr << "Error #" << EnumToUnderlyingValue(errorCode) << endl;
		break;
	}

	return false;
}

int main() try {
	// Create the Headset object, taking the capabilities we need in our program
	// Different capabilities may enable different hardware or software, so use only the capabilities that are needed
	Fove::Headset headset = Fove::Headset::create(Fove::ClientCapabilities::EyeTracking).getValue();

	// Loop indefinitely
	while (true) {
		// Wait for the next eye frame
		// The current thread will sleep until a new frame comes in
		// This allows us to capture data at the full frame rate of eye tracking and not use too much CPU
		const auto waitResult = headset.waitAndFetchNextEyeTrackingData();
		if (!checkError(waitResult.getError())) {
			// Sleep for a second in the event of failure
			// If the wait function fails, it might have returned immediately, and we may eat up 100% of a CPU core if we don't sleep manually
			this_thread::sleep_for(chrono::seconds { 1 }); // Can use 1s in C++14 and later

			continue; // Skip getting the gaze vectors
		}

		// Below we print data
		// Feel free to mess around and call other data query functions,
		// but remember to add the capabilities as needed

		// Get the gaze vector
		const auto gazeData = headset.getCombinedGazeRay();
		if (gazeData.isValid()) {
			cout << "Gaze vectors:   (" << fixed << setprecision(3)
			    << setw(5) << gazeData->direction.x << ", "
			    << setw(5) << gazeData->direction.y << ", "
			    << setw(5) << gazeData->direction.z << ')' << endl;
		} else {
			cout << "getCombinedGazeRay returned error #" << static_cast<int>(gazeData.getError()) << endl;
		}
	}
} catch (...) {

	// If an exception is thrown for any reason, log it and exit
	// The FOVE api is designed not to throw externally, but the standard library can
	cerr << "Error: " << currentExceptionMessage() << endl;
	return EXIT_FAILURE;
}
<|endoftext|>


<commit_before>#ifndef INCLUDE_ACKWARD_CORE_TUPLE_HPP
#define INCLUDE_ACKWARD_CORE_TUPLE_HPP

#include <Python.h>
#include <boost/python/to_python_converter.hpp>
#include <boost/python/tuple.hpp>
#include <boost/tuple/tuple.hpp>

#include <ackward/core/detail/Tuple.hpp>

/** Functions for converting between boost::tuple and
 * boost::python::tuple
 */

namespace ackward {
namespace core {

/** Convert a boost::python::tuple to a boost::tuple

    This uses the boost::python from-python type conversion system to
    convert each element in the input tuple into an element in the
    output tuple.

    @tparam T The boost::tuple type to convert to
    @param t The boost::python::tuple to convert from
    @return A tuple of type T containing the converted elements from
    `t`
 */
template <typename T>
T convertTuple(boost::python::tuple t)
{
    return detail::ConvertTuple<T, boost::tuples::length<T>::value>()(t);
}

/** Convert a boost::tuple into a boost::python::tuple

    This uses the boost::python to-python type conversion system to
    convert each element in the input tuple into an element in the
    output tuple.

    @tparam T The boost::tuple type to convert from
    @param t The boost::tuple to convert
    @return A boost::python::tuple containing the converted elements from `t`
*/
template <typename T>
boost::python::tuple
convertTuple(const T& t)
{
    return detail::ConvertTuple<T, boost::tuples::length<T>::value>()(t);
}

template <typename Tuple>
class TupleConverter {
public:
    typedef detail::convert_tuple<Tuple, boost::tuples::length<Tuple>::value> Impl;

    /* The convert function for boost.python's converter system
     */
    static PyObject* convert(const Tuple& t)
        {
            return Impl::convert(t);
        }

    /* Register this converter with boost.python. This can be
       called as many times as you want; only the first one has any
       effect.
    */
    static void registerConverter()
        {
            static bool initialized = false;

            if (initialized) return;

            initialized = true;

            boost::python::to_python_converter<
            Tuple, ackward::core::TupleConverter<Tuple> >();

            boost::python::converter::registry::push_back(
                &convertible,
                &construct,
                boost::python::type_id<Tuple>());
        }

private:
    /* The convertible function for boost.python's converter system
     */
    static void* convertible(PyObject* obj_ptr)
        {
            return Impl::convertible(obj_ptr);
        }

     /* The construct function for boost.python's converter system
      */
     static void construct(
         PyObject* obj_ptr,
         boost::python::converter::rvalue_from_python_stage1_data* data)
         {
             return Impl::construct(obj_ptr, data);
         }
};

} // namespace core
} // namespace ackward

#endif
<commit_msg>nitpicking<commit_after>#ifndef INCLUDE_ACKWARD_CORE_TUPLE_HPP
#define INCLUDE_ACKWARD_CORE_TUPLE_HPP

#include <Python.h>
#include <boost/python/to_python_converter.hpp>
#include <boost/python/tuple.hpp>
#include <boost/tuple/tuple.hpp>

#include <ackward/core/detail/Tuple.hpp>

/** Functions for converting between boost::tuple and
    boost::python::tuple
 */

namespace ackward {
namespace core {

/** Convert a boost::python::tuple to a boost::tuple

    This uses the boost::python from-python type conversion system to
    convert each element in the input tuple into an element in the
    output tuple.

    @tparam T The boost::tuple type to convert to
    @param t The boost::python::tuple to convert from
    @return A tuple of type T containing the converted elements from
    `t`
 */
template <typename T>
T convertTuple(boost::python::tuple t)
{
    return detail::ConvertTuple<T, boost::tuples::length<T>::value>()(t);
}

/** Convert a boost::tuple into a boost::python::tuple

    This uses the boost::python to-python type conversion system to
    convert each element in the input tuple into an element in the
    output tuple.

    @tparam T The boost::tuple type to convert from
    @param t The boost::tuple to convert
    @return A boost::python::tuple containing the converted elements from `t`
*/
template <typename T>
boost::python::tuple
convertTuple(const T& t)
{
    return detail::ConvertTuple<T, boost::tuples::length<T>::value>()(t);
}

template <typename Tuple>
class TupleConverter {
public:
    typedef detail::convert_tuple<Tuple, boost::tuples::length<Tuple>::value> Impl;

    /* The convert function for boost.python's converter system
     */
    static PyObject* convert(const Tuple& t)
        {
            return Impl::convert(t);
        }

    /* Register this converter with boost.python. This can be
       called as many times as you want; only the first one has any
       effect.
    */
    static void registerConverter()
        {
            static bool initialized = false;

            if (initialized) return;

            initialized = true;

            boost::python::to_python_converter<
            Tuple, ackward::core::TupleConverter<Tuple> >();

            boost::python::converter::registry::push_back(
                &convertible,
                &construct,
                boost::python::type_id<Tuple>());
        }

private:
    /* The convertible function for boost.python's converter system
     */
    static void* convertible(PyObject* obj_ptr)
        {
            return Impl::convertible(obj_ptr);
        }

     /* The construct function for boost.python's converter system
      */
     static void construct(
         PyObject* obj_ptr,
         boost::python::converter::rvalue_from_python_stage1_data* data)
         {
             return Impl::construct(obj_ptr, data);
         }
};

} // namespace core
} // namespace ackward

#endif
<|endoftext|>


<commit_before>#include "stream.h"

Stream Stream::section_stream(uint64_t section_index)
{
    Stream ret;
    auto   header  = peek_header();
    auto   section = header->sections[section_index];
    auto   start   = section.pos;
    auto   length  = section.length;
    ret.buffer     = Buffer(this->buffer, start, length);
    return ret;
}

BinHeader *Stream::peek_header()
{
    return (BinHeader *)buffer.data;
}

const char *Stream::string_ptr(size_t address)
{
    return (const char *)(buffer.data + address);
}

std::string Stream::cstring_data(size_t address)
{
    auto ptr = buffer.data + address;
    return std::string((const char *)ptr);
}

uint64_t Stream::uint64_data(size_t address)
{
    auto ptr = buffer.data + address;
    auto ret = *(uint64_t *)ptr;
    return ret;
}

uint16_t Stream::uint16_data(size_t address)
{
    auto ptr = buffer.data + address;
    auto ret = *(uint16_t *)ptr;
    return ret;
}

int8_t Stream::read_int8()
{
    return _read<int8_t>();
}

uint8_t Stream::read_uint8()
{
    return _read<uint8_t>();
}

int16_t Stream::read_int16()
{
    return _read<int16_t>();
}

int32_t Stream::read_int32()
{
    return _read<int32_t>();
}

int64_t Stream::read_int64()
{
    return _read<int64_t>();
}

dab_register_t Stream::read_reg()
{
    return read_uint16();
}

uint16_t Stream::read_uint16()
{
    return _read<uint16_t>();
}

uint32_t Stream::read_uint32()
{
    return _read<uint32_t>();
}

uint64_t Stream::read_uint64()
{
    return _read<uint64_t>();
}

std::vector<dab_register_t> Stream::read_reglist()
{
    auto count = read_uint8();

    std::vector<dab_register_t> ret;
    for (size_t i = 0; i < count; i++)
    {
        ret.push_back(read_reg());
    }
    return ret;
}

std::string Stream::read_vlc_string()
{
    uint64_t len = read_uint8();
    if (len == 255)
    {
        len = read_uint64();
    }
    assert(len <= remaining());
    std::string ret((const char *)data(), len);
    _position += len;
    return ret;
}

std::string Stream::read_string4()
{
    std::string ret;
    for (int i = 0; i < 4; i++)
    {
        ret += _read<char>();
    }
    return ret;
}

std::string Stream::read_cstring()
{
    std::string ret;
    for (int i = 0; i < 4; i++)
    {
        auto c = _read<char>();
        ;
        if (c == 0)
            break;
        ret += c;
    }
    return ret;
}

void Stream::append(const byte *data, size_t length)
{
    buffer.append(data, length);
}

void Stream::append(Stream &stream, size_t length)
{
    assert(stream.remaining() >= length);
    append(stream.data(), length);
    stream._position += length;
}

void Stream::seek(size_t position)
{
    assert(position < length());
    _position = position;
}

uint64_t Stream::length() const
{
    return buffer.length;
}

uint64_t Stream::position() const
{
    return _position;
}

bool Stream::eof() const
{
    return remaining() == 0;
}

byte *Stream::data() const
{
    return buffer.data + _position;
}

uint64_t Stream::remaining() const
{
    if (buffer.length <= _position)
        return 0;
    return buffer.length - _position;
}
<commit_msg>vm: fix some size_t/uint64_t issues (17)<commit_after>#include "stream.h"

Stream Stream::section_stream(uint64_t section_index)
{
    Stream ret;
    auto   header  = peek_header();
    auto   section = header->sections[section_index];
    auto   start   = section.pos;
    auto   length  = section.length;
    ret.buffer     = Buffer(this->buffer, start, length);
    return ret;
}

BinHeader *Stream::peek_header()
{
    return (BinHeader *)buffer.data;
}

const char *Stream::string_ptr(size_t address)
{
    return (const char *)(buffer.data + address);
}

std::string Stream::cstring_data(size_t address)
{
    auto ptr = buffer.data + address;
    return std::string((const char *)ptr);
}

uint64_t Stream::uint64_data(size_t address)
{
    auto ptr = buffer.data + address;
    auto ret = *(uint64_t *)ptr;
    return ret;
}

uint16_t Stream::uint16_data(size_t address)
{
    auto ptr = buffer.data + address;
    auto ret = *(uint16_t *)ptr;
    return ret;
}

int8_t Stream::read_int8()
{
    return _read<int8_t>();
}

uint8_t Stream::read_uint8()
{
    return _read<uint8_t>();
}

int16_t Stream::read_int16()
{
    return _read<int16_t>();
}

int32_t Stream::read_int32()
{
    return _read<int32_t>();
}

int64_t Stream::read_int64()
{
    return _read<int64_t>();
}

dab_register_t Stream::read_reg()
{
    return read_uint16();
}

uint16_t Stream::read_uint16()
{
    return _read<uint16_t>();
}

uint32_t Stream::read_uint32()
{
    return _read<uint32_t>();
}

uint64_t Stream::read_uint64()
{
    return _read<uint64_t>();
}

std::vector<dab_register_t> Stream::read_reglist()
{
    auto count = read_uint8();

    std::vector<dab_register_t> ret;
    for (size_t i = 0; i < count; i++)
    {
        ret.push_back(read_reg());
    }
    return ret;
}

std::string Stream::read_vlc_string()
{
    uint64_t len = read_uint8();
    if (len == 255)
    {
        len = read_uint64();
    }
    assert(len <= remaining());
    std::string ret((const char *)data(), (size_t)len);
    _position += len;
    return ret;
}

std::string Stream::read_string4()
{
    std::string ret;
    for (int i = 0; i < 4; i++)
    {
        ret += _read<char>();
    }
    return ret;
}

std::string Stream::read_cstring()
{
    std::string ret;
    for (int i = 0; i < 4; i++)
    {
        auto c = _read<char>();
        ;
        if (c == 0)
            break;
        ret += c;
    }
    return ret;
}

void Stream::append(const byte *data, size_t length)
{
    buffer.append(data, length);
}

void Stream::append(Stream &stream, size_t length)
{
    assert(stream.remaining() >= length);
    append(stream.data(), length);
    stream._position += length;
}

void Stream::seek(size_t position)
{
    assert(position < length());
    _position = position;
}

uint64_t Stream::length() const
{
    return buffer.length;
}

uint64_t Stream::position() const
{
    return _position;
}

bool Stream::eof() const
{
    return remaining() == 0;
}

byte *Stream::data() const
{
    return buffer.data + _position;
}

uint64_t Stream::remaining() const
{
    if (buffer.length <= _position)
        return 0;
    return buffer.length - _position;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: MiscUtils.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 10:19:13 $
 *
 *  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 _SCRIPT_FRAMEWORK_MISCUTILS_HXX_
#define _SCRIPT_FRAMEWORK_MISCUTILS_HXX_

#include <rtl/ustring.hxx>

#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif

#include <ucbhelper/content.hxx>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/frame/XModel.hpp>
#include <com/sun/star/frame/XTransientDocumentsDocumentContentFactory.hpp>
#include <com/sun/star/document/XDocumentInfoSupplier.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/container/XContentEnumerationAccess.hpp>
#include <com/sun/star/ucb/XCommandEnvironment.hpp>
#include <com/sun/star/ucb/XSimpleFileAccess.hpp>
#include <com/sun/star/ucb/XContentAccess.hpp>
#include <com/sun/star/sdbc/XResultSet.hpp>
#include <com/sun/star/sdbc/XRow.hpp>
#include <com/sun/star/lang/XMultiComponentFactory.hpp>

#include "util.hxx"

namespace sf_misc
{
// for simplification
#define css ::com::sun::star

class MiscUtils
{
public:
    static css::uno::Sequence< ::rtl::OUString > allOpenTDocUrls( const  css::uno::Reference< css::uno::XComponentContext >& xCtx)
{
    css::uno::Sequence< ::rtl::OUString > result;
    try
    {
        if ( !xCtx.is() )
        {
            return result;
        }
        css::uno::Reference < css::lang::XMultiComponentFactory > xFac( xCtx->getServiceManager(), css::uno::UNO_QUERY );
        if ( xFac.is() )
        {
            css::uno::Reference < com::sun::star::ucb::XSimpleFileAccess > xSFA( xFac->createInstanceWithContext( OUSTR("com.sun.star.ucb.SimpleFileAccess"), xCtx ), css::uno::UNO_QUERY );
            if ( xSFA.is() )
            {
                result = xSFA->getFolderContents( OUSTR("vnd.sun.star.tdoc:/"), true );
            }
        }
    }
    catch ( css::uno::Exception& )
    {
    }
    return result;
}

    static ::rtl::OUString xModelToDocTitle( const css::uno::Reference< css::frame::XModel >& xModel )
{
    // Set a default name, this should never be seen.
    ::rtl::OUString docNameOrURL =
        ::rtl::OUString::createFromAscii("Unknown");
    if ( xModel.is() )
    {
        ::rtl::OUString tempName;
        try
        {
            css::uno::Reference< css::frame::XController > xCurrentController = xModel->getCurrentController();
            if( xCurrentController.is() )
            {
                css::uno::Reference< css::beans::XPropertySet > propSet( xCurrentController->getFrame(), css::uno::UNO_QUERY );
                if ( propSet.is() )
                {
                    if ( sal_True == ( propSet->getPropertyValue(::rtl::OUString::createFromAscii( "Title" ) ) >>= tempName ) )
                    {
                        docNameOrURL = tempName;
                        if ( xModel->getURL().getLength() == 0 )
                        {
                            // process "UntitledX - YYYYYYYY"
                            // to get UntitledX
                            sal_Int32 pos = 0;
                            docNameOrURL = tempName.getToken(0,' ',pos);
                        }
                        else
                        {
                            css::uno::Reference< css::document::XDocumentInfoSupplier >  xDIS( xModel, css::uno::UNO_QUERY_THROW );
                            css::uno::Reference< css::beans::XPropertySet > xProp (xDIS->getDocumentInfo(),  css::uno::UNO_QUERY_THROW );
                            css::uno::Any aTitle = xProp->getPropertyValue(::rtl::OUString::createFromAscii( "Title" ) );

                            aTitle >>= docNameOrURL;
                            if ( docNameOrURL.getLength() == 0 )
                            {
                                docNameOrURL =  parseLocationName( xModel->getURL() );
                            }
                        }
                    }
                }
            }
        }
        catch ( css::uno::Exception& e )
        {
            OSL_TRACE("MiscUtils::xModelToDocTitle() exception thrown: !!! %s",
                ::rtl::OUStringToOString( e.Message,
                    RTL_TEXTENCODING_ASCII_US ).pData->buffer );
        }
    }
    return docNameOrURL;
}
    static ::rtl::OUString tDocUrlToTitle( const ::rtl::OUString& url )
{
    ::rtl::OUString title;

    try
    {
        ::ucb::Content root( url, NULL );
        ::rtl::OUString propName =  OUSTR("Title");
        getUCBProperty( root, propName ) >>= title;
    }
    catch ( css::ucb::ContentCreationException& )
    {
        // carry on, empty value will be returned
    }
    catch ( css::uno::RuntimeException& )
    {
        // carry on, empty value will be returned
    }

    OSL_ENSURE( title.getLength() > 0, "Unable to obtain title!" );
    return title;
}
    static ::rtl::OUString xModelToTdocUrl( const css::uno::Reference< css::frame::XModel >& xModel,
                                            const css::uno::Reference< css::uno::XComponentContext >& xContext )
{
    css::uno::Reference< css::lang::XMultiComponentFactory > xMCF(
        xContext->getServiceManager() );
    css::uno::Reference<
            css::frame::XTransientDocumentsDocumentContentFactory > xDocFac;
    try
    {
        xDocFac =
            css::uno::Reference<
                css::frame::XTransientDocumentsDocumentContentFactory >(
                    xMCF->createInstanceWithContext(
                        rtl::OUString(
                            RTL_CONSTASCII_USTRINGPARAM(
                                "com.sun.star.frame.TransientDocumentsDocumentContentFactory" ) ),
                        xContext ),
                css::uno::UNO_QUERY );
    }
    catch ( css::uno::Exception const & )
    {
        // handled below
    }

    if ( xDocFac.is() )
    {
        try
        {
            css::uno::Reference< css::ucb::XContent > xContent(
                xDocFac->createDocumentContent( xModel ) );
            return xContent->getIdentifier()->getContentIdentifier();
        }
        catch ( css::lang::IllegalArgumentException const & )
        {
            OSL_ENSURE( false, "Invalid document model!" );
        }
    }

    OSL_ENSURE( false, "Unable to obtain URL for document model!" );
    return rtl::OUString();
}
    static css::uno::Reference< css::frame::XModel > tDocUrlToModel( const ::rtl::OUString& url )
{
    css::uno::Any result;

    try
    {
        ::ucb::Content root( url, NULL );
        ::rtl::OUString propName =  OUSTR("DocumentModel");
        result = getUCBProperty( root, propName );
    }
    catch ( css::ucb::ContentCreationException& )
    {
        // carry on, empty value will be returned
    }
    catch ( css::uno::RuntimeException& )
    {
        // carry on, empty value will be returned
    }

    css::uno::Reference< css::frame::XModel > xModel(
        result, css::uno::UNO_QUERY );

    return xModel;
}

    static css::uno::Any getUCBProperty( ::ucb::Content& content, ::rtl::OUString& prop )
{
    css::uno::Any result;
    try
    {
        result = content.getPropertyValue( prop );
    }
    catch ( css::uno::Exception& )
    {
    }
    return result;
}

private:
static ::rtl::OUString parseLocationName( const ::rtl::OUString& location )
{
    // strip out the last leaf of location name
    // e.g. file://dir1/dir2/Blah.sxw - > Blah.sxw
    ::rtl::OUString temp = location;
    INetURLObject aURLObj( temp );
    if ( !aURLObj.HasError() )
        temp = aURLObj.getName( INetURLObject::LAST_SEGMENT, true, INetURLObject::DECODE_WITH_CHARSET );
    return temp;
}

};
} // namespace sf_misc
#endif //
<commit_msg>INTEGRATION: CWS bgdlremove (1.8.46); FILE MERGED 2007/05/18 11:23:13 kso 1.8.46.1: #i77419# - cleanup of ucbhelper namespaces.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: MiscUtils.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: ihi $ $Date: 2007-06-05 14:28:30 $
 *
 *  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 _SCRIPT_FRAMEWORK_MISCUTILS_HXX_
#define _SCRIPT_FRAMEWORK_MISCUTILS_HXX_

#include <rtl/ustring.hxx>

#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif

#include <ucbhelper/content.hxx>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/frame/XModel.hpp>
#include <com/sun/star/frame/XTransientDocumentsDocumentContentFactory.hpp>
#include <com/sun/star/document/XDocumentInfoSupplier.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/container/XContentEnumerationAccess.hpp>
#include <com/sun/star/ucb/XCommandEnvironment.hpp>
#include <com/sun/star/ucb/XSimpleFileAccess.hpp>
#include <com/sun/star/ucb/XContentAccess.hpp>
#include <com/sun/star/sdbc/XResultSet.hpp>
#include <com/sun/star/sdbc/XRow.hpp>
#include <com/sun/star/lang/XMultiComponentFactory.hpp>

#include "util.hxx"

namespace sf_misc
{
// for simplification
#define css ::com::sun::star

class MiscUtils
{
public:
    static css::uno::Sequence< ::rtl::OUString > allOpenTDocUrls( const  css::uno::Reference< css::uno::XComponentContext >& xCtx)
{
    css::uno::Sequence< ::rtl::OUString > result;
    try
    {
        if ( !xCtx.is() )
        {
            return result;
        }
        css::uno::Reference < css::lang::XMultiComponentFactory > xFac( xCtx->getServiceManager(), css::uno::UNO_QUERY );
        if ( xFac.is() )
        {
            css::uno::Reference < com::sun::star::ucb::XSimpleFileAccess > xSFA( xFac->createInstanceWithContext( OUSTR("com.sun.star.ucb.SimpleFileAccess"), xCtx ), css::uno::UNO_QUERY );
            if ( xSFA.is() )
            {
                result = xSFA->getFolderContents( OUSTR("vnd.sun.star.tdoc:/"), true );
            }
        }
    }
    catch ( css::uno::Exception& )
    {
    }
    return result;
}

    static ::rtl::OUString xModelToDocTitle( const css::uno::Reference< css::frame::XModel >& xModel )
{
    // Set a default name, this should never be seen.
    ::rtl::OUString docNameOrURL =
        ::rtl::OUString::createFromAscii("Unknown");
    if ( xModel.is() )
    {
        ::rtl::OUString tempName;
        try
        {
            css::uno::Reference< css::frame::XController > xCurrentController = xModel->getCurrentController();
            if( xCurrentController.is() )
            {
                css::uno::Reference< css::beans::XPropertySet > propSet( xCurrentController->getFrame(), css::uno::UNO_QUERY );
                if ( propSet.is() )
                {
                    if ( sal_True == ( propSet->getPropertyValue(::rtl::OUString::createFromAscii( "Title" ) ) >>= tempName ) )
                    {
                        docNameOrURL = tempName;
                        if ( xModel->getURL().getLength() == 0 )
                        {
                            // process "UntitledX - YYYYYYYY"
                            // to get UntitledX
                            sal_Int32 pos = 0;
                            docNameOrURL = tempName.getToken(0,' ',pos);
                        }
                        else
                        {
                            css::uno::Reference< css::document::XDocumentInfoSupplier >  xDIS( xModel, css::uno::UNO_QUERY_THROW );
                            css::uno::Reference< css::beans::XPropertySet > xProp (xDIS->getDocumentInfo(),  css::uno::UNO_QUERY_THROW );
                            css::uno::Any aTitle = xProp->getPropertyValue(::rtl::OUString::createFromAscii( "Title" ) );

                            aTitle >>= docNameOrURL;
                            if ( docNameOrURL.getLength() == 0 )
                            {
                                docNameOrURL =  parseLocationName( xModel->getURL() );
                            }
                        }
                    }
                }
            }
        }
        catch ( css::uno::Exception& e )
        {
            OSL_TRACE("MiscUtils::xModelToDocTitle() exception thrown: !!! %s",
                ::rtl::OUStringToOString( e.Message,
                    RTL_TEXTENCODING_ASCII_US ).pData->buffer );
        }
    }
    return docNameOrURL;
}
    static ::rtl::OUString tDocUrlToTitle( const ::rtl::OUString& url )
{
    ::rtl::OUString title;

    try
    {
        ::ucbhelper::Content root( url, NULL );
        ::rtl::OUString propName =  OUSTR("Title");
        getUCBProperty( root, propName ) >>= title;
    }
    catch ( css::ucb::ContentCreationException& )
    {
        // carry on, empty value will be returned
    }
    catch ( css::uno::RuntimeException& )
    {
        // carry on, empty value will be returned
    }

    OSL_ENSURE( title.getLength() > 0, "Unable to obtain title!" );
    return title;
}
    static ::rtl::OUString xModelToTdocUrl( const css::uno::Reference< css::frame::XModel >& xModel,
                                            const css::uno::Reference< css::uno::XComponentContext >& xContext )
{
    css::uno::Reference< css::lang::XMultiComponentFactory > xMCF(
        xContext->getServiceManager() );
    css::uno::Reference<
            css::frame::XTransientDocumentsDocumentContentFactory > xDocFac;
    try
    {
        xDocFac =
            css::uno::Reference<
                css::frame::XTransientDocumentsDocumentContentFactory >(
                    xMCF->createInstanceWithContext(
                        rtl::OUString(
                            RTL_CONSTASCII_USTRINGPARAM(
                                "com.sun.star.frame.TransientDocumentsDocumentContentFactory" ) ),
                        xContext ),
                css::uno::UNO_QUERY );
    }
    catch ( css::uno::Exception const & )
    {
        // handled below
    }

    if ( xDocFac.is() )
    {
        try
        {
            css::uno::Reference< css::ucb::XContent > xContent(
                xDocFac->createDocumentContent( xModel ) );
            return xContent->getIdentifier()->getContentIdentifier();
        }
        catch ( css::lang::IllegalArgumentException const & )
        {
            OSL_ENSURE( false, "Invalid document model!" );
        }
    }

    OSL_ENSURE( false, "Unable to obtain URL for document model!" );
    return rtl::OUString();
}
    static css::uno::Reference< css::frame::XModel > tDocUrlToModel( const ::rtl::OUString& url )
{
    css::uno::Any result;

    try
    {
        ::ucbhelper::Content root( url, NULL );
        ::rtl::OUString propName =  OUSTR("DocumentModel");
        result = getUCBProperty( root, propName );
    }
    catch ( css::ucb::ContentCreationException& )
    {
        // carry on, empty value will be returned
    }
    catch ( css::uno::RuntimeException& )
    {
        // carry on, empty value will be returned
    }

    css::uno::Reference< css::frame::XModel > xModel(
        result, css::uno::UNO_QUERY );

    return xModel;
}

    static css::uno::Any getUCBProperty( ::ucbhelper::Content& content, ::rtl::OUString& prop )
{
    css::uno::Any result;
    try
    {
        result = content.getPropertyValue( prop );
    }
    catch ( css::uno::Exception& )
    {
    }
    return result;
}

private:
static ::rtl::OUString parseLocationName( const ::rtl::OUString& location )
{
    // strip out the last leaf of location name
    // e.g. file://dir1/dir2/Blah.sxw - > Blah.sxw
    ::rtl::OUString temp = location;
    INetURLObject aURLObj( temp );
    if ( !aURLObj.HasError() )
        temp = aURLObj.getName( INetURLObject::LAST_SEGMENT, true, INetURLObject::DECODE_WITH_CHARSET );
    return temp;
}

};
} // namespace sf_misc
#endif //
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/**
 * $Log$
 * Revision 1.5  1999/12/14 23:53:25  rahulj
 * Removed the offending Ctrl-M's from the commit message
 * logs which was giving packaging problems.
 *
 * PR:
 * Obtained from:
 * Submitted by:
 * Reviewed by:
 *
 * Revision 1.4  1999/11/23 02:00:12  rahulj
 * Code now works under HPUX 11. Tested inmemory message loader.
 * Revamped makefiles. Builds with both DCE threads as well as pthread libraries.
 *
 * Revision 1.3  1999/11/12 20:36:57  rahulj
 * Changed library name to xerces-c.lib.
 *
 * Revision 1.1.1.1  1999/11/09 01:07:34  twl
 * Initial checkin
 *
 * Revision 1.2  1999/11/08 20:45:23  rahul
 * Swat for adding in Product name and CVS comment log variable.
 *
 */

// ---------------------------------------------------------------------------
// Define these away for this platform
// ---------------------------------------------------------------------------
#define PLATFORM_EXPORT
#define PLATFORM_IMPORT

// ---------------------------------------------------------------------------
// Indicate that we do not support native bools
// ---------------------------------------------------------------------------
#if defined(XML_HPUX_CC)
#define NO_NATIVE_BOOL
#endif

// ---------------------------------------------------------------------------
//  Define our version of the XML character
// ---------------------------------------------------------------------------
typedef unsigned short XMLCh;
typedef unsigned short UTF16Ch;

// ---------------------------------------------------------------------------
//  Define unsigned 16 and 32 bits integers
// ---------------------------------------------------------------------------
typedef unsigned short  XMLUInt16;
typedef unsigned int    XMLUInt32;

// ---------------------------------------------------------------------------
//  Provide prototypes for some string methods that are not always available
//  on all platforms.
// ---------------------------------------------------------------------------
int stricmp(const char* const str1, const char* const  str2);
int strnicmp(const char* const str1, const char* const  str2, const unsigned int count);

// ---------------------------------------------------------------------------
//  The name of the DLL that is built by the HP CC version of the system.
// ---------------------------------------------------------------------------
const char* const XML4C_DLLName = "libxerces-c";
<commit_msg>XMLCh assigned to wchar_t<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/**
 * $Log$
 * Revision 1.6  2000/01/18 21:32:21  aruna1
 * XMLCh assigned to wchar_t
 *
 * Revision 1.5  1999/12/14 23:53:25  rahulj
 * Removed the offending Ctrl-M's from the commit message
 * logs which was giving packaging problems.
 *
 * PR:
 * Obtained from:
 * Submitted by:
 * Reviewed by:
 *
 * Revision 1.4  1999/11/23 02:00:12  rahulj
 * Code now works under HPUX 11. Tested inmemory message loader.
 * Revamped makefiles. Builds with both DCE threads as well as pthread libraries.
 *
 * Revision 1.3  1999/11/12 20:36:57  rahulj
 * Changed library name to xerces-c.lib.
 *
 * Revision 1.1.1.1  1999/11/09 01:07:34  twl
 * Initial checkin
 *
 * Revision 1.2  1999/11/08 20:45:23  rahul
 * Swat for adding in Product name and CVS comment log variable.
 *
 */

// ---------------------------------------------------------------------------
// Define these away for this platform
// ---------------------------------------------------------------------------
#define PLATFORM_EXPORT
#define PLATFORM_IMPORT

// ---------------------------------------------------------------------------
// Indicate that we do not support native bools
// ---------------------------------------------------------------------------
#if defined(XML_HPUX_CC)
#define NO_NATIVE_BOOL
#endif

// ---------------------------------------------------------------------------
//  Define our version of the XML character
// ---------------------------------------------------------------------------
#ifndef INCLUDE_THIS_FILE
#define INCLUDE_THIS_FILE
#include <wchar.h>
#endif
typedef wchar_t XMLCh;
typedef unsigned short UTF16Ch;

// ---------------------------------------------------------------------------
//  Define unsigned 16 and 32 bits integers
// ---------------------------------------------------------------------------
typedef unsigned short  XMLUInt16;
typedef unsigned int    XMLUInt32;

// ---------------------------------------------------------------------------
//  Provide prototypes for some string methods that are not always available
//  on all platforms.
// ---------------------------------------------------------------------------
int stricmp(const char* const str1, const char* const  str2);
int strnicmp(const char* const str1, const char* const  str2, const unsigned int count);

// ---------------------------------------------------------------------------
//  The name of the DLL that is built by the HP CC version of the system.
// ---------------------------------------------------------------------------
const char* const XML4C_DLLName = "libxerces-c";
<|endoftext|>


<commit_before>
#include "util/omx_enum_name.hpp"

namespace mf {

const char *omx_enum_name::get_OMX_COMMANDTYPE_name(OMX_COMMANDTYPE id)
{
	const char *name = "(error)";

	switch (id) {
	case OMX_CommandStateSet:
		name = "OMX_CommandStateSet";
		break;
	case OMX_CommandFlush:
		name = "OMX_CommandFlush";
		break;
	case OMX_CommandPortDisable:
		name = "OMX_CommandPortDisable";
		break;
	case OMX_CommandPortEnable:
		name = "OMX_CommandPortEnable";
		break;
	case OMX_CommandMarkBuffer:
		name = "OMX_CommandMarkBuffer";
		break;
	case OMX_CommandMax:
		name = "OMX_CommandMax";
		break;
	default:
		name = "(unknown)";
		break;
	}

	if (OMX_CommandKhronosExtensions <= id &&
		id < OMX_CommandVendorStartUnused) {
		name = "(OMX_CommandKhronosExtensions)";
	}
	if (OMX_CommandVendorStartUnused <= id &&
		id < OMX_CommandMax) {
		name = "(OMX_CommandVendorStartUnused)";
	}

	return name;
}

const char *omx_enum_name::get_OMX_STATETYPE_name(OMX_STATETYPE id)
{
	const char *name = "(error)";

	switch (id) {
	case OMX_StateInvalid:
		name = "OMX_StateInvalid";
		break;
	case OMX_StateLoaded:
		name = "OMX_StateLoaded";
		break;
	case OMX_StateIdle:
		name = "OMX_StateIdle";
		break;
	case OMX_StateExecuting:
		name = "OMX_StateExecuting";
		break;
	case OMX_StatePause:
		name = "OMX_StatePause";
		break;
	case OMX_StateWaitForResources:
		name = "OMX_StateWaitForResources";
		break;
	case OMX_StateMax:
		name = "OMX_StateMax";
		break;
	default:
		name = "(unknown)";
		break;
	}

	if (OMX_StateKhronosExtensions <= id &&
		id < OMX_StateVendorStartUnused) {
		name = "(OMX_StateKhronosExtensions)";
	}
	if (OMX_StateVendorStartUnused <= id &&
		id < OMX_StateMax) {
		name = "(OMX_StateVendorStartUnused)";
	}

	return name;
}

const char *omx_enum_name::get_OMX_ERRORTYPE_name(OMX_ERRORTYPE id)
{
	const char *name = "(error)";

	switch (id) {
	case OMX_ErrorNone:
		name = "OMX_ErrorNone";
		break;
	case OMX_ErrorInsufficientResources:
		name = "OMX_ErrorInsufficientResources";
		break;
	case OMX_ErrorUndefined:
		name = "OMX_ErrorUndefined";
		break;
	case OMX_ErrorInvalidComponentName:
		name = "OMX_ErrorInvalidComponentName";
		break;
	case OMX_ErrorComponentNotFound:
		name = "OMX_ErrorComponentNotFound";
		break;
	case OMX_ErrorInvalidComponent:
		name = "OMX_ErrorInvalidComponent";
		break;
	case OMX_ErrorBadParameter:
		name = "OMX_ErrorBadParameter";
		break;
	case OMX_ErrorNotImplemented:
		name = "OMX_ErrorNotImplemented";
		break;
	case OMX_ErrorUnderflow:
		name = "OMX_ErrorUnderflow";
		break;
	case OMX_ErrorOverflow:
		name = "OMX_ErrorOverflow";
		break;
	case OMX_ErrorHardware:
		name = "OMX_ErrorHardware";
		break;
	case OMX_ErrorInvalidState:
		name = "OMX_ErrorInvalidState";
		break;
	case OMX_ErrorStreamCorrupt:
		name = "OMX_ErrorStreamCorrupt";
		break;
	case OMX_ErrorPortsNotCompatible:
		name = "OMX_ErrorPortsNotCompatible";
		break;
	case OMX_ErrorResourcesLost:
		name = "OMX_ErrorResourcesLost";
		break;
	case OMX_ErrorNoMore:
		name = "OMX_ErrorNoMore";
		break;
	case OMX_ErrorVersionMismatch:
		name = "OMX_ErrorVersionMismatch";
		break;
	case OMX_ErrorNotReady:
		name = "OMX_ErrorNotReady";
		break;
	case OMX_ErrorTimeout:
		name = "OMX_ErrorTimeout";
		break;
	case OMX_ErrorSameState:
		name = "OMX_ErrorSameState";
		break;
	case OMX_ErrorResourcesPreempted:
		name = "OMX_ErrorResourcesPreempted";
		break;
	case OMX_ErrorPortUnresponsiveDuringAllocation:
		name = "OMX_ErrorPortUnresponsiveDuringAllocation";
		break;
	case OMX_ErrorPortUnresponsiveDuringDeallocation:
		name = "OMX_ErrorPortUnresponsiveDuringDeallocation";
		break;
	case OMX_ErrorPortUnresponsiveDuringStop:
		name = "OMX_ErrorPortUnresponsiveDuringStop";
		break;
	case OMX_ErrorIncorrectStateTransition:
		name = "OMX_ErrorIncorrectStateTransition";
		break;
	case OMX_ErrorIncorrectStateOperation:
		name = "OMX_ErrorIncorrectStateOperation";
		break;
	case OMX_ErrorUnsupportedSetting:
		name = "OMX_ErrorUnsupportedSetting";
		break;
	case OMX_ErrorUnsupportedIndex:
		name = "OMX_ErrorUnsupportedIndex";
		break;
	case OMX_ErrorBadPortIndex:
		name = "OMX_ErrorBadPortIndex";
		break;
	case OMX_ErrorPortUnpopulated:
		name = "OMX_ErrorPortUnpopulated";
		break;
	case OMX_ErrorComponentSuspended:
		name = "OMX_ErrorComponentSuspended";
		break;
	case OMX_ErrorDynamicResourcesUnavailable:
		name = "OMX_ErrorDynamicResourcesUnavailable";
		break;
	case OMX_ErrorMbErrorsInFrame:
		name = "OMX_ErrorMbErrorsInFrame";
		break;
	case OMX_ErrorFormatNotDetected:
		name = "OMX_ErrorFormatNotDetected";
		break;
	case OMX_ErrorContentPipeOpenFailed:
		name = "OMX_ErrorContentPipeOpenFailed";
		break;
	case OMX_ErrorContentPipeCreationFailed:
		name = "OMX_ErrorContentPipeCreationFailed";
		break;
	case OMX_ErrorSeperateTablesUsed:
		name = "OMX_ErrorSeperateTablesUsed";
		break;
	case OMX_ErrorTunnelingUnsupported:
		name = "OMX_ErrorTunnelingUnsupported";
		break;
	case OMX_ErrorMax:
		name = "OMX_ErrorMax";
		break;
	default:
		name = "(unknown)";
		break;
	}

	//OMX_ERRORTYPE is 'signed' int and negative value
	if (OMX_ErrorVendorStartUnused <= id &&
		id < OMX_ErrorKhronosExtensions) {
		name = "(OMX_ErrorKhronosExtensions)";
	}
	if (OMX_ErrorMax <= id &&
		id < OMX_ErrorVendorStartUnused) {
		name = "(OMX_ErrorVendorStartUnused)";
	}

	return name;
}

const char *omx_enum_name::get_OMX_EXTRADATATYPE_name(OMX_EXTRADATATYPE id)
{
	const char *name = "(error)";

	switch (id) {
	case OMX_ExtraDataNone:
		name = "OMX_ExtraDataNone";
		break;
	case OMX_ExtraDataQuantization:
		name = "OMX_ExtraDataQuantization";
		break;
	case OMX_ExtraDataMax:
		name = "OMX_ExtraDataMax";
		break;
	default:
		name = "(unknown)";
		break;
	}

	if (OMX_ExtraDataKhronosExtensions <= id &&
		id < OMX_ExtraDataVendorStartUnused) {
		name = "(OMX_ExtraDataKhronosExtensions)";
	}
	if (OMX_ExtraDataVendorStartUnused <= id &&
		id < OMX_ExtraDataMax) {
		name = "(OMX_ExtraDataVendorStartUnused)";
	}

	return name;
}

const char *omx_enum_name::get_OMX_EVENTTYPE_name(OMX_EVENTTYPE id)
{
	const char *name = "(error)";

	switch (id) {
	case OMX_EventCmdComplete:
		name = "OMX_EventCmdComplete";
		break;
	case OMX_EventError:
		name = "OMX_EventError";
		break;
	case OMX_EventMark:
		name = "OMX_EventMark";
		break;
	case OMX_EventPortSettingsChanged:
		name = "OMX_EventPortSettingsChanged";
		break;
	case OMX_EventBufferFlag:
		name = "OMX_EventBufferFlag";
		break;
	case OMX_EventResourcesAcquired:
		name = "OMX_EventResourcesAcquired";
		break;
	case OMX_EventComponentResumed:
		name = "OMX_EventComponentResumed";
		break;
	case OMX_EventDynamicResourcesAvailable:
		name = "OMX_EventDynamicResourcesAvailable";
		break;
	case OMX_EventPortFormatDetected:
		name = "OMX_EventPortFormatDetected";
		break;
	case OMX_EventMax:
		name = "OMX_EventMax";
		break;
	default:
		name = "(unknown)";
		break;
	}

	if (OMX_EventKhronosExtensions <= id &&
		id < OMX_EventVendorStartUnused) {
		name = "(OMX_EventKhronosExtensions)";
	}
	if (OMX_EventVendorStartUnused <= id &&
		id < OMX_EventMax) {
		name = "(OMX_EventVendorStartUnused)";
	}

	return name;
}

const char *omx_enum_name::get_OMX_BUFFERSUPPLIERTYPE_name(OMX_BUFFERSUPPLIERTYPE id)
{
	const char *name = "(error)";

	switch (id) {
	case OMX_BufferSupplyUnspecified:
		name = "OMX_BufferSupplyUnspecified";
		break;
	case OMX_BufferSupplyInput:
		name = "OMX_BufferSupplyInput";
		break;
	case OMX_BufferSupplyOutput:
		name = "OMX_BufferSupplyOutput";
		break;
	case OMX_BufferSupplyMax:
		name = "OMX_BufferSupplyMax";
		break;
	default:
		name = "(unknown)";
		break;
	}

	if (OMX_BufferSupplyKhronosExtensions <= id &&
		id < OMX_BufferSupplyVendorStartUnused) {
		name = "(OMX_BufferSupplyKhronosExtensions)";
	}
	if (OMX_BufferSupplyVendorStartUnused <= id &&
		id < OMX_BufferSupplyMax) {
		name = "(OMX_BufferSupplyVendorStartUnused)";
	}

	return name;
}

} //namespace mf
<commit_msg>Fix a wrong condition in get_OMX_ERRORTYPE_name() method.<commit_after>
#include "util/omx_enum_name.hpp"

namespace mf {

const char *omx_enum_name::get_OMX_COMMANDTYPE_name(OMX_COMMANDTYPE id)
{
	const char *name = "(error)";

	switch (id) {
	case OMX_CommandStateSet:
		name = "OMX_CommandStateSet";
		break;
	case OMX_CommandFlush:
		name = "OMX_CommandFlush";
		break;
	case OMX_CommandPortDisable:
		name = "OMX_CommandPortDisable";
		break;
	case OMX_CommandPortEnable:
		name = "OMX_CommandPortEnable";
		break;
	case OMX_CommandMarkBuffer:
		name = "OMX_CommandMarkBuffer";
		break;
	case OMX_CommandMax:
		name = "OMX_CommandMax";
		break;
	default:
		name = "(unknown)";
		break;
	}

	if (OMX_CommandKhronosExtensions <= id &&
		id < OMX_CommandVendorStartUnused) {
		name = "(OMX_CommandKhronosExtensions)";
	}
	if (OMX_CommandVendorStartUnused <= id &&
		id < OMX_CommandMax) {
		name = "(OMX_CommandVendorStartUnused)";
	}

	return name;
}

const char *omx_enum_name::get_OMX_STATETYPE_name(OMX_STATETYPE id)
{
	const char *name = "(error)";

	switch (id) {
	case OMX_StateInvalid:
		name = "OMX_StateInvalid";
		break;
	case OMX_StateLoaded:
		name = "OMX_StateLoaded";
		break;
	case OMX_StateIdle:
		name = "OMX_StateIdle";
		break;
	case OMX_StateExecuting:
		name = "OMX_StateExecuting";
		break;
	case OMX_StatePause:
		name = "OMX_StatePause";
		break;
	case OMX_StateWaitForResources:
		name = "OMX_StateWaitForResources";
		break;
	case OMX_StateMax:
		name = "OMX_StateMax";
		break;
	default:
		name = "(unknown)";
		break;
	}

	if (OMX_StateKhronosExtensions <= id &&
		id < OMX_StateVendorStartUnused) {
		name = "(OMX_StateKhronosExtensions)";
	}
	if (OMX_StateVendorStartUnused <= id &&
		id < OMX_StateMax) {
		name = "(OMX_StateVendorStartUnused)";
	}

	return name;
}

const char *omx_enum_name::get_OMX_ERRORTYPE_name(OMX_ERRORTYPE id)
{
	const char *name = "(error)";

	switch (id) {
	case OMX_ErrorNone:
		name = "OMX_ErrorNone";
		break;
	case OMX_ErrorInsufficientResources:
		name = "OMX_ErrorInsufficientResources";
		break;
	case OMX_ErrorUndefined:
		name = "OMX_ErrorUndefined";
		break;
	case OMX_ErrorInvalidComponentName:
		name = "OMX_ErrorInvalidComponentName";
		break;
	case OMX_ErrorComponentNotFound:
		name = "OMX_ErrorComponentNotFound";
		break;
	case OMX_ErrorInvalidComponent:
		name = "OMX_ErrorInvalidComponent";
		break;
	case OMX_ErrorBadParameter:
		name = "OMX_ErrorBadParameter";
		break;
	case OMX_ErrorNotImplemented:
		name = "OMX_ErrorNotImplemented";
		break;
	case OMX_ErrorUnderflow:
		name = "OMX_ErrorUnderflow";
		break;
	case OMX_ErrorOverflow:
		name = "OMX_ErrorOverflow";
		break;
	case OMX_ErrorHardware:
		name = "OMX_ErrorHardware";
		break;
	case OMX_ErrorInvalidState:
		name = "OMX_ErrorInvalidState";
		break;
	case OMX_ErrorStreamCorrupt:
		name = "OMX_ErrorStreamCorrupt";
		break;
	case OMX_ErrorPortsNotCompatible:
		name = "OMX_ErrorPortsNotCompatible";
		break;
	case OMX_ErrorResourcesLost:
		name = "OMX_ErrorResourcesLost";
		break;
	case OMX_ErrorNoMore:
		name = "OMX_ErrorNoMore";
		break;
	case OMX_ErrorVersionMismatch:
		name = "OMX_ErrorVersionMismatch";
		break;
	case OMX_ErrorNotReady:
		name = "OMX_ErrorNotReady";
		break;
	case OMX_ErrorTimeout:
		name = "OMX_ErrorTimeout";
		break;
	case OMX_ErrorSameState:
		name = "OMX_ErrorSameState";
		break;
	case OMX_ErrorResourcesPreempted:
		name = "OMX_ErrorResourcesPreempted";
		break;
	case OMX_ErrorPortUnresponsiveDuringAllocation:
		name = "OMX_ErrorPortUnresponsiveDuringAllocation";
		break;
	case OMX_ErrorPortUnresponsiveDuringDeallocation:
		name = "OMX_ErrorPortUnresponsiveDuringDeallocation";
		break;
	case OMX_ErrorPortUnresponsiveDuringStop:
		name = "OMX_ErrorPortUnresponsiveDuringStop";
		break;
	case OMX_ErrorIncorrectStateTransition:
		name = "OMX_ErrorIncorrectStateTransition";
		break;
	case OMX_ErrorIncorrectStateOperation:
		name = "OMX_ErrorIncorrectStateOperation";
		break;
	case OMX_ErrorUnsupportedSetting:
		name = "OMX_ErrorUnsupportedSetting";
		break;
	case OMX_ErrorUnsupportedIndex:
		name = "OMX_ErrorUnsupportedIndex";
		break;
	case OMX_ErrorBadPortIndex:
		name = "OMX_ErrorBadPortIndex";
		break;
	case OMX_ErrorPortUnpopulated:
		name = "OMX_ErrorPortUnpopulated";
		break;
	case OMX_ErrorComponentSuspended:
		name = "OMX_ErrorComponentSuspended";
		break;
	case OMX_ErrorDynamicResourcesUnavailable:
		name = "OMX_ErrorDynamicResourcesUnavailable";
		break;
	case OMX_ErrorMbErrorsInFrame:
		name = "OMX_ErrorMbErrorsInFrame";
		break;
	case OMX_ErrorFormatNotDetected:
		name = "OMX_ErrorFormatNotDetected";
		break;
	case OMX_ErrorContentPipeOpenFailed:
		name = "OMX_ErrorContentPipeOpenFailed";
		break;
	case OMX_ErrorContentPipeCreationFailed:
		name = "OMX_ErrorContentPipeCreationFailed";
		break;
	case OMX_ErrorSeperateTablesUsed:
		name = "OMX_ErrorSeperateTablesUsed";
		break;
	case OMX_ErrorTunnelingUnsupported:
		name = "OMX_ErrorTunnelingUnsupported";
		break;
	case OMX_ErrorMax:
		name = "OMX_ErrorMax";
		break;
	default:
		name = "(unknown)";
		break;
	}

	//OMX_ERRORTYPE is 'signed' int and negative value
	if (OMX_ErrorVendorStartUnused <= id &&
		id < OMX_ErrorKhronosExtensions) {
		name = "(OMX_ErrorKhronosExtensions)";
	}
	if (id < OMX_ErrorVendorStartUnused) {
		name = "(OMX_ErrorVendorStartUnused)";
	}

	return name;
}

const char *omx_enum_name::get_OMX_EXTRADATATYPE_name(OMX_EXTRADATATYPE id)
{
	const char *name = "(error)";

	switch (id) {
	case OMX_ExtraDataNone:
		name = "OMX_ExtraDataNone";
		break;
	case OMX_ExtraDataQuantization:
		name = "OMX_ExtraDataQuantization";
		break;
	case OMX_ExtraDataMax:
		name = "OMX_ExtraDataMax";
		break;
	default:
		name = "(unknown)";
		break;
	}

	if (OMX_ExtraDataKhronosExtensions <= id &&
		id < OMX_ExtraDataVendorStartUnused) {
		name = "(OMX_ExtraDataKhronosExtensions)";
	}
	if (OMX_ExtraDataVendorStartUnused <= id &&
		id < OMX_ExtraDataMax) {
		name = "(OMX_ExtraDataVendorStartUnused)";
	}

	return name;
}

const char *omx_enum_name::get_OMX_EVENTTYPE_name(OMX_EVENTTYPE id)
{
	const char *name = "(error)";

	switch (id) {
	case OMX_EventCmdComplete:
		name = "OMX_EventCmdComplete";
		break;
	case OMX_EventError:
		name = "OMX_EventError";
		break;
	case OMX_EventMark:
		name = "OMX_EventMark";
		break;
	case OMX_EventPortSettingsChanged:
		name = "OMX_EventPortSettingsChanged";
		break;
	case OMX_EventBufferFlag:
		name = "OMX_EventBufferFlag";
		break;
	case OMX_EventResourcesAcquired:
		name = "OMX_EventResourcesAcquired";
		break;
	case OMX_EventComponentResumed:
		name = "OMX_EventComponentResumed";
		break;
	case OMX_EventDynamicResourcesAvailable:
		name = "OMX_EventDynamicResourcesAvailable";
		break;
	case OMX_EventPortFormatDetected:
		name = "OMX_EventPortFormatDetected";
		break;
	case OMX_EventMax:
		name = "OMX_EventMax";
		break;
	default:
		name = "(unknown)";
		break;
	}

	if (OMX_EventKhronosExtensions <= id &&
		id < OMX_EventVendorStartUnused) {
		name = "(OMX_EventKhronosExtensions)";
	}
	if (OMX_EventVendorStartUnused <= id &&
		id < OMX_EventMax) {
		name = "(OMX_EventVendorStartUnused)";
	}

	return name;
}

const char *omx_enum_name::get_OMX_BUFFERSUPPLIERTYPE_name(OMX_BUFFERSUPPLIERTYPE id)
{
	const char *name = "(error)";

	switch (id) {
	case OMX_BufferSupplyUnspecified:
		name = "OMX_BufferSupplyUnspecified";
		break;
	case OMX_BufferSupplyInput:
		name = "OMX_BufferSupplyInput";
		break;
	case OMX_BufferSupplyOutput:
		name = "OMX_BufferSupplyOutput";
		break;
	case OMX_BufferSupplyMax:
		name = "OMX_BufferSupplyMax";
		break;
	default:
		name = "(unknown)";
		break;
	}

	if (OMX_BufferSupplyKhronosExtensions <= id &&
		id < OMX_BufferSupplyVendorStartUnused) {
		name = "(OMX_BufferSupplyKhronosExtensions)";
	}
	if (OMX_BufferSupplyVendorStartUnused <= id &&
		id < OMX_BufferSupplyMax) {
		name = "(OMX_BufferSupplyVendorStartUnused)";
	}

	return name;
}

} //namespace mf
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: optHeaderTabListbox.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 21:38:17 $
 *
 *  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
 *
 ************************************************************************/

#ifdef SVX_DLLIMPLEMENTATION
#undef SVX_DLLIMPLEMENTATION
#endif

#ifndef SVX_OPTHEADERTABLISTBOX_HXX
#include "optHeaderTabListbox.hxx"
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _HEADBAR_HXX
#include <svtools/headbar.hxx>
#endif

namespace svx
{
// class OptLBoxString_Impl ----------------------------------------------

class OptLBoxString_Impl : public SvLBoxString
{
public:
    OptLBoxString_Impl( SvLBoxEntry* pEntry, USHORT nFlags, const String& rTxt ) :
        SvLBoxString( pEntry, nFlags, rTxt ) {}

    virtual void Paint( const Point& rPos, SvLBox& rDev, USHORT nFlags, SvLBoxEntry* pEntry );
};

// -----------------------------------------------------------------------

void OptLBoxString_Impl::Paint( const Point& rPos, SvLBox& rDev, USHORT, SvLBoxEntry* pEntry )
{
    Font aOldFont( rDev.GetFont() );
    Font aFont( aOldFont );
    //detect readonly state by asking for a valid Image
    if(pEntry && !(!((OptHeaderTabListBox&)rDev).GetCollapsedEntryBmp(pEntry)))
        aFont.SetColor( Application::GetSettings().GetStyleSettings().GetDeactiveTextColor() );
    rDev.SetFont( aFont );
    rDev.DrawText( rPos, GetText() );
    rDev.SetFont( aOldFont );
}
// -----------------------------------------------------------------------------

OptHeaderTabListBox::OptHeaderTabListBox( Window* pParent, WinBits nWinStyle ) :

    SvHeaderTabListBox( pParent, nWinStyle )
{
}

// -----------------------------------------------------------------------
void OptHeaderTabListBox::InitEntry( SvLBoxEntry* pEntry, const XubString& rTxt,
                                     const Image& rImg1, const Image& rImg2 )
{
    SvTabListBox::InitEntry( pEntry, rTxt, rImg1, rImg2 );
    USHORT nTabCount = TabCount();

    for ( USHORT nCol = 1; nCol < nTabCount; ++nCol )
    {
        // alle Spalten mit eigener Klasse initialisieren (Spalte 0 == Bitmap)
        SvLBoxString* pCol = (SvLBoxString*)pEntry->GetItem( nCol );
        OptLBoxString_Impl* pStr = new OptLBoxString_Impl( pEntry, 0, pCol->GetText() );
        pEntry->ReplaceItem( pStr, nCol );
    }
}

} // namespace svx
<commit_msg>INTEGRATION: CWS warnings01 (1.5.222); FILE MERGED 2006/05/04 14:46:58 os 1.5.222.1: warnings removed<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: optHeaderTabListbox.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 15:20:21 $
 *
 *  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
 *
 ************************************************************************/

#ifdef SVX_DLLIMPLEMENTATION
#undef SVX_DLLIMPLEMENTATION
#endif

#ifndef SVX_OPTHEADERTABLISTBOX_HXX
#include "optHeaderTabListbox.hxx"
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _HEADBAR_HXX
#include <svtools/headbar.hxx>
#endif

namespace svx
{
// class OptLBoxString_Impl ----------------------------------------------

class OptLBoxString_Impl : public SvLBoxString
{
public:
    OptLBoxString_Impl( SvLBoxEntry* pEntry, USHORT nFlags, const String& rTxt ) :
        SvLBoxString( pEntry, nFlags, rTxt ) {}

    virtual void Paint( const Point& rPos, SvLBox& rDev, USHORT nFlags, SvLBoxEntry* pEntry );
};

// -----------------------------------------------------------------------

void OptLBoxString_Impl::Paint( const Point& rPos, SvLBox& rDev, USHORT, SvLBoxEntry* pEntry )
{
    Font aOldFont( rDev.GetFont() );
    Font aFont( aOldFont );
    //detect readonly state by asking for a valid Image
    if(pEntry && !(!((OptHeaderTabListBox&)rDev).GetCollapsedEntryBmp(pEntry)))
        aFont.SetColor( Application::GetSettings().GetStyleSettings().GetDeactiveTextColor() );
    rDev.SetFont( aFont );
    rDev.DrawText( rPos, GetText() );
    rDev.SetFont( aOldFont );
}
// -----------------------------------------------------------------------------

OptHeaderTabListBox::OptHeaderTabListBox( Window* pParent, WinBits nWinStyle ) :

    SvHeaderTabListBox( pParent, nWinStyle )
{
}

// -----------------------------------------------------------------------
void OptHeaderTabListBox::InitEntry( SvLBoxEntry* pEntry, const XubString& rTxt,
                                     const Image& rImg1, const Image& rImg2 )
{
    SvTabListBox::InitEntry( pEntry, rTxt, rImg1, rImg2 );
    USHORT _nTabCount = TabCount();

    for ( USHORT nCol = 1; nCol < _nTabCount; ++nCol )
    {
        // alle Spalten mit eigener Klasse initialisieren (Spalte 0 == Bitmap)
        SvLBoxString* pCol = (SvLBoxString*)pEntry->GetItem( nCol );
        OptLBoxString_Impl* pStr = new OptLBoxString_Impl( pEntry, 0, pCol->GetText() );
        pEntry->ReplaceItem( pStr, nCol );
    }
}

} // namespace svx
<|endoftext|>