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

#include <drivers/linux_gpio/linux_gpio.h>
#include <px4_posix.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define PIN_INDEX_BUFFER_MAX (16)
#define PIN_DIRECTION_BUFFER_MAX (30 + PIN_INDEX_BUFFER_MAX)
#define PIN_VALUE_BUFFER_MAX (26 + PIN_INDEX_BUFFER_MAX)

LinuxGPIO::LinuxGPIO(unsigned int pin)
	: _pin(pin)
{
}

int LinuxGPIO::exportPin()
{
	return LinuxGPIO::_exportPin(_pin);
}

int LinuxGPIO::unexportPin()
{
	return LinuxGPIO::_unexportPin(_pin);
}

int LinuxGPIO::setDirection(LinuxGPIO::Direction dir)
{
	return LinuxGPIO::_setDirection(_pin, (int)dir);
}

int LinuxGPIO::readValue()
{
	return LinuxGPIO::_readValue(_pin);
}

int LinuxGPIO::writeValue(LinuxGPIO::Value value)
{
	return LinuxGPIO::_writeValue(_pin, (unsigned int)value);
}

int LinuxGPIO::_exportPin(unsigned int pin)
{
	char pinIndex[PIN_INDEX_BUFFER_MAX];
	int fd;
	int ret;
	int bytes_to_write;

	fd = open("/sys/class/gpio/export", O_WRONLY);

	if (fd == -1) {
		int err = errno;
		PX4_ERR("export failed: open: %s (%d)", strerror(err), err);
		return -1;
	}

	bytes_to_write = snprintf(pinIndex, PIN_INDEX_BUFFER_MAX, "%u", pin);
	ret = write(fd, pinIndex, bytes_to_write);

	if (ret == -1) {
		int err = errno;
		PX4_ERR("export failed: write: %s (%d)", strerror(err), err);
		goto cleanup;

	} else if (ret != bytes_to_write) {
		PX4_ERR("failed to write: incomplete %d != %d", ret, bytes_to_write);
		goto cleanup;
	}

	ret = 0;

cleanup:
	close(fd);

	return ret;
}

int LinuxGPIO::_unexportPin(unsigned int pin)
{
	char pinIndex[PIN_INDEX_BUFFER_MAX];
	int fd;
	int ret;
	int bytes_to_write;

	fd = open("/sys/class/gpio/unexport", O_WRONLY);

	if (fd == -1) {
		int err = errno;
		PX4_ERR("unexport %u: open: %s (%d)", pin, strerror(err), err);
		return -1;
	}

	bytes_to_write = snprintf(pinIndex, PIN_INDEX_BUFFER_MAX, "%u", pin);
	ret = write(fd, pinIndex, bytes_to_write);

	if (ret == -1) {
		int err = errno;
		PX4_ERR("unexport %u: write: %s (%d)", pin, strerror(err), err);
		goto cleanup;

	} else if (ret != bytes_to_write) {
		PX4_ERR("unexport %u: write incomplete %d != %d", pin, ret, bytes_to_write);
		goto cleanup;
	}

	ret = 0;

cleanup:
	close(fd);

	return ret;
}

int LinuxGPIO::_setDirection(unsigned int pin, int dir)
{
	char path[PIN_DIRECTION_BUFFER_MAX];
	int fd;
	int ret;

	snprintf(path, PIN_DIRECTION_BUFFER_MAX, "/sys/class/gpio/gpio%d/direction", pin);
	fd = open(path, O_WRONLY);

	if (fd == -1) {
		int err = errno;
		PX4_ERR("dir %u: open: %s (%d)", pin, strerror(err), err);
		return -1;
	}

	if (dir == 0) {
		ret = write(fd, "in", 2);

	} else {
		ret = write(fd, "out", 3);
	}

	if (ret == -1) {
		int err = errno;
		PX4_ERR("dir %u: write: %s (%d)", pin, strerror(err), err);
		goto cleanup;
	}

	ret = 0;

cleanup:
	close(fd);

	return ret;
}

int LinuxGPIO::_readValue(int pin)
{
	char path[PIN_VALUE_BUFFER_MAX];
	char buf[2];
	int fd;
	int ret;

	snprintf(path, PIN_VALUE_BUFFER_MAX, "/sys/class/gpio/gpio%d/value", pin);
	fd = open(path, O_RDONLY);

	if (fd == -1) {
		int err = errno;
		PX4_ERR("read %u: open: %s (%d)", pin, strerror(err), err);
		return -1;
	}

	ret = read(fd, buf, sizeof(buf));

	if (ret == -1) {
		int err = errno;
		PX4_ERR("read %u: write: %s (%d)", pin, strerror(err), err);
		goto cleanup;
	}

	ret = 0;

	ret = strtol(buf, nullptr, 10);

cleanup:
	close(fd);

	return ret;
}

int LinuxGPIO::_writeValue(int pin, unsigned int value)
{
	char path[PIN_VALUE_BUFFER_MAX];
	char buf[2];
	int fd;
	int ret;

	if (value != (unsigned int)Value::LOW && value != (unsigned int)Value::HIGH) {
		return -EINVAL;
	}

	snprintf(path, PIN_VALUE_BUFFER_MAX, "/sys/class/gpio/gpio%d/value", pin);
	fd = open(path, O_WRONLY);

	if (fd == -1) {
		int err = errno;
		PX4_ERR("set %u: open: %s (%d)", pin, strerror(err), err);
		return -1;
	}

	int buflen = snprintf(buf, sizeof(buf), "%u", value);

	ret = write(fd, buf, buflen);

	if (ret == -1) {
		int err = errno;
		PX4_ERR("set %u: write: %s (%d)", pin, strerror(err), err);
		goto cleanup;
	}

	ret = 0;

cleanup:
	close(fd);

	return ret;
}

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

#include <drivers/linux_gpio/linux_gpio.h>
#include <px4_posix.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define PIN_INDEX_BUFFER_MAX (16)
#define PIN_DIRECTION_BUFFER_MAX (30 + PIN_INDEX_BUFFER_MAX)
#define PIN_VALUE_BUFFER_MAX (26 + PIN_INDEX_BUFFER_MAX)

LinuxGPIO::LinuxGPIO(unsigned int pin)
	: _pin(pin)
{
}

int LinuxGPIO::exportPin()
{
	return LinuxGPIO::_exportPin(_pin);
}

int LinuxGPIO::unexportPin()
{
	return LinuxGPIO::_unexportPin(_pin);
}

int LinuxGPIO::setDirection(LinuxGPIO::Direction dir)
{
	return LinuxGPIO::_setDirection(_pin, (int)dir);
}

int LinuxGPIO::readValue()
{
	return LinuxGPIO::_readValue(_pin);
}

int LinuxGPIO::writeValue(LinuxGPIO::Value value)
{
	return LinuxGPIO::_writeValue(_pin, (unsigned int)value);
}

int LinuxGPIO::_exportPin(unsigned int pin)
{
	char pinIndex[PIN_INDEX_BUFFER_MAX];
	int fd;
	int ret;
	int bytes_to_write;

	if (_readValue(pin) != -1) {
		/* GPIO is already exported */
		return 0;
	}

	fd = open("/sys/class/gpio/export", O_WRONLY);

	if (fd == -1) {
		int err = errno;
		PX4_ERR("export failed: open: %s (%d)", strerror(err), err);
		return -1;
	}

	bytes_to_write = snprintf(pinIndex, PIN_INDEX_BUFFER_MAX, "%u", pin);
	ret = write(fd, pinIndex, bytes_to_write);

	if (ret == -1) {
		int err = errno;
		PX4_ERR("export failed: write: %s (%d)", strerror(err), err);
		goto cleanup;

	} else if (ret != bytes_to_write) {
		PX4_ERR("failed to write: incomplete %d != %d", ret, bytes_to_write);
		goto cleanup;
	}

	ret = 0;

cleanup:
	close(fd);

	return ret;
}

int LinuxGPIO::_unexportPin(unsigned int pin)
{
	char pinIndex[PIN_INDEX_BUFFER_MAX];
	int fd;
	int ret;
	int bytes_to_write;

	fd = open("/sys/class/gpio/unexport", O_WRONLY);

	if (fd == -1) {
		int err = errno;
		PX4_ERR("unexport %u: open: %s (%d)", pin, strerror(err), err);
		return -1;
	}

	bytes_to_write = snprintf(pinIndex, PIN_INDEX_BUFFER_MAX, "%u", pin);
	ret = write(fd, pinIndex, bytes_to_write);

	if (ret == -1) {
		int err = errno;
		PX4_ERR("unexport %u: write: %s (%d)", pin, strerror(err), err);
		goto cleanup;

	} else if (ret != bytes_to_write) {
		PX4_ERR("unexport %u: write incomplete %d != %d", pin, ret, bytes_to_write);
		goto cleanup;
	}

	ret = 0;

cleanup:
	close(fd);

	return ret;
}

int LinuxGPIO::_setDirection(unsigned int pin, int dir)
{
	char path[PIN_DIRECTION_BUFFER_MAX];
	int fd;
	int ret;

	snprintf(path, PIN_DIRECTION_BUFFER_MAX, "/sys/class/gpio/gpio%d/direction", pin);
	fd = open(path, O_WRONLY);

	if (fd == -1) {
		int err = errno;
		PX4_ERR("dir %u: open: %s (%d)", pin, strerror(err), err);
		return -1;
	}

	if (dir == 0) {
		ret = write(fd, "in", 2);

	} else {
		ret = write(fd, "out", 3);
	}

	if (ret == -1) {
		int err = errno;
		PX4_ERR("dir %u: write: %s (%d)", pin, strerror(err), err);
		goto cleanup;
	}

	ret = 0;

cleanup:
	close(fd);

	return ret;
}

int LinuxGPIO::_readValue(int pin)
{
	char path[PIN_VALUE_BUFFER_MAX];
	char buf[2];
	int fd;
	int ret;

	snprintf(path, PIN_VALUE_BUFFER_MAX, "/sys/class/gpio/gpio%d/value", pin);
	fd = open(path, O_RDONLY);

	if (fd == -1) {
		int err = errno;
		PX4_ERR("read %u: open: %s (%d)", pin, strerror(err), err);
		return -1;
	}

	ret = read(fd, buf, sizeof(buf));

	if (ret == -1) {
		int err = errno;
		PX4_ERR("read %u: write: %s (%d)", pin, strerror(err), err);
		goto cleanup;
	}

	ret = 0;

	ret = strtol(buf, nullptr, 10);

cleanup:
	close(fd);

	return ret;
}

int LinuxGPIO::_writeValue(int pin, unsigned int value)
{
	char path[PIN_VALUE_BUFFER_MAX];
	char buf[2];
	int fd;
	int ret;

	if (value != (unsigned int)Value::LOW && value != (unsigned int)Value::HIGH) {
		return -EINVAL;
	}

	snprintf(path, PIN_VALUE_BUFFER_MAX, "/sys/class/gpio/gpio%d/value", pin);
	fd = open(path, O_WRONLY);

	if (fd == -1) {
		int err = errno;
		PX4_ERR("set %u: open: %s (%d)", pin, strerror(err), err);
		return -1;
	}

	int buflen = snprintf(buf, sizeof(buf), "%u", value);

	ret = write(fd, buf, buflen);

	if (ret == -1) {
		int err = errno;
		PX4_ERR("set %u: write: %s (%d)", pin, strerror(err), err);
		goto cleanup;
	}

	ret = 0;

cleanup:
	close(fd);

	return ret;
}

<|endoftext|>


<commit_before>// ================================================================================================
// Shadowrect.cpp
//
//   Copyright (C) 2001 Herf Consulting LLC.  All rights reserved.
//
//   Please do not redistribute this source code.
//
//	 This source is provided "as-is," and Herf Consulting LLC will not be liable
//   for any damages resulting from its use or misuse.
//
// ================================================================================================

#include <stdio.h>
#include <stdlib.h>

#pragma warning(disable: 4244)

typedef unsigned long uint32;
typedef long int32;
typedef float real32;
typedef unsigned char uint8;

// Globals (ack)
uint32 bg = 0xFFFFFF;
real32 srad = 5.1f;
uint32 opac = 153;
uint8 *sprof = NULL;
uint8 *rgbbuf = NULL;
uint32 sprofsize = 0;

// shadow offsets in bitmap space
int32 xoff = 2;
int32 yoff = 3;

// offsets from bitmap to output space
int32 xbitmap = 0, ybitmap = 0;

// size of bitmap
int32 width, height;

// size of output
int32 outwidth, outheight;

// output state
int32 outputY = 0;

int32 topql, topqt, topqr, topqb;

FILE *in = stdin;

// ================================================================================================
// approximation to the gaussian integral [x, infty]
// ================================================================================================
static inline real32 gi(real32 x)
{
	const real32 i6 = 1.f / 6.0f;
	const real32 i4 = 1.f / 4.0f;
	const real32 i3 = 1.f / 3.0f;

	if (x > 1.5f) return 0.0f;
	if (x < -1.5f) return 1.0f;

	real32 x2 = x * x;
	real32 x3 = x2 * x;

	if (x >  0.5) return .5625  - ( x3 * i6 - 3 * x2 * i4 + 1.125 * x);
	if (x > -0.5) return 0.5    - (0.75 * x - x3 * i3);
				  return 0.4375 + (-x3 * i6 - 3 * x2 * i4 - 1.125 * x);
}

static int32 UpdateProfile()
{
	int32 size = srad * 3 + 1;
	int32 c    = size >> 1;

	sprof = new uint8[size];
	sprofsize = size;
	if (sprof == NULL) return -1;

	real32 invr = 1.f / srad;
	for (int32 x = 1; x < size; x ++) {
		real32 xp   = (c - x) * invr;
		real32 gint = gi(xp);
		sprof[x] = 255 - int32(255.f * gint);
	}
	// unstable here!
	sprof[0] = 255;

	return 0;
}

char line[2048];
static char GetLine() {
	if (fgets(line, 2048, in)) {
		return line[0];
	} else {
		return 0;
	}
}

static int32 Initialize()
{
	uint32 ignoreme;

	// try to parse PPM
	GetLine();	if (line[0] != 'P' || line[1] != '6') return -1;
	while (GetLine() == '#') {}
	if (sscanf(line, "%d %d\n", &width, &height) != 2) return -1;
	while (GetLine() == '#') {}
	if (sscanf(line, "%d\n", &ignoreme) != 1) return -1;
	if (ignoreme != 255) return -1;

	rgbbuf = new uint8[width * 3];
	if (!rgbbuf) return -1;

	// setup shadow based on width, height
	int32 sl = int(-srad * 1.5) + xoff;
	int32 sr = int( srad * 1.5 + width + 0.9999) + xoff;
	int32 st = int(-srad * 1.5) + yoff;
	int32 sb = int( srad * 1.5 + height + 0.9999) + yoff;

	if (sl < 0) {
		xbitmap = -sl;
		sr += xbitmap;
		sl = 0;
	}
	if (st < 0) {
		ybitmap = -st;
		sb += ybitmap;
		st = 0;
	}

	int32 maxx = sr - sl;
	int32 maxy = sb - st;
	int32 bitx = width + xbitmap;
	int32 bity = height + ybitmap;

	if (bitx > maxx) maxx = bitx;
	if (bity > maxy) maxy = bity;

	outwidth = maxx;
	outheight = maxy;

	printf("P6\n# Not created by the GIMP\n%d %d\n255\n", outwidth, outheight);

	// find top quadrant of shadow * 2 (.1 fixed point)
	topql = xoff + xbitmap;
	topqr = width + xoff + xbitmap;
	topqt = yoff + ybitmap;
	topqb = height + yoff + ybitmap;

	topqb  = topqt + topqb;
	topqt += topqt;

	topqr  = topql + topqr;
	topql += topql;

	// we've computed xbitmap, ybitmap, outwidth, outheight
	return UpdateProfile();
}

// ================================================================================================
// multiply with black
// ================================================================================================
static inline void PixelDarken(uint32 &d, const uint32 amt)
{
	uint32 rb = d & 0xFF00FF;
	uint32 g  = d & 0x00FF00;
	d &= 0xFF000000;

	rb = rb * amt & 0xFF00FF00;
	g  = g  * amt & 0x00FF0000;

	rb |= g;
	d  |= (rb >> 8);
}

// scan from x0 to x1 using outputY as the scanline
int32 ScanAbs(int32 x0, int32 x1)
{
	if (x1 <= x0) return 0;

	int32 maxi = sprofsize - 1;

	int32 filll2 = x0 * 2;
	int32 fillr2 = x1 * 2;

	int32 center = (sprofsize & ~1) - 1;//(sprof.Used() & ~1) - 1;

	int32 w = topqr - topql - center;
	int32 h = topqb - topqt - center;

	// scan
	int32 y = outputY;

	int32 dy = abs(y * 2 - topqb) - h;
	int32 oy = dy >> 1;
	if (oy < 0) oy = 0;

	uint32 sh0 = sprof[oy];

	sh0 = sh0 * opac >> 8;

	//uint32 *dp0 = dst.Pixel(x0, y);
	for (int32 x = filll2; x < fillr2; x += 2) {

		int32 dx = abs(x - topqr) - w;
		int32 ox = dx >> 1;
		if (ox < 0) ox = 0;

		uint32 sh = 256 - ((sprof[ox]) * sh0 >> 8);
		//uint32 sh = (sprof[ox]) * sh0 >> 8;

		uint32 dst = bg;
		PixelDarken(dst, sh);
		putchar(dst >> 16 & 0xFF);
		putchar(dst >>  8 & 0xFF);
		putchar(dst       & 0xFF);
	}

	return 0;
}

static int32 ProcessLine()
{
	// write a line for "outputY"
	if (outputY < ybitmap || outputY >= (ybitmap + height)) {
		// "write"
		// write a whole line of shadow
		ScanAbs(0, outwidth);
	} else {
		// "read-write"
		// clip and write a line of the input bitmap
		ScanAbs(0, xbitmap);

		// in case read fails, fill buffer with bg color
		uint8 *rgb = rgbbuf;
		for (int32 i = 0; i < width; i++) {
			rgb[0] = bg >> 16 & 0xFF;
			rgb[1] = bg >>  8 & 0xFF;
			rgb[2] = bg       & 0xFF;
			rgb += 3;
		}
		fread(rgbbuf, 3, width, in);
		fwrite(rgbbuf, 3, width, stdout);
		ScanAbs(xbitmap + width, outwidth);
	}

	outputY ++;

	return 0;
}

// shadowrect main:
//   give a background color ("#FFFFFF")
//   give a shadow radius (5.1)
//   give a shadow X offset (2)
//   give a shadow Y offset (3)
//   give an opacity (0.6)

int main(int argc, char **argv)
{
	in = fopen("test.ppm", "rb");

	if (argc < 1) {
		printf("Usage: %s [background] [radius] [xoffset] [yoffset] [%opacity]\x13", argv[0]);
		return -1;
	}

	switch (argc) {
	case 6:
		opac = uint32(2.56 * atof(argv[5]));
	case 5:
		yoff = atoi(argv[4]);
	case 4:
		xoff = atoi(argv[3]);
	case 3:
		srad = atof(argv[2]);
	case 2:
	  	if (argv[1][0] == '#') argv[1]++;
		bg = strtol(argv[1], NULL, 16);
	}

	if (Initialize() != 0) {
		fprintf(stderr, "Input is not a valid PPM\n");
		return -1;	// format problem
	}

	while (outputY < outheight) {
		ProcessLine();
	}

	if (rgbbuf) delete rgbbuf; rgbbuf = NULL;
	if (sprof) delete sprof; sprof = NULL;

	return 0;
}

<commit_msg>update header to reflect apache license :)<commit_after>// ================================================================================================
// Shadowrect.cpp
//
//   Copyright (C) 2001 Herf Consulting LLC.  All rights reserved.
//
// ================================================================================================

#include <stdio.h>
#include <stdlib.h>

#pragma warning(disable: 4244)

typedef unsigned long uint32;
typedef long int32;
typedef float real32;
typedef unsigned char uint8;

// Globals (ack)
uint32 bg = 0xFFFFFF;
real32 srad = 5.1f;
uint32 opac = 153;
uint8 *sprof = NULL;
uint8 *rgbbuf = NULL;
uint32 sprofsize = 0;

// shadow offsets in bitmap space
int32 xoff = 2;
int32 yoff = 3;

// offsets from bitmap to output space
int32 xbitmap = 0, ybitmap = 0;

// size of bitmap
int32 width, height;

// size of output
int32 outwidth, outheight;

// output state
int32 outputY = 0;

int32 topql, topqt, topqr, topqb;

FILE *in = stdin;

// ================================================================================================
// approximation to the gaussian integral [x, infty]
// ================================================================================================
static inline real32 gi(real32 x)
{
	const real32 i6 = 1.f / 6.0f;
	const real32 i4 = 1.f / 4.0f;
	const real32 i3 = 1.f / 3.0f;

	if (x > 1.5f) return 0.0f;
	if (x < -1.5f) return 1.0f;

	real32 x2 = x * x;
	real32 x3 = x2 * x;

	if (x >  0.5) return .5625  - ( x3 * i6 - 3 * x2 * i4 + 1.125 * x);
	if (x > -0.5) return 0.5    - (0.75 * x - x3 * i3);
				  return 0.4375 + (-x3 * i6 - 3 * x2 * i4 - 1.125 * x);
}

static int32 UpdateProfile()
{
	int32 size = srad * 3 + 1;
	int32 c    = size >> 1;

	sprof = new uint8[size];
	sprofsize = size;
	if (sprof == NULL) return -1;

	real32 invr = 1.f / srad;
	for (int32 x = 1; x < size; x ++) {
		real32 xp   = (c - x) * invr;
		real32 gint = gi(xp);
		sprof[x] = 255 - int32(255.f * gint);
	}
	// unstable here!
	sprof[0] = 255;

	return 0;
}

char line[2048];
static char GetLine() {
	if (fgets(line, 2048, in)) {
		return line[0];
	} else {
		return 0;
	}
}

static int32 Initialize()
{
	uint32 ignoreme;

	// try to parse PPM
	GetLine();	if (line[0] != 'P' || line[1] != '6') return -1;
	while (GetLine() == '#') {}
	if (sscanf(line, "%d %d\n", &width, &height) != 2) return -1;
	while (GetLine() == '#') {}
	if (sscanf(line, "%d\n", &ignoreme) != 1) return -1;
	if (ignoreme != 255) return -1;

	rgbbuf = new uint8[width * 3];
	if (!rgbbuf) return -1;

	// setup shadow based on width, height
	int32 sl = int(-srad * 1.5) + xoff;
	int32 sr = int( srad * 1.5 + width + 0.9999) + xoff;
	int32 st = int(-srad * 1.5) + yoff;
	int32 sb = int( srad * 1.5 + height + 0.9999) + yoff;

	if (sl < 0) {
		xbitmap = -sl;
		sr += xbitmap;
		sl = 0;
	}
	if (st < 0) {
		ybitmap = -st;
		sb += ybitmap;
		st = 0;
	}

	int32 maxx = sr - sl;
	int32 maxy = sb - st;
	int32 bitx = width + xbitmap;
	int32 bity = height + ybitmap;

	if (bitx > maxx) maxx = bitx;
	if (bity > maxy) maxy = bity;

	outwidth = maxx;
	outheight = maxy;

	printf("P6\n# Not created by the GIMP\n%d %d\n255\n", outwidth, outheight);

	// find top quadrant of shadow * 2 (.1 fixed point)
	topql = xoff + xbitmap;
	topqr = width + xoff + xbitmap;
	topqt = yoff + ybitmap;
	topqb = height + yoff + ybitmap;

	topqb  = topqt + topqb;
	topqt += topqt;

	topqr  = topql + topqr;
	topql += topql;

	// we've computed xbitmap, ybitmap, outwidth, outheight
	return UpdateProfile();
}

// ================================================================================================
// multiply with black
// ================================================================================================
static inline void PixelDarken(uint32 &d, const uint32 amt)
{
	uint32 rb = d & 0xFF00FF;
	uint32 g  = d & 0x00FF00;
	d &= 0xFF000000;

	rb = rb * amt & 0xFF00FF00;
	g  = g  * amt & 0x00FF0000;

	rb |= g;
	d  |= (rb >> 8);
}

// scan from x0 to x1 using outputY as the scanline
int32 ScanAbs(int32 x0, int32 x1)
{
	if (x1 <= x0) return 0;

	int32 maxi = sprofsize - 1;

	int32 filll2 = x0 * 2;
	int32 fillr2 = x1 * 2;

	int32 center = (sprofsize & ~1) - 1;//(sprof.Used() & ~1) - 1;

	int32 w = topqr - topql - center;
	int32 h = topqb - topqt - center;

	// scan
	int32 y = outputY;

	int32 dy = abs(y * 2 - topqb) - h;
	int32 oy = dy >> 1;
	if (oy < 0) oy = 0;

	uint32 sh0 = sprof[oy];

	sh0 = sh0 * opac >> 8;

	//uint32 *dp0 = dst.Pixel(x0, y);
	for (int32 x = filll2; x < fillr2; x += 2) {

		int32 dx = abs(x - topqr) - w;
		int32 ox = dx >> 1;
		if (ox < 0) ox = 0;

		uint32 sh = 256 - ((sprof[ox]) * sh0 >> 8);
		//uint32 sh = (sprof[ox]) * sh0 >> 8;

		uint32 dst = bg;
		PixelDarken(dst, sh);
		putchar(dst >> 16 & 0xFF);
		putchar(dst >>  8 & 0xFF);
		putchar(dst       & 0xFF);
	}

	return 0;
}

static int32 ProcessLine()
{
	// write a line for "outputY"
	if (outputY < ybitmap || outputY >= (ybitmap + height)) {
		// "write"
		// write a whole line of shadow
		ScanAbs(0, outwidth);
	} else {
		// "read-write"
		// clip and write a line of the input bitmap
		ScanAbs(0, xbitmap);

		// in case read fails, fill buffer with bg color
		uint8 *rgb = rgbbuf;
		for (int32 i = 0; i < width; i++) {
			rgb[0] = bg >> 16 & 0xFF;
			rgb[1] = bg >>  8 & 0xFF;
			rgb[2] = bg       & 0xFF;
			rgb += 3;
		}
		fread(rgbbuf, 3, width, in);
		fwrite(rgbbuf, 3, width, stdout);
		ScanAbs(xbitmap + width, outwidth);
	}

	outputY ++;

	return 0;
}

// shadowrect main:
//   give a background color ("#FFFFFF")
//   give a shadow radius (5.1)
//   give a shadow X offset (2)
//   give a shadow Y offset (3)
//   give an opacity (0.6)

int main(int argc, char **argv)
{
	in = fopen("test.ppm", "rb");

	if (argc < 1) {
		printf("Usage: %s [background] [radius] [xoffset] [yoffset] [%opacity]\x13", argv[0]);
		return -1;
	}

	switch (argc) {
	case 6:
		opac = uint32(2.56 * atof(argv[5]));
	case 5:
		yoff = atoi(argv[4]);
	case 4:
		xoff = atoi(argv[3]);
	case 3:
		srad = atof(argv[2]);
	case 2:
	  	if (argv[1][0] == '#') argv[1]++;
		bg = strtol(argv[1], NULL, 16);
	}

	if (Initialize() != 0) {
		fprintf(stderr, "Input is not a valid PPM\n");
		return -1;	// format problem
	}

	while (outputY < outheight) {
		ProcessLine();
	}

	if (rgbbuf) delete rgbbuf; rgbbuf = NULL;
	if (sprof) delete sprof; sprof = NULL;

	return 0;
}

<|endoftext|>


<commit_before>// Authors: Axel Naumann, Philippe Canal, Danilo Piparo

/*************************************************************************
 * Copyright (C) 1995-2016, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#ifndef ROOT_STAGE1_BUILD
#include "rootclingTCling.h"
#include "rootclingIO.h"
#endif

#include "rootcling_impl.h"
#include "RConfigure.h"
#include "RConfig.h"

#include <iostream>

#ifdef _WIN32
# ifdef system
#  undef system
# endif
# include <windows.h>
# include <Tlhelp32.h> // for MAX_MODULE_NAME32
# include <process.h>
# define PATH_MAX _MAX_PATH
# ifdef interface
// prevent error coming from clang/AST/Attrs.inc
#  undef interface
# endif
#else // _WIN32
# include <limits.h>
# include <unistd.h>
# include <dlfcn.h>
#endif

#ifdef __APPLE__
#include <libgen.h> // Needed for basename
#include <mach-o/dyld.h>
#endif

extern "C" {
R__DLLEXPORT void usedToIdentifyRootClingByDlSym() {}
}

////////////////////////////////////////////////////////////////////////////////

#ifdef __ICC
#pragma warning disable 69
#endif

int main(int argc, char **argv)
{
   // Force the emission of the symbol - the compiler cannot know that argv
   // is always set.
   if (!argv) {
      auto dummyVal =  (int)(long)&usedToIdentifyRootClingByDlSym;
      return dummyVal;
   }

   ROOT::Internal::RootCling::DriverConfig config{};
#ifdef R__HAVE_LLVMRESOURCEDIR
  config.fLLVMResourceDir= "@R__LLVMRESOURCEDIR@";
#endif

#ifdef ROOT_STAGE1_BUILD
   config.fBuildingROOTStage1 = true;
#else
   config.fBuildingROOTStage1 = false;
   config.fTROOT__GetExtraInterpreterArgs = &TROOT__GetExtraInterpreterArgs;
   config.fTCling__GetInterpreter = &TCling__GetInterpreter;
   config.fInitializeStreamerInfoROOTFile = &InitializeStreamerInfoROOTFile;
   config.fAddStreamerInfoToROOTFile = &AddStreamerInfoToROOTFile;
   config.fAddTypedefToROOTFile = &AddTypedefToROOTFile;
   config.fAddEnumToROOTFile = &AddEnumToROOTFile;
   config.fAddAncestorPCMROOTFile = &AddAncestorPCMROOTFile;
   config.fCloseStreamerInfoROOTFile = &CloseStreamerInfoROOTFile;
#endif
   return rootcling_driver(argc, argv, config);
}
<commit_msg>Simply use symbol from libCling; rootcling links against it.<commit_after>// Authors: Axel Naumann, Philippe Canal, Danilo Piparo

/*************************************************************************
 * Copyright (C) 1995-2016, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#ifndef ROOT_STAGE1_BUILD
#include "rootclingTCling.h"
#include "rootclingIO.h"
#endif

#include "rootcling_impl.h"
#include "RConfigure.h"
#include "RConfig.h"

#include <iostream>

#ifdef _WIN32
# ifdef system
#  undef system
# endif
# include <windows.h>
# include <Tlhelp32.h> // for MAX_MODULE_NAME32
# include <process.h>
# define PATH_MAX _MAX_PATH
# ifdef interface
// prevent error coming from clang/AST/Attrs.inc
#  undef interface
# endif
#else // _WIN32
# include <limits.h>
# include <unistd.h>
# include <dlfcn.h>
#endif

#ifdef __APPLE__
#include <libgen.h> // Needed for basename
#include <mach-o/dyld.h>
#endif

extern "C" {
R__DLLEXPORT void usedToIdentifyRootClingByDlSym() {}
}

////////////////////////////////////////////////////////////////////////////////

#ifdef __ICC
#pragma warning disable 69
#endif

int main(int argc, char **argv)
{
   // Force the emission of the symbol - the compiler cannot know that argv
   // is always set.
   if (!argv) {
      auto dummyVal =  (int)(long)&usedToIdentifyRootClingByDlSym;
      return dummyVal;
   }

   ROOT::Internal::RootCling::DriverConfig config{};
#ifdef R__HAVE_LLVMRESOURCEDIR
  config.fLLVMResourceDir= "@R__LLVMRESOURCEDIR@";
#endif

#ifdef ROOT_STAGE1_BUILD
   config.fBuildingROOTStage1 = true;
#else
   config.fBuildingROOTStage1 = false;
   config.fTROOT__GetExtraInterpreterArgs = &TROOT__GetExtraInterpreterArgs;
   config.fTCling__GetInterpreter = &TCling__GetInterpreter;
   config.fInitializeStreamerInfoROOTFile = &InitializeStreamerInfoROOTFile;
   config.fAddStreamerInfoToROOTFile = &AddStreamerInfoToROOTFile;
   config.fAddTypedefToROOTFile = &AddTypedefToROOTFile;
   config.fAddEnumToROOTFile = &AddEnumToROOTFile;
   config.fAddAncestorPCMROOTFile = &AddAncestorPCMROOTFile;
   config.fCloseStreamerInfoROOTFile = &CloseStreamerInfoROOTFile;
#endif
   return ROOT_rootcling_Driver(argc, argv, config);
}
<|endoftext|>


<commit_before><commit_msg>fixed note off velocity<commit_after><|endoftext|>


<commit_before>#include "Camera2DTargetedComponent.h"

#include "Entities/Components/Transform3DComponent.h"
#include "Entities/ComponentTypeEnum.h"
#include "Game/Game.h"

namespace CasaEngine
{
	Camera2DTargetedComponent::Camera2DTargetedComponent(BaseEntity *entity) :
		Camera2DComponent(entity, CAMERA_2D_TARGETED),
		m_pTargetedEntity(nullptr)
	{
	}

	void Camera2DTargetedComponent::Update(const GameTime& gameTime_)
	{
		if (m_pTargetedEntity != nullptr)
		{
			auto viewport = GetViewport();
			const auto winSize = Game::Instance().GetWindowSize();
			auto* const transform_3d_component = m_pTargetedEntity->GetComponentMgr()->GetComponent<Transform3DComponent>();
			CA_ASSERT(transform_3d_component != nullptr, "cameracomponent : the target need to have a Transform3DComponent");
			const auto targetPosition = transform_3d_component->GetPosition();

			const Rectangle deadZone(m_Offset.x + static_cast<float>(winSize.x) * (1.0f - m_DeadZoneRatio.x) / 2.0f,
				m_Offset.y + static_cast<float>(winSize.y) * (1.0f - m_DeadZoneRatio.y) / 2.0f,
				winSize.x * m_DeadZoneRatio.x,
				winSize.y * m_DeadZoneRatio.y);

			if (deadZone.Intersects(Vector2(targetPosition.x, targetPosition.y)) == INT_OUT)
			{
				if (targetPosition.x < deadZone.Left())
				{
					m_Offset.x -= deadZone.Left() - targetPosition.x;
				}
				else if (targetPosition.x > deadZone.Right())
				{
					m_Offset.x += targetPosition.x - deadZone.Right();
				}

				if (targetPosition.y < deadZone.Top())
				{
					m_Offset.y -= deadZone.Top() - targetPosition.y;
				}
				else if (targetPosition.y > deadZone.Bottom())
				{
					m_Offset.y += targetPosition.y - deadZone.Bottom();
				}

				//limits
				if (m_Offset.x > m_Limits.Right() - static_cast<int>(winSize.x))
				{
					m_Offset.x = m_Limits.Right() - static_cast<int>(winSize.x);
				}

				if (m_Offset.x < m_Limits.Left())
				{
					m_Offset.x = m_Limits.Left();
				}

				if (m_Offset.y > m_Limits.Bottom() - static_cast<int>(winSize.y))
				{
					m_Offset.y = m_Limits.Bottom() - static_cast<int>(winSize.y);
				}

				if (m_Offset.y < m_Limits.Top())
				{
					m_Offset.y = m_Limits.Top();
				}
			}
		}
	}

	void Camera2DTargetedComponent::ComputeViewMatrix()
	{
		m_ViewMatrix = Matrix4::CreateTranslation(-m_Offset.x, -m_Offset.y, -50.0f);
	}

	void Camera2DTargetedComponent::SetTargetedEntity(BaseEntity* pTargetedEntity)
	{
		m_pTargetedEntity = pTargetedEntity;
	}

	void Camera2DTargetedComponent::SetDeadZoneRatio(Vector2 deadZoneRatio)
	{
		m_DeadZoneRatio = deadZoneRatio;
	}

	Vector2I Camera2DTargetedComponent::GetOffset() const
	{
		return m_Offset;
	}

	void Camera2DTargetedComponent::SetOffset(Vector2I offset)
	{
		m_Offset = offset;
	}

	RectangleI Camera2DTargetedComponent::GetLimits() const
	{
		return m_Limits;
	}

	void Camera2DTargetedComponent::SetLimits(RectangleI limits)
	{
		m_Limits = limits;
	}
}
<commit_msg>fix Camera2DTargetedComponent<commit_after>#include "Camera2DTargetedComponent.h"

#include "Entities/Components/Transform3DComponent.h"
#include "Entities/ComponentTypeEnum.h"
#include "Game/Game.h"

namespace CasaEngine
{
	Camera2DTargetedComponent::Camera2DTargetedComponent(BaseEntity *entity) :
		Camera2DComponent(entity, CAMERA_2D_TARGETED),
		m_pTargetedEntity(nullptr)
	{
	}

	void Camera2DTargetedComponent::Update(const GameTime& gameTime_)
	{
		if (m_pTargetedEntity != nullptr)
		{
			auto viewport = GetViewport();
			const auto winSize = Game::Instance().GetWindowSize();
			auto* const transform_3d_component = m_pTargetedEntity->GetComponentMgr()->GetComponent<Transform3DComponent>();
			CA_ASSERT(transform_3d_component != nullptr, "cameracomponent : the target need to have a Transform3DComponent");
			const auto targetPosition = transform_3d_component->GetPosition();

			const Rectangle deadZone(m_Offset.x + static_cast<float>(winSize.x) * (1.0f - m_DeadZoneRatio.x) / 2.0f,
				m_Offset.y + static_cast<float>(winSize.y) * (1.0f - m_DeadZoneRatio.y) / 2.0f,
				winSize.x * m_DeadZoneRatio.x,
				winSize.y * m_DeadZoneRatio.y);

			if (deadZone.Intersects(Vector2(targetPosition.x, targetPosition.y)) == INT_OUT)
			{
				m_needToComputeViewMatrix = true;

				if (targetPosition.x < deadZone.Left())
				{
					m_Offset.x -= deadZone.Left() - targetPosition.x;
				}
				else if (targetPosition.x > deadZone.Right())
				{
					m_Offset.x += targetPosition.x - deadZone.Right();
				}

				if (targetPosition.y < deadZone.Top())
				{
					m_Offset.y -= deadZone.Top() - targetPosition.y;
				}
				else if (targetPosition.y > deadZone.Bottom())
				{
					m_Offset.y += targetPosition.y - deadZone.Bottom();
				}

				//limits
				if (m_Offset.x > m_Limits.Right() - static_cast<int>(winSize.x))
				{
					m_Offset.x = m_Limits.Right() - static_cast<int>(winSize.x);
				}

				if (m_Offset.x < m_Limits.Left())
				{
					m_Offset.x = m_Limits.Left();
				}

				if (m_Offset.y > m_Limits.Bottom() - static_cast<int>(winSize.y))
				{
					m_Offset.y = m_Limits.Bottom() - static_cast<int>(winSize.y);
				}

				if (m_Offset.y < m_Limits.Top())
				{
					m_Offset.y = m_Limits.Top();
				}
			}
		}
	}

	void Camera2DTargetedComponent::ComputeViewMatrix()
	{
		m_ViewMatrix = Matrix4::CreateTranslation(-m_Offset.x, -m_Offset.y, -50.0f);
	}

	void Camera2DTargetedComponent::SetTargetedEntity(BaseEntity* pTargetedEntity)
	{
		m_pTargetedEntity = pTargetedEntity;
	}

	void Camera2DTargetedComponent::SetDeadZoneRatio(Vector2 deadZoneRatio)
	{
		m_DeadZoneRatio = deadZoneRatio;
	}

	Vector2I Camera2DTargetedComponent::GetOffset() const
	{
		return m_Offset;
	}

	void Camera2DTargetedComponent::SetOffset(Vector2I offset)
	{
		m_Offset = offset;
	}

	RectangleI Camera2DTargetedComponent::GetLimits() const
	{
		return m_Limits;
	}

	void Camera2DTargetedComponent::SetLimits(RectangleI limits)
	{
		m_Limits = limits;
	}
}
<|endoftext|>


<commit_before>/*
* Reader of /dev/random and company
* (C) 1999-2009,2013 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/

#include <botan/internal/dev_random.h>

#include <sys/types.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>

namespace Botan {

namespace {

int open_nonblocking(const char* pathname)
   {
#ifndef O_NONBLOCK
  #define O_NONBLOCK 0
#endif

#ifndef O_NOCTTY
  #define O_NOCTTY 0
#endif

   const int flags = O_RDONLY | O_NONBLOCK | O_NOCTTY;
   return ::open(pathname, flags);
   }

}

/**
Device_EntropySource constructor
Open a file descriptor to each (available) device in fsnames
*/
Device_EntropySource::Device_EntropySource(const std::vector<std::string>& fsnames)
   {
   for(size_t i = 0; i != fsnames.size(); ++i)
      {
      fd_type fd = open_nonblocking(fsnames[i].c_str());
      if(fd >= 0 && fd < FD_SETSIZE)
         devices.push_back(fd);
      }
   }

/**
Device_EntropySource destructor: close all open devices
*/
Device_EntropySource::~Device_EntropySource()
   {
   for(size_t i = 0; i != devices.size(); ++i)
      ::close(devices[i]);
   }

/**
* Gather entropy from a RNG device
*/
void Device_EntropySource::poll(Entropy_Accumulator& accum)
   {
   if(devices.empty())
      return;

   const size_t ENTROPY_BITS_PER_BYTE = 8;
   const size_t MS_WAIT_TIME = 32;
   const size_t READ_ATTEMPT = accum.desired_remaining_bits() / 4;

   secure_vector<byte>& io_buffer = accum.get_io_buffer(READ_ATTEMPT);

   int max_fd = devices[0];
   fd_set read_set;
   FD_ZERO(&read_set);
   for(size_t i = 0; i != devices.size(); ++i)
      {
      FD_SET(devices[i], &read_set);
      max_fd = std::max(devices[i], max_fd);
      }

   struct ::timeval timeout;

   timeout.tv_sec = (MS_WAIT_TIME / 1000);
   timeout.tv_usec = (MS_WAIT_TIME % 1000) * 1000;

   if(::select(max_fd + 1, &read_set, 0, 0, &timeout) < 0)
      return;

   for(size_t i = 0; i != devices.size(); ++i)
      {
      if(FD_ISSET(devices[i], &read_set))
         {
         const ssize_t got = ::read(devices[i], &io_buffer[0], io_buffer.size());
         accum.add(&io_buffer[0], got, ENTROPY_BITS_PER_BYTE);
         }
      }
   }

}
<commit_msg>Simplify device opening, and avoid leaking a file descriptor if it was too large to fit in an fd_set.<commit_after>/*
* Reader of /dev/random and company
* (C) 1999-2009,2013 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/

#include <botan/internal/dev_random.h>
#include <botan/internal/rounding.h>

#include <sys/types.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>

namespace Botan {

/**
Device_EntropySource constructor
Open a file descriptor to each (available) device in fsnames
*/
Device_EntropySource::Device_EntropySource(const std::vector<std::string>& fsnames)
   {
#ifndef O_NONBLOCK
  #define O_NONBLOCK 0
#endif

#ifndef O_NOCTTY
  #define O_NOCTTY 0
#endif

   const int flags = O_RDONLY | O_NONBLOCK | O_NOCTTY;

   for(auto fsname : fsnames)
      {
      fd_type fd = ::open(fsname.c_str(), flags);

      if(fd >= 0 && fd < FD_SETSIZE)
         devices.push_back(fd);
      else if(fd >= 0)
         ::close(fd);
      }
   }

/**
Device_EntropySource destructor: close all open devices
*/
Device_EntropySource::~Device_EntropySource()
   {
   for(size_t i = 0; i != devices.size(); ++i)
      ::close(devices[i]);
   }

/**
* Gather entropy from a RNG device
*/
void Device_EntropySource::poll(Entropy_Accumulator& accum)
   {
   if(devices.empty())
      return;

   const size_t ENTROPY_BITS_PER_BYTE = 8;
   const size_t MS_WAIT_TIME = 32;
   const size_t READ_ATTEMPT = std::min<size_t>(accum.desired_remaining_bits() / 8, 16);

   int max_fd = devices[0];
   fd_set read_set;
   FD_ZERO(&read_set);
   for(size_t i = 0; i != devices.size(); ++i)
      {
      FD_SET(devices[i], &read_set);
      max_fd = std::max(devices[i], max_fd);
      }

   struct ::timeval timeout;

   timeout.tv_sec = (MS_WAIT_TIME / 1000);
   timeout.tv_usec = (MS_WAIT_TIME % 1000) * 1000;

   if(::select(max_fd + 1, &read_set, 0, 0, &timeout) < 0)
      return;

   secure_vector<byte>& io_buffer = accum.get_io_buffer(READ_ATTEMPT);

   for(size_t i = 0; i != devices.size(); ++i)
      {
      if(FD_ISSET(devices[i], &read_set))
         {
         const ssize_t got = ::read(devices[i], &io_buffer[0], io_buffer.size());
         accum.add(&io_buffer[0], got, ENTROPY_BITS_PER_BYTE);
         }
      }
   }

}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012-2016 Daniele Bartolini and individual contributors.
 * License: https://github.com/taylor001/crown/blob/master/LICENSE
 */

#include "path.h"
#include <ctype.h> // isalpha
#include <string.h> // strlen, strrchr

namespace crown
{
namespace path
{
	bool is_absolute(const char* path)
	{
		CE_ASSERT(path != NULL, "Path must be != NULL");
#if CROWN_PLATFORM_POSIX
		return strlen32(path) > 0 && path[0] == PATH_SEPARATOR;
#elif CROWN_PLATFORM_WINDOWS
		return strlen32(path) > 2 && isalpha(path[0]) && path[1] == ':' && path[2] == PATH_SEPARATOR;
#endif
	}

	bool is_root(const char* path)
	{
		CE_ASSERT(path != NULL, "Path must be != NULL");
#if CROWN_PLATFORM_POSIX
		return is_absolute(path) && strlen32(path) == 1;
#elif CROWN_PLATFORM_WINDOWS
		return is_absolute(path) && strlen32(path) == 3;
#endif
	}

	void join(const char* a, const char* b, DynamicString& path)
	{
		const u32 la = strlen32(a);
		const u32 lb = strlen32(b);
		path.reserve(la + lb + 1);
		path += a;
		path += PATH_SEPARATOR;
		path += b;
	}

	const char* basename(const char* path)
	{
		const char* ls = strrchr(path, '/');
		return ls == NULL ? path : ls + 1;
	}

	const char* extension(const char* path)
	{
		const char* ld = strrchr(path, '.');
		return ld == NULL ? NULL : ld + 1;
	}
} // namespace path
} // namespace crown
<commit_msg>Cleanup<commit_after>/*
 * Copyright (c) 2012-2016 Daniele Bartolini and individual contributors.
 * License: https://github.com/taylor001/crown/blob/master/LICENSE
 */

#include "path.h"
#include <ctype.h> // isalpha
#include <string.h> // strlen, strrchr

namespace crown
{
namespace path
{
	bool is_absolute(const char* path)
	{
		CE_ASSERT(path != NULL, "Path must be != NULL");
#if CROWN_PLATFORM_POSIX
		return strlen32(path) > 0
			&& path[0] == PATH_SEPARATOR
			;
#elif CROWN_PLATFORM_WINDOWS
		return strlen32(path) > 2
			&& isalpha(path[0])
			&& path[1] == ':'
			&& path[2] == PATH_SEPARATOR
			;
#endif
	}

	bool is_root(const char* path)
	{
		CE_ASSERT(path != NULL, "Path must be != NULL");
#if CROWN_PLATFORM_POSIX
		return is_absolute(path) && strlen32(path) == 1;
#elif CROWN_PLATFORM_WINDOWS
		return is_absolute(path) && strlen32(path) == 3;
#endif
	}

	void join(const char* a, const char* b, DynamicString& path)
	{
		const u32 la = strlen32(a);
		const u32 lb = strlen32(b);
		path.reserve(la + lb + 1);
		path += a;
		path += PATH_SEPARATOR;
		path += b;
	}

	const char* basename(const char* path)
	{
		const char* ls = strrchr(path, '/');
		return ls == NULL ? path : ls + 1;
	}

	const char* extension(const char* path)
	{
		const char* ld = strrchr(path, '.');
		return ld == NULL ? NULL : ld + 1;
	}
} // namespace path
} // namespace crown
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999-2000 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.7  2002/11/12 17:27:49  tng
 * DOM Message: add new domain for DOM Messages.
 *
 * Revision 1.6  2002/11/04 22:24:43  peiyongz
 * Locale setting for message loader
 *
 * Revision 1.5  2002/11/04 15:10:40  tng
 * C++ Namespace Support.
 *
 * Revision 1.4  2002/10/10 21:07:55  peiyongz
 * load resource files using environement vars and base name
 *
 * Revision 1.3  2002/10/02 17:08:50  peiyongz
 * XMLString::equals() to replace XMLString::compareString()
 *
 * Revision 1.2  2002/09/30 22:20:40  peiyongz
 * Build with ICU MsgLoader
 *
 * Revision 1.1.1.1  2002/02/01 22:22:19  peiyongz
 * sane_include
 *
 * Revision 1.7  2002/01/21 14:52:25  tng
 * [Bug 5847] ICUMsgLoader can't be compiled with gcc 3.0.3 and ICU2.  And also fix the memory leak introduced by Bug 2730 fix.
 *
 * Revision 1.6  2001/11/01 23:39:18  jasons
 * 2001-11-01  Jason E. Stewart  <jason@openinformatics.com>
 *
 * 	* src/util/MsgLoaders/ICU/ICUMsgLoader.hpp (Repository):
 * 	* src/util/MsgLoaders/ICU/ICUMsgLoader.cpp (Repository):
 * 	Updated to compile with ICU-1.8.1
 *
 * Revision 1.5  2000/03/02 19:55:14  roddey
 * This checkin includes many changes done while waiting for the
 * 1.1.0 code to be finished. I can't list them all here, but a list is
 * available elsewhere.
 *
 * Revision 1.4  2000/02/06 07:48:21  rahulj
 * Year 2K copyright swat.
 *
 * Revision 1.3  2000/01/19 00:58:38  roddey
 * Update to support new ICU 1.4 release.
 *
 * Revision 1.2  1999/11/19 21:24:03  aruna1
 * incorporated ICU 1.3.1 related changes int he file
 *
 * Revision 1.1.1.1  1999/11/09 01:07:23  twl
 * Initial checkin
 *
 * Revision 1.4  1999/11/08 20:45:26  rahul
 * Swat for adding in Product name and CVS comment log variable.
 *
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/XercesDefs.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/XMLMsgLoader.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/XMLUniDefs.hpp>
#include <xercesc/util/Janitor.hpp>
#include "ICUMsgLoader.hpp"

#include "string.h"
#include <stdio.h>
#include <stdlib.h>

XERCES_CPP_NAMESPACE_BEGIN

// ---------------------------------------------------------------------------
//  Local static methods
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
//  Public Constructors and Destructor
// ---------------------------------------------------------------------------
ICUMsgLoader::ICUMsgLoader(const XMLCh* const  msgDomain)
:fLocaleBundle(0)
,fDomainBundle(0)
{
    /***
	    Validate msgDomain
    ***/
    if (!XMLString::equals(msgDomain, XMLUni::fgXMLErrDomain)    &&
        !XMLString::equals(msgDomain, XMLUni::fgExceptDomain)    &&
        !XMLString::equals(msgDomain, XMLUni::fgXMLDOMMsgDomain)    &&
        !XMLString::equals(msgDomain, XMLUni::fgValidityDomain)   )
    {
        XMLPlatformUtils::panic(XMLPlatformUtils::Panic_UnknownMsgDomain);
    }

	/***
	     Resolve domainName
	***/
	int          index = XMLString::lastIndexOf(msgDomain, chForwardSlash);
	char*   domainName = XMLString::transcode(&(msgDomain[index + 1]));
    ArrayJanitor<char> jan1(domainName);

    /***
	     Resolve location

	     REVISIT: another approach would be: through some system API
		          which returns the directory of the XercescLib and
		          that directory would be used to locate the
		 		  resource bundle
    ***/
    char locationBuf[1024];
    memset(locationBuf, 0, sizeof locationBuf);
	char *nlsHome = getenv("XERCESC_NLS_HOME");

    if (nlsHome)
	{
		strcpy(locationBuf, nlsHome);
        strcat(locationBuf, U_FILE_SEP_STRING);
	}

    strcat(locationBuf, "XercescErrMsg");

	/***
	    Open the locale-specific resource bundle
	***/
    UErrorCode err = U_ZERO_ERROR;
    fLocaleBundle = ures_open(locationBuf, XMLMsgLoader::getLocale(), &err);
    if (!U_SUCCESS(err) || fLocaleBundle == NULL)
    {
         XMLPlatformUtils::panic(XMLPlatformUtils::Panic_CantLoadMsgDomain);
    }

	/***
	    Open the domain specific resource bundle within
		the locale-specific resource bundle
	***/
	err = U_ZERO_ERROR;
	fDomainBundle = ures_getByKey(fLocaleBundle, domainName, NULL, &err);

	if (!U_SUCCESS(err) || fDomainBundle == NULL)
	{
         XMLPlatformUtils::panic(XMLPlatformUtils::Panic_CantLoadMsgDomain);
	}

}

ICUMsgLoader::~ICUMsgLoader()
{
    ures_close(fDomainBundle);
    ures_close(fLocaleBundle);
}

// ---------------------------------------------------------------------------
//  Implementation of the virtual message loader API
// ---------------------------------------------------------------------------
bool ICUMsgLoader::loadMsg( const   XMLMsgLoader::XMLMsgId  msgToLoad
                          ,         XMLCh* const            toFill
                          , const   unsigned int            maxChars)
{
    UErrorCode   err = U_ZERO_ERROR;
    int32_t      strLen = 0;

    // Assuming array format
    const UChar *name = ures_getStringByIndex(fDomainBundle, (int32_t)msgToLoad-1, &strLen, &err);

    if (!U_SUCCESS(err) || (name == NULL))
    {
        return false;
    }

    int retStrLen = strLen > maxChars ? maxChars : strLen;

    if (sizeof(UChar)==sizeof(XMLCh))
    {
        XMLString::moveChars(toFill, (XMLCh*)name, retStrLen);
        toFill[retStrLen] = (XMLCh) 0;
    }
    else
    {
        XMLCh* retStr = toFill;
        const UChar *srcPtr = name;

        while (retStrLen--)
           *retStr++ = *srcPtr++;

        *retStr = 0;
    }

    return true;
}

bool ICUMsgLoader::loadMsg( const   XMLMsgLoader::XMLMsgId  msgToLoad
                            ,       XMLCh* const            toFill
                            , const unsigned int           maxChars
                            , const XMLCh* const            repText1
                            , const XMLCh* const            repText2
                            , const XMLCh* const            repText3
                            , const XMLCh* const            repText4)
{
    // Call the other version to load up the message
    if (!loadMsg(msgToLoad, toFill, maxChars))
        return false;

    // And do the token replacement
    XMLString::replaceTokens(toFill, maxChars, repText1, repText2, repText3, repText4);
    return true;
}

bool ICUMsgLoader::loadMsg( const   XMLMsgLoader::XMLMsgId  msgToLoad
                            ,       XMLCh* const            toFill
                            , const unsigned int           maxChars
                            , const char* const             repText1
                            , const char* const             repText2
                            , const char* const             repText3
                            , const char* const             repText4)
{
    //
    //  Transcode the provided parameters and call the other version,
    //  which will do the replacement work.
    //
    XMLCh* tmp1 = 0;
    XMLCh* tmp2 = 0;
    XMLCh* tmp3 = 0;
    XMLCh* tmp4 = 0;

    bool bRet = false;
    if (repText1)
        tmp1 = XMLString::transcode(repText1);
    if (repText2)
        tmp2 = XMLString::transcode(repText2);
    if (repText3)
        tmp3 = XMLString::transcode(repText3);
    if (repText4)
        tmp4 = XMLString::transcode(repText4);

    bRet = loadMsg(msgToLoad, toFill, maxChars, tmp1, tmp2, tmp3, tmp4);

    if (tmp1)
        delete [] tmp1;
    if (tmp2)
        delete [] tmp2;
    if (tmp3)
        delete [] tmp3;
    if (tmp4)
        delete [] tmp4;

    return bRet;
}

XERCES_CPP_NAMESPACE_END
<commit_msg>fix to warning C4018: '>' : signed/unsigned mismatch<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999-2000 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.8  2002/11/20 20:28:17  peiyongz
 * fix to warning C4018: '>' : signed/unsigned mismatch
 *
 * Revision 1.7  2002/11/12 17:27:49  tng
 * DOM Message: add new domain for DOM Messages.
 *
 * Revision 1.6  2002/11/04 22:24:43  peiyongz
 * Locale setting for message loader
 *
 * Revision 1.5  2002/11/04 15:10:40  tng
 * C++ Namespace Support.
 *
 * Revision 1.4  2002/10/10 21:07:55  peiyongz
 * load resource files using environement vars and base name
 *
 * Revision 1.3  2002/10/02 17:08:50  peiyongz
 * XMLString::equals() to replace XMLString::compareString()
 *
 * Revision 1.2  2002/09/30 22:20:40  peiyongz
 * Build with ICU MsgLoader
 *
 * Revision 1.1.1.1  2002/02/01 22:22:19  peiyongz
 * sane_include
 *
 * Revision 1.7  2002/01/21 14:52:25  tng
 * [Bug 5847] ICUMsgLoader can't be compiled with gcc 3.0.3 and ICU2.  And also fix the memory leak introduced by Bug 2730 fix.
 *
 * Revision 1.6  2001/11/01 23:39:18  jasons
 * 2001-11-01  Jason E. Stewart  <jason@openinformatics.com>
 *
 * 	* src/util/MsgLoaders/ICU/ICUMsgLoader.hpp (Repository):
 * 	* src/util/MsgLoaders/ICU/ICUMsgLoader.cpp (Repository):
 * 	Updated to compile with ICU-1.8.1
 *
 * Revision 1.5  2000/03/02 19:55:14  roddey
 * This checkin includes many changes done while waiting for the
 * 1.1.0 code to be finished. I can't list them all here, but a list is
 * available elsewhere.
 *
 * Revision 1.4  2000/02/06 07:48:21  rahulj
 * Year 2K copyright swat.
 *
 * Revision 1.3  2000/01/19 00:58:38  roddey
 * Update to support new ICU 1.4 release.
 *
 * Revision 1.2  1999/11/19 21:24:03  aruna1
 * incorporated ICU 1.3.1 related changes int he file
 *
 * Revision 1.1.1.1  1999/11/09 01:07:23  twl
 * Initial checkin
 *
 * Revision 1.4  1999/11/08 20:45:26  rahul
 * Swat for adding in Product name and CVS comment log variable.
 *
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/XercesDefs.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/XMLMsgLoader.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/XMLUniDefs.hpp>
#include <xercesc/util/Janitor.hpp>
#include "ICUMsgLoader.hpp"

#include "string.h"
#include <stdio.h>
#include <stdlib.h>

XERCES_CPP_NAMESPACE_BEGIN

// ---------------------------------------------------------------------------
//  Local static methods
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
//  Public Constructors and Destructor
// ---------------------------------------------------------------------------
ICUMsgLoader::ICUMsgLoader(const XMLCh* const  msgDomain)
:fLocaleBundle(0)
,fDomainBundle(0)
{
    /***
	    Validate msgDomain
    ***/
    if (!XMLString::equals(msgDomain, XMLUni::fgXMLErrDomain)    &&
        !XMLString::equals(msgDomain, XMLUni::fgExceptDomain)    &&
        !XMLString::equals(msgDomain, XMLUni::fgXMLDOMMsgDomain)    &&
        !XMLString::equals(msgDomain, XMLUni::fgValidityDomain)   )
    {
        XMLPlatformUtils::panic(XMLPlatformUtils::Panic_UnknownMsgDomain);
    }

	/***
	     Resolve domainName
	***/
	int          index = XMLString::lastIndexOf(msgDomain, chForwardSlash);
	char*   domainName = XMLString::transcode(&(msgDomain[index + 1]));
    ArrayJanitor<char> jan1(domainName);

    /***
	     Resolve location

	     REVISIT: another approach would be: through some system API
		          which returns the directory of the XercescLib and
		          that directory would be used to locate the
		 		  resource bundle
    ***/
    char locationBuf[1024];
    memset(locationBuf, 0, sizeof locationBuf);
	char *nlsHome = getenv("XERCESC_NLS_HOME");

    if (nlsHome)
	{
		strcpy(locationBuf, nlsHome);
        strcat(locationBuf, U_FILE_SEP_STRING);
	}

    strcat(locationBuf, "XercescErrMsg");

	/***
	    Open the locale-specific resource bundle
	***/
    UErrorCode err = U_ZERO_ERROR;
    fLocaleBundle = ures_open(locationBuf, XMLMsgLoader::getLocale(), &err);
    if (!U_SUCCESS(err) || fLocaleBundle == NULL)
    {
         XMLPlatformUtils::panic(XMLPlatformUtils::Panic_CantLoadMsgDomain);
    }

	/***
	    Open the domain specific resource bundle within
		the locale-specific resource bundle
	***/
	err = U_ZERO_ERROR;
	fDomainBundle = ures_getByKey(fLocaleBundle, domainName, NULL, &err);

	if (!U_SUCCESS(err) || fDomainBundle == NULL)
	{
         XMLPlatformUtils::panic(XMLPlatformUtils::Panic_CantLoadMsgDomain);
	}

}

ICUMsgLoader::~ICUMsgLoader()
{
    ures_close(fDomainBundle);
    ures_close(fLocaleBundle);
}

// ---------------------------------------------------------------------------
//  Implementation of the virtual message loader API
// ---------------------------------------------------------------------------
bool ICUMsgLoader::loadMsg( const   XMLMsgLoader::XMLMsgId  msgToLoad
                          ,         XMLCh* const            toFill
                          , const   unsigned int            maxChars)
{
    UErrorCode   err = U_ZERO_ERROR;
    int32_t      strLen = 0;

    // Assuming array format
    const UChar *name = ures_getStringByIndex(fDomainBundle, (int32_t)msgToLoad-1, &strLen, &err);

    if (!U_SUCCESS(err) || (name == NULL))
    {
        return false;
    }

    int retStrLen = strLen > (int32_t)maxChars ? maxChars : strLen;

    if (sizeof(UChar)==sizeof(XMLCh))
    {
        XMLString::moveChars(toFill, (XMLCh*)name, retStrLen);
        toFill[retStrLen] = (XMLCh) 0;
    }
    else
    {
        XMLCh* retStr = toFill;
        const UChar *srcPtr = name;

        while (retStrLen--)
           *retStr++ = *srcPtr++;

        *retStr = 0;
    }

    return true;
}

bool ICUMsgLoader::loadMsg( const   XMLMsgLoader::XMLMsgId  msgToLoad
                            ,       XMLCh* const            toFill
                            , const unsigned int           maxChars
                            , const XMLCh* const            repText1
                            , const XMLCh* const            repText2
                            , const XMLCh* const            repText3
                            , const XMLCh* const            repText4)
{
    // Call the other version to load up the message
    if (!loadMsg(msgToLoad, toFill, maxChars))
        return false;

    // And do the token replacement
    XMLString::replaceTokens(toFill, maxChars, repText1, repText2, repText3, repText4);
    return true;
}

bool ICUMsgLoader::loadMsg( const   XMLMsgLoader::XMLMsgId  msgToLoad
                            ,       XMLCh* const            toFill
                            , const unsigned int           maxChars
                            , const char* const             repText1
                            , const char* const             repText2
                            , const char* const             repText3
                            , const char* const             repText4)
{
    //
    //  Transcode the provided parameters and call the other version,
    //  which will do the replacement work.
    //
    XMLCh* tmp1 = 0;
    XMLCh* tmp2 = 0;
    XMLCh* tmp3 = 0;
    XMLCh* tmp4 = 0;

    bool bRet = false;
    if (repText1)
        tmp1 = XMLString::transcode(repText1);
    if (repText2)
        tmp2 = XMLString::transcode(repText2);
    if (repText3)
        tmp3 = XMLString::transcode(repText3);
    if (repText4)
        tmp4 = XMLString::transcode(repText4);

    bRet = loadMsg(msgToLoad, toFill, maxChars, tmp1, tmp2, tmp3, tmp4);

    if (tmp1)
        delete [] tmp1;
    if (tmp2)
        delete [] tmp2;
    if (tmp3)
        delete [] tmp3;
    if (tmp4)
        delete [] tmp4;

    return bRet;
}

XERCES_CPP_NAMESPACE_END
<|endoftext|>


<commit_before>/******************************************************************************

  nomlib - C++11 cross-platform game engine

Copyright (c) 2013, Jeffrey Carpenter <jeffrey.carp@gmail.com>
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.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

******************************************************************************/

#include <iostream>
#include <string>

#include <nomlib/graphics.hpp>
#include <nomlib/gui.hpp>
#include <nomlib/system.hpp>

/// File path name of the resources directory; this must be a relative file path.
const std::string APP_RESOURCES_DIR = "Resources";

const nom::Path p;
const std::string RESOURCE_ICON = APP_RESOURCES_DIR + p.native() + "icon.png";
const std::string RESOURCE_BITMAP_FONT = APP_RESOURCES_DIR + p.native() + "VIII.png";
const std::string RESOURCE_BITMAP_SMALL_FONT = APP_RESOURCES_DIR + p.native() + "VIII_small.png";
const std::string RESOURCE_TRUETYPE_FONT = APP_RESOURCES_DIR + p.native() + "arial.ttf";

/// Name of our application.
const std::string APP_NAME = "nom::BitmapFont";

/// Width, in pixels, of our effective rendering surface.
const nom::int32 WINDOW_WIDTH = 768;

/// Height, in pixels, of our effective rendering surface.
const nom::int32 WINDOW_HEIGHT = 448;

/// Relative filename path to saved screenshot example
///
/// Default path should resolve to the same directory as the app example
/// executable
const std::string OUTPUT_SCREENSHOT_FILENAME = "screenshot.png";

//const std::string RESOURCE_FONT_TEXT_STRING = "!"#$%&'()*+,-.//0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
const std::string RESOURCE_FONT_TEXT_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZ\nabcdefghijklmnopqrstuvwxyz\n0123456789\n...\n,'[]()/\\n";

/// \brief nom::BitmapFont usage example
class App: public nom::SDL_App
{
  public:
    App ( nom::int32 argc, char* argv[] )
    {
      NOM_LOG_TRACE ( NOM );

      // Fatal error; if we are not able to complete this step, it means that
      // we probably cannot rely on our resource paths!
      if ( nom::nomlib_init ( argc, argv ) == false )
      {
        nom::DialogMessageBox ( APP_NAME, "Could not initialize nomlib." );
        exit ( NOM_EXIT_FAILURE );
      }
    } // App

    ~App ( void )
    {
      NOM_LOG_TRACE ( NOM );
    } // ~App

    bool onInit ( void )
    {
      nom::uint32 window_flags = 0; //SDL_WINDOW_RESIZABLE
      if ( nom::set_hint ( SDL_HINT_RENDER_VSYNC, "0" ) == false )
      {
NOM_LOG_INFO ( NOM, "Could not disable vertical refresh." );
      }
/*
      if ( nom::set_hint ( SDL_HINT_RENDER_SCALE_QUALITY, "Nearest" ) == false )
      {
        NOM_LOG_INFO ( NOM, "Could not set scale quality." );
      }
*/
      if ( this->window.create ( APP_NAME, WINDOW_WIDTH, WINDOW_HEIGHT, window_flags ) == false )
      {
        return false;
      }
      this->window_size = this->window.size();

      if ( this->window.set_window_icon ( RESOURCE_ICON ) == false )
      {
        nom::DialogMessageBox ( APP_NAME, "Could not load window icon: " + RESOURCE_ICON );
        return false;
      }

      if ( this->bitmap_font.load ( RESOURCE_BITMAP_FONT, NOM_COLOR4U_MAGENTA ) == false )
      {
        nom::DialogMessageBox ( APP_NAME, "Could not load BitmapFont: " + RESOURCE_BITMAP_FONT );
        return false;
      }

      if ( this->bitmap_small_font.load ( RESOURCE_BITMAP_SMALL_FONT, NOM_COLOR4U_MAGENTA ) == false )
      {
        nom::DialogMessageBox ( APP_NAME, "Could not load BitmapFont: " + RESOURCE_BITMAP_SMALL_FONT );
        return false;
      }

      if ( this->truetype_font.load ( RESOURCE_TRUETYPE_FONT, NOM_COLOR4U_WHITE ) == false )
      {
        nom::DialogMessageBox ( APP_NAME, "Could not load TrueTypeFont: " + RESOURCE_TRUETYPE_FONT );
        return false;
      }

/*
      this->truetype_font.setFontSize ( 18 );
      this->truetype_font.setRenderingStyle ( nom::IFont::RenderStyle::Blended );
      this->truetype_font.setColor ( NOM_COLOR4U_WHITE );
      this->truetype_font.setText ( "Use arrow keys to change cursor!" );
      this->truetype_font.setPosition ( nom::Coords ( ( window_size.x - 200 ) / 2, window_size.y - 100 ) );
*/

NOM_DUMP_VAR(this->label.type());
NOM_DUMP_VAR(this->label_title.type());
      this->label.set_font ( this->bitmap_font );
      this->label_title.set_font ( this->bitmap_small_font );

      this->label.set_position  ( ( this->window_size.x - this->label.width() ) / 2,
                                  ( this->window_size.y - this->label.height() ) / 2
                                );

      this->label_title.set_position  ( ( this->window_size.x - this->label_title.width() ) / 2,
                                        ( this->window_size.y - this->label_title.height() ) / 8
                                      );

      this->label.set_text ( RESOURCE_FONT_TEXT_STRING );
      //this->label_title.set_text ( "INFO" );
      this->label.set_color ( NOM_COLOR4U_WHITE );
      this->label_title.set_color ( NOM_COLOR4U_RED );
      //this->label.set_style ( nom::Label::FontStyle::Faded );
      this->label.set_alignment ( nom::Label::TextAlignment::MiddleCenter );
      //this->label_title.set_alignment ( nom::Label::TextAlignment::MiddleLeft );
NOM_DUMP_VAR(this->label.type());
NOM_DUMP_VAR(this->label_title.type());

      return true;
    } // onInit

    nom::int32 Run ( void )
    {
      this->update.start();
      this->fps.start();

      // 1. Events
      // 2. Logic
      // 3. Render
      while ( this->running() == true )
      {
        while ( this->PollEvents ( &this->event ) )
        {
          this->onEvent ( &this->event );
        }

        this->window.update();
        this->fps.update();

        // Refresh the frames per second at 1 second intervals
        if ( this->update.ticks() > 1000 )
        {
          if ( this->show_fps() == true )
          {
            this->window.set_window_title ( APP_NAME + " - " + this->fps.asString() + ' ' + "fps" );
          }
          else
          {
            this->window.set_window_title ( APP_NAME + " [" + std::to_string(this->window.window_id()) + "]" + " - " + "Display" + ' ' + std::to_string ( this->window.window_display_id() ) );
          }

          this->update.restart();
        } // end refresh cycle

        this->window.fill ( NOM_COLOR4U_PRIMARY_COLORKEY );

        this->label.draw ( this->window );
        this->label_title.draw ( this->window );
      } // end while SDL_App::running() is true

      return NOM_EXIT_SUCCESS;
    } // Run

  private:
    /// Event handler for key down actions
    ///
    /// Re-implements nom::Input::onKeyDown()
    void onKeyDown ( nom::int32 key, nom::int32 mod, nom::uint32 window_id )
    {
      switch ( key )
      {
        default: break;

        // Use inherited SDL_App::onQuit() method -- you may also provide your own
        // event handler for this.
        case SDLK_ESCAPE:
        case SDLK_q: this->onQuit(); break;

        case SDLK_BACKSLASH:
        {
          if ( this->toggle_fps() )
          {
            // Stub for doing something cool here
          }
          else
          {
            // Stub for doing something cool here
          }
          break;
        }

        case SDLK_F1:
        {
          if ( this->window.save_screenshot( OUTPUT_SCREENSHOT_FILENAME ) == false )
          {
            nom::DialogMessageBox( APP_NAME,  "Could not save screenshot");
          }
          break;
        }

        case SDLK_f:
        {
          if ( this->window.fullscreen() == true )
          {
            this->window.toggle_fullscreen();
          }
          else if ( this->window.fullscreen() == false )
          {
            this->window.toggle_fullscreen();

            // Scale window contents up by the new width & height
            this->window.set_logical_size ( this->window_size.x, this->window_size.y );
          }
        }
        break;
      } // end switch key
    } // onKeyDown

  private:
    /// Window handle
    nom::Window window;
    nom::Point2i window_size;

    /// Interval at which we refresh the frames per second counter
    nom::Timer update;

    /// Timer for tracking frames per second
    nom::FPS fps;

    /// Input events
    Input::Event event;

    nom::BitmapFont bitmap_font;
    nom::BitmapFont bitmap_small_font;

    nom::TrueTypeFont truetype_font;

    nom::Label label;
    nom::Label label_title;
}; // class App

nom::int32 main ( nom::int32 argc, char* argv[] )
{
  App game ( argc, argv );

  if ( game.onInit() == false )
  {
    nom::DialogMessageBox ( APP_NAME, "Could not initialize application." );
    return NOM_EXIT_FAILURE;
  }

  return game.Run();

  // ...Goodbye cruel world..!
}
<commit_msg>examples/fonts: Disable loading of small bitmap font<commit_after>/******************************************************************************

  nomlib - C++11 cross-platform game engine

Copyright (c) 2013, Jeffrey Carpenter <jeffrey.carp@gmail.com>
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.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

******************************************************************************/

#include <iostream>
#include <string>

#include <nomlib/graphics.hpp>
#include <nomlib/gui.hpp>
#include <nomlib/system.hpp>

/// File path name of the resources directory; this must be a relative file path.
const std::string APP_RESOURCES_DIR = "Resources";

const nom::Path p;
const std::string RESOURCE_ICON = APP_RESOURCES_DIR + p.native() + "icon.png";
const std::string RESOURCE_BITMAP_FONT = APP_RESOURCES_DIR + p.native() + "VIII.png";
const std::string RESOURCE_BITMAP_SMALL_FONT = APP_RESOURCES_DIR + p.native() + "VIII_small.png";
const std::string RESOURCE_TRUETYPE_FONT = APP_RESOURCES_DIR + p.native() + "arial.ttf";

/// Name of our application.
const std::string APP_NAME = "nom::BitmapFont";

/// Width, in pixels, of our effective rendering surface.
const nom::int32 WINDOW_WIDTH = 768;

/// Height, in pixels, of our effective rendering surface.
const nom::int32 WINDOW_HEIGHT = 448;

/// Relative filename path to saved screenshot example
///
/// Default path should resolve to the same directory as the app example
/// executable
const std::string OUTPUT_SCREENSHOT_FILENAME = "screenshot.png";

//const std::string RESOURCE_FONT_TEXT_STRING = "!"#$%&'()*+,-.//0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
const std::string RESOURCE_FONT_TEXT_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZ\nabcdefghijklmnopqrstuvwxyz\n0123456789\n...\n,'[]()/\\n";
//const std::string RESOURCE_FONT_TEXT_STRING = "A";

/// \brief nom::BitmapFont usage example
class App: public nom::SDL_App
{
  public:
    App ( nom::int32 argc, char* argv[] )
    {
      NOM_LOG_TRACE ( NOM );

      // Fatal error; if we are not able to complete this step, it means that
      // we probably cannot rely on our resource paths!
      if ( nom::nomlib_init ( argc, argv ) == false )
      {
        nom::DialogMessageBox ( APP_NAME, "Could not initialize nomlib." );
        exit ( NOM_EXIT_FAILURE );
      }
    } // App

    ~App ( void )
    {
      NOM_LOG_TRACE ( NOM );
    } // ~App

    bool onInit ( void )
    {
      nom::uint32 window_flags = 0; //SDL_WINDOW_RESIZABLE
      if ( nom::set_hint ( SDL_HINT_RENDER_VSYNC, "0" ) == false )
      {
NOM_LOG_INFO ( NOM, "Could not disable vertical refresh." );
      }
/*
      if ( nom::set_hint ( SDL_HINT_RENDER_SCALE_QUALITY, "Nearest" ) == false )
      {
        NOM_LOG_INFO ( NOM, "Could not set scale quality." );
      }
*/
      if ( this->window.create ( APP_NAME, WINDOW_WIDTH, WINDOW_HEIGHT, window_flags ) == false )
      {
        return false;
      }
      this->window_size = this->window.size();

      if ( this->window.set_window_icon ( RESOURCE_ICON ) == false )
      {
        nom::DialogMessageBox ( APP_NAME, "Could not load window icon: " + RESOURCE_ICON );
        return false;
      }

      if ( this->bitmap_font.load ( RESOURCE_BITMAP_FONT, NOM_COLOR4U_MAGENTA ) == false )
      {
        nom::DialogMessageBox ( APP_NAME, "Could not load BitmapFont: " + RESOURCE_BITMAP_FONT );
        return false;
      }
/*
      if ( this->bitmap_small_font.load ( RESOURCE_BITMAP_SMALL_FONT, NOM_COLOR4U_MAGENTA ) == false )
      {
        nom::DialogMessageBox ( APP_NAME, "Could not load BitmapFont: " + RESOURCE_BITMAP_SMALL_FONT );
        return false;
      }
*/
      if ( this->truetype_font.load ( RESOURCE_TRUETYPE_FONT, NOM_COLOR4U_WHITE ) == false )
      {
        nom::DialogMessageBox ( APP_NAME, "Could not load TrueTypeFont: " + RESOURCE_TRUETYPE_FONT );
        return false;
      }

/*
      this->truetype_font.setFontSize ( 18 );
      this->truetype_font.setRenderingStyle ( nom::IFont::RenderStyle::Blended );
      this->truetype_font.setColor ( NOM_COLOR4U_WHITE );
      this->truetype_font.setText ( "Use arrow keys to change cursor!" );
      this->truetype_font.setPosition ( nom::Coords ( ( window_size.x - 200 ) / 2, window_size.y - 100 ) );
*/

NOM_DUMP_VAR(this->label.type());
NOM_DUMP_VAR(this->label_title.type());
      this->label.set_font ( this->bitmap_font );
      //this->label_title.set_font ( this->bitmap_small_font );

      this->label.set_position  ( ( this->window_size.x - this->label.width() ) / 2,
                                  ( this->window_size.y - this->label.height() ) / 2
                                );
/*
      this->label_title.set_position  ( ( this->window_size.x - this->label_title.width() ) / 2,
                                        ( this->window_size.y - this->label_title.height() ) / 8
                                      );
*/
      this->label.set_text ( RESOURCE_FONT_TEXT_STRING );
      //this->label_title.set_text ( "INFO" );
      this->label.set_color ( NOM_COLOR4U_WHITE );
      //this->label_title.set_color ( NOM_COLOR4U_RED );
      //this->label.set_style ( nom::Label::FontStyle::Faded );
      this->label.set_alignment ( nom::Label::TextAlignment::MiddleCenter );
      //this->label_title.set_alignment ( nom::Label::TextAlignment::MiddleLeft );
NOM_DUMP_VAR(this->label.type());
NOM_DUMP_VAR(this->label_title.type());

      return true;
    } // onInit

    nom::int32 Run ( void )
    {
      this->update.start();
      this->fps.start();

      // 1. Events
      // 2. Logic
      // 3. Render
      while ( this->running() == true )
      {
        while ( this->PollEvents ( &this->event ) )
        {
          this->onEvent ( &this->event );
        }

        this->window.update();
        this->fps.update();

        // Refresh the frames per second at 1 second intervals
        if ( this->update.ticks() > 1000 )
        {
          if ( this->show_fps() == true )
          {
            this->window.set_window_title ( APP_NAME + " - " + this->fps.asString() + ' ' + "fps" );
          }
          else
          {
            this->window.set_window_title ( APP_NAME + " [" + std::to_string(this->window.window_id()) + "]" + " - " + "Display" + ' ' + std::to_string ( this->window.window_display_id() ) );
          }

          this->update.restart();
        } // end refresh cycle

        this->window.fill ( NOM_COLOR4U_PRIMARY_COLORKEY );
        this->label.draw ( this->window );

        //this->label_title.draw ( this->window );
      } // end while SDL_App::running() is true

      return NOM_EXIT_SUCCESS;
    } // Run

  private:
    /// Event handler for key down actions
    ///
    /// Re-implements nom::Input::onKeyDown()
    void onKeyDown ( nom::int32 key, nom::int32 mod, nom::uint32 window_id )
    {
      switch ( key )
      {
        default: break;

        // Use inherited SDL_App::onQuit() method -- you may also provide your own
        // event handler for this.
        case SDLK_ESCAPE:
        case SDLK_q: this->onQuit(); break;

        case SDLK_BACKSLASH:
        {
          if ( this->toggle_fps() )
          {
            // Stub for doing something cool here
          }
          else
          {
            // Stub for doing something cool here
          }
          break;
        }

        case SDLK_F1:
        {
          if ( this->window.save_screenshot( OUTPUT_SCREENSHOT_FILENAME ) == false )
          {
            nom::DialogMessageBox( APP_NAME,  "Could not save screenshot");
          }
          break;
        }

        case SDLK_f:
        {
          if ( this->window.fullscreen() == true )
          {
            this->window.toggle_fullscreen();
          }
          else if ( this->window.fullscreen() == false )
          {
            this->window.toggle_fullscreen();

            // Scale window contents up by the new width & height
            this->window.set_logical_size ( this->window_size.x, this->window_size.y );
          }
        }
        break;
      } // end switch key
    } // onKeyDown

  private:
    /// Window handle
    nom::Window window;
    nom::Point2i window_size;

    /// Interval at which we refresh the frames per second counter
    nom::Timer update;

    /// Timer for tracking frames per second
    nom::FPS fps;

    /// Input events
    Input::Event event;

    nom::BitmapFont bitmap_font;
    nom::BitmapFont bitmap_small_font;

    nom::TrueTypeFont truetype_font;

    nom::Label label;
    nom::Label label_title;
}; // class App

nom::int32 main ( nom::int32 argc, char* argv[] )
{
  App game ( argc, argv );

  if ( game.onInit() == false )
  {
    nom::DialogMessageBox ( APP_NAME, "Could not initialize application." );
    return NOM_EXIT_FAILURE;
  }

  return game.Run();

  // ...Goodbye cruel world..!
}
<|endoftext|>