<commit_before>#include <xpcc/architecture/platform.hpp>
#include "../stm32f4_discovery.hpp"

#include <xpcc/processing/timeout.hpp>
#include <xpcc/processing/protothread.hpp>
#include <xpcc/driver/temperature/tmp102.hpp>

#include <xpcc/io/iostream.hpp>

xpcc::IODeviceWrapper<Usart2> device;
xpcc::IOStream stream(device);

// example of a debug transaction, which outputs the wrapped transactions choices.
class CustomI2cTransaction : public xpcc::I2cTransaction
{
	xpcc::I2cTransaction *transaction;

public:
	CustomI2cTransaction()
			:	transaction(nullptr)
	{}

	void
	setTransaction(xpcc::I2cTransaction *transaction)
	{
		this->transaction = transaction;
	}

protected:
	virtual bool
	attaching()
	{
		bool result = transaction->attaching();
		stream << "T: attaching: " << result << xpcc::endl;
		return result;
	}

	virtual Starting
	starting()
	{
		xpcc::I2cTransaction::Starting result = transaction->starting();
		stream << "T: starting: addr=" << result.address << " next=" << (int)result.next << xpcc::endl;
		return result;
	}

	virtual Writing
	writing()
	{
		xpcc::I2cTransaction::Writing result = transaction->writing();
		stream << "T: writing: length=" << result.length << " next=" << (int)result.next << xpcc::endl;
		return result;
	}

	virtual Reading
	reading()
	{
		xpcc::I2cTransaction::Reading result = transaction->reading();
		stream << "T: reading: length=" << result.length << " next=" << (int)result.next << xpcc::endl;
		return result;
	}

	virtual void
	detaching(DetachCause cause)
	{
		transaction->detaching(cause);
		stream << "T: detaching: cause=" << (int)cause << xpcc::endl;
	}
};
static CustomI2cTransaction myTransaction;

// this custom I2c Master wraps the original transaction into the above debug transaction.
class MyI2cMaster2 : public I2cMaster1
{
public:
	static bool
	start(xpcc::I2cTransaction *transaction, xpcc::I2c::Configuration_t configuration = nullptr)
	{
		myTransaction.setTransaction(transaction);
		stream << "st" << xpcc::endl;
		return I2cMaster1::start(&myTransaction, configuration);
	}

	static bool
	startBlocking(xpcc::I2cTransaction *transaction, xpcc::I2c::Configuration_t configuration = nullptr)
	{
		myTransaction.setTransaction(transaction);
		stream << "stBl" << xpcc::endl;
		return I2cMaster1::start(&myTransaction, configuration);
	}
};

typedef I2cMaster1 MyI2cMaster;

struct DeviceConfiguration
{
	// shared memory for both devices as a cheap way
	// to `tag` the current configuration of the peripheral
	// so we do not need to configure it unnecessarily.
	static char tag;

	/// 100kHz I2C configuration
	static void
	standard_configuration()
	{
		if (tag != 's') {
			stream << "config: 20kHz" << xpcc::endl;
			MyI2cMaster::initialize<defaultSystemClock,  20000>();
			tag = 's';
		}
	}

	/// 400kHz I2C configuration
	static void
	fast_configuration()
	{
		if (tag != 'f') {
			stream << "config: 100kHz" << xpcc::endl;
			MyI2cMaster::initialize<defaultSystemClock, 100000>();
			tag = 'f';
		}
	}
};
char DeviceConfiguration::tag = 0;

class ProtofaceTemperatureOne : public xpcc::pt::Protothread
{
public:
	ProtofaceTemperatureOne()
	:	temperature(temperatureData, 0x48)
	{
		// this i2c device will be driven with only 20kHz
		temperature.attachPeripheralConfiguration(DeviceConfiguration::standard_configuration);
	}

	bool
	update()
	{
		PT_BEGIN();

		// we need to configure the device before we can use it
		// so we wait until the task started
		PT_WAIT_UNTIL(temperature.startConfigure());
		// and we wait until it finished
		PT_WAIT_UNTIL(temperature.runConfigure());

		while (true)
		{
			// lets wait until we can read out the device
			PT_WAIT_UNTIL(temperature.startReadTemperature());
			// and until this task finishes
			PT_WAIT_UNTIL(temperature.runReadTemperature());
			// did we succeed with the readout?
			if (temperature.isSuccessful()) {
				tf = temperature.getTemperature();
				stream << "t1: " << (int)tf << xpcc::endl;
			} else {
				tf = NAN;
				stream << "t1: NACK"<< xpcc::endl;
			}

			this->timer.restart(200);
			PT_WAIT_UNTIL(this->timer.isExpired());
			LedRed::toggle();
		}

		PT_END();
	}

private:
	float tf;
	xpcc::Timeout<> timer;
	uint8_t temperatureData[2];
	xpcc::Tmp102<MyI2cMaster> temperature;
};

class ProtofaceTemperatureTwo : public xpcc::pt::Protothread
{
public:
	ProtofaceTemperatureTwo()
	:	temperature(temperatureData, 0x48)
	{
		// this device will be clocked at 100kHz
		temperature.attachPeripheralConfiguration(DeviceConfiguration::fast_configuration);
	}

	bool
	update()
	{
		PT_BEGIN();

		PT_WAIT_UNTIL(temperature.startConfigure());
		PT_WAIT_UNTIL(temperature.runConfigure());

		while (true)
		{
			PT_WAIT_UNTIL(temperature.startReadTemperature());
			PT_WAIT_UNTIL(temperature.runReadTemperature());
			if (temperature.isSuccessful()) {
				tf = temperature.getTemperature();
				stream << "t2: " << (int)tf << xpcc::endl;
			} else {
				tf = NAN;
				stream << "t2: NACK"<< xpcc::endl;
			}

			this->timer.restart(500);
			PT_WAIT_UNTIL(this->timer.isExpired());
			LedGreen::toggle();
		}

		PT_END();
	}

private:
	float tf;
	xpcc::Timeout<> timer;
	uint8_t temperatureData[2];
	xpcc::Tmp102<MyI2cMaster> temperature;
};

ProtofaceTemperatureOne one;
ProtofaceTemperatureTwo two;

// ----------------------------------------------------------------------------
MAIN_FUNCTION
{
	defaultSystemClock::enable();
	xpcc::cortex::SysTickTimer::enable();

	LedOrange::setOutput(xpcc::Gpio::High);
	LedGreen::setOutput(xpcc::Gpio::Low);
	LedRed::setOutput(xpcc::Gpio::High);
	LedBlue::setOutput(xpcc::Gpio::High);

	GpioOutputA2::connect(Usart2::Tx);
	Usart2::initialize<defaultSystemClock, xpcc::Uart::B38400>(10);

	GpioB7::connect(MyI2cMaster::Sda);
	GpioB8::connect(MyI2cMaster::Scl);
	GpioB7::configure(Gpio::InputType::PullUp);
	GpioB8::configure(Gpio::InputType::PullUp);

	stream << "\n\nRESTART\n\n";

	while (1)
	{
		one.update();
		two.update();
		LedOrange::toggle();
	}

	return 0;
}
<commit_msg>Adapt STM32 protoface example for new changes.<commit_after>#include <xpcc/architecture/platform.hpp>
#include "../stm32f4_discovery.hpp"

#include <xpcc/processing/timeout.hpp>
#include <xpcc/processing/protothread.hpp>
#include <xpcc/driver/temperature/tmp102.hpp>

#include <xpcc/io/iostream.hpp>

xpcc::IODeviceWrapper<Usart2> device;
xpcc::IOStream stream(device);

// example of a debug transaction, which outputs the wrapped transactions choices.
class CustomI2cTransaction : public xpcc::I2cTransaction
{
	xpcc::I2cTransaction *transaction;

public:
	CustomI2cTransaction()
			:	transaction(nullptr)
	{}

	void
	setTransaction(xpcc::I2cTransaction *transaction)
	{
		this->transaction = transaction;
	}

protected:
	virtual bool
	attaching()
	{
		bool result = transaction->attaching();
		stream << "T: attaching: " << result << xpcc::endl;
		return result;
	}

	virtual Starting
	starting()
	{
		xpcc::I2cTransaction::Starting result = transaction->starting();
		stream << "T: starting: addr=" << result.address << " next=" << (int)result.next << xpcc::endl;
		return result;
	}

	virtual Writing
	writing()
	{
		xpcc::I2cTransaction::Writing result = transaction->writing();
		stream << "T: writing: length=" << result.length << " next=" << (int)result.next << xpcc::endl;
		return result;
	}

	virtual Reading
	reading()
	{
		xpcc::I2cTransaction::Reading result = transaction->reading();
		stream << "T: reading: length=" << result.length << " next=" << (int)result.next << xpcc::endl;
		return result;
	}

	virtual void
	detaching(DetachCause cause)
	{
		transaction->detaching(cause);
		stream << "T: detaching: cause=" << (int)cause << xpcc::endl;
	}
};
static CustomI2cTransaction myTransaction;

// this custom I2c Master wraps the original transaction into the above debug transaction.
class MyI2cMaster2 : public I2cMaster1
{
public:
	static bool
	start(xpcc::I2cTransaction *transaction, xpcc::I2c::Configuration_t configuration = nullptr)
	{
		myTransaction.setTransaction(transaction);
		stream << "st" << xpcc::endl;
		return I2cMaster1::start(&myTransaction, configuration);
	}

	static bool
	startBlocking(xpcc::I2cTransaction *transaction, xpcc::I2c::Configuration_t configuration = nullptr)
	{
		myTransaction.setTransaction(transaction);
		stream << "stBl" << xpcc::endl;
		return I2cMaster1::start(&myTransaction, configuration);
	}
};

typedef I2cMaster1 MyI2cMaster;

struct DeviceConfiguration
{
	// shared memory for both devices as a cheap way
	// to `tag` the current configuration of the peripheral
	// so we do not need to configure it unnecessarily.
	static char tag;

	/// 100kHz I2C configuration
	static void
	slow_configuration()
	{
		if (tag != 's') {
			stream << "config: 20kHz" << xpcc::endl;
			MyI2cMaster::initialize<defaultSystemClock,  20000>();
			tag = 's';
		}
	}

	/// 400kHz I2C configuration
	static void
	fast_configuration()
	{
		if (tag != 'f') {
			stream << "config: 100kHz" << xpcc::endl;
			MyI2cMaster::initialize<defaultSystemClock, 100000>();
			tag = 'f';
		}
	}
};
char DeviceConfiguration::tag = 0;

class ProtofaceTemperatureOne : public xpcc::pt::Protothread
{
public:
	ProtofaceTemperatureOne()
	:	temperature(temperatureData, 0x48)
	{
		// this i2c device will be driven with only 20kHz
		temperature.attachPeripheralConfiguration(DeviceConfiguration::slow_configuration);
	}

	bool
	update()
	{
		PT_BEGIN();

		// ping the device until it responds
		while(true)
		{
			// we wait until the task started
			PT_WAIT_UNTIL(temperature.startPing());
			// we wait until the task finished
			PT_WAIT_UNTIL(temperature.runPing());
			// if the device responds to the ping, break
			if (temperature.isPingSuccessful())
				break;
			// otherwise, try again in 100ms
			this->timer.restart(100);
			PT_WAIT_UNTIL(this->timer.isExpired());
		}

		do
		{
			// we need to configure the device before we can use it
			// so we wait until the task started
			PT_WAIT_UNTIL(temperature.startConfiguration());
			// and we wait until it finished
			PT_WAIT_UNTIL(temperature.runConfiguration());
		}
		while(temperature.isConfigurationSuccessful());

		while (true)
		{
			// lets wait until we can read out the device
			PT_WAIT_UNTIL(temperature.startReadTemperature());
			// and until this task finishes
			PT_WAIT_UNTIL(temperature.runReadTemperature());
			// did we succeed with the readout?
			if (temperature.isReadTemperatureSuccessful())
			{
				tf = temperature.getTemperature();
				stream << "t1: " << (int)tf << xpcc::endl;
			}
			else {
				tf = NAN;
				stream << "t1: NACK"<< xpcc::endl;
			}

			this->timer.restart(200);
			PT_WAIT_UNTIL(this->timer.isExpired());
			LedRed::toggle();
		}

		PT_END();
	}

private:
	float tf;
	xpcc::Timeout<> timer;
	uint8_t temperatureData[2];
	xpcc::Tmp102<MyI2cMaster> temperature;
};

class ProtofaceTemperatureTwo : public xpcc::pt::Protothread
{
public:
	ProtofaceTemperatureTwo()
	:	temperature(temperatureData, 0x48)
	{
		// this device will be clocked at 100kHz
		temperature.attachPeripheralConfiguration(DeviceConfiguration::fast_configuration);
	}

	bool
	update()
	{
		PT_BEGIN();

		PT_WAIT_UNTIL(temperature.startConfiguration());
		PT_WAIT_UNTIL(temperature.runConfiguration());

		while (true)
		{
			PT_WAIT_UNTIL(temperature.startReadTemperature());
			PT_WAIT_UNTIL(temperature.runReadTemperature());
			if (temperature.isReadTemperatureSuccessful())
			{
				tf = temperature.getTemperature();
				stream << "t2: " << (int)tf << xpcc::endl;
			}
			else {
				tf = NAN;
				stream << "t2: NACK"<< xpcc::endl;
			}

			this->timer.restart(500);
			PT_WAIT_UNTIL(this->timer.isExpired());
			LedGreen::toggle();
		}

		PT_END();
	}

private:
	float tf;
	xpcc::Timeout<> timer;
	uint8_t temperatureData[2];
	xpcc::Tmp102<MyI2cMaster> temperature;
};

ProtofaceTemperatureOne one;
ProtofaceTemperatureTwo two;

// ----------------------------------------------------------------------------
MAIN_FUNCTION
{
	defaultSystemClock::enable();
	xpcc::cortex::SysTickTimer::enable();

	LedOrange::setOutput(xpcc::Gpio::High);
	LedGreen::setOutput(xpcc::Gpio::Low);
	LedRed::setOutput(xpcc::Gpio::High);
	LedBlue::setOutput(xpcc::Gpio::High);

	GpioOutputA2::connect(Usart2::Tx);
	Usart2::initialize<defaultSystemClock, xpcc::Uart::B38400>(10);

	GpioB7::connect(MyI2cMaster::Sda);
	GpioB8::connect(MyI2cMaster::Scl);
	GpioB7::configure(Gpio::InputType::PullUp);
	GpioB8::configure(Gpio::InputType::PullUp);

	stream << "\n\nRESTART\n\n";

	while (1)
	{
		one.update();
		two.update();
		LedOrange::toggle();
	}

	return 0;
}
<|endoftext|>


<commit_before>/*
 * StatZone 1.0.5
 * Copyright (c) 2012-2021, Frederic Cambus
 * https://www.statdns.com
 *
 * Created: 2012-02-13
 * Last Updated: 2021-03-30
 *
 * StatZone is released under the BSD 2-Clause license
 * See LICENSE file for details.
 */

#include <err.h>
#include <getopt.h>
#include <inttypes.h>
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <time.h>

#include <string>
#include <unordered_set>

#ifdef HAVE_SECCOMP
#include <sys/prctl.h>
#include <linux/seccomp.h>
#include "seccomp.h"
#endif

#include "compat.h"
#include "config.h"
#include "strtolower.h"

struct timespec begin, current, elapsed;
struct results results;

static void
error(const char *str)
{
	errx(EXIT_FAILURE, "%s", str);
}

static void
usage()
{
	printf("statzone [-hv] zonefile\n\n" \
	    "The options are as follows:\n\n" \
	    "	-h	Display usage.\n" \
	    "	-v	Display version.\n");
}

static void
summary()
{
	/* Stopping timer */
	clock_gettime(CLOCK_MONOTONIC, &current);
	timespecsub(&current, &begin, &elapsed);

	/* Print summary */
	fprintf(stderr, "Processed %" PRIu64 " lines in %f seconds.\n",
	    results.processedLines,
	    elapsed.tv_sec + elapsed.tv_nsec / 1E9);
}

int
main(int argc, char *argv[])
{
	struct stat zonefile_stat;

	std::unordered_set<std::string> signed_domains;
	std::unordered_set<std::string> unique_ns;

	int opt, token_count;

	char linebuffer[LINE_LENGTH_MAX];
	char *input, *domain, *previous_domain = NULL;
	char *rdata, *token = NULL, *token_lc = NULL;

	FILE *zonefile;

	if (pledge("stdio rpath", NULL) == -1) {
		err(EXIT_FAILURE, "pledge");
	}

#ifdef HAVE_SECCOMP
	if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) {
		perror("Can't initialize seccomp");
		return EXIT_FAILURE;
	}

	if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &statzone)) {
		perror("Can't load seccomp filter");
		return EXIT_FAILURE;
	}
#endif

#ifdef SIGINFO
	signal(SIGINFO, summary);
#endif

	while ((opt = getopt(argc, argv, "hv")) != -1) {
		switch (opt) {

		case 'h':
			usage();
			return EXIT_SUCCESS;

		case 'v':
			printf("%s\n", VERSION);
			return EXIT_SUCCESS;
		}
	}

	if (optind < argc) {
		input = argv[optind];
	} else {
		usage();
		return EXIT_SUCCESS;
	}

	/* Starting timer */
	clock_gettime(CLOCK_MONOTONIC, &begin);

	/* Open zone file */
	if (!strcmp(input, "-")) {
		/* Read from standard input */
		zonefile = stdin;
	} else {
		/* Attempt to read from file */
		if (!(zonefile = fopen(input, "r"))) {
			perror("Can't open zone file");
			return EXIT_FAILURE;
		}
	}

	/* Get zone file size */
	if (fstat(fileno(zonefile), &zonefile_stat)) {
		perror("Can't stat zone file");
		return EXIT_FAILURE;
	}

	while (fgets(linebuffer, LINE_LENGTH_MAX, zonefile)) {
		if (!*linebuffer)
			continue;

		if (*linebuffer == ';') /* Comments */
			continue;

		if (*linebuffer == '$') /* Directives */
			continue;

		token_count = 0;
		token = strtok(linebuffer, " \t");

		if (token)
			domain = strtolower(token);

		while (token) {
			if (*token == ';') { /* Comments */
				token = NULL;
				continue;
			}

			token_lc = strtolower(token);
			if (token_count && !strcmp(token_lc, "nsec")) {
				token = NULL;
				continue;
			}

			if (token_count && !strcmp(token_lc, "nsec3")) {
				token = NULL;
				continue;
			}

			if (token_count && !strcmp(token_lc, "rrsig")) {
				token = NULL;
				continue;
			}

			if (token_count && !strcmp(token_lc, "a"))
				results.a++;

			if (token_count && !strcmp(token_lc, "aaaa"))
				results.aaaa++;

			if (token_count && !strcmp(token_lc, "ds")) {
				results.ds++;

				signed_domains.insert(domain);
			}

			if (!strcmp(token_lc, "ns")) {
				results.ns++;

				if (previous_domain == NULL ||
				    strlen(previous_domain) != strlen(domain) ||
				    strncmp(domain, previous_domain, strlen(domain))) {
					results.domains++;

					free(previous_domain);
					previous_domain = strdup(domain);

					if (previous_domain == NULL)
						error("Memory allocation error.");

					if (!strncmp(domain, "xn--", 4))
						results.idn++;
				}

				rdata = strtok(NULL, "\n");

				if (rdata && strchr(rdata, ' '))
					rdata = strtok(NULL, "\n");

				if (rdata)
					unique_ns.insert(rdata);
			}

			token = strtok(NULL, " \t");
			token_count++;
		}

		results.processedLines++;
	}

	/* Don't count origin */
	if (results.domains)
		results.domains--;

	/* Printing CVS values */
	fprintf(stdout, "---[ CSV values ]--------------------------------------------------------------\n");
	fprintf(stdout, "IPv4 Glue,IPv6 Glue,NS,Unique NS,DS,Signed,IDNs,Domains\n");
	fprintf(stdout, "%" PRIu64 ",", results.a);
	fprintf(stdout, "%" PRIu64 ",", results.aaaa);
	fprintf(stdout, "%" PRIu64 ",", results.ns);
	fprintf(stdout, "%lu,", unique_ns.size());
	fprintf(stdout, "%" PRIu64 ",", results.ds);
	fprintf(stdout, "%lu,", signed_domains.size());
	fprintf(stdout, "%" PRIu64 ",", results.idn);
	fprintf(stdout, "%" PRIu64 "\n", results.domains);

	/* Printing results */
	summary();

	/* Clean up */
	free(previous_domain);
	fclose(zonefile);

	return EXIT_SUCCESS;
}
<commit_msg>Use std::chrono to calculate elapsed time in summary().<commit_after>/*
 * StatZone 1.0.5
 * Copyright (c) 2012-2021, Frederic Cambus
 * https://www.statdns.com
 *
 * Created: 2012-02-13
 * Last Updated: 2021-03-30
 *
 * StatZone is released under the BSD 2-Clause license
 * See LICENSE file for details.
 */

#include <err.h>
#include <getopt.h>
#include <inttypes.h>
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>

#include <chrono>
#include <iostream>
#include <string>
#include <unordered_set>

#ifdef HAVE_SECCOMP
#include <sys/prctl.h>
#include <linux/seccomp.h>
#include "seccomp.h"
#endif

#include "compat.h"
#include "config.h"
#include "strtolower.h"

std::chrono::steady_clock::time_point begin, current, elapsed;
struct results results;

static void
error(const char *str)
{
	errx(EXIT_FAILURE, "%s", str);
}

static void
usage()
{
	printf("statzone [-hv] zonefile\n\n" \
	    "The options are as follows:\n\n" \
	    "	-h	Display usage.\n" \
	    "	-v	Display version.\n");
}

static void
summary()
{
	/* Stopping timer */
	current = std::chrono::steady_clock::now();

	/* Print summary */
	std::cerr << "Processed " << results.processedLines << " lines in ";
	std::cerr << std::chrono::duration_cast<std::chrono::microseconds>(current - begin).count() / 1E6;
	std::cerr << " seconds." << std::endl;
}

int
main(int argc, char *argv[])
{
	struct stat zonefile_stat;

	std::unordered_set<std::string> signed_domains;
	std::unordered_set<std::string> unique_ns;

	int opt, token_count;

	char linebuffer[LINE_LENGTH_MAX];
	char *input, *domain, *previous_domain = NULL;
	char *rdata, *token = NULL, *token_lc = NULL;

	FILE *zonefile;

	if (pledge("stdio rpath", NULL) == -1) {
		err(EXIT_FAILURE, "pledge");
	}

#ifdef HAVE_SECCOMP
	if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) {
		perror("Can't initialize seccomp");
		return EXIT_FAILURE;
	}

	if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &statzone)) {
		perror("Can't load seccomp filter");
		return EXIT_FAILURE;
	}
#endif

#ifdef SIGINFO
	signal(SIGINFO, summary);
#endif

	while ((opt = getopt(argc, argv, "hv")) != -1) {
		switch (opt) {

		case 'h':
			usage();
			return EXIT_SUCCESS;

		case 'v':
			printf("%s\n", VERSION);
			return EXIT_SUCCESS;
		}
	}

	if (optind < argc) {
		input = argv[optind];
	} else {
		usage();
		return EXIT_SUCCESS;
	}

	/* Starting timer */
	begin = std::chrono::steady_clock::now();

	/* Open zone file */
	if (!strcmp(input, "-")) {
		/* Read from standard input */
		zonefile = stdin;
	} else {
		/* Attempt to read from file */
		if (!(zonefile = fopen(input, "r"))) {
			perror("Can't open zone file");
			return EXIT_FAILURE;
		}
	}

	/* Get zone file size */
	if (fstat(fileno(zonefile), &zonefile_stat)) {
		perror("Can't stat zone file");
		return EXIT_FAILURE;
	}

	while (fgets(linebuffer, LINE_LENGTH_MAX, zonefile)) {
		if (!*linebuffer)
			continue;

		if (*linebuffer == ';') /* Comments */
			continue;

		if (*linebuffer == '$') /* Directives */
			continue;

		token_count = 0;
		token = strtok(linebuffer, " \t");

		if (token)
			domain = strtolower(token);

		while (token) {
			if (*token == ';') { /* Comments */
				token = NULL;
				continue;
			}

			token_lc = strtolower(token);
			if (token_count && !strcmp(token_lc, "nsec")) {
				token = NULL;
				continue;
			}

			if (token_count && !strcmp(token_lc, "nsec3")) {
				token = NULL;
				continue;
			}

			if (token_count && !strcmp(token_lc, "rrsig")) {
				token = NULL;
				continue;
			}

			if (token_count && !strcmp(token_lc, "a"))
				results.a++;

			if (token_count && !strcmp(token_lc, "aaaa"))
				results.aaaa++;

			if (token_count && !strcmp(token_lc, "ds")) {
				results.ds++;

				signed_domains.insert(domain);
			}

			if (!strcmp(token_lc, "ns")) {
				results.ns++;

				if (previous_domain == NULL ||
				    strlen(previous_domain) != strlen(domain) ||
				    strncmp(domain, previous_domain, strlen(domain))) {
					results.domains++;

					free(previous_domain);
					previous_domain = strdup(domain);

					if (previous_domain == NULL)
						error("Memory allocation error.");

					if (!strncmp(domain, "xn--", 4))
						results.idn++;
				}

				rdata = strtok(NULL, "\n");

				if (rdata && strchr(rdata, ' '))
					rdata = strtok(NULL, "\n");

				if (rdata)
					unique_ns.insert(rdata);
			}

			token = strtok(NULL, " \t");
			token_count++;
		}

		results.processedLines++;
	}

	/* Don't count origin */
	if (results.domains)
		results.domains--;

	/* Printing CVS values */
	fprintf(stdout, "---[ CSV values ]--------------------------------------------------------------\n");
	fprintf(stdout, "IPv4 Glue,IPv6 Glue,NS,Unique NS,DS,Signed,IDNs,Domains\n");
	fprintf(stdout, "%" PRIu64 ",", results.a);
	fprintf(stdout, "%" PRIu64 ",", results.aaaa);
	fprintf(stdout, "%" PRIu64 ",", results.ns);
	fprintf(stdout, "%lu,", unique_ns.size());
	fprintf(stdout, "%" PRIu64 ",", results.ds);
	fprintf(stdout, "%lu,", signed_domains.size());
	fprintf(stdout, "%" PRIu64 ",", results.idn);
	fprintf(stdout, "%" PRIu64 "\n", results.domains);

	/* Printing results */
	summary();

	/* Clean up */
	free(previous_domain);
	fclose(zonefile);

	return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include "../include/obj.hpp"

Menu::Menu()
{
	Menu::texture_.loadFromFile("media/menu.png");	// Загрузка текстуры меню
	Menu::sprite_.setTexture(Menu::texture_);
	Menu::sprite_.setTextureRect(sf::IntRect(0, 0, 400, 359));	// Установка текстуры в зависимомти от стороны в которую смотрит танк
}

Menu::~Menu()
{

}

int Menu::draw(sf::RenderWindow &window, sf::Event &event, sf::Texture &local_texture_)
{
	int pos	= 0;

	Menu::spriteTank_.setTexture(local_texture_);
	Menu::spriteTank_.setTextureRect(sf::IntRect(96, 0, 16, 16));	// Установка текстуры в зависимомти от стороны в которую смотрит танк

	// window.setSize(Vector2u(400, 359));

	while (sf::Keyboard::isKeyPressed(sf::Keyboard::Return));

	while (window.isOpen())
	{

		while (window.pollEvent(event))							// Отслеживание события закрытия окна
		{
			if (event.type == sf::Event::Closed) {
				window.close();
				return 0;
			}
		}

		if (sf::Keyboard::isKeyPressed(sf::Keyboard::Return))
			return pos + 1;

		if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
		{
			if (pos == 0)
				pos	= 1;
			else
				pos	= 0;

			while (sf::Keyboard::isKeyPressed(sf::Keyboard::Down));
		}

		if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
		{
			if (pos == 1)
				pos	= 0;
			else
				pos	= 1;

			while (sf::Keyboard::isKeyPressed(sf::Keyboard::Up));
		}

		if (pos == 0)
			Menu::spriteTank_.setPosition(120 , 191);
		else
			Menu::spriteTank_.setPosition(120 , 217);

		window.clear(sf::Color(0,0,0));
		window.draw(Menu::sprite_);
		window.draw(Menu::spriteTank_);
		window.display();
	}
}<commit_msg>Add exit by esc button<commit_after>#include "../include/obj.hpp"

Menu::Menu()
{
	Menu::texture_.loadFromFile("media/menu.png");	// Загрузка текстуры меню
	Menu::sprite_.setTexture(Menu::texture_);
	Menu::sprite_.setTextureRect(sf::IntRect(0, 0, 400, 359));	// Установка текстуры в зависимомти от стороны в которую смотрит танк
}

Menu::~Menu()
{

}

int Menu::draw(sf::RenderWindow &window, sf::Event &event, sf::Texture &local_texture_)
{
	int pos	= 0;

	Menu::spriteTank_.setTexture(local_texture_);
	Menu::spriteTank_.setTextureRect(sf::IntRect(96, 0, 16, 16));	// Установка текстуры в зависимомти от стороны в которую смотрит танк

	// window.setSize(Vector2u(400, 359));

	while (sf::Keyboard::isKeyPressed(sf::Keyboard::Return));

	while (window.isOpen())
	{

		while (window.pollEvent(event))							// Отслеживание события закрытия окна
		{
			if (event.type == sf::Event::Closed) {
				window.close();
				return 0;
			}
		}

		if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape))
		{
			window.close();
			return 0;
		}

		if (sf::Keyboard::isKeyPressed(sf::Keyboard::Return))
			return pos + 1;

		if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
		{
			if (pos == 0)
				pos	= 1;
			else
				pos	= 0;

			while (sf::Keyboard::isKeyPressed(sf::Keyboard::Down));
		}

		if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
		{
			if (pos == 1)
				pos	= 0;
			else
				pos	= 1;

			while (sf::Keyboard::isKeyPressed(sf::Keyboard::Up));
		}

		if (pos == 0)
			Menu::spriteTank_.setPosition(120 , 191);
		else
			Menu::spriteTank_.setPosition(120 , 217);

		window.clear(sf::Color(0,0,0));
		window.draw(Menu::sprite_);
		window.draw(Menu::spriteTank_);
		window.display();
	}
}<|endoftext|>


<commit_before>/**
 * Copyright 2017 Shusheng Shao <iblackangel@163.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <mpl/mlog.h>
#include <mpl/msysinfo.h>
#include <mpl/mdatetime.h>
#include <mpl/mapplication.h>
#include <mpl/mprocess.h>
#include <mpl/mstring.h>
#include <mpl/merror.h>

#ifdef _MSC_VER
# pragma warning (push)
# pragma warning (disable: 4996)
#endif

MPL_BEGIN_NAMESPACE

MLog *MLog::_ins = NULL;

MLog *MLog::instance()
{
	if (NULL == _ins) {
		_ins = new MLog();
		atexit(desposed);
	}
	return _ins;
}

void MLog::desposed()
{
	if (NULL != _ins) {
		delete _ins; _ins = NULL;
	}
}

MLog::MLog()
{
	_priority = kDebug;
	_performance = kNormal;
}

MLog::~MLog()
{
}

void MLog::init(int pri, const char *logfile, int performance)
{
	_priority = pri;
	if (logfile != NULL) {
		_logfile = logfile;
	}
	_performance = performance;
}

void MLog::log(const std::string &file, const std::string &func,
			   uint32_t line, int pri,
			   const char *__format, ...)
{
	MScopedLock locker(_mutex);

	// according to pri
	if (pri > _priority) return;

	// combine log head
	std::string head;

	int len;
	std::string buffer;
	va_list vargs;
	va_start(vargs, __format);
	len = vsnprintf(NULL, 0, __format, vargs);
	buffer.resize(len);
	va_start(vargs, __format);
	vsnprintf(&buffer[0], len + 1, __format, vargs);
	va_end(vargs);

	// DATETIME HOSTNAME APPLICATIONNAME[PID] FILE FUNC[LINE]
	std::string logstr = format("%s %s %s[%lld] %s %s[%u]: <%s> %s",
								now().c_str(), hostname().c_str(),
								applicationName().c_str(), process::pid(),
								file.c_str(), func.c_str(), line,
								strpriority(pri).c_str(),
								buffer.c_str());

	std::cout << logstr << std::endl;

	if (_logfile.empty()) {
#ifdef M_OS_LINUX
		syslog(LOG_DEBUG, "%s", logstr.c_str());
#else
		OutputDebugString(logstr.c_str());
#endif
	} else {
		FILE *fp = fopen(_logfile.c_str(), "a");
		if (fp == NULL) {
			std::string errstr = mpl::format("open %s failed: %s",
												 _logfile.c_str(), error().c_str());
			fprintf(stderr, "%s\n", errstr.c_str());
			syslog(LOG_ERR, "%s", errstr.c_str());
			return;
		}
		fprintf(fp, "%s\n", logstr.c_str());
		fflush(fp);
		fclose(fp);
	}
}

std::string MLog::strpriority(int pri) const
{
	std::string ret = "debug";
	switch (pri) {
	case kEmerg:
		ret = "emerg"; break;
	case kAlert:
		ret = "alert"; break;
	case kCrit:
		ret = "crit"; break;
	case kError:
		ret = "error"; break;
	case kWarn:
		ret = "warn"; break;
	case kNotice:
		ret = "notice"; break;
	case kInfo:
		ret = "info"; break;
	default:
		break;
	}
	return ret;
}

MPL_END_NAMESPACE

#ifdef _MSC_VER
# pragma warning (pop)
#endif
<commit_msg>update mlog<commit_after>/**
 * Copyright 2017 Shusheng Shao <iblackangel@163.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <mpl/mlog.h>
#include <mpl/msysinfo.h>
#include <mpl/mdatetime.h>
#include <mpl/mapplication.h>
#include <mpl/mprocess.h>
#include <mpl/mstring.h>
#include <mpl/merror.h>

#ifdef _MSC_VER
# pragma warning (push)
# pragma warning (disable: 4996)
#endif

MPL_BEGIN_NAMESPACE

MLog *MLog::_ins = NULL;

MLog *MLog::instance()
{
	if (NULL == _ins) {
		_ins = new MLog();
		atexit(desposed);
	}
	return _ins;
}

void MLog::desposed()
{
	if (NULL != _ins) {
		delete _ins; _ins = NULL;
	}
}

MLog::MLog()
{
	_priority = kDebug;
	_performance = kNormal;
}

MLog::~MLog()
{
}

void MLog::init(int pri, const char *logfile, int performance)
{
	_priority = pri;
	if (logfile != NULL) {
		_logfile = logfile;
	}
	_performance = performance;
}

void MLog::log(const std::string &file, const std::string &func,
			   uint32_t line, int pri,
			   const char *__format, ...)
{
	MScopedLock locker(_mutex);

	// according to pri
	if (pri > _priority) return;

	// combine log head
	std::string head;

	int len;
	std::string buffer;
	va_list vargs;
	va_start(vargs, __format);
	len = vsnprintf(NULL, 0, __format, vargs);
	buffer.resize(len);
	va_start(vargs, __format);
	vsnprintf(&buffer[0], len + 1, __format, vargs);
	va_end(vargs);

	// DATETIME HOSTNAME APPLICATIONNAME[PID] FILE FUNC[LINE]
	std::string logstr = format("%s %s %s[%lld] %s %s[%u]: <%s> %s",
								now().c_str(), hostname().c_str(),
								applicationName().c_str(), process::pid(),
								file.c_str(), func.c_str(), line,
								strpriority(pri).c_str(),
								buffer.c_str());

	std::cout << logstr << std::endl;

	if (_logfile.empty()) {
#ifdef M_OS_LINUX
		syslog(LOG_DEBUG, "%s", logstr.c_str());
#else
		OutputDebugString(logstr.c_str());
#endif
	} else {
		FILE *fp = fopen(_logfile.c_str(), "a");
		if (fp == NULL) {
			std::string errstr = mpl::format("open %s failed: %s",
												 _logfile.c_str(), error().c_str());
			fprintf(stderr, "%s\n", errstr.c_str());
#ifdef M_OS_LINUX
			syslog(LOG_ERR, "%s", errstr.c_str());
#else
			OutputDebugString(logstr.c_str());
#endif /* M_OS_LINUX */
			return;
		}
		fprintf(fp, "%s\n", logstr.c_str());
		fflush(fp);
		fclose(fp);
	}
}

std::string MLog::strpriority(int pri) const
{
	std::string ret = "debug";
	switch (pri) {
	case kEmerg:
		ret = "emerg"; break;
	case kAlert:
		ret = "alert"; break;
	case kCrit:
		ret = "crit"; break;
	case kError:
		ret = "error"; break;
	case kWarn:
		ret = "warn"; break;
	case kNotice:
		ret = "notice"; break;
	case kInfo:
		ret = "info"; break;
	default:
		break;
	}
	return ret;
}

MPL_END_NAMESPACE

#ifdef _MSC_VER
# pragma warning (pop)
#endif
<|endoftext|>


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

#include "phd.h"
#include "about_dialog.h"
#include <wx/fs_mem.h>
#include <wx/html/htmlwin.h>

BEGIN_EVENT_TABLE(AboutDialog, wxDialog)
    EVT_HTML_LINK_CLICKED(ABOUT_LINK,AboutDialog::OnLink)
END_EVENT_TABLE()

AboutDialog::AboutDialog()
    : wxDialog(pFrame, wxID_ANY, wxString::Format(_("About %s"), APPNAME),
               wxDefaultPosition, wxDefaultSize, wxCAPTION | wxCLOSE_BOX)
{
    SetBackgroundColour(*wxWHITE);

    wxBoxSizer *pSizer = new wxBoxSizer(wxHORIZONTAL);

    #include "icons/phd2_64.png.h"
    wxBitmap phd2(wxBITMAP_PNG_FROM_DATA(phd2_64));
    wxStaticBitmap *pImage = new wxStaticBitmap(this, wxID_ANY, phd2);

    wxFileSystem::AddHandler(new wxMemoryFSHandler);
    wxMemoryFSHandler::AddFile("about.html", wxString::Format(
        ""
        ""
        "%s %s
"
        "

"
        "PHD2 home - openphdguiding.org "
        "	"
        "Source code on GitHub"
        "

"
        ""
        "Project maintainers
"
        "
"
        "
"
        "Andy Galasso	"
        "Bruce Waddington	"
        "
"
        "
"
        "
"
        "Past maintainers
"
        "
"
        "
"
        "Craig Stark	"
        "Bret McKee	"
        "
"
        "
"
        "
"
        "Credits
"
        "
"
        "
"
        "Bernhard Reutner-Fischer    	"
        "Stefan Elste	"
        "Geoffrey Hausheer   	"
        "Jared Wellman	"
        "
"
        "
"
        "John Wainwright	"
        "Sylvain Girard	"
        "Max Chen	"
        "Carsten Przygoda	"
        "
"
        "
"
        "Hans Lambermont	"
        "David Ault	"
        "Markus Wieczorek	"
        "Linkage	"
        "
"
        "
"
        "Robin Glover	"
        "Patrick Chevalley	"
        "Scott Edwards	"
        "Eiji Kaneshige	"
        "
"
        "
"
        "Konstantin Menshikoff   	"
        "Jakub Bartas	"
        "Javier R	"
        "Oleh Malyi	"
        "
"
        "
"
        "Tsung-Chi Wu	"
        "Raffi Enficiaud	"
        "Sabin Fota	"
        "Dylan O'Donnell	"
        "
"
        "
"
        "Katsuhiro Kojima	"
        "Simon Taylor	"
        "Hallgeir Holien	"
        "Laurent Schmitz	"
        "
"
        "
"
        "Atushi Sakauchi	"
        "Giorgio Mazzacurati   	"
        "Günter Scholz	"
        "Ray Gralak	"
        "
"
        "
"
        "Khalefa Algadi	"
        "David C. Partridge	"
        "Matteo Ghellere	"
        "norma	"
        "
"
        "
"
        "Edgar D. Klenske	"
        "Bernhard Schölkopf	"
        "Philipp Hennig	"
        "Stephan Wenninger	"
        "
"
        "
"
        "Wagner Trindade	"
        "Cyril Richard	"
        "Mattia Verga	"
        "Iván Zabala	"
        "
"
        "
"
        "Ken Self	"
        "Alex Helms	"
        "Randy Pufahl	"
        "Jasem Mutlaq	"
        "
"
        "
"
        "Thomas Stibor	"
        "Ludovic Pollet	"
        "Paweł Pleskaczyński	"
        "nabePla	"
        "
"
        "
"
        "Philip Peake	"
        "Manuel Rosales	"
        "Marcel Greter	"
        "Miquel Recacha	"
        "
"
        "
"
        "Mario Nicotra	"
        "Gerry Roberts	"
        "	"
        "	"
        "
"
        "

"
        "
"
        "
"
        "Copyright 2006-2013 Craig Stark
"
        "Copyright 2009 Geoffrey Hausheer
"
        "Copyright 2012-2013 Bret McKee
"
        "Copyright 2013 Sylvain Girard
"
        "Copyright 2013-2020 Andy Galasso
"
        "Copyright 2013-2020 Bruce Waddington
"
        "Copyright 2014 Hans Lambermont
"
        "Copyright 2014 Robin Glover
"
        "Copyright 2014-2017 Max Planck Society
"
        "Copyright 2017 Ken Self
"
        "Copyright 2019 Jasem Mutlaq
"
        "
"
        "
"
        "The Predictive PEC guide algorithm is based on
"
        "Gaussian Process Based Predictive Control
for Periodic Error Correction"
        ""
        "", APPNAME, FULLVER));
    wxHtmlWindow *pHtml;
    pHtml = new wxHtmlWindow(this, ABOUT_LINK, wxDefaultPosition, wxSize(580, 500), wxHW_SCROLLBAR_AUTO);
    pHtml->SetBorders(0);
    pHtml->LoadPage("memory:about.html");
    pHtml->SetSize(pHtml->GetInternalRepresentation()->GetWidth(), pHtml->GetInternalRepresentation()->GetHeight());

    pSizer->Add(pImage, wxSizerFlags(0).Border(wxALL, 10));
    pSizer->Add(pHtml, wxSizerFlags(0).Border(wxALL, 10));

    wxBoxSizer *pTopLevelSizer = new wxBoxSizer(wxVERTICAL);
    pTopLevelSizer->Add(pSizer, wxSizerFlags(0).Expand());
    SetSizerAndFit(pTopLevelSizer);
}

AboutDialog::~AboutDialog(void)
{
    wxMemoryFSHandler::RemoveFile("about.html");
}

void AboutDialog::OnLink(wxHtmlLinkEvent & event)
{
    wxLaunchDefaultBrowser(event.GetLinkInfo().GetHref());
}
<commit_msg>update copyright message to 2021<commit_after>/*
 *  about_dialog.cpp
 *  PHD Guiding
 *
 *  Created by Sylvain Girard.
 *  Copyright (c) 2013 Sylvain Girard.
 *  All rights reserved.
 *
 *  This source code is distributed under the following "BSD" license
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *    Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimer.
 *    Redistributions in binary form must reproduce the above copyright notice,
 *     this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *    Neither the name of Craig Stark, Stark Labs nor the names of its
 *     contributors may be used to endorse or promote products derived from
 *     this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 *  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 *  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 *  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 *  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 *  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include "phd.h"
#include "about_dialog.h"
#include <wx/fs_mem.h>
#include <wx/html/htmlwin.h>

BEGIN_EVENT_TABLE(AboutDialog, wxDialog)
    EVT_HTML_LINK_CLICKED(ABOUT_LINK,AboutDialog::OnLink)
END_EVENT_TABLE()

AboutDialog::AboutDialog()
    : wxDialog(pFrame, wxID_ANY, wxString::Format(_("About %s"), APPNAME),
               wxDefaultPosition, wxDefaultSize, wxCAPTION | wxCLOSE_BOX)
{
    SetBackgroundColour(*wxWHITE);

    wxBoxSizer *pSizer = new wxBoxSizer(wxHORIZONTAL);

    #include "icons/phd2_64.png.h"
    wxBitmap phd2(wxBITMAP_PNG_FROM_DATA(phd2_64));
    wxStaticBitmap *pImage = new wxStaticBitmap(this, wxID_ANY, phd2);

    wxFileSystem::AddHandler(new wxMemoryFSHandler);
    wxMemoryFSHandler::AddFile("about.html", wxString::Format(
        ""
        ""
        "%s %s
"
        "

"
        "PHD2 home - openphdguiding.org "
        "	"
        "Source code on GitHub"
        "

"
        ""
        "Project maintainers
"
        "
"
        "
"
        "Andy Galasso	"
        "Bruce Waddington	"
        "
"
        "
"
        "
"
        "Past maintainers
"
        "
"
        "
"
        "Craig Stark	"
        "Bret McKee	"
        "
"
        "
"
        "
"
        "Credits
"
        "
"
        "
"
        "Bernhard Reutner-Fischer    	"
        "Stefan Elste	"
        "Geoffrey Hausheer   	"
        "Jared Wellman	"
        "
"
        "
"
        "John Wainwright	"
        "Sylvain Girard	"
        "Max Chen	"
        "Carsten Przygoda	"
        "
"
        "
"
        "Hans Lambermont	"
        "David Ault	"
        "Markus Wieczorek	"
        "Linkage	"
        "
"
        "
"
        "Robin Glover	"
        "Patrick Chevalley	"
        "Scott Edwards	"
        "Eiji Kaneshige	"
        "
"
        "
"
        "Konstantin Menshikoff   	"
        "Jakub Bartas	"
        "Javier R	"
        "Oleh Malyi	"
        "
"
        "
"
        "Tsung-Chi Wu	"
        "Raffi Enficiaud	"
        "Sabin Fota	"
        "Dylan O'Donnell	"
        "
"
        "
"
        "Katsuhiro Kojima	"
        "Simon Taylor	"
        "Hallgeir Holien	"
        "Laurent Schmitz	"
        "
"
        "
"
        "Atushi Sakauchi	"
        "Giorgio Mazzacurati   	"
        "Günter Scholz	"
        "Ray Gralak	"
        "
"
        "
"
        "Khalefa Algadi	"
        "David C. Partridge	"
        "Matteo Ghellere	"
        "norma	"
        "
"
        "
"
        "Edgar D. Klenske	"
        "Bernhard Schölkopf	"
        "Philipp Hennig	"
        "Stephan Wenninger	"
        "
"
        "
"
        "Wagner Trindade	"
        "Cyril Richard	"
        "Mattia Verga	"
        "Iván Zabala	"
        "
"
        "
"
        "Ken Self	"
        "Alex Helms	"
        "Randy Pufahl	"
        "Jasem Mutlaq	"
        "
"
        "
"
        "Thomas Stibor	"
        "Ludovic Pollet	"
        "Paweł Pleskaczyński	"
        "nabePla	"
        "
"
        "
"
        "Philip Peake	"
        "Manuel Rosales	"
        "Marcel Greter	"
        "Miquel Recacha	"
        "
"
        "
"
        "Mario Nicotra	"
        "Gerry Roberts	"
        "	"
        "	"
        "
"
        "

"
        "
"
        "
"
        "Copyright 2006-2013 Craig Stark
"
        "Copyright 2009 Geoffrey Hausheer
"
        "Copyright 2012-2013 Bret McKee
"
        "Copyright 2013 Sylvain Girard
"
        "Copyright 2013-2021 Andy Galasso
"
        "Copyright 2013-2021 Bruce Waddington
"
        "Copyright 2014 Hans Lambermont
"
        "Copyright 2014 Robin Glover
"
        "Copyright 2014-2017 Max Planck Society
"
        "Copyright 2017 Ken Self
"
        "Copyright 2019 Jasem Mutlaq
"
        "
"
        "
"
        "The Predictive PEC guide algorithm is based on
"
        "Gaussian Process Based Predictive Control
for Periodic Error Correction"
        ""
        "", APPNAME, FULLVER));
    wxHtmlWindow *pHtml;
    pHtml = new wxHtmlWindow(this, ABOUT_LINK, wxDefaultPosition, wxSize(580, 500), wxHW_SCROLLBAR_AUTO);
    pHtml->SetBorders(0);
    pHtml->LoadPage("memory:about.html");
    pHtml->SetSize(pHtml->GetInternalRepresentation()->GetWidth(), pHtml->GetInternalRepresentation()->GetHeight());

    pSizer->Add(pImage, wxSizerFlags(0).Border(wxALL, 10));
    pSizer->Add(pHtml, wxSizerFlags(0).Border(wxALL, 10));

    wxBoxSizer *pTopLevelSizer = new wxBoxSizer(wxVERTICAL);
    pTopLevelSizer->Add(pSizer, wxSizerFlags(0).Expand());
    SetSizerAndFit(pTopLevelSizer);
}

AboutDialog::~AboutDialog(void)
{
    wxMemoryFSHandler::RemoveFile("about.html");
}

void AboutDialog::OnLink(wxHtmlLinkEvent & event)
{
    wxLaunchDefaultBrowser(event.GetLinkInfo().GetHref());
}
<|endoftext|>


<commit_before>/** @file

  A brief file description

  @section license License

  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
 */

#include "HttpDataFetcherImpl.h"
#include "Utils.h"
#include "gzip.h"

#include <arpa/inet.h>

using std::string;
using namespace EsiLib;

const int HttpDataFetcherImpl::FETCH_EVENT_ID_BASE = 10000;

inline void HttpDataFetcherImpl::_release(RequestData &req_data) {
  if (req_data.bufp) {
    if (req_data.hdr_loc) {
      TSHandleMLocRelease(req_data.bufp, TS_NULL_MLOC, req_data.hdr_loc);
      req_data.hdr_loc = 0;
    }
    TSMBufferDestroy(req_data.bufp);
    req_data.bufp = 0;
  }
}

HttpDataFetcherImpl::HttpDataFetcherImpl(TSCont contp,sockaddr const* client_addr,
                                         const char *debug_tag)
  : _contp(contp), _n_pending_requests(0), _curr_event_id_base(FETCH_EVENT_ID_BASE),
    _headers_str(""),_client_addr(client_addr) {
  _http_parser = TSHttpParserCreate();
  snprintf(_debug_tag, sizeof(_debug_tag), "%s", debug_tag);
}

HttpDataFetcherImpl::~HttpDataFetcherImpl() {
  clear();
  TSHttpParserDestroy(_http_parser);
}

bool
HttpDataFetcherImpl::addFetchRequest(const string &url, FetchedDataProcessor *callback_obj /* = 0 */) {
  // do we already have a request for this?
  std::pair<UrlToContentMap::iterator, bool> insert_result =
    _pages.insert(UrlToContentMap::value_type(url, RequestData()));
  if (callback_obj) {
    ((insert_result.first)->second).callback_objects.push_back(callback_obj);
  }
  if (!insert_result.second) {
    TSDebug(_debug_tag, "[%s] Fetch request for url [%s] already added", __FUNCTION__,
             url.data());
    return true;
  }

  char buff[1024];
  char *http_req;
  int length;

  length = sizeof("GET ") - 1 + url.length() + sizeof(" HTTP/1.0\r\n") - 1 + _headers_str.length() + sizeof("\r\n") - 1;
  if (length < (int)sizeof(buff)) {
    http_req = buff;
  }else {
    http_req = (char *)malloc(length + 1);
    if (http_req == NULL) {
      TSError("[%s] malloc %d bytes fail", __FUNCTION__, length + 1);
      return false;
    }
  }

  sprintf(http_req, "GET %s HTTP/1.0\r\n"
      "%s\r\n", url.c_str(), _headers_str.c_str());

  TSFetchEvent event_ids;
  event_ids.success_event_id = _curr_event_id_base;
  event_ids.failure_event_id = _curr_event_id_base + 1;
  event_ids.timeout_event_id = _curr_event_id_base + 2;
  _curr_event_id_base += 3;

  TSFetchUrl(http_req, length, _client_addr, _contp, AFTER_BODY,
                  event_ids);
  if (http_req != buff) {
    free(http_req);
  }

  TSDebug(_debug_tag, "[%s] Successfully added fetch request for URL [%s]",
           __FUNCTION__, url.data());
  _page_entry_lookup.push_back(insert_result.first);
  ++_n_pending_requests;
  return true;
}

bool
HttpDataFetcherImpl::_isFetchEvent(TSEvent event, int &base_event_id) const {
  base_event_id = _getBaseEventId(event);
  if ((base_event_id < 0) || (base_event_id >= static_cast<int>(_page_entry_lookup.size()))) {
    TSDebug(_debug_tag, "[%s] Event id %d not within fetch event id range [%d, %ld)",
             __FUNCTION__, event, FETCH_EVENT_ID_BASE, FETCH_EVENT_ID_BASE + (_page_entry_lookup.size() * 3));
    return false;
  }
  return true;
}

bool
HttpDataFetcherImpl::handleFetchEvent(TSEvent event, void *edata) {
  int base_event_id;
  if (!_isFetchEvent(event, base_event_id)) {
    TSError("[%s] Event %d is not a fetch event", __FUNCTION__, event);
    return false;
  }

  UrlToContentMap::iterator &req_entry = _page_entry_lookup[base_event_id];
  const string &req_str = req_entry->first;
  RequestData &req_data = req_entry->second;

  if (req_data.complete) {
    // can only happen if there's a bug in this or fetch API code
    TSError("[%s] URL [%s] already completed; Retaining original data", __FUNCTION__, req_str.c_str());
    return false;
  }

  --_n_pending_requests;
  req_data.complete = true;

  int event_id = (static_cast<int>(event) - FETCH_EVENT_ID_BASE) % 3;
  if (event_id != 0) { // failure or timeout
    TSError("[%s] Received failure/timeout event id %d for request [%s]",
             __FUNCTION__, event_id, req_str.data());
    return true;
  }

  int page_data_len;
  const char *page_data = TSFetchRespGet(static_cast<TSHttpTxn>(edata), &page_data_len);
  req_data.response.assign(page_data, page_data_len);
  bool valid_data_received = false;
  const char *startptr = req_data.response.data(), *endptr = startptr + page_data_len;

  req_data.bufp = TSMBufferCreate();
  req_data.hdr_loc = TSHttpHdrCreate(req_data.bufp);
  TSHttpHdrTypeSet(req_data.bufp, req_data.hdr_loc, TS_HTTP_TYPE_RESPONSE);
  TSHttpParserClear(_http_parser);

  if (TSHttpHdrParseResp(_http_parser, req_data.bufp, req_data.hdr_loc, &startptr, endptr) == TS_PARSE_DONE) {
    TSHttpStatus resp_status = TSHttpHdrStatusGet(req_data.bufp, req_data.hdr_loc);
    if (resp_status == TS_HTTP_STATUS_OK) {
      valid_data_received = true;
      req_data.body_len = endptr - startptr;
      req_data.body = startptr;
      TSDebug(_debug_tag,
               "[%s] Inserted page data of size %d starting with [%.6s] for request [%s]", __FUNCTION__,
               req_data.body_len, (req_data.body_len ? req_data.body : "(null)"), req_str.c_str());

      if (_checkHeaderValue(req_data.bufp, req_data.hdr_loc,
                       TS_MIME_FIELD_CONTENT_ENCODING,
                       TS_MIME_LEN_CONTENT_ENCODING,
                       TS_HTTP_VALUE_GZIP, TS_HTTP_LEN_GZIP, false)) {
        BufferList buf_list;
        req_data.raw_response = "";
        if (gunzip(req_data.body, req_data.body_len, buf_list)) {
          for (BufferList::iterator iter = buf_list.begin(); iter != buf_list.end(); ++iter) {
            req_data.raw_response.append(iter->data(),iter->size());
          }
          req_data.body_len = req_data.raw_response.size();
          req_data.body = req_data.raw_response.data();
        } else {
          TSError("[%s] Error while gunzipping data", __FUNCTION__);
        }
      }

      for (CallbackObjectList::iterator list_iter = req_data.callback_objects.begin();
           list_iter != req_data.callback_objects.end(); ++list_iter) {
        (*list_iter)->processData(req_str.data(), req_str.size(), req_data.body, req_data.body_len);
      }

    } else {
      TSDebug(_debug_tag, "[%s] Received non-OK status %d for request [%s]",
               __FUNCTION__, resp_status, req_str.data());
    }
  } else {
    TSDebug(_debug_tag, "[%s] Could not parse response for request [%s]",
             __FUNCTION__, req_str.data());
  }

  if (!valid_data_received) {
    _release(req_data);
    req_data.response.clear();
  }

  return true;
}

bool
HttpDataFetcherImpl::_checkHeaderValue(TSMBuffer bufp, TSMLoc hdr_loc, const char *name, int name_len,
                 const char *exp_value, int exp_value_len, bool prefix) const {
  TSMLoc field_loc = TSMimeHdrFieldFind(bufp, hdr_loc, name, name_len);
  if (!field_loc) {
    return false;
  }
  bool retval = false;
  if (exp_value && exp_value_len) {
    const char *value;
    int value_len;
    int n_values = TSMimeHdrFieldValuesCount(bufp, hdr_loc, field_loc);
    for (int i = 0; i < n_values; ++i) {
      value = TSMimeHdrFieldValueStringGet(bufp, hdr_loc, field_loc, i, &value_len);
      if ( NULL != value || value_len ) {
        if (prefix) {
          if ((value_len >= exp_value_len) &&
              (strncasecmp(value, exp_value, exp_value_len) == 0)) {
            retval = true;
          }
        } else if (Utils::areEqual(value, value_len, exp_value, exp_value_len)) {
          retval = true;
        }
      } else {
        TSDebug(_debug_tag, "[%s] Error while getting value # %d of header [%.*s]", __FUNCTION__,
                 i, name_len, name);
      }
      if (retval) {
        break;
      }
    }
  } else { // only presence required
    retval = true;
  }
  TSHandleMLocRelease(bufp, hdr_loc, field_loc);
  return retval;
}

bool
HttpDataFetcherImpl::getData(const string &url, ResponseData &resp_data) const {
  UrlToContentMap::const_iterator iter = _pages.find(url);
  if (iter == _pages.end()) {
    TSError("Content being requested for unregistered URL [%s]", url.data());
    return false;
  }
  const RequestData &req_data = iter->second; // handy reference
  if (!req_data.complete) {
    // request not completed yet
    TSError("Request for URL [%s] not complete", url.data());
    return false;
  }
  if (req_data.response.empty()) {
    // did not receive valid data
    TSError("No valid data received for URL [%s]; returning empty data to be safe", url.data());
    resp_data.clear();
    return false;
  }

  resp_data.set(req_data.body, req_data.body_len, req_data.bufp, req_data.hdr_loc);
  TSDebug(_debug_tag, "[%s] Found data for URL [%s] of size %d starting with [%.5s]",
           __FUNCTION__, url.data(), req_data.body_len, req_data.body);
  return true;
}

void
HttpDataFetcherImpl::clear() {
  for (UrlToContentMap::iterator iter = _pages.begin(); iter != _pages.end(); ++iter) {
    _release(iter->second);
  }
  _n_pending_requests = 0;
  _pages.clear();
  _page_entry_lookup.clear();
  _headers_str.clear();
  _curr_event_id_base = FETCH_EVENT_ID_BASE;
}

DataStatus
HttpDataFetcherImpl::getRequestStatus(const string &url) const {
  UrlToContentMap::const_iterator iter = _pages.find(url);
  if (iter == _pages.end()) {
    TSError("Status being requested for unregistered URL [%s]", url.data());
    return STATUS_ERROR;
  }
  if (!(iter->second).complete) {
    return STATUS_DATA_PENDING;
  }
  if ((iter->second).response.empty()) {
    return STATUS_ERROR;
  }
  return STATUS_DATA_AVAILABLE;
}

void
HttpDataFetcherImpl::useHeader(const HttpHeader &header) {
  // request data body would not be passed to async request and so we should not pass on the content length
  if (Utils::areEqual(header.name, header.name_len,
                      TS_MIME_FIELD_CONTENT_LENGTH, TS_MIME_LEN_CONTENT_LENGTH)) {
    return;
  }

  // should not support partial request for async request
  if (Utils::areEqual(header.name, header.name_len,
                      TS_MIME_FIELD_RANGE, TS_MIME_LEN_RANGE)) {
    return;
  }

  // should not support keep-alive for async requests
  if (Utils::areEqual(header.name, header.name_len,
              TS_MIME_FIELD_CONNECTION, TS_MIME_LEN_CONNECTION)) {
      return;
  }

  _headers_str.append(header.name, header.name_len);
  _headers_str.append(": ");
  _headers_str.append(header.value, header.value_len);
  _headers_str.append("\r\n");
}

void
HttpDataFetcherImpl::useHeaders(const HttpHeaderList &headers) {
  for (HttpHeaderList::const_iterator iter = headers.begin(); iter != headers.end(); ++iter) {
    useHeader(*iter);
  }
}
<commit_msg>TS-1690: Fix build on arm/Ubuntu/gcc 4.4<commit_after>/** @file

  A brief file description

  @section license License

  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
 */

#include "HttpDataFetcherImpl.h"
#include "Utils.h"
#include "gzip.h"

#include <arpa/inet.h>

using std::string;
using namespace EsiLib;

const int HttpDataFetcherImpl::FETCH_EVENT_ID_BASE = 10000;

inline void HttpDataFetcherImpl::_release(RequestData &req_data) {
  if (req_data.bufp) {
    if (req_data.hdr_loc) {
      TSHandleMLocRelease(req_data.bufp, TS_NULL_MLOC, req_data.hdr_loc);
      req_data.hdr_loc = 0;
    }
    TSMBufferDestroy(req_data.bufp);
    req_data.bufp = 0;
  }
}

HttpDataFetcherImpl::HttpDataFetcherImpl(TSCont contp,sockaddr const* client_addr,
                                         const char *debug_tag)
  : _contp(contp), _n_pending_requests(0), _curr_event_id_base(FETCH_EVENT_ID_BASE),
    _headers_str(""),_client_addr(client_addr) {
  _http_parser = TSHttpParserCreate();
  snprintf(_debug_tag, sizeof(_debug_tag), "%s", debug_tag);
}

HttpDataFetcherImpl::~HttpDataFetcherImpl() {
  clear();
  TSHttpParserDestroy(_http_parser);
}

bool
HttpDataFetcherImpl::addFetchRequest(const string &url, FetchedDataProcessor *callback_obj /* = 0 */) {
  // do we already have a request for this?
  std::pair<UrlToContentMap::iterator, bool> insert_result =
    _pages.insert(UrlToContentMap::value_type(url, RequestData()));
  if (callback_obj) {
    ((insert_result.first)->second).callback_objects.push_back(callback_obj);
  }
  if (!insert_result.second) {
    TSDebug(_debug_tag, "[%s] Fetch request for url [%s] already added", __FUNCTION__,
             url.data());
    return true;
  }

  char buff[1024];
  char *http_req;
  int length;

  length = sizeof("GET ") - 1 + url.length() + sizeof(" HTTP/1.0\r\n") - 1 + _headers_str.length() + sizeof("\r\n") - 1;
  if (length < (int)sizeof(buff)) {
    http_req = buff;
  }else {
    http_req = (char *)malloc(length + 1);
    if (http_req == NULL) {
      TSError("[%s] malloc %d bytes fail", __FUNCTION__, length + 1);
      return false;
    }
  }

  sprintf(http_req, "GET %s HTTP/1.0\r\n"
      "%s\r\n", url.c_str(), _headers_str.c_str());

  TSFetchEvent event_ids;
  event_ids.success_event_id = _curr_event_id_base;
  event_ids.failure_event_id = _curr_event_id_base + 1;
  event_ids.timeout_event_id = _curr_event_id_base + 2;
  _curr_event_id_base += 3;

  TSFetchUrl(http_req, length, _client_addr, _contp, AFTER_BODY,
                  event_ids);
  if (http_req != buff) {
    free(http_req);
  }

  TSDebug(_debug_tag, "[%s] Successfully added fetch request for URL [%s]",
           __FUNCTION__, url.data());
  _page_entry_lookup.push_back(insert_result.first);
  ++_n_pending_requests;
  return true;
}

bool
HttpDataFetcherImpl::_isFetchEvent(TSEvent event, int &base_event_id) const {
  base_event_id = _getBaseEventId(event);
  if ((base_event_id < 0) || (base_event_id >= static_cast<int>(_page_entry_lookup.size()))) {
    TSDebug(_debug_tag, "[%s] Event id %d not within fetch event id range [%d, %ld)",
             __FUNCTION__, event, FETCH_EVENT_ID_BASE, static_cast<long int>(FETCH_EVENT_ID_BASE + (_page_entry_lookup.size() * 3)));
    return false;
  }
  return true;
}

bool
HttpDataFetcherImpl::handleFetchEvent(TSEvent event, void *edata) {
  int base_event_id;
  if (!_isFetchEvent(event, base_event_id)) {
    TSError("[%s] Event %d is not a fetch event", __FUNCTION__, event);
    return false;
  }

  UrlToContentMap::iterator &req_entry = _page_entry_lookup[base_event_id];
  const string &req_str = req_entry->first;
  RequestData &req_data = req_entry->second;

  if (req_data.complete) {
    // can only happen if there's a bug in this or fetch API code
    TSError("[%s] URL [%s] already completed; Retaining original data", __FUNCTION__, req_str.c_str());
    return false;
  }

  --_n_pending_requests;
  req_data.complete = true;

  int event_id = (static_cast<int>(event) - FETCH_EVENT_ID_BASE) % 3;
  if (event_id != 0) { // failure or timeout
    TSError("[%s] Received failure/timeout event id %d for request [%s]",
             __FUNCTION__, event_id, req_str.data());
    return true;
  }

  int page_data_len;
  const char *page_data = TSFetchRespGet(static_cast<TSHttpTxn>(edata), &page_data_len);
  req_data.response.assign(page_data, page_data_len);
  bool valid_data_received = false;
  const char *startptr = req_data.response.data(), *endptr = startptr + page_data_len;

  req_data.bufp = TSMBufferCreate();
  req_data.hdr_loc = TSHttpHdrCreate(req_data.bufp);
  TSHttpHdrTypeSet(req_data.bufp, req_data.hdr_loc, TS_HTTP_TYPE_RESPONSE);
  TSHttpParserClear(_http_parser);

  if (TSHttpHdrParseResp(_http_parser, req_data.bufp, req_data.hdr_loc, &startptr, endptr) == TS_PARSE_DONE) {
    TSHttpStatus resp_status = TSHttpHdrStatusGet(req_data.bufp, req_data.hdr_loc);
    if (resp_status == TS_HTTP_STATUS_OK) {
      valid_data_received = true;
      req_data.body_len = endptr - startptr;
      req_data.body = startptr;
      TSDebug(_debug_tag,
               "[%s] Inserted page data of size %d starting with [%.6s] for request [%s]", __FUNCTION__,
               req_data.body_len, (req_data.body_len ? req_data.body : "(null)"), req_str.c_str());

      if (_checkHeaderValue(req_data.bufp, req_data.hdr_loc,
                       TS_MIME_FIELD_CONTENT_ENCODING,
                       TS_MIME_LEN_CONTENT_ENCODING,
                       TS_HTTP_VALUE_GZIP, TS_HTTP_LEN_GZIP, false)) {
        BufferList buf_list;
        req_data.raw_response = "";
        if (gunzip(req_data.body, req_data.body_len, buf_list)) {
          for (BufferList::iterator iter = buf_list.begin(); iter != buf_list.end(); ++iter) {
            req_data.raw_response.append(iter->data(),iter->size());
          }
          req_data.body_len = req_data.raw_response.size();
          req_data.body = req_data.raw_response.data();
        } else {
          TSError("[%s] Error while gunzipping data", __FUNCTION__);
        }
      }

      for (CallbackObjectList::iterator list_iter = req_data.callback_objects.begin();
           list_iter != req_data.callback_objects.end(); ++list_iter) {
        (*list_iter)->processData(req_str.data(), req_str.size(), req_data.body, req_data.body_len);
      }

    } else {
      TSDebug(_debug_tag, "[%s] Received non-OK status %d for request [%s]",
               __FUNCTION__, resp_status, req_str.data());
    }
  } else {
    TSDebug(_debug_tag, "[%s] Could not parse response for request [%s]",
             __FUNCTION__, req_str.data());
  }

  if (!valid_data_received) {
    _release(req_data);
    req_data.response.clear();
  }

  return true;
}

bool
HttpDataFetcherImpl::_checkHeaderValue(TSMBuffer bufp, TSMLoc hdr_loc, const char *name, int name_len,
                 const char *exp_value, int exp_value_len, bool prefix) const {
  TSMLoc field_loc = TSMimeHdrFieldFind(bufp, hdr_loc, name, name_len);
  if (!field_loc) {
    return false;
  }
  bool retval = false;
  if (exp_value && exp_value_len) {
    const char *value;
    int value_len;
    int n_values = TSMimeHdrFieldValuesCount(bufp, hdr_loc, field_loc);
    for (int i = 0; i < n_values; ++i) {
      value = TSMimeHdrFieldValueStringGet(bufp, hdr_loc, field_loc, i, &value_len);
      if ( NULL != value || value_len ) {
        if (prefix) {
          if ((value_len >= exp_value_len) &&
              (strncasecmp(value, exp_value, exp_value_len) == 0)) {
            retval = true;
          }
        } else if (Utils::areEqual(value, value_len, exp_value, exp_value_len)) {
          retval = true;
        }
      } else {
        TSDebug(_debug_tag, "[%s] Error while getting value # %d of header [%.*s]", __FUNCTION__,
                 i, name_len, name);
      }
      if (retval) {
        break;
      }
    }
  } else { // only presence required
    retval = true;
  }
  TSHandleMLocRelease(bufp, hdr_loc, field_loc);
  return retval;
}

bool
HttpDataFetcherImpl::getData(const string &url, ResponseData &resp_data) const {
  UrlToContentMap::const_iterator iter = _pages.find(url);
  if (iter == _pages.end()) {
    TSError("Content being requested for unregistered URL [%s]", url.data());
    return false;
  }
  const RequestData &req_data = iter->second; // handy reference
  if (!req_data.complete) {
    // request not completed yet
    TSError("Request for URL [%s] not complete", url.data());
    return false;
  }
  if (req_data.response.empty()) {
    // did not receive valid data
    TSError("No valid data received for URL [%s]; returning empty data to be safe", url.data());
    resp_data.clear();
    return false;
  }

  resp_data.set(req_data.body, req_data.body_len, req_data.bufp, req_data.hdr_loc);
  TSDebug(_debug_tag, "[%s] Found data for URL [%s] of size %d starting with [%.5s]",
           __FUNCTION__, url.data(), req_data.body_len, req_data.body);
  return true;
}

void
HttpDataFetcherImpl::clear() {
  for (UrlToContentMap::iterator iter = _pages.begin(); iter != _pages.end(); ++iter) {
    _release(iter->second);
  }
  _n_pending_requests = 0;
  _pages.clear();
  _page_entry_lookup.clear();
  _headers_str.clear();
  _curr_event_id_base = FETCH_EVENT_ID_BASE;
}

DataStatus
HttpDataFetcherImpl::getRequestStatus(const string &url) const {
  UrlToContentMap::const_iterator iter = _pages.find(url);
  if (iter == _pages.end()) {
    TSError("Status being requested for unregistered URL [%s]", url.data());
    return STATUS_ERROR;
  }
  if (!(iter->second).complete) {
    return STATUS_DATA_PENDING;
  }
  if ((iter->second).response.empty()) {
    return STATUS_ERROR;
  }
  return STATUS_DATA_AVAILABLE;
}

void
HttpDataFetcherImpl::useHeader(const HttpHeader &header) {
  // request data body would not be passed to async request and so we should not pass on the content length
  if (Utils::areEqual(header.name, header.name_len,
                      TS_MIME_FIELD_CONTENT_LENGTH, TS_MIME_LEN_CONTENT_LENGTH)) {
    return;
  }

  // should not support partial request for async request
  if (Utils::areEqual(header.name, header.name_len,
                      TS_MIME_FIELD_RANGE, TS_MIME_LEN_RANGE)) {
    return;
  }

  // should not support keep-alive for async requests
  if (Utils::areEqual(header.name, header.name_len,
              TS_MIME_FIELD_CONNECTION, TS_MIME_LEN_CONNECTION)) {
      return;
  }

  _headers_str.append(header.name, header.name_len);
  _headers_str.append(": ");
  _headers_str.append(header.value, header.value_len);
  _headers_str.append("\r\n");
}

void
HttpDataFetcherImpl::useHeaders(const HttpHeaderList &headers) {
  for (HttpHeaderList::const_iterator iter = headers.begin(); iter != headers.end(); ++iter) {
    useHeader(*iter);
  }
}
<|endoftext|>


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

#include "ResId.hxx"
#include "TabPages.hrc"
#include "SchSfxItemIds.hxx"
/*
#include "Strings.hrc"
#include "Bitmaps.hrc"
#include "Bitmaps_HC.hrc"
*/

/*
#ifndef _SVX_SVXIDS_HRC //autogen
#include <svx/svxids.hrc>
#endif
#include "schattr.hxx"
*/
// header for class SfxInt32Item
#ifndef _SFXINTITEM_HXX
#include <svtools/intitem.hxx>
#endif
//#define ITEMID_CHARTTEXTORDER SCHATTR_TEXT_ORDER
// #define ITEMID_CHARTTEXTORIENT   SCHATTR_TEXT_ORIENT
#ifndef _SVX_CHRTITEM_HXX //autogen
#include <svx/chrtitem.hxx>
#endif
/*
#include "schresid.hxx"
#include "strings.hrc"
#include "chtmodel.hxx"
#include "attrib.hxx"
#include "attrib.hrc"
#include "app.hrc"
*/

//.............................................................................
namespace chart
{
//.............................................................................

SchAlignmentTabPage::SchAlignmentTabPage(Window* pWindow,
                                         const SfxItemSet& rInAttrs) :
    SfxTabPage(pWindow, SchResId(TP_ALIGNMENT), rInAttrs),

//  aCbxTextBreak   ( this, ResId( CBX_TEXTBREAK ) ),
//  aCbxTextOverlap ( this, ResId( CBX_TEXTOVERLAP ) ),
//  aFlTextBreak    ( this, ResId( FL_TEXTBREAK ) ),
//  aRbtSideBySide(this, ResId(RBT_SIDEBYSIDE)),
//  aRbtUpDown(this, ResId(RBT_UPDOWN)),
//  aRbtDownUp(this, ResId(RBT_DOWNUP)),
//  aRbtAutoOrder(this, ResId(RBT_AUTOORDER)),
//  aFlOrder(this, ResId(FL_ORDER)),
//  eOrderMode(CHORDMODE_X_AXIS),

    //Seit 4/1998 koennen Texte frei gedreht werden: SCHATTR_TEXT_DEGREES
    aFlAlign        ( this, ResId( FL_ALIGN ) ),
    aCtrlDial       ( this, ResId( CTR_DIAL ) ),
    aFtRotate       ( this, ResId( FT_DEGREES ) ),
    aNfRotate       ( this, ResId( NF_ORIENT ) ),
    aCbStacked      ( this, ResId( BTN_TXTSTACKED ) ),
    aOrientHlp      ( this, aCtrlDial, aNfRotate, aCbStacked )

{
    FreeResource();

    aCbStacked.EnableTriState( FALSE );
    aOrientHlp.AddDependentWindow( aFtRotate, STATE_CHECK );
}

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

SchAlignmentTabPage::~SchAlignmentTabPage()
{
}

/*************************************************************************
|*
|* Markierungs-Handler
|*
\************************************************************************/

/*
IMPL_LINK( SchAlignmentTabPage, CheckButtonHdl, Button *, pBtn )
{

    if (eOrderMode != CHORDMODE_NONE)
    {
        BOOL bEnable=TRUE;
        aRbtSideBySide.Enable(bEnable);
        aRbtUpDown.Enable(bEnable);
        aRbtDownUp.Enable(bEnable);
        aRbtAutoOrder.Enable(bEnable);
        aFlOrder.Enable(bEnable);
    }
    return 0;
}
*/

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

SfxTabPage* SchAlignmentTabPage::Create(Window* pWindow,
                                        const SfxItemSet& rOutAttrs)
{
    return new SchAlignmentTabPage(pWindow, rOutAttrs);
}

/*************************************************************************
|*
|* Fuellt uebergebenen Item-Set mit Dialogbox-Attributen
|*
\*************************************************************************/

BOOL SchAlignmentTabPage::FillItemSet(SfxItemSet& rOutAttrs)
{
    //Seit 4/1998 koennen Texte frei gedreht werden: SCHATTR_TEXT_DEGREES
    bool bStacked = aOrientHlp.GetStackedState() == STATE_CHECK;
    rOutAttrs.Put( SfxBoolItem( SCHATTR_TEXT_STACKED, bStacked ) );

    sal_Int32 nDegrees = bStacked ? 0 : aCtrlDial.GetRotation();
    rOutAttrs.Put( SfxInt32Item( SCHATTR_TEXT_DEGREES, nDegrees ) );

    /*
    if (eOrderMode != CHORDMODE_NONE)
    {
        SvxChartTextOrder eOrder;

//      if (aRbtUpDown.IsChecked()) eOrder = CHTXTORDER_UPDOWN;
//      else if (aRbtDownUp.IsChecked()) eOrder = CHTXTORDER_DOWNUP;
//           else if (aRbtAutoOrder.IsChecked()) eOrder = CHTXTORDER_AUTO;
                  else eOrder = CHTXTORDER_SIDEBYSIDE;

        rOutAttrs.Put(SvxChartTextOrderItem(eOrder));
    }
    */

    // Textumbruch
//  BOOL bTextOverlap = aCbxTextOverlap.IsChecked();
//  rOutAttrs.Put( SfxBoolItem( SCHATTR_TEXT_OVERLAP, bTextOverlap ) );

//  BOOL bTextBreak = aCbxTextBreak.IsChecked();
//  rOutAttrs.Put( SfxBoolItem( SID_TEXTBREAK, bTextBreak ) );

    /*
    BOOL                bAttrsChanged   = FALSE;
    const SfxItemSet&   rOldSet         = GetItemSet();
    */
//  TriState            eState;

    return TRUE;
}

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

void SchAlignmentTabPage::Reset(const SfxItemSet& rInAttrs)
{
    const SfxPoolItem *pPoolItem = NULL;

    /*
    if (rInAttrs.GetItemState(SCHATTR_TEXT_ORDER,
                              TRUE, &pPoolItem) == SFX_ITEM_SET &&
        eOrderMode != CHORDMODE_NONE)
    {
        switch (((const SvxChartTextOrderItem*)pPoolItem)->GetValue())
        {
            case CHTXTORDER_SIDEBYSIDE:
                aRbtSideBySide.Check(TRUE);
                break;

            case CHTXTORDER_UPDOWN:
                aRbtUpDown.Check(TRUE);
                break;

            case CHTXTORDER_DOWNUP:
                aRbtDownUp.Check(TRUE);
                break;

            case CHTXTORDER_AUTO:
                aRbtAutoOrder.Check(TRUE);
                break;
        }
    }
    */

    //Seit 4/1998 koennen Texte frei gedreht werden: SCHATTR_TEXT_DEGREES
    const SfxPoolItem* pItem;

    pItem = GetItem( rInAttrs, SCHATTR_TEXT_DEGREES );
    sal_Int32 nDegrees = pItem ? ((const SfxInt32Item*)pItem)->GetValue() : 0;
    aCtrlDial.SetRotation( nDegrees );

    pItem = GetItem( rInAttrs, SCHATTR_TEXT_STACKED );
    bool bStacked = pItem && ((const SfxBoolItem*)pItem)->GetValue();
    aOrientHlp.SetStackedState( bStacked ? STATE_CHECK : STATE_NOCHECK );

    // Textumbruch
    /*
    if( rInAttrs.GetItemState( SID_TEXTBREAK, FALSE, &pPoolItem ) >= SFX_ITEM_AVAILABLE )
    {
        BOOL bTextBreak = ( (const SfxBoolItem*) pPoolItem)->GetValue();
//      aCbxTextBreak.Check( bTextBreak );
    }
    else
    {
//      aCbxTextBreak.Hide();
//      aFlTextBreak.Hide();
    }
    // Textueberlapp
    if( (rInAttrs.GetItemState( SCHATTR_TEXT_OVERLAP, FALSE, &pPoolItem ) >= SFX_ITEM_AVAILABLE) && bTextCanOverlap)
    {
        BOOL bTextOverlap = ( (const SfxBoolItem*) pPoolItem)->GetValue();
//      aCbxTextOverlap.Check( bTextOverlap );
    }
    else
    {
//      aCbxTextOverlap.Hide();
    }
    */
}

/*************************************************************************
|*
|* Anordnungs-Controls hiden
|*
\*************************************************************************/

/*
void SchAlignmentTabPage::SetOrderMode(OrderMode eMode)
{
    eOrderMode = eMode;

    if (eOrderMode == CHORDMODE_NONE)
    {
        aRbtSideBySide.Hide();
        aRbtUpDown.Hide();
        aRbtDownUp.Hide();
        aRbtAutoOrder.Hide();
        aFlOrder.Hide();
    }
}
*/

//.............................................................................
} //namespace chart
//.............................................................................

<commit_msg>INTEGRATION: CWS pchfix02 (1.5.80); FILE MERGED 2006/09/01 17:18:36 kaib 1.5.80.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: tp_TitleRotation.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 13:00:18 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "tp_TitleRotation.hxx"

#include "ResId.hxx"
#include "TabPages.hrc"
#include "SchSfxItemIds.hxx"
/*
#include "Strings.hrc"
#include "Bitmaps.hrc"
#include "Bitmaps_HC.hrc"
*/

/*
#ifndef _SVX_SVXIDS_HRC //autogen
#include <svx/svxids.hrc>
#endif
#include "schattr.hxx"
*/
// header for class SfxInt32Item
#ifndef _SFXINTITEM_HXX
#include <svtools/intitem.hxx>
#endif
//#define ITEMID_CHARTTEXTORDER SCHATTR_TEXT_ORDER
// #define ITEMID_CHARTTEXTORIENT   SCHATTR_TEXT_ORIENT
#ifndef _SVX_CHRTITEM_HXX //autogen
#include <svx/chrtitem.hxx>
#endif
/*
#include "schresid.hxx"
#include "strings.hrc"
#include "chtmodel.hxx"
#include "attrib.hxx"
#include "attrib.hrc"
#include "app.hrc"
*/

//.............................................................................
namespace chart
{
//.............................................................................

SchAlignmentTabPage::SchAlignmentTabPage(Window* pWindow,
                                         const SfxItemSet& rInAttrs) :
    SfxTabPage(pWindow, SchResId(TP_ALIGNMENT), rInAttrs),

//  aCbxTextBreak   ( this, ResId( CBX_TEXTBREAK ) ),
//  aCbxTextOverlap ( this, ResId( CBX_TEXTOVERLAP ) ),
//  aFlTextBreak    ( this, ResId( FL_TEXTBREAK ) ),
//  aRbtSideBySide(this, ResId(RBT_SIDEBYSIDE)),
//  aRbtUpDown(this, ResId(RBT_UPDOWN)),
//  aRbtDownUp(this, ResId(RBT_DOWNUP)),
//  aRbtAutoOrder(this, ResId(RBT_AUTOORDER)),
//  aFlOrder(this, ResId(FL_ORDER)),
//  eOrderMode(CHORDMODE_X_AXIS),

    //Seit 4/1998 koennen Texte frei gedreht werden: SCHATTR_TEXT_DEGREES
    aFlAlign        ( this, ResId( FL_ALIGN ) ),
    aCtrlDial       ( this, ResId( CTR_DIAL ) ),
    aFtRotate       ( this, ResId( FT_DEGREES ) ),
    aNfRotate       ( this, ResId( NF_ORIENT ) ),
    aCbStacked      ( this, ResId( BTN_TXTSTACKED ) ),
    aOrientHlp      ( this, aCtrlDial, aNfRotate, aCbStacked )

{
    FreeResource();

    aCbStacked.EnableTriState( FALSE );
    aOrientHlp.AddDependentWindow( aFtRotate, STATE_CHECK );
}

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

SchAlignmentTabPage::~SchAlignmentTabPage()
{
}

/*************************************************************************
|*
|* Markierungs-Handler
|*
\************************************************************************/

/*
IMPL_LINK( SchAlignmentTabPage, CheckButtonHdl, Button *, pBtn )
{

    if (eOrderMode != CHORDMODE_NONE)
    {
        BOOL bEnable=TRUE;
        aRbtSideBySide.Enable(bEnable);
        aRbtUpDown.Enable(bEnable);
        aRbtDownUp.Enable(bEnable);
        aRbtAutoOrder.Enable(bEnable);
        aFlOrder.Enable(bEnable);
    }
    return 0;
}
*/

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

SfxTabPage* SchAlignmentTabPage::Create(Window* pWindow,
                                        const SfxItemSet& rOutAttrs)
{
    return new SchAlignmentTabPage(pWindow, rOutAttrs);
}

/*************************************************************************
|*
|* Fuellt uebergebenen Item-Set mit Dialogbox-Attributen
|*
\*************************************************************************/

BOOL SchAlignmentTabPage::FillItemSet(SfxItemSet& rOutAttrs)
{
    //Seit 4/1998 koennen Texte frei gedreht werden: SCHATTR_TEXT_DEGREES
    bool bStacked = aOrientHlp.GetStackedState() == STATE_CHECK;
    rOutAttrs.Put( SfxBoolItem( SCHATTR_TEXT_STACKED, bStacked ) );

    sal_Int32 nDegrees = bStacked ? 0 : aCtrlDial.GetRotation();
    rOutAttrs.Put( SfxInt32Item( SCHATTR_TEXT_DEGREES, nDegrees ) );

    /*
    if (eOrderMode != CHORDMODE_NONE)
    {
        SvxChartTextOrder eOrder;

//      if (aRbtUpDown.IsChecked()) eOrder = CHTXTORDER_UPDOWN;
//      else if (aRbtDownUp.IsChecked()) eOrder = CHTXTORDER_DOWNUP;
//           else if (aRbtAutoOrder.IsChecked()) eOrder = CHTXTORDER_AUTO;
                  else eOrder = CHTXTORDER_SIDEBYSIDE;

        rOutAttrs.Put(SvxChartTextOrderItem(eOrder));
    }
    */

    // Textumbruch
//  BOOL bTextOverlap = aCbxTextOverlap.IsChecked();
//  rOutAttrs.Put( SfxBoolItem( SCHATTR_TEXT_OVERLAP, bTextOverlap ) );

//  BOOL bTextBreak = aCbxTextBreak.IsChecked();
//  rOutAttrs.Put( SfxBoolItem( SID_TEXTBREAK, bTextBreak ) );

    /*
    BOOL                bAttrsChanged   = FALSE;
    const SfxItemSet&   rOldSet         = GetItemSet();
    */
//  TriState            eState;

    return TRUE;
}

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

void SchAlignmentTabPage::Reset(const SfxItemSet& rInAttrs)
{
    const SfxPoolItem *pPoolItem = NULL;

    /*
    if (rInAttrs.GetItemState(SCHATTR_TEXT_ORDER,
                              TRUE, &pPoolItem) == SFX_ITEM_SET &&
        eOrderMode != CHORDMODE_NONE)
    {
        switch (((const SvxChartTextOrderItem*)pPoolItem)->GetValue())
        {
            case CHTXTORDER_SIDEBYSIDE:
                aRbtSideBySide.Check(TRUE);
                break;

            case CHTXTORDER_UPDOWN:
                aRbtUpDown.Check(TRUE);
                break;

            case CHTXTORDER_DOWNUP:
                aRbtDownUp.Check(TRUE);
                break;

            case CHTXTORDER_AUTO:
                aRbtAutoOrder.Check(TRUE);
                break;
        }
    }
    */

    //Seit 4/1998 koennen Texte frei gedreht werden: SCHATTR_TEXT_DEGREES
    const SfxPoolItem* pItem;

    pItem = GetItem( rInAttrs, SCHATTR_TEXT_DEGREES );
    sal_Int32 nDegrees = pItem ? ((const SfxInt32Item*)pItem)->GetValue() : 0;
    aCtrlDial.SetRotation( nDegrees );

    pItem = GetItem( rInAttrs, SCHATTR_TEXT_STACKED );
    bool bStacked = pItem && ((const SfxBoolItem*)pItem)->GetValue();
    aOrientHlp.SetStackedState( bStacked ? STATE_CHECK : STATE_NOCHECK );

    // Textumbruch
    /*
    if( rInAttrs.GetItemState( SID_TEXTBREAK, FALSE, &pPoolItem ) >= SFX_ITEM_AVAILABLE )
    {
        BOOL bTextBreak = ( (const SfxBoolItem*) pPoolItem)->GetValue();
//      aCbxTextBreak.Check( bTextBreak );
    }
    else
    {
//      aCbxTextBreak.Hide();
//      aFlTextBreak.Hide();
    }
    // Textueberlapp
    if( (rInAttrs.GetItemState( SCHATTR_TEXT_OVERLAP, FALSE, &pPoolItem ) >= SFX_ITEM_AVAILABLE) && bTextCanOverlap)
    {
        BOOL bTextOverlap = ( (const SfxBoolItem*) pPoolItem)->GetValue();
//      aCbxTextOverlap.Check( bTextOverlap );
    }
    else
    {
//      aCbxTextOverlap.Hide();
    }
    */
}

/*************************************************************************
|*
|* Anordnungs-Controls hiden
|*
\*************************************************************************/

/*
void SchAlignmentTabPage::SetOrderMode(OrderMode eMode)
{
    eOrderMode = eMode;

    if (eOrderMode == CHORDMODE_NONE)
    {
        aRbtSideBySide.Hide();
        aRbtUpDown.Hide();
        aRbtDownUp.Hide();
        aRbtAutoOrder.Hide();
        aFlOrder.Hide();
    }
}
*/

//.............................................................................
} //namespace chart
//.............................................................................

<|endoftext|>


<commit_before>#pragma once
/// A class that behaves a bit like a string, but work off of long lived const char* data, and help avoid copying of data
#include <algorithm>
#include <cassert>

namespace cdnalizer {

using iterator = const char*;
using base_pair = std::pair<iterator, iterator>;

struct pair : base_pair {
    pair() : base_pair() {};
    pair(iterator first, iterator second) : base_pair(first, second) {};
    int length() const { return second-first; }
    char operator[](int i) const {
        assert(i < length());
        return first[i];
    }
    operator bool() const { return length() > 0; }
    bool operator <(const pair& other) const {
        return std::lexicographical_compare(
            first, second,
            other.first, other.second);
    }
    bool operator <(const std::string& other) const {
        return std::lexicographical_compare(
            first, second,
            other.begin(), other.end());
    }
    bool operator ==(const pair& other) const {
        if ((first == other.first) && (second == other.second))
            return std::equal(first, second, other.first);
        return false;
    }
    bool operator ==(const std::string& other) const {
        if (length() == other.length())
            return std::equal(first, second, other.cbegin());
        return false;
    }
};

bool operator <(const std::string& a, const pair& b) {
        return std::lexicographical_compare(
            a.begin(), a.end(),
            b.first, b.second);
}

bool operator ==(const std::string& a, const pair& b) { return b == a; }

}
<commit_msg>Commented the code a bit<commit_after>#pragma once
/// A class that behaves a bit like a string, but work off of long lived const char* data, and help avoid copying of data
#include <algorithm>
#include <cassert>

namespace cdnalizer {

using iterator = const char*;
using base_pair = std::pair<iterator, iterator>;

/** A pair of iterators into a const char array.
 *
 * Designed to minimize data copying when working with const char arrays.
 *
 * It gives you some of the features you know and love from string,
 * but is very minimal as it only stores two pointers, to the start and one past the end of the array.
 *
 */
struct pair : base_pair {
    pair() : base_pair() {};
    pair(iterator first, iterator second) : base_pair(first, second) {};
    /// @return the length of the selection
    size_t length() const {
        assert(second>first); // You have a pair (string) with a negative length
        return second-first;
    }
    /// Subscript into the selection
    char operator[](int i) const {
        assert(i < length());
        return first[i];
    }
    /// @returns true if we have some data
    operator bool() const { return length() > 0; }
    /// Allows sorting with other paths
    bool operator <(const pair& other) const {
        return std::lexicographical_compare(
            first, second,
            other.first, other.second);
    }
    /// Allows sorting amongst normal strings
    bool operator <(const std::string& other) const {
        return std::lexicographical_compare(
            first, second,
            other.begin(), other.end());
    }
    /// Compare to another path - @returns true if they both contain the same leterns
    bool operator ==(const pair& other) const {
        if (length() == other.length())
            return std::equal(first, second, other.first);
        return false;
    }
    /// Compare to a string
    bool operator ==(const std::string& other) const {
        if (length() == other.length())
            return std::equal(first, second, other.cbegin());
        return false;
    }
};

/// Allows sorting amongst a list of strings
bool operator <(const std::string& a, const pair& b) {
        return std::lexicographical_compare(
            a.begin(), a.end(),
            b.first, b.second);
}

/// Allows comparing to a string, when the string is the lhs argument
bool operator ==(const std::string& a, const pair& b) { return b == a; }

}
<|endoftext|>