text
stringlengths 54
60.6k
|
---|
<commit_before>/****************************************************************************
*
* Copyright (c) 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 "SDP3X.hpp"
/**
* @file SDP3X.hpp
*
* Driver for Sensirion SDP3X Differential Pressure Sensor
*
*/
int
SDP3X::probe()
{
return !init_sdp3x();
}
int SDP3X::write_command(uint16_t command)
{
uint8_t cmd[2];
cmd[0] = static_cast<uint8_t>(command >> 8);
cmd[1] = static_cast<uint8_t>(command & 0xff);
return transfer(&cmd[0], 2, nullptr, 0);
}
bool
SDP3X::init_sdp3x()
{
// step 1 - reset on broadcast
uint16_t prev_addr = get_address();
set_address(SDP3X_RESET_ADDR);
uint8_t reset_cmd = SDP3X_RESET_CMD;
int ret = transfer(&reset_cmd, 1, nullptr, 0);
set_address(prev_addr);
if (ret != PX4_OK) {
perf_count(_comms_errors);
PX4_ERR("reset failed");
return false;
}
// wait until sensor is ready
usleep(20000);
// step 2 - configure
ret = write_command(SDP3X_CONT_MEAS_AVG_MODE);
if (ret != PX4_OK) {
perf_count(_comms_errors);
PX4_ERR("config failed");
return false;
}
usleep(10000);
// step 3 - get scale
uint8_t val[9];
ret = transfer(nullptr, 0, &val[0], 9);
if (ret != PX4_OK) {
perf_count(_comms_errors);
PX4_ERR("get scale failed");
return false;
}
// Check the CRC
if (!crc(&val[0], 2, val[2]) || !crc(&val[3], 2, val[5]) || !crc(&val[6], 2, val[8])) {
perf_count(_comms_errors);
return false;
}
_scale = (((uint16_t)val[6]) << 8) | val[7];
return true;
}
int
SDP3X::collect()
{
perf_begin(_sample_perf);
// read 6 bytes from the sensor
uint8_t val[6];
int ret = transfer(nullptr, 0, &val[0], 6);
if (ret != PX4_OK) {
perf_count(_comms_errors);
return ret;
}
// Check the CRC
if (!crc(&val[0], 2, val[2]) || !crc(&val[3], 2, val[5])) {
perf_count(_comms_errors);
return EAGAIN;
} else {
ret = 0;
}
int16_t P = (((uint16_t)val[0]) << 8) | val[1];
int16_t temp = (((uint16_t)val[3]) << 8) | val[4];
float diff_press_pa_raw = static_cast<float>(P) / static_cast<float>(_scale);
float temperature_c = temp / static_cast<float>(SDP3X_SCALE_TEMPERATURE);
// the raw value still should be compensated for the known offset
diff_press_pa_raw -= _diff_pres_offset;
differential_pressure_s report;
// track maximum differential pressure measured (so we can work out top speed).
if (diff_press_pa_raw > _max_differential_pressure_pa) {
_max_differential_pressure_pa = diff_press_pa_raw;
}
report.timestamp = hrt_absolute_time();
report.error_count = perf_event_count(_comms_errors);
report.temperature = temperature_c;
report.differential_pressure_filtered_pa = _filter.apply(diff_press_pa_raw);
report.differential_pressure_raw_pa = diff_press_pa_raw;
report.max_differential_pressure_pa = _max_differential_pressure_pa;
if (_airspeed_pub != nullptr && !(_pub_blocked)) {
// publish it
orb_publish(ORB_ID(differential_pressure), _airspeed_pub, &report);
}
new_report(report);
// notify anyone waiting for data
poll_notify(POLLIN);
ret = OK;
perf_end(_sample_perf);
return ret;
}
void
SDP3X::cycle()
{
int ret = PX4_ERROR;
// measurement phase
ret = collect();
if (PX4_OK != ret) {
_sensor_ok = false;
DEVICE_DEBUG("measure error");
}
// schedule a fresh cycle call when the measurement is done
work_queue(HPWORK, &_work, (worker_t)&Airspeed::cycle_trampoline, this, USEC2TICK(CONVERSION_INTERVAL));
}
bool SDP3X::crc(const uint8_t data[], unsigned size, uint8_t checksum)
{
uint8_t crc = 0xff;
// calculate 8-bit checksum with polynomial 0x31 (x^8 + x^5 + x^4 + 1)
for (unsigned i = 0; i < size; i++) {
crc ^= (data[i]);
for (int bit = 8; bit > 0; --bit) {
if (crc & 0x80) {
crc = (crc << 1) ^ 0x31;
} else {
crc = (crc << 1);
}
}
}
// verify checksum
return (crc == checksum);
}
<commit_msg>sdp3x_airspeed: fix shadowing warning for crc<commit_after>/****************************************************************************
*
* Copyright (c) 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 "SDP3X.hpp"
/**
* @file SDP3X.hpp
*
* Driver for Sensirion SDP3X Differential Pressure Sensor
*
*/
int
SDP3X::probe()
{
return !init_sdp3x();
}
int SDP3X::write_command(uint16_t command)
{
uint8_t cmd[2];
cmd[0] = static_cast<uint8_t>(command >> 8);
cmd[1] = static_cast<uint8_t>(command & 0xff);
return transfer(&cmd[0], 2, nullptr, 0);
}
bool
SDP3X::init_sdp3x()
{
// step 1 - reset on broadcast
uint16_t prev_addr = get_address();
set_address(SDP3X_RESET_ADDR);
uint8_t reset_cmd = SDP3X_RESET_CMD;
int ret = transfer(&reset_cmd, 1, nullptr, 0);
set_address(prev_addr);
if (ret != PX4_OK) {
perf_count(_comms_errors);
PX4_ERR("reset failed");
return false;
}
// wait until sensor is ready
usleep(20000);
// step 2 - configure
ret = write_command(SDP3X_CONT_MEAS_AVG_MODE);
if (ret != PX4_OK) {
perf_count(_comms_errors);
PX4_ERR("config failed");
return false;
}
usleep(10000);
// step 3 - get scale
uint8_t val[9];
ret = transfer(nullptr, 0, &val[0], 9);
if (ret != PX4_OK) {
perf_count(_comms_errors);
PX4_ERR("get scale failed");
return false;
}
// Check the CRC
if (!crc(&val[0], 2, val[2]) || !crc(&val[3], 2, val[5]) || !crc(&val[6], 2, val[8])) {
perf_count(_comms_errors);
return false;
}
_scale = (((uint16_t)val[6]) << 8) | val[7];
return true;
}
int
SDP3X::collect()
{
perf_begin(_sample_perf);
// read 6 bytes from the sensor
uint8_t val[6];
int ret = transfer(nullptr, 0, &val[0], 6);
if (ret != PX4_OK) {
perf_count(_comms_errors);
return ret;
}
// Check the CRC
if (!crc(&val[0], 2, val[2]) || !crc(&val[3], 2, val[5])) {
perf_count(_comms_errors);
return EAGAIN;
} else {
ret = 0;
}
int16_t P = (((uint16_t)val[0]) << 8) | val[1];
int16_t temp = (((uint16_t)val[3]) << 8) | val[4];
float diff_press_pa_raw = static_cast<float>(P) / static_cast<float>(_scale);
float temperature_c = temp / static_cast<float>(SDP3X_SCALE_TEMPERATURE);
// the raw value still should be compensated for the known offset
diff_press_pa_raw -= _diff_pres_offset;
differential_pressure_s report;
// track maximum differential pressure measured (so we can work out top speed).
if (diff_press_pa_raw > _max_differential_pressure_pa) {
_max_differential_pressure_pa = diff_press_pa_raw;
}
report.timestamp = hrt_absolute_time();
report.error_count = perf_event_count(_comms_errors);
report.temperature = temperature_c;
report.differential_pressure_filtered_pa = _filter.apply(diff_press_pa_raw);
report.differential_pressure_raw_pa = diff_press_pa_raw;
report.max_differential_pressure_pa = _max_differential_pressure_pa;
if (_airspeed_pub != nullptr && !(_pub_blocked)) {
// publish it
orb_publish(ORB_ID(differential_pressure), _airspeed_pub, &report);
}
new_report(report);
// notify anyone waiting for data
poll_notify(POLLIN);
ret = OK;
perf_end(_sample_perf);
return ret;
}
void
SDP3X::cycle()
{
int ret = PX4_ERROR;
// measurement phase
ret = collect();
if (PX4_OK != ret) {
_sensor_ok = false;
DEVICE_DEBUG("measure error");
}
// schedule a fresh cycle call when the measurement is done
work_queue(HPWORK, &_work, (worker_t)&Airspeed::cycle_trampoline, this, USEC2TICK(CONVERSION_INTERVAL));
}
bool SDP3X::crc(const uint8_t data[], unsigned size, uint8_t checksum)
{
uint8_t crc_value = 0xff;
// calculate 8-bit checksum with polynomial 0x31 (x^8 + x^5 + x^4 + 1)
for (unsigned i = 0; i < size; i++) {
crc_value ^= (data[i]);
for (int bit = 8; bit > 0; --bit) {
if (crc_value & 0x80) {
crc_value = (crc_value << 1) ^ 0x31;
} else {
crc_value = (crc_value << 1);
}
}
}
// verify checksum
return (crc_value == checksum);
}
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (c) 2013, 2014 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file ets_airspeed.cpp
* @author Simon Wilks
*
* Driver for the Eagle Tree Airspeed V3 connected via I2C.
*/
#include <nuttx/config.h>
#include <drivers/device/i2c.h>
#include <sys/types.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdbool.h>
#include <semaphore.h>
#include <string.h>
#include <fcntl.h>
#include <poll.h>
#include <errno.h>
#include <stdio.h>
#include <math.h>
#include <unistd.h>
#include <nuttx/arch.h>
#include <nuttx/wqueue.h>
#include <nuttx/clock.h>
#include <arch/board/board.h>
#include <systemlib/airspeed.h>
#include <systemlib/err.h>
#include <systemlib/param/param.h>
#include <systemlib/perf_counter.h>
#include <drivers/drv_airspeed.h>
#include <drivers/drv_hrt.h>
#include <drivers/device/ringbuffer.h>
#include <uORB/uORB.h>
#include <uORB/topics/differential_pressure.h>
#include <uORB/topics/subsystem_info.h>
#include <drivers/airspeed/airspeed.h>
Airspeed::Airspeed(int bus, int address, unsigned conversion_interval, const char* path) :
I2C("Airspeed", path, bus, address, 100000),
_reports(nullptr),
_buffer_overflows(perf_alloc(PC_COUNT, "airspeed_buffer_overflows")),
_max_differential_pressure_pa(0),
_sensor_ok(false),
_last_published_sensor_ok(true), /* initialize differently to force publication */
_measure_ticks(0),
_collect_phase(false),
_diff_pres_offset(0.0f),
_airspeed_pub(-1),
_subsys_pub(-1),
_class_instance(-1),
_conversion_interval(conversion_interval),
_sample_perf(perf_alloc(PC_ELAPSED, "airspeed_read")),
_comms_errors(perf_alloc(PC_COUNT, "airspeed_comms_errors"))
{
// enable debug() calls
_debug_enabled = false;
// work_cancel in the dtor will explode if we don't do this...
memset(&_work, 0, sizeof(_work));
}
Airspeed::~Airspeed()
{
/* make sure we are truly inactive */
stop();
if (_class_instance != -1)
unregister_class_devname(AIRSPEED_BASE_DEVICE_PATH, _class_instance);
/* free any existing reports */
if (_reports != nullptr)
delete _reports;
// free perf counters
perf_free(_sample_perf);
perf_free(_comms_errors);
perf_free(_buffer_overflows);
}
int
Airspeed::init()
{
int ret = ERROR;
/* do I2C init (and probe) first */
if (I2C::init() != OK)
goto out;
/* allocate basic report buffers */
_reports = new RingBuffer(2, sizeof(differential_pressure_s));
if (_reports == nullptr)
goto out;
/* register alternate interfaces if we have to */
_class_instance = register_class_devname(AIRSPEED_BASE_DEVICE_PATH);
/* publication init */
if (_class_instance == CLASS_DEVICE_PRIMARY) {
/* advertise sensor topic, measure manually to initialize valid report */
struct differential_pressure_s arp;
measure();
_reports->get(&arp);
/* measurement will have generated a report, publish */
_airspeed_pub = orb_advertise(ORB_ID(differential_pressure), &arp);
if (_airspeed_pub < 0)
warnx("uORB started?");
}
ret = OK;
out:
return ret;
}
int
Airspeed::probe()
{
/* on initial power up the device may need more than one retry
for detection. Once it is running the number of retries can
be reduced
*/
_retries = 4;
int ret = measure();
// drop back to 2 retries once initialised
_retries = 2;
return ret;
}
int
Airspeed::ioctl(struct file *filp, int cmd, unsigned long arg)
{
switch (cmd) {
case SENSORIOCSPOLLRATE: {
switch (arg) {
/* switching to manual polling */
case SENSOR_POLLRATE_MANUAL:
stop();
_measure_ticks = 0;
return OK;
/* external signalling (DRDY) not supported */
case SENSOR_POLLRATE_EXTERNAL:
/* zero would be bad */
case 0:
return -EINVAL;
/* set default/max polling rate */
case SENSOR_POLLRATE_MAX:
case SENSOR_POLLRATE_DEFAULT: {
/* do we need to start internal polling? */
bool want_start = (_measure_ticks == 0);
/* set interval for next measurement to minimum legal value */
_measure_ticks = USEC2TICK(_conversion_interval);
/* if we need to start the poll state machine, do it */
if (want_start)
start();
return OK;
}
/* adjust to a legal polling interval in Hz */
default: {
/* do we need to start internal polling? */
bool want_start = (_measure_ticks == 0);
/* convert hz to tick interval via microseconds */
unsigned ticks = USEC2TICK(1000000 / arg);
/* check against maximum rate */
if (ticks < USEC2TICK(_conversion_interval))
return -EINVAL;
/* update interval for next measurement */
_measure_ticks = ticks;
/* if we need to start the poll state machine, do it */
if (want_start)
start();
return OK;
}
}
}
case SENSORIOCGPOLLRATE:
if (_measure_ticks == 0)
return SENSOR_POLLRATE_MANUAL;
return (1000 / _measure_ticks);
case SENSORIOCSQUEUEDEPTH: {
/* lower bound is mandatory, upper bound is a sanity check */
if ((arg < 1) || (arg > 100))
return -EINVAL;
irqstate_t flags = irqsave();
if (!_reports->resize(arg)) {
irqrestore(flags);
return -ENOMEM;
}
irqrestore(flags);
return OK;
}
case SENSORIOCGQUEUEDEPTH:
return _reports->size();
case SENSORIOCRESET:
/* XXX implement this */
return -EINVAL;
case AIRSPEEDIOCSSCALE: {
struct airspeed_scale *s = (struct airspeed_scale*)arg;
_diff_pres_offset = s->offset_pa;
return OK;
}
case AIRSPEEDIOCGSCALE: {
struct airspeed_scale *s = (struct airspeed_scale*)arg;
s->offset_pa = _diff_pres_offset;
s->scale = 1.0f;
return OK;
}
default:
/* give it to the superclass */
return I2C::ioctl(filp, cmd, arg);
}
}
ssize_t
Airspeed::read(struct file *filp, char *buffer, size_t buflen)
{
unsigned count = buflen / sizeof(differential_pressure_s);
differential_pressure_s *abuf = reinterpret_cast<differential_pressure_s *>(buffer);
int ret = 0;
/* buffer must be large enough */
if (count < 1)
return -ENOSPC;
/* if automatic measurement is enabled */
if (_measure_ticks > 0) {
/*
* While there is space in the caller's buffer, and reports, copy them.
* Note that we may be pre-empted by the workq thread while we are doing this;
* we are careful to avoid racing with them.
*/
while (count--) {
if (_reports->get(abuf)) {
ret += sizeof(*abuf);
abuf++;
}
}
/* if there was no data, warn the caller */
return ret ? ret : -EAGAIN;
}
/* manual measurement - run one conversion */
do {
_reports->flush();
/* trigger a measurement */
if (OK != measure()) {
ret = -EIO;
break;
}
/* wait for it to complete */
usleep(_conversion_interval);
/* run the collection phase */
if (OK != collect()) {
ret = -EIO;
break;
}
/* state machine will have generated a report, copy it out */
if (_reports->get(abuf)) {
ret = sizeof(*abuf);
}
} while (0);
return ret;
}
void
Airspeed::start()
{
/* reset the report ring and state machine */
_collect_phase = false;
_reports->flush();
/* schedule a cycle to start things */
work_queue(HPWORK, &_work, (worker_t)&Airspeed::cycle_trampoline, this, 1);
}
void
Airspeed::stop()
{
work_cancel(HPWORK, &_work);
}
void
Airspeed::update_status()
{
if (_sensor_ok != _last_published_sensor_ok) {
/* notify about state change */
struct subsystem_info_s info = {
true,
true,
_sensor_ok,
subsystem_info_s::SUBSYSTEM_TYPE_DIFFPRESSURE
};
if (_subsys_pub > 0) {
orb_publish(ORB_ID(subsystem_info), _subsys_pub, &info);
} else {
_subsys_pub = orb_advertise(ORB_ID(subsystem_info), &info);
}
_last_published_sensor_ok = _sensor_ok;
}
}
void
Airspeed::cycle_trampoline(void *arg)
{
Airspeed *dev = (Airspeed *)arg;
dev->cycle();
// XXX we do not know if this is
// really helping - do not update the
// subsys state right now
//dev->update_status();
}
void
Airspeed::print_info()
{
perf_print_counter(_sample_perf);
perf_print_counter(_comms_errors);
perf_print_counter(_buffer_overflows);
warnx("poll interval: %u ticks", _measure_ticks);
_reports->print_info("report queue");
}
void
Airspeed::new_report(const differential_pressure_s &report)
{
if (!_reports->force(&report))
perf_count(_buffer_overflows);
}
<commit_msg>Airspeed: fix code style<commit_after>/****************************************************************************
*
* Copyright (c) 2013-2015 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file airspeed.cpp
* @author Simon Wilks <[email protected]>
* @author Lorenz Meier <[email protected]>
*
* Driver for the Eagle Tree Airspeed V3 connected via I2C.
*/
#include <nuttx/config.h>
#include <drivers/device/i2c.h>
#include <sys/types.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdbool.h>
#include <semaphore.h>
#include <string.h>
#include <fcntl.h>
#include <poll.h>
#include <errno.h>
#include <stdio.h>
#include <math.h>
#include <unistd.h>
#include <nuttx/arch.h>
#include <nuttx/wqueue.h>
#include <nuttx/clock.h>
#include <arch/board/board.h>
#include <systemlib/airspeed.h>
#include <systemlib/err.h>
#include <systemlib/param/param.h>
#include <systemlib/perf_counter.h>
#include <drivers/drv_airspeed.h>
#include <drivers/drv_hrt.h>
#include <drivers/device/ringbuffer.h>
#include <uORB/uORB.h>
#include <uORB/topics/differential_pressure.h>
#include <uORB/topics/subsystem_info.h>
#include <drivers/airspeed/airspeed.h>
Airspeed::Airspeed(int bus, int address, unsigned conversion_interval, const char *path) :
I2C("Airspeed", path, bus, address, 100000),
_reports(nullptr),
_buffer_overflows(perf_alloc(PC_COUNT, "airspeed_buffer_overflows")),
_max_differential_pressure_pa(0),
_sensor_ok(false),
_last_published_sensor_ok(true), /* initialize differently to force publication */
_measure_ticks(0),
_collect_phase(false),
_diff_pres_offset(0.0f),
_airspeed_pub(-1),
_subsys_pub(-1),
_class_instance(-1),
_conversion_interval(conversion_interval),
_sample_perf(perf_alloc(PC_ELAPSED, "airspeed_read")),
_comms_errors(perf_alloc(PC_COUNT, "airspeed_comms_errors"))
{
// enable debug() calls
_debug_enabled = false;
// work_cancel in the dtor will explode if we don't do this...
memset(&_work, 0, sizeof(_work));
}
Airspeed::~Airspeed()
{
/* make sure we are truly inactive */
stop();
if (_class_instance != -1) {
unregister_class_devname(AIRSPEED_BASE_DEVICE_PATH, _class_instance);
}
/* free any existing reports */
if (_reports != nullptr) {
delete _reports;
}
// free perf counters
perf_free(_sample_perf);
perf_free(_comms_errors);
perf_free(_buffer_overflows);
}
int
Airspeed::init()
{
int ret = ERROR;
/* do I2C init (and probe) first */
if (I2C::init() != OK) {
goto out;
}
/* allocate basic report buffers */
_reports = new RingBuffer(2, sizeof(differential_pressure_s));
if (_reports == nullptr) {
goto out;
}
/* register alternate interfaces if we have to */
_class_instance = register_class_devname(AIRSPEED_BASE_DEVICE_PATH);
/* publication init */
if (_class_instance == CLASS_DEVICE_PRIMARY) {
/* advertise sensor topic, measure manually to initialize valid report */
struct differential_pressure_s arp;
measure();
_reports->get(&arp);
/* measurement will have generated a report, publish */
_airspeed_pub = orb_advertise(ORB_ID(differential_pressure), &arp);
if (_airspeed_pub < 0) {
warnx("uORB started?");
}
}
ret = OK;
out:
return ret;
}
int
Airspeed::probe()
{
/* on initial power up the device may need more than one retry
for detection. Once it is running the number of retries can
be reduced
*/
_retries = 4;
int ret = measure();
// drop back to 2 retries once initialised
_retries = 2;
return ret;
}
int
Airspeed::ioctl(struct file *filp, int cmd, unsigned long arg)
{
switch (cmd) {
case SENSORIOCSPOLLRATE: {
switch (arg) {
/* switching to manual polling */
case SENSOR_POLLRATE_MANUAL:
stop();
_measure_ticks = 0;
return OK;
/* external signalling (DRDY) not supported */
case SENSOR_POLLRATE_EXTERNAL:
/* zero would be bad */
case 0:
return -EINVAL;
/* set default/max polling rate */
case SENSOR_POLLRATE_MAX:
case SENSOR_POLLRATE_DEFAULT: {
/* do we need to start internal polling? */
bool want_start = (_measure_ticks == 0);
/* set interval for next measurement to minimum legal value */
_measure_ticks = USEC2TICK(_conversion_interval);
/* if we need to start the poll state machine, do it */
if (want_start) {
start();
}
return OK;
}
/* adjust to a legal polling interval in Hz */
default: {
/* do we need to start internal polling? */
bool want_start = (_measure_ticks == 0);
/* convert hz to tick interval via microseconds */
unsigned ticks = USEC2TICK(1000000 / arg);
/* check against maximum rate */
if (ticks < USEC2TICK(_conversion_interval)) {
return -EINVAL;
}
/* update interval for next measurement */
_measure_ticks = ticks;
/* if we need to start the poll state machine, do it */
if (want_start) {
start();
}
return OK;
}
}
}
case SENSORIOCGPOLLRATE:
if (_measure_ticks == 0) {
return SENSOR_POLLRATE_MANUAL;
}
return (1000 / _measure_ticks);
case SENSORIOCSQUEUEDEPTH: {
/* lower bound is mandatory, upper bound is a sanity check */
if ((arg < 1) || (arg > 100)) {
return -EINVAL;
}
irqstate_t flags = irqsave();
if (!_reports->resize(arg)) {
irqrestore(flags);
return -ENOMEM;
}
irqrestore(flags);
return OK;
}
case SENSORIOCGQUEUEDEPTH:
return _reports->size();
case SENSORIOCRESET:
/* XXX implement this */
return -EINVAL;
case AIRSPEEDIOCSSCALE: {
struct airspeed_scale *s = (struct airspeed_scale *)arg;
_diff_pres_offset = s->offset_pa;
return OK;
}
case AIRSPEEDIOCGSCALE: {
struct airspeed_scale *s = (struct airspeed_scale *)arg;
s->offset_pa = _diff_pres_offset;
s->scale = 1.0f;
return OK;
}
default:
/* give it to the superclass */
return I2C::ioctl(filp, cmd, arg);
}
}
ssize_t
Airspeed::read(struct file *filp, char *buffer, size_t buflen)
{
unsigned count = buflen / sizeof(differential_pressure_s);
differential_pressure_s *abuf = reinterpret_cast<differential_pressure_s *>(buffer);
int ret = 0;
/* buffer must be large enough */
if (count < 1) {
return -ENOSPC;
}
/* if automatic measurement is enabled */
if (_measure_ticks > 0) {
/*
* While there is space in the caller's buffer, and reports, copy them.
* Note that we may be pre-empted by the workq thread while we are doing this;
* we are careful to avoid racing with them.
*/
while (count--) {
if (_reports->get(abuf)) {
ret += sizeof(*abuf);
abuf++;
}
}
/* if there was no data, warn the caller */
return ret ? ret : -EAGAIN;
}
/* manual measurement - run one conversion */
do {
_reports->flush();
/* trigger a measurement */
if (OK != measure()) {
ret = -EIO;
break;
}
/* wait for it to complete */
usleep(_conversion_interval);
/* run the collection phase */
if (OK != collect()) {
ret = -EIO;
break;
}
/* state machine will have generated a report, copy it out */
if (_reports->get(abuf)) {
ret = sizeof(*abuf);
}
} while (0);
return ret;
}
void
Airspeed::start()
{
/* reset the report ring and state machine */
_collect_phase = false;
_reports->flush();
/* schedule a cycle to start things */
work_queue(HPWORK, &_work, (worker_t)&Airspeed::cycle_trampoline, this, 1);
}
void
Airspeed::stop()
{
work_cancel(HPWORK, &_work);
}
void
Airspeed::update_status()
{
if (_sensor_ok != _last_published_sensor_ok) {
/* notify about state change */
struct subsystem_info_s info = {
true,
true,
_sensor_ok,
subsystem_info_s::SUBSYSTEM_TYPE_DIFFPRESSURE
};
if (_subsys_pub > 0) {
orb_publish(ORB_ID(subsystem_info), _subsys_pub, &info);
} else {
_subsys_pub = orb_advertise(ORB_ID(subsystem_info), &info);
}
_last_published_sensor_ok = _sensor_ok;
}
}
void
Airspeed::cycle_trampoline(void *arg)
{
Airspeed *dev = (Airspeed *)arg;
dev->cycle();
// XXX we do not know if this is
// really helping - do not update the
// subsys state right now
//dev->update_status();
}
void
Airspeed::print_info()
{
perf_print_counter(_sample_perf);
perf_print_counter(_comms_errors);
perf_print_counter(_buffer_overflows);
warnx("poll interval: %u ticks", _measure_ticks);
_reports->print_info("report queue");
}
void
Airspeed::new_report(const differential_pressure_s &report)
{
if (!_reports->force(&report)) {
perf_count(_buffer_overflows);
}
}
<|endoftext|> |
<commit_before>#pragma once
#include <string>
#include <string_view>
#include <vector>
#include <cctype>
#include <algorithm>
#include <cstring>
#include <iterator>
#include <utility>
#include <initializer_list>
#include <numeric>
#include <sstream>
#include <iomanip>
#include <functional>
#include <cassert>
#include "acmacs-base/to-string.hh"
// ----------------------------------------------------------------------
namespace string
{
// ----------------------------------------------------------------------
inline std::string first_letter_of_words(std::string s)
{
std::string result;
bool add = true;
for (char c: s) {
if (c == ' ') {
add = true;
}
else if (add) {
result.push_back(c);
add = false;
}
}
return result;
}
// ----------------------------------------------------------------------
namespace _internal {
template <typename InputIterator, typename Source> inline std::pair<InputIterator, InputIterator> strip_begin_end(Source& source)
{
auto predicate = [](auto c) { return std::isspace(c); }; // have to use lambda, other compiler cannot infer Predicate type from isspace
auto e = std::find_if_not(source.rbegin(), source.rend(), predicate);
auto b = std::find_if_not(source.begin(), e.base(), predicate);
return std::make_pair(b, e.base());
}
} // namespace _internal
// inline std::string& strip(std::string& source)
// {
// auto be = _internal::strip_begin_end<std::string::iterator>(source);
// source.erase(be.second, source.end()); // erase at the end first
// source.erase(source.begin(), be.first); // invalidates be.second!
// return source;
// }
// inline std::string strip(std::string&& source)
// {
// auto be = _internal::strip_begin_end<std::string::iterator>(source);
// source.erase(be.second, source.end()); // erase at the end first
// source.erase(source.begin(), be.first); // invalidates be.second!
// return source;
// }
inline std::string strip(std::string source)
{
auto be = _internal::strip_begin_end<std::string::const_iterator>(source);
return std::string(be.first, be.second);
}
// ----------------------------------------------------------------------
inline std::string replace(std::string source, std::string look_for, std::string replace_with)
{
std::string result;
std::string::size_type start = 0;
while (true) {
const auto pos = source.find(look_for, start);
if (pos != std::string::npos) {
result.append(source.begin() + static_cast<std::string::difference_type>(start), source.begin() + static_cast<std::string::difference_type>(pos));
result.append(replace_with);
start = pos + look_for.size();
}
else {
result.append(source.begin() + static_cast<std::string::difference_type>(start), source.end());
break;
}
}
return result;
}
// ----------------------------------------------------------------------
namespace _internal
{
template <typename Iter> inline std::string transform(Iter first, Iter last, std::function<char (char)> func)
{
std::string result;
std::transform(first, last, std::back_inserter(result), func);
return result;
}
}
template <typename S> inline std::string lower(const S& source) { return _internal::transform(source.begin(), source.end(), ::tolower); }
inline std::string lower(const char* source) { return _internal::transform(source, source + std::strlen(source), ::tolower); }
inline std::string lower(char* source) { return lower(const_cast<const char*>(source)); }
template <typename S> inline std::string upper(const S& source) { return _internal::transform(source.begin(), source.end(), ::toupper); }
inline std::string upper(const char* source) { return _internal::transform(source, source + std::strlen(source), ::toupper); }
inline std::string upper(char* source) { return upper(const_cast<const char*>(source)); }
// inline std::string& capitalize(std::string& source)
// {
// if (!source.empty()) {
// std::transform(source.begin(), source.begin() + 1, source.begin(), ::toupper);
// std::transform(source.begin() + 1, source.end(), source.begin() + 1, ::tolower);
// }
// return source;
// }
template <typename S> inline std::string capitalize(const S& source)
{
std::string result;
if (!source.empty()) {
std::transform(source.begin(), source.begin() + 1, std::back_inserter(result), ::toupper);
std::transform(source.begin() + 1, source.end(), std::back_inserter(result), ::tolower);
}
return result;
}
// ----------------------------------------------------------------------
// ends_with
// ----------------------------------------------------------------------
template <typename S> inline bool ends_with(const S& data, const char* end)
{
const std::string_view end_view{end};
return std::string_view(data.data() + data.size() - end_view.size(), end_view.size()) == end_view;
}
// ----------------------------------------------------------------------
// compare
// ----------------------------------------------------------------------
inline int compare(const char* a, size_t al, const char* b, size_t bl)
{
auto r = std::memcmp(a, b, std::min(al, bl));
if (r == 0 && al != bl)
return al < bl ? -1 : 1;
else
return r;
}
inline int compare(std::string a, std::string b) { return compare(a.c_str(), a.size(), b.c_str(), b.size()); }
inline int compare(std::string a, const char* b) { return compare(a.c_str(), a.size(), b, std::strlen(b)); }
inline int compare(const char* a, std::string b) { return compare(a, std::strlen(a), b.c_str(), b.size()); }
inline int compare(std::initializer_list<std::string> as, std::initializer_list<std::string> bs)
{
assert(as.size() == bs.size());
for (auto ap = as.begin(), bp = bs.begin(); ap != as.end(); ++ap, ++bp) {
if (const auto r = compare(*ap, *bp); r != 0)
return r;
}
return 0;
}
// ----------------------------------------------------------------------
// join
// ----------------------------------------------------------------------
template <typename Iterator> inline std::string join(std::string separator, Iterator first, Iterator last)
{
std::string result;
if (first != last) {
// Note last - first below does not supported for std::set
// const size_t resulting_size = std::accumulate(first, last, separator.size() * static_cast<size_t>(last - first - 1), [](size_t acc, const std::string& n) -> size_t { return acc + n.size(); });
// result.reserve(resulting_size);
for ( ; first != last; ++first) {
const auto f_s = acmacs::to_string(*first);
if (!f_s.empty()) {
if (!result.empty())
result.append(separator);
result.append(f_s);
}
}
}
return result;
}
template <typename Iterator, typename Converter> inline std::string join(std::string separator, Iterator first, Iterator last, Converter convert)
{
std::string result;
for ( ; first != last; ++first) {
const auto f_s = convert(*first);
if (!f_s.empty()) {
if (!result.empty())
result.append(separator);
result.append(f_s);
}
}
return result;
}
template <typename Collection> inline std::string join(std::string separator, const Collection& values)
{
return join(separator, std::begin(values), std::end(values));
}
inline std::string join(std::string separator, std::initializer_list<std::string>&& values)
{
return join(separator, std::begin(values), std::end(values));
}
inline std::string join(std::string separator, std::initializer_list<std::string_view>&& values)
{
return join(separator, std::begin(values), std::end(values));
}
inline std::string join(std::initializer_list<std::string>&& parts)
{
// std::vector<std::string> p{parts};
// return join(" ", std::begin(p), std::remove(std::begin(p), std::end(p), std::string()));
return join(" ", std::begin(parts), std::end(parts));
}
enum ShowBase { NotShowBase, ShowBase };
enum OutputCase { Uppercase, Lowercase };
template <typename T, typename = std::enable_if<std::is_integral<T>::value>> inline std::string to_hex_string(T aValue, enum ShowBase aShowBase, OutputCase aOutputCase = Uppercase)
{
std::ostringstream stream;
// stream << (aShowBase == ShowBase ? std::showbase : std::noshowbase);
if (aShowBase == ShowBase)
stream << "0x";
stream << std::setfill('0') << std::setw(sizeof(aValue)*2) << std::hex << std::noshowbase;
stream << (aOutputCase == Uppercase ? std::uppercase : std::nouppercase);
if constexpr (std::is_same_v<T, char> || std::is_same_v<T, unsigned char>) {
stream << static_cast<unsigned>(aValue);
}
else {
stream << aValue;
}
return stream.str();
}
template <typename T> inline std::string to_hex_string(const T* aPtr)
{
std::ostringstream stream;
const void* value = reinterpret_cast<const void*>(aPtr);
stream << value; // std::setfill('0') << std::setw(sizeof(value)*2) << std::hex << value;
return stream.str();
}
// ----------------------------------------------------------------------
} // namespace string
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>string::string_view()<commit_after>#pragma once
#include <string>
#include <string_view>
#include <vector>
#include <cctype>
#include <algorithm>
#include <cstring>
#include <iterator>
#include <utility>
#include <initializer_list>
#include <numeric>
#include <sstream>
#include <iomanip>
#include <functional>
#include <cassert>
#include "acmacs-base/to-string.hh"
// ----------------------------------------------------------------------
namespace string
{
// ----------------------------------------------------------------------
inline std::string first_letter_of_words(std::string s)
{
std::string result;
bool add = true;
for (char c: s) {
if (c == ' ') {
add = true;
}
else if (add) {
result.push_back(c);
add = false;
}
}
return result;
}
// ----------------------------------------------------------------------
namespace _internal {
template <typename InputIterator, typename Source> inline std::pair<InputIterator, InputIterator> strip_begin_end(Source& source)
{
auto predicate = [](auto c) { return std::isspace(c); }; // have to use lambda, other compiler cannot infer Predicate type from isspace
auto e = std::find_if_not(source.rbegin(), source.rend(), predicate);
auto b = std::find_if_not(source.begin(), e.base(), predicate);
return std::make_pair(b, e.base());
}
} // namespace _internal
// inline std::string& strip(std::string& source)
// {
// auto be = _internal::strip_begin_end<std::string::iterator>(source);
// source.erase(be.second, source.end()); // erase at the end first
// source.erase(source.begin(), be.first); // invalidates be.second!
// return source;
// }
// inline std::string strip(std::string&& source)
// {
// auto be = _internal::strip_begin_end<std::string::iterator>(source);
// source.erase(be.second, source.end()); // erase at the end first
// source.erase(source.begin(), be.first); // invalidates be.second!
// return source;
// }
inline std::string strip(std::string source)
{
auto be = _internal::strip_begin_end<std::string::const_iterator>(source);
return std::string(be.first, be.second);
}
// ----------------------------------------------------------------------
inline std::string replace(std::string source, std::string look_for, std::string replace_with)
{
std::string result;
std::string::size_type start = 0;
while (true) {
const auto pos = source.find(look_for, start);
if (pos != std::string::npos) {
result.append(source.begin() + static_cast<std::string::difference_type>(start), source.begin() + static_cast<std::string::difference_type>(pos));
result.append(replace_with);
start = pos + look_for.size();
}
else {
result.append(source.begin() + static_cast<std::string::difference_type>(start), source.end());
break;
}
}
return result;
}
// ----------------------------------------------------------------------
namespace _internal
{
template <typename Iter> inline std::string transform(Iter first, Iter last, std::function<char (char)> func)
{
std::string result;
std::transform(first, last, std::back_inserter(result), func);
return result;
}
}
template <typename S> inline std::string lower(const S& source) { return _internal::transform(source.begin(), source.end(), ::tolower); }
inline std::string lower(const char* source) { return _internal::transform(source, source + std::strlen(source), ::tolower); }
inline std::string lower(char* source) { return lower(const_cast<const char*>(source)); }
template <typename S> inline std::string upper(const S& source) { return _internal::transform(source.begin(), source.end(), ::toupper); }
inline std::string upper(const char* source) { return _internal::transform(source, source + std::strlen(source), ::toupper); }
inline std::string upper(char* source) { return upper(const_cast<const char*>(source)); }
// inline std::string& capitalize(std::string& source)
// {
// if (!source.empty()) {
// std::transform(source.begin(), source.begin() + 1, source.begin(), ::toupper);
// std::transform(source.begin() + 1, source.end(), source.begin() + 1, ::tolower);
// }
// return source;
// }
template <typename S> inline std::string capitalize(const S& source)
{
std::string result;
if (!source.empty()) {
std::transform(source.begin(), source.begin() + 1, std::back_inserter(result), ::toupper);
std::transform(source.begin() + 1, source.end(), std::back_inserter(result), ::tolower);
}
return result;
}
// ----------------------------------------------------------------------
// ends_with
// ----------------------------------------------------------------------
template <typename S> inline bool ends_with(const S& data, const char* end)
{
const std::string_view end_view{end};
return std::string_view(data.data() + data.size() - end_view.size(), end_view.size()) == end_view;
}
// ----------------------------------------------------------------------
// compare
// ----------------------------------------------------------------------
inline int compare(const char* a, size_t al, const char* b, size_t bl)
{
auto r = std::memcmp(a, b, std::min(al, bl));
if (r == 0 && al != bl)
return al < bl ? -1 : 1;
else
return r;
}
inline int compare(std::string a, std::string b) { return compare(a.c_str(), a.size(), b.c_str(), b.size()); }
inline int compare(std::string a, const char* b) { return compare(a.c_str(), a.size(), b, std::strlen(b)); }
inline int compare(const char* a, std::string b) { return compare(a, std::strlen(a), b.c_str(), b.size()); }
inline int compare(std::initializer_list<std::string> as, std::initializer_list<std::string> bs)
{
assert(as.size() == bs.size());
for (auto ap = as.begin(), bp = bs.begin(); ap != as.end(); ++ap, ++bp) {
if (const auto r = compare(*ap, *bp); r != 0)
return r;
}
return 0;
}
// ----------------------------------------------------------------------
// join
// ----------------------------------------------------------------------
template <typename Iterator> inline std::string join(std::string separator, Iterator first, Iterator last)
{
std::string result;
if (first != last) {
// Note last - first below does not supported for std::set
// const size_t resulting_size = std::accumulate(first, last, separator.size() * static_cast<size_t>(last - first - 1), [](size_t acc, const std::string& n) -> size_t { return acc + n.size(); });
// result.reserve(resulting_size);
for ( ; first != last; ++first) {
const auto f_s = acmacs::to_string(*first);
if (!f_s.empty()) {
if (!result.empty())
result.append(separator);
result.append(f_s);
}
}
}
return result;
}
template <typename Iterator, typename Converter> inline std::string join(std::string separator, Iterator first, Iterator last, Converter convert)
{
std::string result;
for ( ; first != last; ++first) {
const auto f_s = convert(*first);
if (!f_s.empty()) {
if (!result.empty())
result.append(separator);
result.append(f_s);
}
}
return result;
}
template <typename Collection> inline std::string join(std::string separator, const Collection& values)
{
return join(separator, std::begin(values), std::end(values));
}
inline std::string join(std::string separator, std::initializer_list<std::string>&& values)
{
return join(separator, std::begin(values), std::end(values));
}
inline std::string join(std::string separator, std::initializer_list<std::string_view>&& values)
{
return join(separator, std::begin(values), std::end(values));
}
inline std::string join(std::initializer_list<std::string>&& parts)
{
// std::vector<std::string> p{parts};
// return join(" ", std::begin(p), std::remove(std::begin(p), std::end(p), std::string()));
return join(" ", std::begin(parts), std::end(parts));
}
enum ShowBase { NotShowBase, ShowBase };
enum OutputCase { Uppercase, Lowercase };
template <typename T, typename = std::enable_if<std::is_integral<T>::value>> inline std::string to_hex_string(T aValue, enum ShowBase aShowBase, OutputCase aOutputCase = Uppercase)
{
std::ostringstream stream;
// stream << (aShowBase == ShowBase ? std::showbase : std::noshowbase);
if (aShowBase == ShowBase)
stream << "0x";
stream << std::setfill('0') << std::setw(sizeof(aValue)*2) << std::hex << std::noshowbase;
stream << (aOutputCase == Uppercase ? std::uppercase : std::nouppercase);
if constexpr (std::is_same_v<T, char> || std::is_same_v<T, unsigned char>) {
stream << static_cast<unsigned>(aValue);
}
else {
stream << aValue;
}
return stream.str();
}
template <typename T> inline std::string to_hex_string(const T* aPtr)
{
std::ostringstream stream;
const void* value = reinterpret_cast<const void*>(aPtr);
stream << value; // std::setfill('0') << std::setw(sizeof(value)*2) << std::hex << value;
return stream.str();
}
// ----------------------------------------------------------------------
template <typename S> inline std::string_view string_view(const S& aSrc, size_t aOffset)
{
return std::string_view(aSrc.data() + aOffset, aSrc.size() - aOffset);
}
// ----------------------------------------------------------------------
} // namespace string
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|> |
<commit_before>#include "hext/Rule.h"
#include "hext/ResultTree.h"
namespace hext {
Rule::Rule(
GumboTag tag,
bool is_optional,
bool is_any_descendant,
std::vector<std::unique_ptr<MatchPattern>>&& match_patterns,
std::vector<std::unique_ptr<CapturePattern>>&& capture_patterns
)
: children_()
, match_patterns_(std::move(match_patterns))
, capture_patterns_(std::move(capture_patterns))
, gumbo_tag_(tag)
, is_optional_(is_optional)
, is_any_descendant_(is_any_descendant)
{
}
void Rule::append_child(Rule&& r, std::size_t level)
{
if( level > 0 && !this->children_.empty() )
{
this->children_.back().append_child(std::move(r), level - 1);
return;
}
this->children_.push_back(std::move(r));
}
bool Rule::optional() const
{
return this->is_optional_;
}
std::unique_ptr<ResultTree> Rule::extract(const GumboNode * node) const
{
auto rt = MakeUnique<ResultTree>();
auto first_child = this->children_.begin();
if( this->children_.size() && first_child->matches(node) )
{
auto values = first_child->capture(node);
auto child_rt = rt->create_branch(values);
this->extract_children(node, child_rt);
}
else
{
this->extract_children(node, rt.get());
}
return std::move(rt);
}
bool Rule::matches(const GumboNode * node) const
{
if( !node )
return false;
if( this->gumbo_tag_ != GUMBO_TAG_UNKNOWN )
if( node->type != GUMBO_NODE_ELEMENT ||
node->v.element.tag != this->gumbo_tag_ )
return false;
for(const auto& pattern : this->match_patterns_)
if( !pattern->matches(node) )
return false;
return true;
}
std::vector<ResultPair> Rule::capture(const GumboNode * node) const
{
if( !node )
return std::vector<ResultPair>();
std::vector<ResultPair> values;
values.reserve(this->capture_patterns_.size());
for(const auto& pattern : this->capture_patterns_ )
values.push_back(pattern->capture(node));
return values;
}
bool Rule::extract_children(const GumboNode * node, ResultTree * rt) const
{
if( !node || !rt )
return false;
if( node->type != GUMBO_NODE_ELEMENT )
return false;
if( this->children_.empty() )
return true;
int match_count = 0;
const GumboVector * child_nodes = &node->v.element.children;
MatchContext mc(
this->children_.cbegin(),
this->children_.cend(),
child_nodes
);
while( auto grouped_match = mc.match_next() )
{
++match_count;
auto branch = rt->create_branch();
for( const auto& match_pair : *grouped_match )
{
const Rule * child_rule = match_pair.first;
const GumboNode * child_node = match_pair.second;
assert(child_rule && child_node);
auto values = child_rule->capture(child_node);
auto child_rt = branch->create_branch(values);
if( !child_rule->extract_children(child_node, child_rt) )
{
rt->delete_branch(branch);
--match_count;
break;
}
}
}
if( this->is_any_descendant_ )
{
const GumboVector * node_children = &node->v.element.children;
for(unsigned int i = 0; i < node_children->length; ++i)
{
auto child_node = static_cast<const GumboNode *>(node_children->data[i]);
this->extract_children(child_node, rt);
}
}
return match_count > 0;
}
} // namespace hext
<commit_msg>Rule: fix returning incomplete ResultTrees if top-most rule matches<commit_after>#include "hext/Rule.h"
#include "hext/ResultTree.h"
namespace hext {
Rule::Rule(
GumboTag tag,
bool is_optional,
bool is_any_descendant,
std::vector<std::unique_ptr<MatchPattern>>&& match_patterns,
std::vector<std::unique_ptr<CapturePattern>>&& capture_patterns
)
: children_()
, match_patterns_(std::move(match_patterns))
, capture_patterns_(std::move(capture_patterns))
, gumbo_tag_(tag)
, is_optional_(is_optional)
, is_any_descendant_(is_any_descendant)
{
}
void Rule::append_child(Rule&& r, std::size_t level)
{
if( level > 0 && !this->children_.empty() )
{
this->children_.back().append_child(std::move(r), level - 1);
return;
}
this->children_.push_back(std::move(r));
}
bool Rule::optional() const
{
return this->is_optional_;
}
std::unique_ptr<ResultTree> Rule::extract(const GumboNode * node) const
{
auto rt = MakeUnique<ResultTree>();
if( this->children_.size() == 1 )
{
auto first_child = this->children_.begin();
if( first_child->matches(node) )
{
auto values = first_child->capture(node);
auto child_rt = rt->create_branch(values);
if( !first_child->extract_children(node, child_rt) )
rt->delete_branch(child_rt);
return std::move(rt);
}
}
this->extract_children(node, rt.get());
return std::move(rt);
}
bool Rule::matches(const GumboNode * node) const
{
if( !node )
return false;
if( this->gumbo_tag_ != GUMBO_TAG_UNKNOWN )
if( node->type != GUMBO_NODE_ELEMENT ||
node->v.element.tag != this->gumbo_tag_ )
return false;
for(const auto& pattern : this->match_patterns_)
if( !pattern->matches(node) )
return false;
return true;
}
std::vector<ResultPair> Rule::capture(const GumboNode * node) const
{
if( !node )
return std::vector<ResultPair>();
std::vector<ResultPair> values;
values.reserve(this->capture_patterns_.size());
for(const auto& pattern : this->capture_patterns_ )
values.push_back(pattern->capture(node));
return values;
}
bool Rule::extract_children(const GumboNode * node, ResultTree * rt) const
{
if( !node || !rt )
return false;
if( node->type != GUMBO_NODE_ELEMENT )
return false;
if( this->children_.empty() )
return true;
int match_count = 0;
const GumboVector * child_nodes = &node->v.element.children;
MatchContext mc(
this->children_.cbegin(),
this->children_.cend(),
child_nodes
);
while( auto grouped_match = mc.match_next() )
{
++match_count;
auto branch = rt->create_branch();
for( const auto& match_pair : *grouped_match )
{
const Rule * child_rule = match_pair.first;
const GumboNode * child_node = match_pair.second;
assert(child_rule && child_node);
auto values = child_rule->capture(child_node);
auto child_rt = branch->create_branch(values);
if( !child_rule->extract_children(child_node, child_rt) )
{
rt->delete_branch(branch);
--match_count;
break;
}
}
}
if( this->is_any_descendant_ )
{
const GumboVector * node_children = &node->v.element.children;
for(unsigned int i = 0; i < node_children->length; ++i)
{
auto child_node = static_cast<const GumboNode *>(node_children->data[i]);
this->extract_children(child_node, rt);
}
}
return match_count > 0;
}
} // namespace hext
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/base/host_resolver_proc.h"
#include "build/build_config.h"
#if defined(OS_POSIX) && !defined(OS_MACOSX)
#include <resolv.h>
#endif
#include "base/logging.h"
#include "net/base/address_list.h"
#include "net/base/dns_reload_timer.h"
#include "net/base/net_errors.h"
#include "net/base/sys_addrinfo.h"
namespace net {
namespace {
bool IsAllLocalhostOfOneFamily(const struct addrinfo* ai) {
bool saw_v4_localhost = false;
bool saw_v6_localhost = false;
for (; ai != NULL; ai = ai->ai_next) {
switch (ai->ai_family) {
case AF_INET: {
const struct sockaddr_in* addr_in =
reinterpret_cast<struct sockaddr_in*>(ai->ai_addr);
if ((ntohl(addr_in->sin_addr.s_addr) & 0xff000000) == 0x7f000000)
saw_v4_localhost = true;
else
return false;
break;
}
case AF_INET6: {
const struct sockaddr_in6* addr_in6 =
reinterpret_cast<struct sockaddr_in6*>(ai->ai_addr);
if (IN6_IS_ADDR_LOOPBACK(&addr_in6->sin6_addr))
saw_v6_localhost = true;
else
return false;
break;
}
default:
NOTREACHED();
return false;
}
}
return saw_v4_localhost != saw_v6_localhost;
}
} // namespace
HostResolverProc* HostResolverProc::default_proc_ = NULL;
HostResolverProc::HostResolverProc(HostResolverProc* previous) {
SetPreviousProc(previous);
// Implicitly fall-back to the global default procedure.
if (!previous)
SetPreviousProc(default_proc_);
}
void HostResolverProc::SetPreviousProc(HostResolverProc* proc) {
HostResolverProc* current_previous = previous_proc_;
previous_proc_ = NULL;
// Now that we've guaranteed |this| is the last proc in a chain, we can
// detect potential cycles using GetLastProc().
previous_proc_ = (GetLastProc(proc) == this) ? current_previous : proc;
}
void HostResolverProc::SetLastProc(HostResolverProc* proc) {
GetLastProc(this)->SetPreviousProc(proc);
}
// static
HostResolverProc* HostResolverProc::GetLastProc(HostResolverProc* proc) {
if (proc == NULL)
return NULL;
HostResolverProc* last_proc = proc;
while (last_proc->previous_proc_ != NULL)
last_proc = last_proc->previous_proc_;
return last_proc;
}
// static
HostResolverProc* HostResolverProc::SetDefault(HostResolverProc* proc) {
HostResolverProc* old = default_proc_;
default_proc_ = proc;
return old;
}
// static
HostResolverProc* HostResolverProc::GetDefault() {
return default_proc_;
}
HostResolverProc::~HostResolverProc() {
}
int HostResolverProc::ResolveUsingPrevious(
const std::string& host,
AddressFamily address_family,
HostResolverFlags host_resolver_flags,
AddressList* addrlist,
int* os_error) {
if (previous_proc_) {
return previous_proc_->Resolve(host, address_family, host_resolver_flags,
addrlist, os_error);
}
// Final fallback is the system resolver.
return SystemHostResolverProc(host, address_family, host_resolver_flags,
addrlist, os_error);
}
int SystemHostResolverProc(const std::string& host,
AddressFamily address_family,
HostResolverFlags host_resolver_flags,
AddressList* addrlist,
int* os_error) {
static const size_t kMaxHostLength = 4096;
if (os_error)
*os_error = 0;
// The result of |getaddrinfo| for empty hosts is inconsistent across systems.
// On Windows it gives the default interface's address, whereas on Linux it
// gives an error. We will make it fail on all platforms for consistency.
if (host.empty())
return ERR_NAME_NOT_RESOLVED;
// Limit the size of hostnames that will be resolved to combat issues in some
// platform's resolvers.
if (host.size() > kMaxHostLength)
return ERR_NAME_NOT_RESOLVED;
struct addrinfo* ai = NULL;
struct addrinfo hints = {0};
switch (address_family) {
case ADDRESS_FAMILY_IPV4:
hints.ai_family = AF_INET;
break;
case ADDRESS_FAMILY_IPV6:
hints.ai_family = AF_INET6;
break;
case ADDRESS_FAMILY_UNSPECIFIED:
hints.ai_family = AF_UNSPEC;
break;
default:
NOTREACHED();
hints.ai_family = AF_UNSPEC;
}
#if defined(OS_WIN) || defined(OS_OPENBSD)
// DO NOT USE AI_ADDRCONFIG ON WINDOWS.
//
// The following comment in <winsock2.h> is the best documentation I found
// on AI_ADDRCONFIG for Windows:
// Flags used in "hints" argument to getaddrinfo()
// - AI_ADDRCONFIG is supported starting with Vista
// - default is AI_ADDRCONFIG ON whether the flag is set or not
// because the performance penalty in not having ADDRCONFIG in
// the multi-protocol stack environment is severe;
// this defaulting may be disabled by specifying the AI_ALL flag,
// in that case AI_ADDRCONFIG must be EXPLICITLY specified to
// enable ADDRCONFIG behavior
//
// Not only is AI_ADDRCONFIG unnecessary, but it can be harmful. If the
// computer is not connected to a network, AI_ADDRCONFIG causes getaddrinfo
// to fail with WSANO_DATA (11004) for "localhost", probably because of the
// following note on AI_ADDRCONFIG in the MSDN getaddrinfo page:
// The IPv4 or IPv6 loopback address is not considered a valid global
// address.
// See http://crbug.com/5234.
//
// OpenBSD does not support it, either.
hints.ai_flags = 0;
#else
hints.ai_flags = AI_ADDRCONFIG;
#endif
// On Linux AI_ADDRCONFIG doesn't consider loopback addreses, even if only
// loopback addresses are configured. So don't use it when there are only
// loopback addresses.
if (host_resolver_flags & HOST_RESOLVER_LOOPBACK_ONLY)
hints.ai_flags &= ~AI_ADDRCONFIG;
if (host_resolver_flags & HOST_RESOLVER_CANONNAME)
hints.ai_flags |= AI_CANONNAME;
// Restrict result set to only this socket type to avoid duplicates.
hints.ai_socktype = SOCK_STREAM;
int err = getaddrinfo(host.c_str(), NULL, &hints, &ai);
bool should_retry = false;
#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD)
// If we fail, re-initialise the resolver just in case there have been any
// changes to /etc/resolv.conf and retry. See http://crbug.com/11380 for info.
if (err && DnsReloadTimerHasExpired()) {
res_nclose(&_res);
if (!res_ninit(&_res))
should_retry = true;
}
#endif
// If the lookup was restricted (either by address family, or address
// detection), and the results where all localhost of a single family,
// maybe we should retry. There were several bugs related to these
// issues, for example http://crbug.com/42058 and http://crbug.com/49024
if ((hints.ai_family != AF_UNSPEC || hints.ai_flags & AI_ADDRCONFIG) &&
err == 0 && IsAllLocalhostOfOneFamily(ai)) {
if (host_resolver_flags & HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6) {
hints.ai_family = AF_UNSPEC;
should_retry = true;
}
if (hints.ai_flags & AI_ADDRCONFIG) {
hints.ai_flags &= ~AI_ADDRCONFIG;
should_retry = true;
}
}
if (should_retry) {
freeaddrinfo(ai);
ai = NULL;
err = getaddrinfo(host.c_str(), NULL, &hints, &ai);
}
if (err) {
if (os_error) {
#if defined(OS_WIN)
*os_error = WSAGetLastError();
#else
*os_error = err;
#endif
}
return ERR_NAME_NOT_RESOLVED;
}
addrlist->Adopt(ai);
return OK;
}
} // namespace net
<commit_msg>Don't call freeaddrinfo(NULL) to avoid crash on FreeBSD.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/base/host_resolver_proc.h"
#include "build/build_config.h"
#if defined(OS_POSIX) && !defined(OS_MACOSX)
#include <resolv.h>
#endif
#include "base/logging.h"
#include "net/base/address_list.h"
#include "net/base/dns_reload_timer.h"
#include "net/base/net_errors.h"
#include "net/base/sys_addrinfo.h"
namespace net {
namespace {
bool IsAllLocalhostOfOneFamily(const struct addrinfo* ai) {
bool saw_v4_localhost = false;
bool saw_v6_localhost = false;
for (; ai != NULL; ai = ai->ai_next) {
switch (ai->ai_family) {
case AF_INET: {
const struct sockaddr_in* addr_in =
reinterpret_cast<struct sockaddr_in*>(ai->ai_addr);
if ((ntohl(addr_in->sin_addr.s_addr) & 0xff000000) == 0x7f000000)
saw_v4_localhost = true;
else
return false;
break;
}
case AF_INET6: {
const struct sockaddr_in6* addr_in6 =
reinterpret_cast<struct sockaddr_in6*>(ai->ai_addr);
if (IN6_IS_ADDR_LOOPBACK(&addr_in6->sin6_addr))
saw_v6_localhost = true;
else
return false;
break;
}
default:
NOTREACHED();
return false;
}
}
return saw_v4_localhost != saw_v6_localhost;
}
} // namespace
HostResolverProc* HostResolverProc::default_proc_ = NULL;
HostResolverProc::HostResolverProc(HostResolverProc* previous) {
SetPreviousProc(previous);
// Implicitly fall-back to the global default procedure.
if (!previous)
SetPreviousProc(default_proc_);
}
void HostResolverProc::SetPreviousProc(HostResolverProc* proc) {
HostResolverProc* current_previous = previous_proc_;
previous_proc_ = NULL;
// Now that we've guaranteed |this| is the last proc in a chain, we can
// detect potential cycles using GetLastProc().
previous_proc_ = (GetLastProc(proc) == this) ? current_previous : proc;
}
void HostResolverProc::SetLastProc(HostResolverProc* proc) {
GetLastProc(this)->SetPreviousProc(proc);
}
// static
HostResolverProc* HostResolverProc::GetLastProc(HostResolverProc* proc) {
if (proc == NULL)
return NULL;
HostResolverProc* last_proc = proc;
while (last_proc->previous_proc_ != NULL)
last_proc = last_proc->previous_proc_;
return last_proc;
}
// static
HostResolverProc* HostResolverProc::SetDefault(HostResolverProc* proc) {
HostResolverProc* old = default_proc_;
default_proc_ = proc;
return old;
}
// static
HostResolverProc* HostResolverProc::GetDefault() {
return default_proc_;
}
HostResolverProc::~HostResolverProc() {
}
int HostResolverProc::ResolveUsingPrevious(
const std::string& host,
AddressFamily address_family,
HostResolverFlags host_resolver_flags,
AddressList* addrlist,
int* os_error) {
if (previous_proc_) {
return previous_proc_->Resolve(host, address_family, host_resolver_flags,
addrlist, os_error);
}
// Final fallback is the system resolver.
return SystemHostResolverProc(host, address_family, host_resolver_flags,
addrlist, os_error);
}
int SystemHostResolverProc(const std::string& host,
AddressFamily address_family,
HostResolverFlags host_resolver_flags,
AddressList* addrlist,
int* os_error) {
static const size_t kMaxHostLength = 4096;
if (os_error)
*os_error = 0;
// The result of |getaddrinfo| for empty hosts is inconsistent across systems.
// On Windows it gives the default interface's address, whereas on Linux it
// gives an error. We will make it fail on all platforms for consistency.
if (host.empty())
return ERR_NAME_NOT_RESOLVED;
// Limit the size of hostnames that will be resolved to combat issues in some
// platform's resolvers.
if (host.size() > kMaxHostLength)
return ERR_NAME_NOT_RESOLVED;
struct addrinfo* ai = NULL;
struct addrinfo hints = {0};
switch (address_family) {
case ADDRESS_FAMILY_IPV4:
hints.ai_family = AF_INET;
break;
case ADDRESS_FAMILY_IPV6:
hints.ai_family = AF_INET6;
break;
case ADDRESS_FAMILY_UNSPECIFIED:
hints.ai_family = AF_UNSPEC;
break;
default:
NOTREACHED();
hints.ai_family = AF_UNSPEC;
}
#if defined(OS_WIN) || defined(OS_OPENBSD)
// DO NOT USE AI_ADDRCONFIG ON WINDOWS.
//
// The following comment in <winsock2.h> is the best documentation I found
// on AI_ADDRCONFIG for Windows:
// Flags used in "hints" argument to getaddrinfo()
// - AI_ADDRCONFIG is supported starting with Vista
// - default is AI_ADDRCONFIG ON whether the flag is set or not
// because the performance penalty in not having ADDRCONFIG in
// the multi-protocol stack environment is severe;
// this defaulting may be disabled by specifying the AI_ALL flag,
// in that case AI_ADDRCONFIG must be EXPLICITLY specified to
// enable ADDRCONFIG behavior
//
// Not only is AI_ADDRCONFIG unnecessary, but it can be harmful. If the
// computer is not connected to a network, AI_ADDRCONFIG causes getaddrinfo
// to fail with WSANO_DATA (11004) for "localhost", probably because of the
// following note on AI_ADDRCONFIG in the MSDN getaddrinfo page:
// The IPv4 or IPv6 loopback address is not considered a valid global
// address.
// See http://crbug.com/5234.
//
// OpenBSD does not support it, either.
hints.ai_flags = 0;
#else
hints.ai_flags = AI_ADDRCONFIG;
#endif
// On Linux AI_ADDRCONFIG doesn't consider loopback addreses, even if only
// loopback addresses are configured. So don't use it when there are only
// loopback addresses.
if (host_resolver_flags & HOST_RESOLVER_LOOPBACK_ONLY)
hints.ai_flags &= ~AI_ADDRCONFIG;
if (host_resolver_flags & HOST_RESOLVER_CANONNAME)
hints.ai_flags |= AI_CANONNAME;
// Restrict result set to only this socket type to avoid duplicates.
hints.ai_socktype = SOCK_STREAM;
int err = getaddrinfo(host.c_str(), NULL, &hints, &ai);
bool should_retry = false;
#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD)
// If we fail, re-initialise the resolver just in case there have been any
// changes to /etc/resolv.conf and retry. See http://crbug.com/11380 for info.
if (err && DnsReloadTimerHasExpired()) {
res_nclose(&_res);
if (!res_ninit(&_res))
should_retry = true;
}
#endif
// If the lookup was restricted (either by address family, or address
// detection), and the results where all localhost of a single family,
// maybe we should retry. There were several bugs related to these
// issues, for example http://crbug.com/42058 and http://crbug.com/49024
if ((hints.ai_family != AF_UNSPEC || hints.ai_flags & AI_ADDRCONFIG) &&
err == 0 && IsAllLocalhostOfOneFamily(ai)) {
if (host_resolver_flags & HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6) {
hints.ai_family = AF_UNSPEC;
should_retry = true;
}
if (hints.ai_flags & AI_ADDRCONFIG) {
hints.ai_flags &= ~AI_ADDRCONFIG;
should_retry = true;
}
}
if (should_retry) {
if (ai != NULL) {
freeaddrinfo(ai);
ai = NULL;
}
err = getaddrinfo(host.c_str(), NULL, &hints, &ai);
}
if (err) {
if (os_error) {
#if defined(OS_WIN)
*os_error = WSAGetLastError();
#else
*os_error = err;
#endif
}
return ERR_NAME_NOT_RESOLVED;
}
addrlist->Adopt(ai);
return OK;
}
} // namespace net
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <malloc.h>
#ifdef USE_MKL
#define MKL_ILP64
#define FLEXCOMPLEX
#define MKL_INT size_t
#include <mkl.h>
#else
#include <cblas.h>
#endif
size_t num_repeats = 1;
inline static float time_diff(struct timeval time1, struct timeval time2)
{
return time2.tv_sec - time1.tv_sec
+ ((float)(time2.tv_usec - time1.tv_usec))/1000000;
}
void test_dgemm(size_t m, size_t n, size_t k)
{
struct timeval start, end;
double *A, *B, *C;
printf("test col-wise matrix in MKL BLAS: M(%ld x %ld) * M(%ld %ld)\n",
m, k, k, n);
A = (double *) memalign(64, m*k*sizeof( double ));
B = (double *) memalign(64, k*n*sizeof( double ));
if (A == NULL || B == NULL) {
printf( "\n ERROR: Can't allocate memory for matrices. Aborting... \n\n");
free(A);
free(B);
return;
}
#pragma omp parallel for
for (size_t i = 0; i < (m*k); i++) {
A[i] = (double)(i+1);
}
#pragma omp parallel for
for (size_t i = 0; i < (k*n); i++) {
B[i] = (double)(-i-1);
}
//#pragma omp parallel for
// for (size_t i = 0; i < (m*n); i++) {
// C[i] = 0.0;
// }
for (size_t i = 0; i < num_repeats; i++) {
gettimeofday(&start, NULL);
C = (double *) memalign(64, m*n*sizeof( double ));
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, m, n, k, 1, A,
m, B, k, 0, C, m);
mkl_free(C);
gettimeofday(&end, NULL);
printf("It takes %.3f seconds\n", time_diff(start, end));
}
mkl_free(A);
mkl_free(B);
}
void test_dgemms(size_t block_size, size_t max_num_blocks)
{
size_t long_dim = 60 * 1024 * 1024;
for (size_t num_blocks = 1; num_blocks <= max_num_blocks; num_blocks *= 2)
test_dgemm(long_dim, block_size, num_blocks * block_size);
for (size_t num_blocks = 1; num_blocks <= max_num_blocks; num_blocks *= 2)
test_dgemm(num_blocks * block_size, block_size, long_dim);
}
int main()
{
test_dgemms(4, 128);
test_dgemms(64, 8);
}
<commit_msg>[Matrix]: test MKL dense matrix multiplication.<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <malloc.h>
#ifdef USE_MKL
#define MKL_ILP64
#define FLEXCOMPLEX
#define MKL_INT size_t
#include <mkl.h>
#else
#include <cblas.h>
#endif
size_t num_repeats = 1;
inline static float time_diff(struct timeval time1, struct timeval time2)
{
return time2.tv_sec - time1.tv_sec
+ ((float)(time2.tv_usec - time1.tv_usec))/1000000;
}
void test_dgemm(size_t m, size_t n, size_t k)
{
struct timeval start, end;
double *A, *B, *C;
printf("test col-wise matrix in MKL BLAS: M(%ld x %ld) * M(%ld %ld)\n",
m, k, k, n);
A = (double *) memalign(64, m*k*sizeof( double ));
B = (double *) memalign(64, k*n*sizeof( double ));
if (A == NULL || B == NULL) {
printf( "\n ERROR: Can't allocate memory for matrices. Aborting... \n\n");
free(A);
free(B);
return;
}
#pragma omp parallel for
for (size_t i = 0; i < (m*k); i++) {
A[i] = (double)(i+1);
}
#pragma omp parallel for
for (size_t i = 0; i < (k*n); i++) {
B[i] = (double)(-i-1);
}
//#pragma omp parallel for
// for (size_t i = 0; i < (m*n); i++) {
// C[i] = 0.0;
// }
for (size_t i = 0; i < num_repeats; i++) {
gettimeofday(&start, NULL);
C = (double *) memalign(64, m*n*sizeof( double ));
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, m, n, k, 1, A,
m, B, k, 0, C, m);
free(C);
gettimeofday(&end, NULL);
printf("It takes %.3f seconds\n", time_diff(start, end));
}
free(A);
free(B);
}
void test_dgemms(size_t block_size, size_t max_num_blocks)
{
size_t long_dim = 60 * 1024 * 1024;
for (size_t num_blocks = 1; num_blocks <= max_num_blocks; num_blocks *= 2)
test_dgemm(long_dim, block_size, num_blocks * block_size);
for (size_t num_blocks = 1; num_blocks <= max_num_blocks; num_blocks *= 2)
test_dgemm(num_blocks * block_size, block_size, long_dim);
}
int main()
{
test_dgemms(4, 128);
test_dgemms(64, 8);
}
<|endoftext|> |
<commit_before>#include "inner_bc.hpp"
#include "source/newtonian/two_dimensional/simple_flux_calculator.hpp"
#include "safe_retrieve.hpp"
namespace {
double calc_tracer_flux(const Edge& edge,
const Tessellation& tess,
const vector<ComputationalCell>& cells,
const string& name,
const Conserved& hf)
{
if(hf.Mass>0 &&
edge.neighbors.first>0 &&
edge.neighbors.first<tess.GetPointNo()){
assert(cells.at(static_cast<size_t>(edge.neighbors.first)).tracers.count(name)==1);
return hf.Mass*
cells.at(static_cast<size_t>(edge.neighbors.first)).tracers.find(name)->second;
}
if(hf.Mass<0 &&
edge.neighbors.second>0 &&
edge.neighbors.second<tess.GetPointNo()){
assert(cells.at(static_cast<size_t>(edge.neighbors.second)).tracers.count(name)==1);
return hf.Mass*
cells.at(static_cast<size_t>(edge.neighbors.second)).tracers.find(name)->second;
}
return 0;
}
double calc_total_downward_momentum
(const Tessellation& tess,
const vector<ComputationalCell>& cell_list,
const vector<Extensive>& extensive_list)
{
double res = 0;
for(size_t i=0;i<extensive_list.size();++i){
const ComputationalCell& cell = cell_list[i];
if(!safe_retrieve(cell.stickers,string("ghost"))){
const Vector2D r = tess.GetCellCM(static_cast<int>(i));
const double radius = sqrt(ScalarProd(r,r));
res -= ScalarProd(r,extensive_list[i].momentum)/radius;
}
}
return res;
}
}
InnerBC::InnerBC(const RiemannSolver& rs,
const string& ghost,
const double acceleration,
const double bottom_area,
const CoreAtmosphereGravity& cag):
rs_(rs),
ghost_(ghost),
a_(acceleration),
bottom_area_(bottom_area),
cag_(cag) {}
namespace {
const vector<pair<double,double> > calc_radius_mass_list
(const Tessellation& tess,
const vector<ComputationalCell>& cell_list,
const vector<Extensive>& extensive_live)
{
vector<pair<double,double> > res;
for(size_t i=0;i<cell_list.size();++i){
if(!safe_retrieve(cell_list[i].stickers,
string("ghost")))
res.push_back
(pair<double,double>
(abs(tess.GetCellCM(static_cast<int>(i))),
extensive_live[i].mass));
}
return res;
}
}
vector<Extensive> InnerBC::operator()
(const Tessellation& tess,
const vector<Vector2D>& point_velocities,
const vector<ComputationalCell>& cells,
const vector<Extensive>& extensives,
const CacheData& /*cd*/,
const EquationOfState& eos,
const double /*time*/,
const double dt) const
{
const double tdm =
calc_total_downward_momentum(tess,
cells,
extensives);
const CoreAtmosphereGravity::EnclosedMassCalculator emc
(cag_.getCoreMass(),
calc_radius_mass_list(tess,
cells,
extensives),
cag_.getSampleRadii(),
cag_.getSection2Shell());
const CoreAtmosphereGravity::AccelerationCalculator ac
(cag_.getGravitationConstant(), emc);
vector<Extensive> res(tess.getAllEdges().size());
for(size_t i=0;i<tess.getAllEdges().size();++i){
const Conserved hydro_flux =
calcHydroFlux(tess,point_velocities,
cells, eos, i,
pair<bool,double>
(tdm>0,
tdm>0 ? tdm/dt/bottom_area_ : dt*a_),
ac);
res.at(i).mass = hydro_flux.Mass;
res.at(i).momentum = hydro_flux.Momentum;
res.at(i).energy = hydro_flux.Energy;
for(map<string,double>::const_iterator it =
cells.front().tracers.begin();
it!=cells.front().tracers.end();
++it)
res.at(i).tracers[it->first] =
calc_tracer_flux(tess.getAllEdges().at(i),
tess,cells,it->first,hydro_flux);
}
return res;
}
namespace {
Primitive boost(const Primitive& origin,
const Vector2D& v)
{
Primitive res = origin;
res.Velocity += v;
return res;
}
Conserved support_riemann(const RiemannSolver& rs,
const Vector2D& rmp,
const Edge& edge,
const Primitive& cell,
const Vector2D& support,
bool left_real)
{
const Vector2D& p = Parallel(edge);
Conserved res = left_real ?
rotate_solve_rotate_back
(rs,
cell,
boost(reflect(cell,p),support),
0,
remove_parallel_component
(edge.vertices.second-rmp,p),
p) :
rotate_solve_rotate_back
(rs,
boost(reflect(cell,p),support),
cell,
0,
remove_parallel_component
(rmp-edge.vertices.second,p),
p);
res.Mass = 0;
res.Energy = 0;
return res;
}
Conserved support_atlas
(const double rmf,
const Vector2D& r)
{
const double radius = sqrt(ScalarProd(r,r));
Conserved res;
res.Mass = 0;
res.Energy = 0;
res.Momentum = rmf*r/radius;
return res;
}
Primitive gravinterpolate
(const ComputationalCell& origin,
const Vector2D& cm,
const Vector2D& centroid,
const Vector2D& acc,
const EquationOfState& eos)
{
const double energy =
eos.dp2e(origin.density,
origin.pressure,
origin.tracers);
const double sound_speed =
eos.dp2c(origin.density,
origin.pressure,
origin.tracers);
return Primitive
(origin.density,
origin.pressure + origin.density*ScalarProd(acc,centroid-cm),
origin.velocity,
energy,
sound_speed);
}
Conserved bulk_riemann
(const RiemannSolver& rs,
const Tessellation& tess,
const vector<Vector2D>& point_velocities,
const vector<ComputationalCell>& cells,
const EquationOfState& eos,
const Edge& edge,
const CoreAtmosphereGravity::AccelerationCalculator& ac)
{
const Vector2D left_pos =
tess.GetCellCM(edge.neighbors.first);
const Vector2D right_pos =
tess.GetCellCM(edge.neighbors.second);
const Vector2D left_acc = ac(left_pos);
const Vector2D right_acc = ac(right_pos);
const Vector2D centroid =
0.5*(edge.vertices.first+edge.vertices.second);
const size_t left_index =
static_cast<size_t>(edge.neighbors.first);
const size_t right_index =
static_cast<size_t>(edge.neighbors.second);
const Primitive left =
gravinterpolate
(cells[left_index],
left_pos,
centroid,
left_acc,
eos);
const Primitive right =
gravinterpolate
(cells[right_index],
right_pos,
centroid,
right_acc,
eos);
const Vector2D p = Parallel(edge);
const Vector2D n =
tess.GetMeshPoint(edge.neighbors.second) -
tess.GetMeshPoint(edge.neighbors.first);
const double velocity = Projection
(tess.CalcFaceVelocity
(point_velocities.at(left_index),
point_velocities.at(right_index),
tess.GetCellCM(edge.neighbors.first),
tess.GetCellCM(edge.neighbors.second),
calc_centroid(edge)),n);
return rotate_solve_rotate_back
(rs,left,right,velocity,n,p);
}
double calc_radius_sqr(const Vector2D& p)
{
return ScalarProd(p,p);
}
bool point_above_edge
(const Vector2D& p,
const Edge& edge)
{
return calc_radius_sqr(p)>calc_radius_sqr(edge.vertices.first) &&
calc_radius_sqr(p)>calc_radius_sqr(edge.vertices.second);
}
}
const Conserved InnerBC::calcHydroFlux
(const Tessellation& tess,
const vector<Vector2D>& point_velocities,
const vector<ComputationalCell>& cells,
const EquationOfState& eos,
const size_t i,
const pair<bool,double>& support,
const CoreAtmosphereGravity::AccelerationCalculator& ac) const
{
const Edge& edge = tess.GetEdge(static_cast<int>(i));
const pair<bool,bool> flags
(edge.neighbors.first>=0 && edge.neighbors.first<tess.GetPointNo(),
edge.neighbors.second>=0 && edge.neighbors.second<tess.GetPointNo());
assert(flags.first || flags.second);
if(!flags.first)
return support_riemann
(rs_,
tess.GetMeshPoint(edge.neighbors.second),
edge,
convert_to_primitive
(cells.at
(static_cast<size_t>(edge.neighbors.second)),
eos),
Vector2D(0,0),
false);
if(!flags.second)
return support_riemann
(rs_,
tess.GetMeshPoint(edge.neighbors.first),
edge,
convert_to_primitive
(cells.at
(static_cast<size_t>(edge.neighbors.first)),
eos),
Vector2D(0,0),
true);
const size_t left_index =
static_cast<size_t>(edge.neighbors.first);
const size_t right_index =
static_cast<size_t>(edge.neighbors.second);
const ComputationalCell& left_cell = cells.at(left_index);
const ComputationalCell& right_cell = cells.at(right_index);
if(safe_retrieve(left_cell.stickers,ghost_)){
if(safe_retrieve(right_cell.stickers,ghost_))
return Conserved();
if(point_above_edge
(tess.GetMeshPoint(edge.neighbors.second),edge))
return support.first ?
support_atlas
(support.second,
tess.GetMeshPoint(edge.neighbors.second)) :
support_riemann
(rs_,
tess.GetMeshPoint(edge.neighbors.second),
edge,
convert_to_primitive(right_cell,eos),
Vector2D(0,support.second),
false);
return support_riemann
(rs_,
tess.GetMeshPoint(edge.neighbors.second),
edge,
convert_to_primitive(right_cell,eos),
Vector2D(0,0),
false);
}
if(safe_retrieve(right_cell.stickers,ghost_)){
if(point_above_edge
(tess.GetMeshPoint(edge.neighbors.first),edge))
return support.first ?
support_atlas
(-support.second,
tess.GetMeshPoint(edge.neighbors.first)) :
support_riemann
(rs_,
tess.GetMeshPoint(edge.neighbors.first),
edge,
convert_to_primitive(left_cell,eos),
Vector2D(0,support.second),
true);
return support_riemann
(rs_,
tess.GetMeshPoint(edge.neighbors.first),
edge,
convert_to_primitive(left_cell,eos),
Vector2D(0,0),
true);
}
return bulk_riemann
(rs_,
tess,
point_velocities,
cells,
eos,
edge,
ac);
}
<commit_msg>modified boundary condition so that upper boundary would be free flow<commit_after>#include "inner_bc.hpp"
#include "source/newtonian/two_dimensional/simple_flux_calculator.hpp"
#include "safe_retrieve.hpp"
namespace {
double calc_tracer_flux(const Edge& edge,
const Tessellation& tess,
const vector<ComputationalCell>& cells,
const string& name,
const Conserved& hf)
{
if(hf.Mass>0 &&
edge.neighbors.first>0 &&
edge.neighbors.first<tess.GetPointNo()){
assert(cells.at(static_cast<size_t>(edge.neighbors.first)).tracers.count(name)==1);
return hf.Mass*
cells.at(static_cast<size_t>(edge.neighbors.first)).tracers.find(name)->second;
}
if(hf.Mass<0 &&
edge.neighbors.second>0 &&
edge.neighbors.second<tess.GetPointNo()){
assert(cells.at(static_cast<size_t>(edge.neighbors.second)).tracers.count(name)==1);
return hf.Mass*
cells.at(static_cast<size_t>(edge.neighbors.second)).tracers.find(name)->second;
}
return 0;
}
double calc_total_downward_momentum
(const Tessellation& tess,
const vector<ComputationalCell>& cell_list,
const vector<Extensive>& extensive_list)
{
double res = 0;
for(size_t i=0;i<extensive_list.size();++i){
const ComputationalCell& cell = cell_list[i];
if(!safe_retrieve(cell.stickers,string("ghost"))){
const Vector2D r = tess.GetCellCM(static_cast<int>(i));
const double radius = sqrt(ScalarProd(r,r));
res -= ScalarProd(r,extensive_list[i].momentum)/radius;
}
}
return res;
}
}
InnerBC::InnerBC(const RiemannSolver& rs,
const string& ghost,
const double acceleration,
const double bottom_area,
const CoreAtmosphereGravity& cag):
rs_(rs),
ghost_(ghost),
a_(acceleration),
bottom_area_(bottom_area),
cag_(cag) {}
namespace {
const vector<pair<double,double> > calc_radius_mass_list
(const Tessellation& tess,
const vector<ComputationalCell>& cell_list,
const vector<Extensive>& extensive_live)
{
vector<pair<double,double> > res;
for(size_t i=0;i<cell_list.size();++i){
if(!safe_retrieve(cell_list[i].stickers,
string("ghost")))
res.push_back
(pair<double,double>
(abs(tess.GetCellCM(static_cast<int>(i))),
extensive_live[i].mass));
}
return res;
}
}
vector<Extensive> InnerBC::operator()
(const Tessellation& tess,
const vector<Vector2D>& point_velocities,
const vector<ComputationalCell>& cells,
const vector<Extensive>& extensives,
const CacheData& /*cd*/,
const EquationOfState& eos,
const double /*time*/,
const double dt) const
{
const double tdm =
calc_total_downward_momentum(tess,
cells,
extensives);
const CoreAtmosphereGravity::EnclosedMassCalculator emc
(cag_.getCoreMass(),
calc_radius_mass_list(tess,
cells,
extensives),
cag_.getSampleRadii(),
cag_.getSection2Shell());
const CoreAtmosphereGravity::AccelerationCalculator ac
(cag_.getGravitationConstant(), emc);
vector<Extensive> res(tess.getAllEdges().size());
for(size_t i=0;i<tess.getAllEdges().size();++i){
const Conserved hydro_flux =
calcHydroFlux(tess,point_velocities,
cells, eos, i,
pair<bool,double>
(tdm>0,
tdm>0 ? tdm/dt/bottom_area_ : dt*a_),
ac);
res.at(i).mass = hydro_flux.Mass;
res.at(i).momentum = hydro_flux.Momentum;
res.at(i).energy = hydro_flux.Energy;
for(map<string,double>::const_iterator it =
cells.front().tracers.begin();
it!=cells.front().tracers.end();
++it)
res.at(i).tracers[it->first] =
calc_tracer_flux(tess.getAllEdges().at(i),
tess,cells,it->first,hydro_flux);
}
return res;
}
namespace {
Primitive boost(const Primitive& origin,
const Vector2D& v)
{
Primitive res = origin;
res.Velocity += v;
return res;
}
Conserved free_flow(const RiemannSolver& rs,
const Vector2D& rmp,
const Edge& edge,
const Primitive& cell,
bool left_real)
{
const Vector2D& p = Parallel(edge);
return left_real ?
rotate_solve_rotate_back
(rs,
cell,
cell,
0,
remove_parallel_component
(edge.vertices.second-rmp,p),
p) :
rotate_solve_rotate_back
(rs,
cell,
cell,
0,
remove_parallel_component
(rmp-edge.vertices.second,p),
p);
}
Conserved support_riemann(const RiemannSolver& rs,
const Vector2D& rmp,
const Edge& edge,
const Primitive& cell,
const Vector2D& support,
bool left_real)
{
const Vector2D& p = Parallel(edge);
Conserved res = left_real ?
rotate_solve_rotate_back
(rs,
cell,
boost(reflect(cell,p),support),
0,
remove_parallel_component
(edge.vertices.second-rmp,p),
p) :
rotate_solve_rotate_back
(rs,
boost(reflect(cell,p),support),
cell,
0,
remove_parallel_component
(rmp-edge.vertices.second,p),
p);
res.Mass = 0;
res.Energy = 0;
return res;
}
Primitive gravinterpolate
(const ComputationalCell& origin,
const Vector2D& cm,
const Vector2D& centroid,
const Vector2D& acc,
const EquationOfState& eos)
{
const double energy =
eos.dp2e(origin.density,
origin.pressure,
origin.tracers);
const double sound_speed =
eos.dp2c(origin.density,
origin.pressure,
origin.tracers);
return Primitive
(origin.density,
origin.pressure + origin.density*ScalarProd(acc,centroid-cm),
origin.velocity,
energy,
sound_speed);
}
Conserved bulk_riemann
(const RiemannSolver& rs,
const Tessellation& tess,
const vector<Vector2D>& point_velocities,
const vector<ComputationalCell>& cells,
const EquationOfState& eos,
const Edge& edge,
const CoreAtmosphereGravity::AccelerationCalculator& ac)
{
const Vector2D left_pos =
tess.GetCellCM(edge.neighbors.first);
const Vector2D right_pos =
tess.GetCellCM(edge.neighbors.second);
const Vector2D left_acc = ac(left_pos);
const Vector2D right_acc = ac(right_pos);
const Vector2D centroid =
0.5*(edge.vertices.first+edge.vertices.second);
const size_t left_index =
static_cast<size_t>(edge.neighbors.first);
const size_t right_index =
static_cast<size_t>(edge.neighbors.second);
const Primitive left =
gravinterpolate
(cells[left_index],
left_pos,
centroid,
left_acc,
eos);
const Primitive right =
gravinterpolate
(cells[right_index],
right_pos,
centroid,
right_acc,
eos);
const Vector2D p = Parallel(edge);
const Vector2D n =
tess.GetMeshPoint(edge.neighbors.second) -
tess.GetMeshPoint(edge.neighbors.first);
const double velocity = Projection
(tess.CalcFaceVelocity
(point_velocities.at(left_index),
point_velocities.at(right_index),
tess.GetCellCM(edge.neighbors.first),
tess.GetCellCM(edge.neighbors.second),
calc_centroid(edge)),n);
return rotate_solve_rotate_back
(rs,left,right,velocity,n,p);
}
double calc_radius_sqr(const Vector2D& p)
{
return ScalarProd(p,p);
}
bool point_below_edge
(const Vector2D& p,
const Edge& edge)
{
return calc_radius_sqr(p)<calc_radius_sqr(edge.vertices.first) &&
calc_radius_sqr(p)<calc_radius_sqr(edge.vertices.second);
}
}
const Conserved InnerBC::calcHydroFlux
(const Tessellation& tess,
const vector<Vector2D>& point_velocities,
const vector<ComputationalCell>& cells,
const EquationOfState& eos,
const size_t i,
const pair<bool,double>& support,
const CoreAtmosphereGravity::AccelerationCalculator& ac) const
{
const Edge& edge = tess.GetEdge(static_cast<int>(i));
const pair<bool,bool> flags
(edge.neighbors.first>=0 && edge.neighbors.first<tess.GetPointNo(),
edge.neighbors.second>=0 && edge.neighbors.second<tess.GetPointNo());
assert(flags.first || flags.second);
if(!flags.first)
return support_riemann
(rs_,
tess.GetMeshPoint(edge.neighbors.second),
edge,
convert_to_primitive
(cells.at
(static_cast<size_t>(edge.neighbors.second)),
eos),
Vector2D(0,0),
false);
if(!flags.second)
return support_riemann
(rs_,
tess.GetMeshPoint(edge.neighbors.first),
edge,
convert_to_primitive
(cells.at
(static_cast<size_t>(edge.neighbors.first)),
eos),
Vector2D(0,0),
true);
const size_t left_index =
static_cast<size_t>(edge.neighbors.first);
const size_t right_index =
static_cast<size_t>(edge.neighbors.second);
const ComputationalCell& left_cell = cells.at(left_index);
const ComputationalCell& right_cell = cells.at(right_index);
if(safe_retrieve(left_cell.stickers,ghost_)){
if(safe_retrieve(right_cell.stickers,ghost_))
return Conserved();
return point_below_edge
(tess.GetMeshPoint(edge.neighbors.second),edge) ?
free_flow
(rs_,
tess.GetMeshPoint(edge.neighbors.second),
edge,
convert_to_primitive(right_cell,eos),
false) :
support_riemann
(rs_,
tess.GetMeshPoint(edge.neighbors.second),
edge,
convert_to_primitive(right_cell,eos),
Vector2D(0,0),
false);
}
if(safe_retrieve(right_cell.stickers,ghost_)){
return point_below_edge
(tess.GetMeshPoint(edge.neighbors.second),edge) ?
free_flow
(rs_,
tess.GetMeshPoint(edge.neighbors.first),
edge,
convert_to_primitive(left_cell,eos),
true) :
support_riemann
(rs_,
tess.GetMeshPoint(edge.neighbors.first),
edge,
convert_to_primitive(left_cell,eos),
Vector2D(0,support.second),
true);
}
return bulk_riemann
(rs_,
tess,
point_velocities,
cells,
eos,
edge,
ac);
}
<|endoftext|> |
<commit_before>#include <sirius.h>
#include <thread>
using namespace sirius;
void test_fft_mpi_correctness(vector3d<int>& dims__)
{
Communicator comm(MPI_COMM_WORLD);
double a1[] = {10, 2, 0};
double a2[] = {0, 8, 0};
double a3[] = {-8, 0, 10};
Simulation_parameters p;
Unit_cell uc(p, comm);
uc.set_lattice_vectors(a1, a2, a3);
auto& rlv = uc.reciprocal_lattice_vectors();
MPI_FFT3D fft(dims__, 1, comm);
fft.init_gvec(15.0, rlv);
#ifdef __PRINT_MEMORY_USAGE
MEMORY_USAGE_INFO();
#endif
std::vector<double_complex> pw_coefs(fft.num_gvec());
if (comm.rank() == 0) printf("num_gvec: %i\n", fft.num_gvec());
DUMP("num_gvec_loc: %i", fft.num_gvec_loc());
for (int ig = 0; ig < std::min(40, fft.num_gvec()); ig++)
{
memset(&pw_coefs[0], 0, pw_coefs.size() * sizeof(double_complex));
auto gvec = fft.gvec(ig);
if (comm.rank() == 0) printf("G: %i %i %i\n", gvec[0], gvec[1], gvec[2]);
pw_coefs[ig] = 1.0;
fft.input_pw(&pw_coefs[fft.gvec_offset()]);
fft.transform(1);
mdarray<double_complex, 3> tmp(&fft.buffer(0), fft.size(0), fft.size(1), fft.local_size_z());
double d = 0;
// loop over 3D array (real space)
for (int j0 = 0; j0 < fft.size(0); j0++)
{
for (int j1 = 0; j1 < fft.size(1); j1++)
{
for (int j2 = 0; j2 < fft.local_size_z(); j2++)
{
// get real space fractional coordinate
vector3d<double> fv(double(j0) / fft.size(0),
double(j1) / fft.size(1),
double(j2 + fft.offset_z()) / fft.size(2));
double_complex z = std::exp(twopi * double_complex(0.0, (fv * gvec)));
d += std::pow(std::abs(tmp(j0, j1, j2) - z), 2);
//printf("pos: %f %f %f, fft: %f %f exp: %f %f\n", fv[0], fv[1], fv[2],
// std::real(tmp(j0, j1, j2)), std::imag(tmp(j0, j1, j2)), std::real(z), std::imag(z));
}
}
}
comm.allreduce(&d, 1);
if (comm.rank() == 0) printf("difference: %12.6f\n", d);
}
}
void test_fft_mpi(vector3d<int>& dims__)
{
printf("test of threaded FFTs (OMP version)\n");
matrix3d<double> reciprocal_lattice_vectors;
for (int i = 0; i < 3; i++) reciprocal_lattice_vectors(i, i) = 1.0;
Communicator comm(MPI_COMM_WORLD);
MPI_FFT3D fft(dims__, 1, comm);
int num_phi = 160;
Timer t1("fft_mpi");
for (int i = 0; i < num_phi; i++)
{
fft.transform(1);
fft.transform(-1);
}
double tval = t1.stop();
printf("performance: %f, (FFT/sec.)\n", 2 * num_phi / tval);
}
int main(int argn, char **argv)
{
cmd_args args;
args.register_key("--dims=", "{vector3d<int>} FFT dimensions");
args.parse_args(argn, argv);
if (argn == 1)
{
printf("Usage: %s [options]\n", argv[0]);
args.print_help();
exit(0);
}
vector3d<int> dims = args.value< vector3d<int> >("dims");
Platform::initialize(1);
//test_fft_mpi(dims);
test_fft_mpi_correctness(dims);
Platform::finalize();
}
<commit_msg>update test<commit_after>#include <sirius.h>
#include <thread>
using namespace sirius;
void test_fft_mpi_correctness(vector3d<int>& dims__)
{
Communicator comm(MPI_COMM_WORLD);
double a1[] = {10, 2, 0};
double a2[] = {0, 8, 0};
double a3[] = {-8, 0, 10};
Simulation_parameters p;
Unit_cell uc(p, comm);
uc.set_lattice_vectors(a1, a2, a3);
auto& rlv = uc.reciprocal_lattice_vectors();
MPI_FFT3D fft(dims__, 1, comm);
fft.init_gvec(15.0, rlv);
#ifdef __PRINT_MEMORY_USAGE
MEMORY_USAGE_INFO();
#endif
std::vector<double_complex> pw_coefs(fft.num_gvec());
if (comm.rank() == 0) printf("num_gvec: %i\n", fft.num_gvec());
DUMP("num_gvec_loc: %i", fft.num_gvec_loc());
for (int ig = 0; ig < std::min(40, fft.num_gvec()); ig++)
{
memset(&pw_coefs[0], 0, pw_coefs.size() * sizeof(double_complex));
auto gvec = fft.gvec(ig);
if (comm.rank() == 0) printf("G: %i %i %i\n", gvec[0], gvec[1], gvec[2]);
pw_coefs[ig] = 1.0;
fft.input_pw(&pw_coefs[fft.gvec_offset()]);
fft.transform(1);
mdarray<double_complex, 3> tmp(&fft.buffer(0), fft.size(0), fft.size(1), fft.local_size_z());
double d = 0;
// loop over 3D array (real space)
for (int j0 = 0; j0 < fft.size(0); j0++)
{
for (int j1 = 0; j1 < fft.size(1); j1++)
{
for (int j2 = 0; j2 < fft.local_size_z(); j2++)
{
// get real space fractional coordinate
vector3d<double> fv(double(j0) / fft.size(0),
double(j1) / fft.size(1),
double(j2 + fft.offset_z()) / fft.size(2));
double_complex z = std::exp(twopi * double_complex(0.0, (fv * gvec)));
d += std::pow(std::abs(tmp(j0, j1, j2) - z), 2);
//printf("pos: %f %f %f, fft: %f %f exp: %f %f\n", fv[0], fv[1], fv[2],
// std::real(tmp(j0, j1, j2)), std::imag(tmp(j0, j1, j2)), std::real(z), std::imag(z));
}
}
}
comm.allreduce(&d, 1);
if (comm.rank() == 0) printf("difference: %12.6f\n", d);
}
}
void test_fft_mpi_performance(vector3d<int>& dims__)
{
matrix3d<double> reciprocal_lattice_vectors;
for (int i = 0; i < 3; i++) reciprocal_lattice_vectors(i, i) = 1.0;
Communicator comm(MPI_COMM_WORLD);
MPI_FFT3D fft(dims__, 1, comm);
int num_phi = 100;
Timer t1("fft_mpi");
for (int i = 0; i < num_phi; i++)
{
fft.transform(1);
fft.transform(-1);
}
double tval = t1.stop();
printf("performance: %f, (FFT/sec.)\n", 2 * num_phi / tval);
}
int main(int argn, char **argv)
{
cmd_args args;
args.register_key("--dims=", "{vector3d<int>} FFT dimensions");
args.parse_args(argn, argv);
if (argn == 1)
{
printf("Usage: %s [options]\n", argv[0]);
args.print_help();
exit(0);
}
vector3d<int> dims = args.value< vector3d<int> >("dims");
Platform::initialize(1);
test_fft_mpi_correctness(dims);
test_fft_mpi_performance(dims);
Platform::finalize();
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2013, Steven Siloti
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author 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 <libtorrent/hasher.hpp>
#include <libtorrent/kademlia/item.hpp>
#include <libtorrent/bencode.hpp>
#include "ed25519.h"
#ifdef TORRENT_DEBUG
#include "libtorrent/lazy_entry.hpp"
#endif
namespace libtorrent { namespace dht
{
namespace
{
enum { canonical_length = 1200 };
int canonical_string(std::pair<char const*, int> v, boost::uint64_t seq
, std::pair<char const*, int> salt, char out[canonical_length])
{
// v must be valid bencoding!
#ifdef TORRENT_DEBUG
lazy_entry e;
error_code ec;
TORRENT_ASSERT(lazy_bdecode(v.first, v.first + v.second, e, ec) == 0);
#endif
char* ptr = out;
int left = canonical_length - (ptr - out);
if (salt.second > 0)
{
ptr += snprintf(ptr, left, "4:salt%d:", salt.second);
left = canonical_length - (ptr - out);
memcpy(ptr, salt.first, (std::min)(salt.second, left));
ptr += (std::min)(salt.second, left);
left = canonical_length - (ptr - out);
}
ptr += snprintf(ptr, canonical_length - (ptr - out)
, "3:seqi%" PRId64 "e1:v", seq);
left = canonical_length - (ptr - out);
memcpy(ptr, v.first, (std::min)(v.second, left));
ptr += (std::min)(v.second, left);
TORRENT_ASSERT((ptr - out) <= canonical_length);
return ptr - out;
}
}
sha1_hash item_target_id(
std::pair<char const*, int> v
, std::pair<char const*, int> salt
, char const* pk)
{
hasher h;
if (pk)
{
h.update(pk, item_pk_len);
if (salt.second > 0) h.update(salt.first, salt.second);
}
else
{
h.update(v.first, v.second);
}
return h.final();
}
bool verify_mutable_item(
std::pair<char const*, int> v,
std::pair<char const*, int> salt,
boost::uint64_t seq,
char const* pk,
char const* sig)
{
#ifdef TORRENT_USE_VALGRIND
VALGRIND_CHECK_MEM_IS_DEFINED(v.first, v.second);
VALGRIND_CHECK_MEM_IS_DEFINED(pk, item_pk_len);
VALGRIND_CHECK_MEM_IS_DEFINED(sig, item_sig_len);
#endif
char str[canonical_length];
int len = canonical_string(v, seq, salt, str);
return ed25519_verify((unsigned char const*)sig,
(unsigned char const*)str,
len,
(unsigned char const*)pk) == 1;
}
void sign_mutable_item(
std::pair<char const*, int> v,
std::pair<char const*, int> salt,
boost::uint64_t seq,
char const* pk,
char const* sk,
char* sig)
{
#ifdef TORRENT_USE_VALGRIND
VALGRIND_CHECK_MEM_IS_DEFINED(v.first, v.second);
VALGRIND_CHECK_MEM_IS_DEFINED(sk, item_sk_len);
VALGRIND_CHECK_MEM_IS_DEFINED(pk, item_pk_len);
#endif
char str[canonical_length];
int len = canonical_string(v, seq, salt, str);
ed25519_sign((unsigned char*)sig,
(unsigned char const*)str,
len,
(unsigned char const*)pk,
(unsigned char const*)sk
);
}
sha1_hash mutable_item_cas(std::pair<char const*, int> v
, std::pair<char const*, int> salt
, boost::uint64_t seq)
{
char str[canonical_length];
int len = canonical_string(v, seq, salt, str);
return hasher(str, len).final();
}
item::item(entry const& v
, std::pair<char const*, int> salt
, boost::uint64_t seq, char const* pk, char const* sk)
{
assign(v, salt, seq, pk, sk);
}
item::item(lazy_entry const* v, std::pair<char const*, int> salt
, boost::uint64_t seq, char const* pk, char const* sig)
{
if (!assign(v, salt, seq, pk, sig))
throw invalid_item();
}
void item::assign(entry const& v, std::pair<char const*, int> salt
, boost::uint64_t seq, char const* pk, char const* sk)
{
m_value = v;
if (pk && sk)
{
char buffer[1000];
int bsize = bencode(buffer, v);
TORRENT_ASSERT(bsize <= 1000);
sign_mutable_item(std::make_pair(buffer, bsize)
, salt, seq, pk, sk, m_sig);
memcpy(m_pk, pk, item_pk_len);
m_seq = seq;
m_mutable = true;
}
else
m_mutable = false;
}
bool item::assign(lazy_entry const* v
, std::pair<char const*, int> salt
, boost::uint64_t seq, char const* pk, char const* sig)
{
TORRENT_ASSERT(v->data_section().second <= 1000);
if (pk && sig)
{
if (!verify_mutable_item(v->data_section(), salt, seq, pk, sig))
return false;
memcpy(m_pk, pk, item_pk_len);
memcpy(m_sig, sig, item_sig_len);
if (salt.second > 0)
m_salt.assign(salt.first, salt.second);
m_seq = seq;
m_mutable = true;
}
else
m_mutable = false;
m_value = *v;
return true;
}
sha1_hash item::cas()
{
TORRENT_ASSERT(m_mutable);
char buffer[1000];
int bsize = bencode(buffer, m_value);
return mutable_item_cas(std::make_pair(buffer, bsize)
, std::pair<char const*, int>(m_salt.c_str(), m_salt.size()), m_seq);
}
} } // namespace libtorrent::dht
<commit_msg>fix valgrind build<commit_after>/*
Copyright (c) 2013, Steven Siloti
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author 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 <libtorrent/hasher.hpp>
#include <libtorrent/kademlia/item.hpp>
#include <libtorrent/bencode.hpp>
#include "ed25519.h"
#ifdef TORRENT_DEBUG
#include "libtorrent/lazy_entry.hpp"
#endif
#ifdef TORRENT_USE_VALGRIND
#include <valgrind/memcheck.h>
#endif
namespace libtorrent { namespace dht
{
namespace
{
enum { canonical_length = 1200 };
int canonical_string(std::pair<char const*, int> v, boost::uint64_t seq
, std::pair<char const*, int> salt, char out[canonical_length])
{
// v must be valid bencoding!
#ifdef TORRENT_DEBUG
lazy_entry e;
error_code ec;
TORRENT_ASSERT(lazy_bdecode(v.first, v.first + v.second, e, ec) == 0);
#endif
char* ptr = out;
int left = canonical_length - (ptr - out);
if (salt.second > 0)
{
ptr += snprintf(ptr, left, "4:salt%d:", salt.second);
left = canonical_length - (ptr - out);
memcpy(ptr, salt.first, (std::min)(salt.second, left));
ptr += (std::min)(salt.second, left);
left = canonical_length - (ptr - out);
}
ptr += snprintf(ptr, canonical_length - (ptr - out)
, "3:seqi%" PRId64 "e1:v", seq);
left = canonical_length - (ptr - out);
memcpy(ptr, v.first, (std::min)(v.second, left));
ptr += (std::min)(v.second, left);
TORRENT_ASSERT((ptr - out) <= canonical_length);
return ptr - out;
}
}
sha1_hash item_target_id(
std::pair<char const*, int> v
, std::pair<char const*, int> salt
, char const* pk)
{
hasher h;
if (pk)
{
h.update(pk, item_pk_len);
if (salt.second > 0) h.update(salt.first, salt.second);
}
else
{
h.update(v.first, v.second);
}
return h.final();
}
bool verify_mutable_item(
std::pair<char const*, int> v,
std::pair<char const*, int> salt,
boost::uint64_t seq,
char const* pk,
char const* sig)
{
#ifdef TORRENT_USE_VALGRIND
VALGRIND_CHECK_MEM_IS_DEFINED(v.first, v.second);
VALGRIND_CHECK_MEM_IS_DEFINED(pk, item_pk_len);
VALGRIND_CHECK_MEM_IS_DEFINED(sig, item_sig_len);
#endif
char str[canonical_length];
int len = canonical_string(v, seq, salt, str);
return ed25519_verify((unsigned char const*)sig,
(unsigned char const*)str,
len,
(unsigned char const*)pk) == 1;
}
void sign_mutable_item(
std::pair<char const*, int> v,
std::pair<char const*, int> salt,
boost::uint64_t seq,
char const* pk,
char const* sk,
char* sig)
{
#ifdef TORRENT_USE_VALGRIND
VALGRIND_CHECK_MEM_IS_DEFINED(v.first, v.second);
VALGRIND_CHECK_MEM_IS_DEFINED(sk, item_sk_len);
VALGRIND_CHECK_MEM_IS_DEFINED(pk, item_pk_len);
#endif
char str[canonical_length];
int len = canonical_string(v, seq, salt, str);
ed25519_sign((unsigned char*)sig,
(unsigned char const*)str,
len,
(unsigned char const*)pk,
(unsigned char const*)sk
);
}
sha1_hash mutable_item_cas(std::pair<char const*, int> v
, std::pair<char const*, int> salt
, boost::uint64_t seq)
{
char str[canonical_length];
int len = canonical_string(v, seq, salt, str);
return hasher(str, len).final();
}
item::item(entry const& v
, std::pair<char const*, int> salt
, boost::uint64_t seq, char const* pk, char const* sk)
{
assign(v, salt, seq, pk, sk);
}
item::item(lazy_entry const* v, std::pair<char const*, int> salt
, boost::uint64_t seq, char const* pk, char const* sig)
{
if (!assign(v, salt, seq, pk, sig))
throw invalid_item();
}
void item::assign(entry const& v, std::pair<char const*, int> salt
, boost::uint64_t seq, char const* pk, char const* sk)
{
m_value = v;
if (pk && sk)
{
char buffer[1000];
int bsize = bencode(buffer, v);
TORRENT_ASSERT(bsize <= 1000);
sign_mutable_item(std::make_pair(buffer, bsize)
, salt, seq, pk, sk, m_sig);
memcpy(m_pk, pk, item_pk_len);
m_seq = seq;
m_mutable = true;
}
else
m_mutable = false;
}
bool item::assign(lazy_entry const* v
, std::pair<char const*, int> salt
, boost::uint64_t seq, char const* pk, char const* sig)
{
TORRENT_ASSERT(v->data_section().second <= 1000);
if (pk && sig)
{
if (!verify_mutable_item(v->data_section(), salt, seq, pk, sig))
return false;
memcpy(m_pk, pk, item_pk_len);
memcpy(m_sig, sig, item_sig_len);
if (salt.second > 0)
m_salt.assign(salt.first, salt.second);
m_seq = seq;
m_mutable = true;
}
else
m_mutable = false;
m_value = *v;
return true;
}
sha1_hash item::cas()
{
TORRENT_ASSERT(m_mutable);
char buffer[1000];
int bsize = bencode(buffer, m_value);
return mutable_item_cas(std::make_pair(buffer, bsize)
, std::pair<char const*, int>(m_salt.c_str(), m_salt.size()), m_seq);
}
} } // namespace libtorrent::dht
<|endoftext|> |
<commit_before>/**
* @file
*
* @brief
*
* @copyright BSD License (see doc/COPYING or http://www.libelektra.org)
*/
#ifndef FACTORY_HPP
#define FACTORY_HPP
#include <map>
#include <memory>
#include <stdexcept>
#include <string>
#include <vector>
#include <command.hpp>
#include <external.hpp>
#include <ansicolors.hpp>
// TODO: to add a new command, 1.) include your header here
#include <check.hpp>
#include <convert.hpp>
#include <cp.hpp>
#include <editor.hpp>
#include <export.hpp>
#include <file.hpp>
#include <fstab.hpp>
#include <get.hpp>
#include <globalmount.hpp>
#include <import.hpp>
#include <info.hpp>
#include <list.hpp>
#include <ls.hpp>
#include <merge.hpp>
#include <metaget.hpp>
#include <metals.hpp>
#include <metaset.hpp>
#include <mount.hpp>
#include <mv.hpp>
#include <remount.hpp>
#include <rm.hpp>
#include <set.hpp>
#include <sget.hpp>
#include <shell.hpp>
#include <specmount.hpp>
#include <test.hpp>
#include <umount.hpp>
#include <validation.hpp>
class Instancer
{
public:
virtual Command * get () = 0;
virtual ~Instancer ()
{
}
};
template <class T>
class Cnstancer : public Instancer
{
virtual T * get () override
{
return new T ();
}
};
class Factory
{
std::map<std::string, Instancer *> m_factory;
public:
Factory () : m_factory ()
{
// TODO: to add a new command, 2.) add a line here -> and you are done
m_factory.insert (std::make_pair ("get", new Cnstancer<GetCommand> ()));
m_factory.insert (std::make_pair ("set", new Cnstancer<SetCommand> ()));
m_factory.insert (std::make_pair ("rm", new Cnstancer<RemoveCommand> ()));
m_factory.insert (std::make_pair ("ls", new Cnstancer<LsCommand> ()));
m_factory.insert (std::make_pair ("cp", new Cnstancer<CpCommand> ()));
m_factory.insert (std::make_pair ("mv", new Cnstancer<MvCommand> ()));
m_factory.insert (std::make_pair ("mount", new Cnstancer<MountCommand> ()));
m_factory.insert (std::make_pair ("remount", new Cnstancer<RemountCommand> ()));
m_factory.insert (std::make_pair ("shell", new Cnstancer<ShellCommand> ()));
m_factory.insert (std::make_pair ("getmeta", new Cnstancer<MetaGetCommand> ()));
m_factory.insert (std::make_pair ("setmeta", new Cnstancer<MetaSetCommand> ()));
m_factory.insert (std::make_pair ("lsmeta", new Cnstancer<MetaLsCommand> ()));
m_factory.insert (std::make_pair ("info", new Cnstancer<InfoCommand> ()));
m_factory.insert (std::make_pair ("test", new Cnstancer<TestCommand> ()));
m_factory.insert (std::make_pair ("check", new Cnstancer<CheckCommand> ()));
m_factory.insert (std::make_pair ("vset", new Cnstancer<ValidationCommand> ()));
m_factory.insert (std::make_pair ("fstab", new Cnstancer<FstabCommand> ()));
m_factory.insert (std::make_pair ("export", new Cnstancer<ExportCommand> ()));
m_factory.insert (std::make_pair ("import", new Cnstancer<ImportCommand> ()));
m_factory.insert (std::make_pair ("convert", new Cnstancer<ConvertCommand> ()));
m_factory.insert (std::make_pair ("umount", new Cnstancer<UmountCommand> ()));
m_factory.insert (std::make_pair ("file", new Cnstancer<FileCommand> ()));
m_factory.insert (std::make_pair ("sget", new Cnstancer<ShellGetCommand> ()));
m_factory.insert (std::make_pair ("merge", new Cnstancer<MergeCommand>));
m_factory.insert (std::make_pair ("list", new Cnstancer<ListCommand> ()));
m_factory.insert (std::make_pair ("editor", new Cnstancer<EditorCommand> ()));
m_factory.insert (std::make_pair ("spec-mount", new Cnstancer<SpecMountCommand> ()));
m_factory.insert (std::make_pair ("smount", new Cnstancer<SpecMountCommand> ()));
m_factory.insert (std::make_pair ("global-mount", new Cnstancer<GlobalMountCommand> ()));
m_factory.insert (std::make_pair ("gmount", new Cnstancer<GlobalMountCommand> ()));
}
~Factory ()
{
for (auto & elem : m_factory)
{
delete elem.second;
}
}
/**Returns a list of available commands */
std::vector<std::string> getCommands () const
{
std::vector<std::string> ret;
for (auto & elem : m_factory)
{
std::string text = getStdColor (ANSI_COLOR::BOLD);
text += elem.first;
text += getStdColor (ANSI_COLOR::RESET);
text += "\t";
Command * cmd = elem.second->get ();
text += cmd->getShortHelpText ();
delete cmd;
ret.push_back (text);
}
ret.push_back(getStdColor (ANSI_COLOR::BOLD) + "help" + getStdColor (ANSI_COLOR::RESET) + "\t" + "View the man page of a tool");
ret.push_back(getStdColor (ANSI_COLOR::BOLD) + "list-tools" + getStdColor (ANSI_COLOR::RESET) + "\t" + "List all external tool");
return ret;
}
CommandPtr get (std::string const & which)
{
Instancer * instancer = m_factory[which];
if (instancer)
{
CommandPtr ret (instancer->get ());
return ret;
}
else
{
m_factory.erase (which);
return CommandPtr (new ExternalCommand ());
}
}
};
#endif
<commit_msg>fix formatting<commit_after>/**
* @file
*
* @brief
*
* @copyright BSD License (see doc/COPYING or http://www.libelektra.org)
*/
#ifndef FACTORY_HPP
#define FACTORY_HPP
#include <map>
#include <memory>
#include <stdexcept>
#include <string>
#include <vector>
#include <ansicolors.hpp>
#include <command.hpp>
#include <external.hpp>
// TODO: to add a new command, 1.) include your header here
#include <check.hpp>
#include <convert.hpp>
#include <cp.hpp>
#include <editor.hpp>
#include <export.hpp>
#include <file.hpp>
#include <fstab.hpp>
#include <get.hpp>
#include <globalmount.hpp>
#include <import.hpp>
#include <info.hpp>
#include <list.hpp>
#include <ls.hpp>
#include <merge.hpp>
#include <metaget.hpp>
#include <metals.hpp>
#include <metaset.hpp>
#include <mount.hpp>
#include <mv.hpp>
#include <remount.hpp>
#include <rm.hpp>
#include <set.hpp>
#include <sget.hpp>
#include <shell.hpp>
#include <specmount.hpp>
#include <test.hpp>
#include <umount.hpp>
#include <validation.hpp>
class Instancer
{
public:
virtual Command * get () = 0;
virtual ~Instancer ()
{
}
};
template <class T>
class Cnstancer : public Instancer
{
virtual T * get () override
{
return new T ();
}
};
class Factory
{
std::map<std::string, Instancer *> m_factory;
public:
Factory () : m_factory ()
{
// TODO: to add a new command, 2.) add a line here -> and you are done
m_factory.insert (std::make_pair ("get", new Cnstancer<GetCommand> ()));
m_factory.insert (std::make_pair ("set", new Cnstancer<SetCommand> ()));
m_factory.insert (std::make_pair ("rm", new Cnstancer<RemoveCommand> ()));
m_factory.insert (std::make_pair ("ls", new Cnstancer<LsCommand> ()));
m_factory.insert (std::make_pair ("cp", new Cnstancer<CpCommand> ()));
m_factory.insert (std::make_pair ("mv", new Cnstancer<MvCommand> ()));
m_factory.insert (std::make_pair ("mount", new Cnstancer<MountCommand> ()));
m_factory.insert (std::make_pair ("remount", new Cnstancer<RemountCommand> ()));
m_factory.insert (std::make_pair ("shell", new Cnstancer<ShellCommand> ()));
m_factory.insert (std::make_pair ("getmeta", new Cnstancer<MetaGetCommand> ()));
m_factory.insert (std::make_pair ("setmeta", new Cnstancer<MetaSetCommand> ()));
m_factory.insert (std::make_pair ("lsmeta", new Cnstancer<MetaLsCommand> ()));
m_factory.insert (std::make_pair ("info", new Cnstancer<InfoCommand> ()));
m_factory.insert (std::make_pair ("test", new Cnstancer<TestCommand> ()));
m_factory.insert (std::make_pair ("check", new Cnstancer<CheckCommand> ()));
m_factory.insert (std::make_pair ("vset", new Cnstancer<ValidationCommand> ()));
m_factory.insert (std::make_pair ("fstab", new Cnstancer<FstabCommand> ()));
m_factory.insert (std::make_pair ("export", new Cnstancer<ExportCommand> ()));
m_factory.insert (std::make_pair ("import", new Cnstancer<ImportCommand> ()));
m_factory.insert (std::make_pair ("convert", new Cnstancer<ConvertCommand> ()));
m_factory.insert (std::make_pair ("umount", new Cnstancer<UmountCommand> ()));
m_factory.insert (std::make_pair ("file", new Cnstancer<FileCommand> ()));
m_factory.insert (std::make_pair ("sget", new Cnstancer<ShellGetCommand> ()));
m_factory.insert (std::make_pair ("merge", new Cnstancer<MergeCommand>));
m_factory.insert (std::make_pair ("list", new Cnstancer<ListCommand> ()));
m_factory.insert (std::make_pair ("editor", new Cnstancer<EditorCommand> ()));
m_factory.insert (std::make_pair ("spec-mount", new Cnstancer<SpecMountCommand> ()));
m_factory.insert (std::make_pair ("smount", new Cnstancer<SpecMountCommand> ()));
m_factory.insert (std::make_pair ("global-mount", new Cnstancer<GlobalMountCommand> ()));
m_factory.insert (std::make_pair ("gmount", new Cnstancer<GlobalMountCommand> ()));
}
~Factory ()
{
for (auto & elem : m_factory)
{
delete elem.second;
}
}
/**Returns a list of available commands */
std::vector<std::string> getCommands () const
{
std::vector<std::string> ret;
for (auto & elem : m_factory)
{
std::string text = getStdColor (ANSI_COLOR::BOLD);
text += elem.first;
text += getStdColor (ANSI_COLOR::RESET);
text += "\t";
Command * cmd = elem.second->get ();
text += cmd->getShortHelpText ();
delete cmd;
ret.push_back (text);
}
ret.push_back (getStdColor (ANSI_COLOR::BOLD) + "help" + getStdColor (ANSI_COLOR::RESET) + "\t" +
"View the man page of a tool");
ret.push_back (getStdColor (ANSI_COLOR::BOLD) + "list-tools" + getStdColor (ANSI_COLOR::RESET) + "\t" +
"List all external tool");
return ret;
}
CommandPtr get (std::string const & which)
{
Instancer * instancer = m_factory[which];
if (instancer)
{
CommandPtr ret (instancer->get ());
return ret;
}
else
{
m_factory.erase (which);
return CommandPtr (new ExternalCommand ());
}
}
};
#endif
<|endoftext|> |
<commit_before>// @(#)root/net:$Id$
// Author: Fons Rademakers 19/1/2001
/*************************************************************************
* Copyright (C) 1995-2001, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TPServerSocket //
// //
// This class implements parallel server sockets. A parallel server //
// socket waits for requests to come in over the network. It performs //
// some operation based on that request and then possibly returns a //
// full duplex parallel socket to the requester. The actual work is //
// done via the TSystem class (either TUnixSystem or TWinNTSystem). //
// //
//////////////////////////////////////////////////////////////////////////
#include "TPServerSocket.h"
#include "TPSocket.h"
#include "TROOT.h"
#include "TVirtualMutex.h"
ClassImp(TPServerSocket)
//______________________________________________________________________________
TPServerSocket::TPServerSocket(Int_t port, Bool_t reuse, Int_t backlog,
Int_t tcpwindowsize) :
TServerSocket(port, reuse, backlog, tcpwindowsize)
{
// Create a parallel server socket object on a specified port. Set reuse
// to true to force reuse of the server socket (i.e. do not wait for the
// time out to pass). Using backlog one can set the desirable queue length
// for pending connections.
// Use tcpwindowsize to specify the size of the receive buffer, it has
// to be specified here to make sure the window scale option is set (for
// tcpwindowsize > 65KB and for platforms supporting window scaling).
// Use IsValid() to check the validity of the
// server socket. In case server socket is not valid use GetErrorCode()
// to obtain the specific error value. These values are:
// 0 = no error (socket is valid)
// -1 = low level socket() call failed
// -2 = low level bind() call failed
// -3 = low level listen() call failed
// Every valid server socket is added to the TROOT sockets list which
// will make sure that any open sockets are properly closed on
// program termination.
fTcpWindowSize = tcpwindowsize;
SetName("PServerSocket");
}
//______________________________________________________________________________
TPServerSocket::TPServerSocket(const char *service, Bool_t reuse, Int_t backlog,
Int_t tcpwindowsize) :
TServerSocket(service, reuse, backlog, tcpwindowsize)
{
// Create a parallel server socket object for a named service. Set reuse
// to true to force reuse of the server socket (i.e. do not wait for the
// time out to pass). Using backlog one can set the desirable queue length
// for pending connections.
// Use tcpwindowsize to specify the size of the receive buffer, it has
// to be specified here to make sure the window scale option is set (for
// tcpwindowsize > 65KB and for platforms supporting window scaling).
// Use IsValid() to check the validity of the
// server socket. In case server socket is not valid use GetErrorCode()
// to obtain the specific error value. These values are:
// 0 = no error (socket is valid)
// -1 = low level socket() call failed
// -2 = low level bind() call failed
// -3 = low level listen() call failed
// Every valid server socket is added to the TROOT sockets list which
// will make sure that any open sockets are properly closed on
// program termination.
fTcpWindowSize = tcpwindowsize;
SetName("PServerSocket");
}
//______________________________________________________________________________
TSocket *TPServerSocket::Accept(UChar_t Opt)
{
// Accept a connection on a parallel server socket. Returns a full-duplex
// parallel communication TPSocket object. If no pending connections are
// present on the queue and nonblocking mode has not been enabled
// with SetOption(kNoBlock,1) the call blocks until a connection is
// present. The returned socket must be deleted by the user. The socket
// is also added to the TROOT sockets list which will make sure that
// any open sockets are properly closed on program termination.
// In case of error 0 is returned and in case non-blocking I/O is
// enabled and no connections are available -1 is returned.
TSocket *setupSocket = 0;
TSocket **pSockets;
TPSocket *newPSocket = 0;
Int_t size, port;
// wait for the incoming connections to the server and accept them
setupSocket = TServerSocket::Accept(Opt);
if (setupSocket <= 0) return 0;
// receive the port number and number of parallel sockets from the
// client and establish 'n' connections
if (setupSocket->Recv(port, size) < 0) {
Error("Accept", "error receiving port number and number of sockets");
return 0;
}
// Check if client is running in single mode
if (size == 0) {
pSockets = new TSocket*[1];
pSockets[0] = setupSocket;
// create TPSocket object with the original socket
newPSocket = new TPSocket(pSockets, 1);
} else {
pSockets = new TSocket*[size];
for (int i = 0; i < size; i++) {
pSockets[i] = new TSocket(setupSocket->GetInetAddress(),
port, fTcpWindowSize);
R__LOCKGUARD2(gROOTMutex);
gROOT->GetListOfSockets()->Remove(pSockets[i]);
}
// create TPSocket object with all the accepted sockets
newPSocket = new TPSocket(pSockets, size);
}
// Transmit authentication information, if any
if (setupSocket->IsAuthenticated())
newPSocket->SetSecContext(setupSocket->GetSecContext());
// clean up, if needed
if (size > 0)
delete setupSocket;
// return the TSocket object
return newPSocket;
}
<commit_msg>Suppress warning: ordered comparison of pointer with integer zero<commit_after>// @(#)root/net:$Id$
// Author: Fons Rademakers 19/1/2001
/*************************************************************************
* Copyright (C) 1995-2001, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TPServerSocket //
// //
// This class implements parallel server sockets. A parallel server //
// socket waits for requests to come in over the network. It performs //
// some operation based on that request and then possibly returns a //
// full duplex parallel socket to the requester. The actual work is //
// done via the TSystem class (either TUnixSystem or TWinNTSystem). //
// //
//////////////////////////////////////////////////////////////////////////
#include "TPServerSocket.h"
#include "TPSocket.h"
#include "TROOT.h"
#include "TVirtualMutex.h"
ClassImp(TPServerSocket)
//______________________________________________________________________________
TPServerSocket::TPServerSocket(Int_t port, Bool_t reuse, Int_t backlog,
Int_t tcpwindowsize) :
TServerSocket(port, reuse, backlog, tcpwindowsize)
{
// Create a parallel server socket object on a specified port. Set reuse
// to true to force reuse of the server socket (i.e. do not wait for the
// time out to pass). Using backlog one can set the desirable queue length
// for pending connections.
// Use tcpwindowsize to specify the size of the receive buffer, it has
// to be specified here to make sure the window scale option is set (for
// tcpwindowsize > 65KB and for platforms supporting window scaling).
// Use IsValid() to check the validity of the
// server socket. In case server socket is not valid use GetErrorCode()
// to obtain the specific error value. These values are:
// 0 = no error (socket is valid)
// -1 = low level socket() call failed
// -2 = low level bind() call failed
// -3 = low level listen() call failed
// Every valid server socket is added to the TROOT sockets list which
// will make sure that any open sockets are properly closed on
// program termination.
fTcpWindowSize = tcpwindowsize;
SetName("PServerSocket");
}
//______________________________________________________________________________
TPServerSocket::TPServerSocket(const char *service, Bool_t reuse, Int_t backlog,
Int_t tcpwindowsize) :
TServerSocket(service, reuse, backlog, tcpwindowsize)
{
// Create a parallel server socket object for a named service. Set reuse
// to true to force reuse of the server socket (i.e. do not wait for the
// time out to pass). Using backlog one can set the desirable queue length
// for pending connections.
// Use tcpwindowsize to specify the size of the receive buffer, it has
// to be specified here to make sure the window scale option is set (for
// tcpwindowsize > 65KB and for platforms supporting window scaling).
// Use IsValid() to check the validity of the
// server socket. In case server socket is not valid use GetErrorCode()
// to obtain the specific error value. These values are:
// 0 = no error (socket is valid)
// -1 = low level socket() call failed
// -2 = low level bind() call failed
// -3 = low level listen() call failed
// Every valid server socket is added to the TROOT sockets list which
// will make sure that any open sockets are properly closed on
// program termination.
fTcpWindowSize = tcpwindowsize;
SetName("PServerSocket");
}
//______________________________________________________________________________
TSocket *TPServerSocket::Accept(UChar_t Opt)
{
// Accept a connection on a parallel server socket. Returns a full-duplex
// parallel communication TPSocket object. If no pending connections are
// present on the queue and nonblocking mode has not been enabled
// with SetOption(kNoBlock,1) the call blocks until a connection is
// present. The returned socket must be deleted by the user. The socket
// is also added to the TROOT sockets list which will make sure that
// any open sockets are properly closed on program termination.
// In case of error 0 is returned and in case non-blocking I/O is
// enabled and no connections are available -1 is returned.
TSocket *setupSocket = 0;
TSocket **pSockets;
TPSocket *newPSocket = 0;
Int_t size, port;
// wait for the incoming connections to the server and accept them
setupSocket = TServerSocket::Accept(Opt);
if (setupSocket == 0) return 0;
// receive the port number and number of parallel sockets from the
// client and establish 'n' connections
if (setupSocket->Recv(port, size) < 0) {
Error("Accept", "error receiving port number and number of sockets");
return 0;
}
// Check if client is running in single mode
if (size == 0) {
pSockets = new TSocket*[1];
pSockets[0] = setupSocket;
// create TPSocket object with the original socket
newPSocket = new TPSocket(pSockets, 1);
} else {
pSockets = new TSocket*[size];
for (int i = 0; i < size; i++) {
pSockets[i] = new TSocket(setupSocket->GetInetAddress(),
port, fTcpWindowSize);
R__LOCKGUARD2(gROOTMutex);
gROOT->GetListOfSockets()->Remove(pSockets[i]);
}
// create TPSocket object with all the accepted sockets
newPSocket = new TPSocket(pSockets, size);
}
// Transmit authentication information, if any
if (setupSocket->IsAuthenticated())
newPSocket->SetSecContext(setupSocket->GetSecContext());
// clean up, if needed
if (size > 0)
delete setupSocket;
// return the TSocket object
return newPSocket;
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please
** contact Nokia at http://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qmessage.h"
#include "qmessage_p.h"
#include "qmessageid_p.h"
#include "qmessageaccountid_p.h"
#include "qmessagestore.h"
#include "qmessagecontentcontainer_p.h"
#include "qmessagefolderid_p.h"
#include "winhelpers_p.h"
#include <QDebug>
QMessage QMessagePrivate::from(const QMessageId &id)
{
QMessage result;
result.d_ptr->_id = id;
result.d_ptr->_parentAccountId = QMessageAccountIdPrivate::from(QMessageIdPrivate::storeRecordKey(id));
return result;
}
QString QMessagePrivate::senderName(const QMessage &message)
{
return message.d_ptr->_senderName;
}
void QMessagePrivate::setSenderName(const QMessage &message, const QString &senderName)
{
message.d_ptr->_senderName = senderName;
}
void QMessagePrivate::setSize(const QMessage &message, uint size)
{
message.d_ptr->_size = size;
}
#ifdef QMESSAGING_OPTIONAL_FOLDER
void QMessagePrivate::setParentFolderId(QMessage& message, const QMessageFolderId& id)
{
message.d_ptr->_parentFolderId = id;
message.d_ptr->_modified = true;
}
#endif
void QMessagePrivate::setStandardFolder(QMessage& message, QMessage::StandardFolder sf)
{
message.d_ptr->_standardFolder = sf;
message.d_ptr->_modified = true;
}
void QMessagePrivate::ensurePropertiesPresent(QMessage *msg) const
{
if (!_elementsPresent.properties && _id.isValid()) {
QMessageStore::ErrorCode ignoredError(QMessageStore::NoError);
if (MapiSessionPtr session = MapiSession::createSession(&ignoredError)) {
session->updateMessageProperties(&ignoredError, msg);
}
}
}
void QMessagePrivate::ensureRecipientsPresent(QMessage *msg) const
{
if (!_elementsPresent.recipients && _id.isValid()) {
QMessageStore::ErrorCode ignoredError(QMessageStore::NoError);
if (MapiSessionPtr session = MapiSession::createSession(&ignoredError)) {
session->updateMessageRecipients(&ignoredError, msg);
}
}
}
void QMessagePrivate::ensureBodyPresent(QMessage *msg) const
{
if (!_elementsPresent.body && _id.isValid()) {
QMessageStore::ErrorCode ignoredError(QMessageStore::NoError);
if (MapiSessionPtr session = MapiSession::createSession(&ignoredError)) {
session->updateMessageBody(&ignoredError, msg);
}
}
}
void QMessagePrivate::ensureAttachmentsPresent(QMessage *msg) const
{
if (!_elementsPresent.attachments && _id.isValid()) {
QMessageStore::ErrorCode ignoredError(QMessageStore::NoError);
if (MapiSessionPtr session = MapiSession::createSession(&ignoredError)) {
session->updateMessageAttachments(&ignoredError, msg);
}
}
}
QMessage::QMessage()
:
QMessageContentContainer(),
d_ptr(new QMessagePrivate(this))
{
d_ptr->_modified = false;
d_ptr->_size = 0;
setDerivedMessage(this);
}
QMessage::QMessage(const QMessageId& id)
:
QMessageContentContainer(),
d_ptr(new QMessagePrivate(this))
{
*this = QMessageStore::instance()->message(id);
setDerivedMessage(this);
}
QMessage::QMessage(const QMessage &other)
:
QMessageContentContainer(other),
d_ptr(new QMessagePrivate(this))
{
this->operator=(other);
setDerivedMessage(this);
}
QMessage& QMessage::operator=(const QMessage& other)
{
if (&other != this) {
QMessageContentContainer::operator=(other);
*d_ptr = *other.d_ptr;
setDerivedMessage(this);
}
return *this;
}
QMessage::~QMessage()
{
delete d_ptr;
d_ptr = 0;
}
QMessage QMessage::fromTransmissionFormat(Type t, const QByteArray &ba)
{
Q_UNUSED(t)
Q_UNUSED(ba)
return QMessage(); // stub
}
QMessage QMessage::fromTransmissionFormatFile(Type t, const QString& fileName)
{
Q_UNUSED(t)
Q_UNUSED(fileName)
return QMessage(); // stub
}
QByteArray QMessage::toTransmissionFormat() const
{
return QByteArray(); // stub
}
void QMessage::toTransmissionFormat(QDataStream& out) const
{
Q_UNUSED(out)
}
QMessageId QMessage::id() const
{
return d_ptr->_id;
}
QMessage::Type QMessage::type() const
{
return d_ptr->_type;
}
void QMessage::setType(Type t)
{
d_ptr->_modified = true;
d_ptr->_type = t;
}
QMessageAccountId QMessage::parentAccountId() const
{
return d_ptr->_parentAccountId;
}
void QMessage::setParentAccountId(const QMessageAccountId &accountId)
{
d_ptr->_modified = true;
d_ptr->_parentAccountId = accountId;
}
#ifdef QMESSAGING_OPTIONAL_FOLDER
QMessageFolderId QMessage::parentFolderId() const
{
return d_ptr->_parentFolderId;
}
#endif
QMessage::StandardFolder QMessage::standardFolder() const
{
d_ptr->ensurePropertiesPresent(const_cast<QMessage*>(this));
return d_ptr->_standardFolder;
}
QMessageAddress QMessage::from() const
{
d_ptr->ensurePropertiesPresent(const_cast<QMessage*>(this));
return d_ptr->_from;
}
void QMessage::setFrom(const QMessageAddress &address)
{
d_ptr->_modified = true;
d_ptr->_from = address;
}
QString QMessage::subject() const
{
d_ptr->ensurePropertiesPresent(const_cast<QMessage*>(this));
return d_ptr->_subject;
}
void QMessage::setSubject(const QString &s)
{
d_ptr->_modified = true;
d_ptr->_subject = s;
}
QDateTime QMessage::date() const
{
d_ptr->ensurePropertiesPresent(const_cast<QMessage*>(this));
return d_ptr->_date;
}
void QMessage::setDate(const QDateTime &d)
{
d_ptr->_modified = true;
d_ptr->_date = d;
}
QDateTime QMessage::receivedDate() const
{
d_ptr->ensurePropertiesPresent(const_cast<QMessage*>(this));
return d_ptr->_receivedDate;
}
void QMessage::setReceivedDate(const QDateTime &d)
{
d_ptr->_modified = true;
d_ptr->_receivedDate = d;
}
QMessageAddressList QMessage::to() const
{
d_ptr->ensureRecipientsPresent(const_cast<QMessage*>(this));
return d_ptr->_to;
}
void QMessage::setTo(const QMessageAddressList& toList)
{
d_ptr->_modified = true;
d_ptr->_to = toList;
}
void QMessage::setTo(const QMessageAddress& address)
{
d_ptr->_modified = true;
d_ptr->_to = QMessageAddressList() << address;
}
QMessageAddressList QMessage::cc() const
{
d_ptr->ensureRecipientsPresent(const_cast<QMessage*>(this));
return d_ptr->_cc;
}
void QMessage::setCc(const QMessageAddressList& ccList)
{
d_ptr->_modified = true;
d_ptr->_cc = ccList;
}
QMessageAddressList QMessage::bcc() const
{
d_ptr->ensureRecipientsPresent(const_cast<QMessage*>(this));
return d_ptr->_bcc;
}
void QMessage::setBcc(const QMessageAddressList& bccList)
{
d_ptr->_modified = true;
d_ptr->_bcc = bccList;
}
QMessage::StatusFlags QMessage::status() const
{
d_ptr->ensurePropertiesPresent(const_cast<QMessage*>(this));
return d_ptr->_status;
}
void QMessage::setStatus(QMessage::StatusFlags newStatus)
{
d_ptr->_modified = true;
d_ptr->_status = newStatus;
}
void QMessage::setStatus(QMessage::Status flag, bool set)
{
d_ptr->_modified = true;
if (set) {
d_ptr->_status |= flag;
} else {
d_ptr->_status &= ~flag;
}
}
QMessage::Priority QMessage::priority() const
{
d_ptr->ensurePropertiesPresent(const_cast<QMessage*>(this));
return d_ptr->_priority;
}
void QMessage::setPriority(Priority newPriority)
{
d_ptr->_modified = true;
d_ptr->_priority = newPriority;
}
uint QMessage::size() const
{
d_ptr->ensurePropertiesPresent(const_cast<QMessage*>(this));
return d_ptr->_size;
}
QMessageContentContainerId QMessage::bodyId() const
{
d_ptr->ensureBodyPresent(const_cast<QMessage*>(this));
return d_ptr->_bodyId;
}
void QMessage::setBody(const QString &bodyText, const QByteArray &mimeType)
{
QByteArray mainType("text");
QByteArray subType("plain");
QByteArray charset("utf-16");
// TODO:
//QByteArray charset(charsetFor(bodyText));
int index = mimeType.indexOf("/");
if (index != -1) {
mainType = mimeType.left(index).trimmed();
subType = mimeType.mid(index + 1).trimmed();
index = subType.indexOf(";");
if (index != -1) {
subType = subType.left(index).trimmed();
}
}
QMessageContentContainerPrivate *container(((QMessageContentContainer *)(this))->d_ptr);
QMessageContentContainerId existingBodyId(bodyId());
if (existingBodyId.isValid()) {
if (existingBodyId == QMessageContentContainerPrivate::bodyContentId()) {
// The body content is in the message itself
container->setContent(bodyText, mainType, subType, charset);
} else {
// The body content is in the first attachment
QMessageContentContainerPrivate *attachmentContainer(container->attachment(existingBodyId)->d_ptr);
attachmentContainer->setContent(bodyText, mainType, subType, charset);
}
} else {
if (container->_attachments.isEmpty()) {
// Put the content directly into the message
container->setContent(bodyText, mainType, subType, charset);
d_ptr->_bodyId = QMessageContentContainerPrivate::bodyContentId();
} else {
// Add the body as the first attachment
QMessageContentContainer newBody;
newBody.d_ptr->setContent(bodyText, mainType, subType, charset);
d_ptr->_bodyId = container->prependContent(newBody);
}
}
}
void QMessage::setBody(QTextStream &in, const QByteArray &mimeType)
{
setBody(in.readAll(), mimeType);
}
QMessageContentContainerIdList QMessage::attachmentIds() const
{
d_ptr->ensureAttachmentsPresent(const_cast<QMessage*>(this));
QMessageContentContainerIdList result;
QMessageContentContainerId bodyId(bodyId());
foreach (const QMessageContentContainerId &contentId, contentIds()) {
if (contentId != bodyId) {
result.append(contentId);
}
}
return result;
}
void QMessage::appendAttachments(const QStringList &fileNames)
{
if (!fileNames.isEmpty()) {
d_ptr->_modified = true;
QMessageContentContainerPrivate *container(((QMessageContentContainer *)(this))->d_ptr);
if (container->_attachments.isEmpty()) {
QMessageContentContainerId existingBodyId(bodyId());
if (existingBodyId == QMessageContentContainerPrivate::bodyContentId()) {
// The body content is in the message itself - move it to become the first attachment
QMessageContentContainer newBody(*this);
container->setContentType("multipart", "mixed", "");
d_ptr->_bodyId = container->prependContent(newBody);
} else {
// This message is now multipart
container->setContentType("multipart", "mixed", "");
}
container->_available = true;
}
foreach (const QString &filename, fileNames) {
QMessageContentContainer attachment;
if (attachment.d_ptr->createAttachment(filename)) {
container->appendContent(attachment);
}
}
}
}
void QMessage::clearAttachments()
{
d_ptr->_modified = true;
QMessageContentContainerPrivate *container(((QMessageContentContainer *)(this))->d_ptr);
container->_attachments.clear();
}
bool QMessage::isModified() const
{
return d_ptr->_modified;
}
QMessage QMessage::createResponseMessage(ResponseType type) const
{
Q_UNUSED(type)
return QMessage(); // stub
}
<commit_msg>Set charset correctly on windows.<commit_after>/****************************************************************************
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please
** contact Nokia at http://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qmessage.h"
#include "qmessage_p.h"
#include "qmessageid_p.h"
#include "qmessageaccountid_p.h"
#include "qmessagestore.h"
#include "qmessagecontentcontainer_p.h"
#include "qmessagefolderid_p.h"
#include "winhelpers_p.h"
#include <QDebug>
namespace {
QByteArray charsetFor(const QString &input)
{
QByteArray result(QMessage::preferredCharsetFor(input));
if (result.isEmpty()) {
result = "UTF-16";
}
return result;
}
}
QMessage QMessagePrivate::from(const QMessageId &id)
{
QMessage result;
result.d_ptr->_id = id;
result.d_ptr->_parentAccountId = QMessageAccountIdPrivate::from(QMessageIdPrivate::storeRecordKey(id));
return result;
}
QString QMessagePrivate::senderName(const QMessage &message)
{
return message.d_ptr->_senderName;
}
void QMessagePrivate::setSenderName(const QMessage &message, const QString &senderName)
{
message.d_ptr->_senderName = senderName;
}
void QMessagePrivate::setSize(const QMessage &message, uint size)
{
message.d_ptr->_size = size;
}
#ifdef QMESSAGING_OPTIONAL_FOLDER
void QMessagePrivate::setParentFolderId(QMessage& message, const QMessageFolderId& id)
{
message.d_ptr->_parentFolderId = id;
message.d_ptr->_modified = true;
}
#endif
void QMessagePrivate::setStandardFolder(QMessage& message, QMessage::StandardFolder sf)
{
message.d_ptr->_standardFolder = sf;
message.d_ptr->_modified = true;
}
void QMessagePrivate::ensurePropertiesPresent(QMessage *msg) const
{
if (!_elementsPresent.properties && _id.isValid()) {
QMessageStore::ErrorCode ignoredError(QMessageStore::NoError);
if (MapiSessionPtr session = MapiSession::createSession(&ignoredError)) {
session->updateMessageProperties(&ignoredError, msg);
}
}
}
void QMessagePrivate::ensureRecipientsPresent(QMessage *msg) const
{
if (!_elementsPresent.recipients && _id.isValid()) {
QMessageStore::ErrorCode ignoredError(QMessageStore::NoError);
if (MapiSessionPtr session = MapiSession::createSession(&ignoredError)) {
session->updateMessageRecipients(&ignoredError, msg);
}
}
}
void QMessagePrivate::ensureBodyPresent(QMessage *msg) const
{
if (!_elementsPresent.body && _id.isValid()) {
QMessageStore::ErrorCode ignoredError(QMessageStore::NoError);
if (MapiSessionPtr session = MapiSession::createSession(&ignoredError)) {
session->updateMessageBody(&ignoredError, msg);
}
}
}
void QMessagePrivate::ensureAttachmentsPresent(QMessage *msg) const
{
if (!_elementsPresent.attachments && _id.isValid()) {
QMessageStore::ErrorCode ignoredError(QMessageStore::NoError);
if (MapiSessionPtr session = MapiSession::createSession(&ignoredError)) {
session->updateMessageAttachments(&ignoredError, msg);
}
}
}
QMessage::QMessage()
:
QMessageContentContainer(),
d_ptr(new QMessagePrivate(this))
{
d_ptr->_modified = false;
d_ptr->_size = 0;
setDerivedMessage(this);
}
QMessage::QMessage(const QMessageId& id)
:
QMessageContentContainer(),
d_ptr(new QMessagePrivate(this))
{
*this = QMessageStore::instance()->message(id);
setDerivedMessage(this);
}
QMessage::QMessage(const QMessage &other)
:
QMessageContentContainer(other),
d_ptr(new QMessagePrivate(this))
{
this->operator=(other);
setDerivedMessage(this);
}
QMessage& QMessage::operator=(const QMessage& other)
{
if (&other != this) {
QMessageContentContainer::operator=(other);
*d_ptr = *other.d_ptr;
setDerivedMessage(this);
}
return *this;
}
QMessage::~QMessage()
{
delete d_ptr;
d_ptr = 0;
}
QMessage QMessage::fromTransmissionFormat(Type t, const QByteArray &ba)
{
Q_UNUSED(t)
Q_UNUSED(ba)
return QMessage(); // stub
}
QMessage QMessage::fromTransmissionFormatFile(Type t, const QString& fileName)
{
Q_UNUSED(t)
Q_UNUSED(fileName)
return QMessage(); // stub
}
QByteArray QMessage::toTransmissionFormat() const
{
return QByteArray(); // stub
}
void QMessage::toTransmissionFormat(QDataStream& out) const
{
Q_UNUSED(out)
}
QMessageId QMessage::id() const
{
return d_ptr->_id;
}
QMessage::Type QMessage::type() const
{
return d_ptr->_type;
}
void QMessage::setType(Type t)
{
d_ptr->_modified = true;
d_ptr->_type = t;
}
QMessageAccountId QMessage::parentAccountId() const
{
return d_ptr->_parentAccountId;
}
void QMessage::setParentAccountId(const QMessageAccountId &accountId)
{
d_ptr->_modified = true;
d_ptr->_parentAccountId = accountId;
}
#ifdef QMESSAGING_OPTIONAL_FOLDER
QMessageFolderId QMessage::parentFolderId() const
{
return d_ptr->_parentFolderId;
}
#endif
QMessage::StandardFolder QMessage::standardFolder() const
{
d_ptr->ensurePropertiesPresent(const_cast<QMessage*>(this));
return d_ptr->_standardFolder;
}
QMessageAddress QMessage::from() const
{
d_ptr->ensurePropertiesPresent(const_cast<QMessage*>(this));
return d_ptr->_from;
}
void QMessage::setFrom(const QMessageAddress &address)
{
d_ptr->_modified = true;
d_ptr->_from = address;
}
QString QMessage::subject() const
{
d_ptr->ensurePropertiesPresent(const_cast<QMessage*>(this));
return d_ptr->_subject;
}
void QMessage::setSubject(const QString &s)
{
d_ptr->_modified = true;
d_ptr->_subject = s;
}
QDateTime QMessage::date() const
{
d_ptr->ensurePropertiesPresent(const_cast<QMessage*>(this));
return d_ptr->_date;
}
void QMessage::setDate(const QDateTime &d)
{
d_ptr->_modified = true;
d_ptr->_date = d;
}
QDateTime QMessage::receivedDate() const
{
d_ptr->ensurePropertiesPresent(const_cast<QMessage*>(this));
return d_ptr->_receivedDate;
}
void QMessage::setReceivedDate(const QDateTime &d)
{
d_ptr->_modified = true;
d_ptr->_receivedDate = d;
}
QMessageAddressList QMessage::to() const
{
d_ptr->ensureRecipientsPresent(const_cast<QMessage*>(this));
return d_ptr->_to;
}
void QMessage::setTo(const QMessageAddressList& toList)
{
d_ptr->_modified = true;
d_ptr->_to = toList;
}
void QMessage::setTo(const QMessageAddress& address)
{
d_ptr->_modified = true;
d_ptr->_to = QMessageAddressList() << address;
}
QMessageAddressList QMessage::cc() const
{
d_ptr->ensureRecipientsPresent(const_cast<QMessage*>(this));
return d_ptr->_cc;
}
void QMessage::setCc(const QMessageAddressList& ccList)
{
d_ptr->_modified = true;
d_ptr->_cc = ccList;
}
QMessageAddressList QMessage::bcc() const
{
d_ptr->ensureRecipientsPresent(const_cast<QMessage*>(this));
return d_ptr->_bcc;
}
void QMessage::setBcc(const QMessageAddressList& bccList)
{
d_ptr->_modified = true;
d_ptr->_bcc = bccList;
}
QMessage::StatusFlags QMessage::status() const
{
d_ptr->ensurePropertiesPresent(const_cast<QMessage*>(this));
return d_ptr->_status;
}
void QMessage::setStatus(QMessage::StatusFlags newStatus)
{
d_ptr->_modified = true;
d_ptr->_status = newStatus;
}
void QMessage::setStatus(QMessage::Status flag, bool set)
{
d_ptr->_modified = true;
if (set) {
d_ptr->_status |= flag;
} else {
d_ptr->_status &= ~flag;
}
}
QMessage::Priority QMessage::priority() const
{
d_ptr->ensurePropertiesPresent(const_cast<QMessage*>(this));
return d_ptr->_priority;
}
void QMessage::setPriority(Priority newPriority)
{
d_ptr->_modified = true;
d_ptr->_priority = newPriority;
}
uint QMessage::size() const
{
d_ptr->ensurePropertiesPresent(const_cast<QMessage*>(this));
return d_ptr->_size;
}
QMessageContentContainerId QMessage::bodyId() const
{
d_ptr->ensureBodyPresent(const_cast<QMessage*>(this));
return d_ptr->_bodyId;
}
void QMessage::setBody(const QString &bodyText, const QByteArray &mimeType)
{
QByteArray mainType("text");
QByteArray subType("plain");
QByteArray charset;
int index = mimeType.indexOf("/");
if (index != -1) {
mainType = mimeType.left(index).trimmed();
subType = mimeType.mid(index + 1).trimmed();
index = subType.indexOf(";");
if (index != -1) {
QString remainder = subType.mid(index + 1);
subType = subType.left(index).trimmed();
QRegExp charsetPattern("charset=(\\S+)");
index = charsetPattern.indexIn(remainder);
if (index != -1) {
charset = charsetPattern.cap(1).toLatin1();
}
}
}
if (charset.isEmpty()) {
charset = charsetFor(bodyText);
}
QMessageContentContainerPrivate *container(((QMessageContentContainer *)(this))->d_ptr);
QMessageContentContainerId existingBodyId(bodyId());
if (existingBodyId.isValid()) {
if (existingBodyId == QMessageContentContainerPrivate::bodyContentId()) {
// The body content is in the message itself
container->setContent(bodyText, mainType, subType, charset);
} else {
// The body content is in the first attachment
QMessageContentContainerPrivate *attachmentContainer(container->attachment(existingBodyId)->d_ptr);
attachmentContainer->setContent(bodyText, mainType, subType, charset);
}
} else {
if (container->_attachments.isEmpty()) {
// Put the content directly into the message
container->setContent(bodyText, mainType, subType, charset);
d_ptr->_bodyId = QMessageContentContainerPrivate::bodyContentId();
} else {
// Add the body as the first attachment
QMessageContentContainer newBody;
newBody.d_ptr->setContent(bodyText, mainType, subType, charset);
d_ptr->_bodyId = container->prependContent(newBody);
}
}
}
void QMessage::setBody(QTextStream &in, const QByteArray &mimeType)
{
setBody(in.readAll(), mimeType);
}
QMessageContentContainerIdList QMessage::attachmentIds() const
{
d_ptr->ensureAttachmentsPresent(const_cast<QMessage*>(this));
QMessageContentContainerIdList result;
QMessageContentContainerId bodyId(bodyId());
foreach (const QMessageContentContainerId &contentId, contentIds()) {
if (contentId != bodyId) {
result.append(contentId);
}
}
return result;
}
void QMessage::appendAttachments(const QStringList &fileNames)
{
if (!fileNames.isEmpty()) {
d_ptr->_modified = true;
QMessageContentContainerPrivate *container(((QMessageContentContainer *)(this))->d_ptr);
if (container->_attachments.isEmpty()) {
QMessageContentContainerId existingBodyId(bodyId());
if (existingBodyId == QMessageContentContainerPrivate::bodyContentId()) {
// The body content is in the message itself - move it to become the first attachment
QMessageContentContainer newBody(*this);
container->setContentType("multipart", "mixed", "");
d_ptr->_bodyId = container->prependContent(newBody);
} else {
// This message is now multipart
container->setContentType("multipart", "mixed", "");
}
container->_available = true;
}
foreach (const QString &filename, fileNames) {
QMessageContentContainer attachment;
if (attachment.d_ptr->createAttachment(filename)) {
container->appendContent(attachment);
}
}
}
}
void QMessage::clearAttachments()
{
d_ptr->_modified = true;
QMessageContentContainerPrivate *container(((QMessageContentContainer *)(this))->d_ptr);
container->_attachments.clear();
}
bool QMessage::isModified() const
{
return d_ptr->_modified;
}
QMessage QMessage::createResponseMessage(ResponseType type) const
{
Q_UNUSED(type)
return QMessage(); // stub
}
<|endoftext|> |
<commit_before>/*
* Copyright © 2010 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
/**
* \file ir_function_inlining.cpp
*
* Replaces calls to functions with the body of the function.
*/
#include <inttypes.h>
#include "ir.h"
#include "ir_visitor.h"
#include "ir_function_inlining.h"
#include "ir_expression_flattening.h"
#include "glsl_types.h"
#include "hash_table.h"
class ir_function_inlining_visitor : public ir_hierarchical_visitor {
public:
ir_function_inlining_visitor()
{
progress = false;
}
virtual ~ir_function_inlining_visitor()
{
/* empty */
}
virtual ir_visitor_status visit_enter(ir_expression *);
virtual ir_visitor_status visit_enter(ir_call *);
virtual ir_visitor_status visit_enter(ir_assignment *);
virtual ir_visitor_status visit_enter(ir_return *);
virtual ir_visitor_status visit_enter(ir_texture *);
virtual ir_visitor_status visit_enter(ir_swizzle *);
bool progress;
};
bool
automatic_inlining_predicate(ir_instruction *ir)
{
ir_call *call = ir->as_call();
if (call && can_inline(call))
return true;
return false;
}
bool
do_function_inlining(exec_list *instructions)
{
ir_function_inlining_visitor v;
do_expression_flattening(instructions, automatic_inlining_predicate);
v.run(instructions);
return v.progress;
}
static void
replace_return_with_assignment(ir_instruction *ir, void *data)
{
void *ctx = talloc_parent(ir);
ir_variable *retval = (ir_variable *)data;
ir_return *ret = ir->as_return();
if (ret) {
if (ret->value) {
ir_rvalue *lhs = new(ctx) ir_dereference_variable(retval);
ret->replace_with(new(ctx) ir_assignment(lhs, ret->value, NULL));
} else {
/* un-valued return has to be the last return, or we shouldn't
* have reached here. (see can_inline()).
*/
assert(!ret->next->is_tail_sentinal());
}
}
}
ir_rvalue *
ir_call::generate_inline(ir_instruction *next_ir)
{
void *ctx = talloc_parent(this);
ir_variable **parameters;
int num_parameters;
int i;
ir_variable *retval = NULL;
struct hash_table *ht;
ht = hash_table_ctor(0, hash_table_pointer_hash, hash_table_pointer_compare);
num_parameters = 0;
foreach_iter(exec_list_iterator, iter_sig, this->callee->parameters)
num_parameters++;
parameters = new ir_variable *[num_parameters];
/* Generate storage for the return value. */
if (this->callee->return_type) {
retval = new(ctx) ir_variable(this->callee->return_type, "__retval",
ir_var_auto);
next_ir->insert_before(retval);
}
/* Generate the declarations for the parameters to our inlined code,
* and set up the mapping of real function body variables to ours.
*/
i = 0;
exec_list_iterator sig_param_iter = this->callee->parameters.iterator();
exec_list_iterator param_iter = this->actual_parameters.iterator();
for (i = 0; i < num_parameters; i++) {
ir_variable *sig_param = (ir_variable *) sig_param_iter.get();
ir_rvalue *param = (ir_rvalue *) param_iter.get();
/* Generate a new variable for the parameter. */
if (sig_param->type->base_type == GLSL_TYPE_SAMPLER) {
/* For samplers, we want the inlined sampler references
* referencing the passed in sampler variable, since that
* will have the location information, which an assignment of
* a sampler wouldn't.
*/
parameters[i] = NULL;
hash_table_insert(ht, param->variable_referenced(), sig_param);
} else {
parameters[i] = sig_param->clone(ht);
parameters[i]->mode = ir_var_auto;
next_ir->insert_before(parameters[i]);
}
/* Move the actual param into our param variable if it's an 'in' type. */
if (parameters[i] && (sig_param->mode == ir_var_in ||
sig_param->mode == ir_var_inout)) {
ir_assignment *assign;
assign = new(ctx) ir_assignment(new(ctx) ir_dereference_variable(parameters[i]),
param, NULL);
next_ir->insert_before(assign);
}
sig_param_iter.next();
param_iter.next();
}
/* Generate the inlined body of the function. */
foreach_iter(exec_list_iterator, iter, callee->body) {
ir_instruction *ir = (ir_instruction *)iter.get();
ir_instruction *new_ir = ir->clone(ht);
next_ir->insert_before(new_ir);
visit_tree(new_ir, replace_return_with_assignment, retval);
}
/* Copy back the value of any 'out' parameters from the function body
* variables to our own.
*/
i = 0;
param_iter = this->actual_parameters.iterator();
sig_param_iter = this->callee->parameters.iterator();
for (i = 0; i < num_parameters; i++) {
ir_instruction *const param = (ir_instruction *) param_iter.get();
const ir_variable *const sig_param = (ir_variable *) sig_param_iter.get();
/* Move our param variable into the actual param if it's an 'out' type. */
if (parameters[i] && (sig_param->mode == ir_var_out ||
sig_param->mode == ir_var_inout)) {
ir_assignment *assign;
assign = new(ctx) ir_assignment(param->clone(NULL)->as_rvalue(),
new(ctx) ir_dereference_variable(parameters[i]),
NULL);
next_ir->insert_before(assign);
}
param_iter.next();
sig_param_iter.next();
}
delete [] parameters;
hash_table_dtor(ht);
if (retval)
return new(ctx) ir_dereference_variable(retval);
else
return NULL;
}
ir_visitor_status
ir_function_inlining_visitor::visit_enter(ir_expression *ir)
{
(void) ir;
return visit_continue_with_parent;
}
ir_visitor_status
ir_function_inlining_visitor::visit_enter(ir_return *ir)
{
(void) ir;
return visit_continue_with_parent;
}
ir_visitor_status
ir_function_inlining_visitor::visit_enter(ir_texture *ir)
{
(void) ir;
return visit_continue_with_parent;
}
ir_visitor_status
ir_function_inlining_visitor::visit_enter(ir_swizzle *ir)
{
(void) ir;
return visit_continue_with_parent;
}
ir_visitor_status
ir_function_inlining_visitor::visit_enter(ir_call *ir)
{
if (can_inline(ir)) {
/* If the call was part of some tree, then it should have been
* flattened out or we shouldn't have seen it because of a
* visit_continue_with_parent in this visitor.
*/
assert(ir == base_ir);
(void) ir->generate_inline(ir);
ir->remove();
this->progress = true;
}
return visit_continue;
}
ir_visitor_status
ir_function_inlining_visitor::visit_enter(ir_assignment *ir)
{
ir_call *call = ir->rhs->as_call();
if (!call || !can_inline(call))
return visit_continue;
/* generates the parameter setup, function body, and returns the return
* value of the function
*/
ir_rvalue *rhs = call->generate_inline(ir);
assert(rhs);
ir->rhs = rhs;
this->progress = true;
return visit_continue;
}
<commit_msg>glsl2: Remove an inlined unvalued return statement.<commit_after>/*
* Copyright © 2010 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
/**
* \file ir_function_inlining.cpp
*
* Replaces calls to functions with the body of the function.
*/
#include <inttypes.h>
#include "ir.h"
#include "ir_visitor.h"
#include "ir_function_inlining.h"
#include "ir_expression_flattening.h"
#include "glsl_types.h"
#include "hash_table.h"
class ir_function_inlining_visitor : public ir_hierarchical_visitor {
public:
ir_function_inlining_visitor()
{
progress = false;
}
virtual ~ir_function_inlining_visitor()
{
/* empty */
}
virtual ir_visitor_status visit_enter(ir_expression *);
virtual ir_visitor_status visit_enter(ir_call *);
virtual ir_visitor_status visit_enter(ir_assignment *);
virtual ir_visitor_status visit_enter(ir_return *);
virtual ir_visitor_status visit_enter(ir_texture *);
virtual ir_visitor_status visit_enter(ir_swizzle *);
bool progress;
};
bool
automatic_inlining_predicate(ir_instruction *ir)
{
ir_call *call = ir->as_call();
if (call && can_inline(call))
return true;
return false;
}
bool
do_function_inlining(exec_list *instructions)
{
ir_function_inlining_visitor v;
do_expression_flattening(instructions, automatic_inlining_predicate);
v.run(instructions);
return v.progress;
}
static void
replace_return_with_assignment(ir_instruction *ir, void *data)
{
void *ctx = talloc_parent(ir);
ir_variable *retval = (ir_variable *)data;
ir_return *ret = ir->as_return();
if (ret) {
if (ret->value) {
ir_rvalue *lhs = new(ctx) ir_dereference_variable(retval);
ret->replace_with(new(ctx) ir_assignment(lhs, ret->value, NULL));
} else {
/* un-valued return has to be the last return, or we shouldn't
* have reached here. (see can_inline()).
*/
assert(!ret->next->is_tail_sentinal());
ret->remove();
}
}
}
ir_rvalue *
ir_call::generate_inline(ir_instruction *next_ir)
{
void *ctx = talloc_parent(this);
ir_variable **parameters;
int num_parameters;
int i;
ir_variable *retval = NULL;
struct hash_table *ht;
ht = hash_table_ctor(0, hash_table_pointer_hash, hash_table_pointer_compare);
num_parameters = 0;
foreach_iter(exec_list_iterator, iter_sig, this->callee->parameters)
num_parameters++;
parameters = new ir_variable *[num_parameters];
/* Generate storage for the return value. */
if (this->callee->return_type) {
retval = new(ctx) ir_variable(this->callee->return_type, "__retval",
ir_var_auto);
next_ir->insert_before(retval);
}
/* Generate the declarations for the parameters to our inlined code,
* and set up the mapping of real function body variables to ours.
*/
i = 0;
exec_list_iterator sig_param_iter = this->callee->parameters.iterator();
exec_list_iterator param_iter = this->actual_parameters.iterator();
for (i = 0; i < num_parameters; i++) {
ir_variable *sig_param = (ir_variable *) sig_param_iter.get();
ir_rvalue *param = (ir_rvalue *) param_iter.get();
/* Generate a new variable for the parameter. */
if (sig_param->type->base_type == GLSL_TYPE_SAMPLER) {
/* For samplers, we want the inlined sampler references
* referencing the passed in sampler variable, since that
* will have the location information, which an assignment of
* a sampler wouldn't.
*/
parameters[i] = NULL;
hash_table_insert(ht, param->variable_referenced(), sig_param);
} else {
parameters[i] = sig_param->clone(ht);
parameters[i]->mode = ir_var_auto;
next_ir->insert_before(parameters[i]);
}
/* Move the actual param into our param variable if it's an 'in' type. */
if (parameters[i] && (sig_param->mode == ir_var_in ||
sig_param->mode == ir_var_inout)) {
ir_assignment *assign;
assign = new(ctx) ir_assignment(new(ctx) ir_dereference_variable(parameters[i]),
param, NULL);
next_ir->insert_before(assign);
}
sig_param_iter.next();
param_iter.next();
}
/* Generate the inlined body of the function. */
foreach_iter(exec_list_iterator, iter, callee->body) {
ir_instruction *ir = (ir_instruction *)iter.get();
ir_instruction *new_ir = ir->clone(ht);
next_ir->insert_before(new_ir);
visit_tree(new_ir, replace_return_with_assignment, retval);
}
/* Copy back the value of any 'out' parameters from the function body
* variables to our own.
*/
i = 0;
param_iter = this->actual_parameters.iterator();
sig_param_iter = this->callee->parameters.iterator();
for (i = 0; i < num_parameters; i++) {
ir_instruction *const param = (ir_instruction *) param_iter.get();
const ir_variable *const sig_param = (ir_variable *) sig_param_iter.get();
/* Move our param variable into the actual param if it's an 'out' type. */
if (parameters[i] && (sig_param->mode == ir_var_out ||
sig_param->mode == ir_var_inout)) {
ir_assignment *assign;
assign = new(ctx) ir_assignment(param->clone(NULL)->as_rvalue(),
new(ctx) ir_dereference_variable(parameters[i]),
NULL);
next_ir->insert_before(assign);
}
param_iter.next();
sig_param_iter.next();
}
delete [] parameters;
hash_table_dtor(ht);
if (retval)
return new(ctx) ir_dereference_variable(retval);
else
return NULL;
}
ir_visitor_status
ir_function_inlining_visitor::visit_enter(ir_expression *ir)
{
(void) ir;
return visit_continue_with_parent;
}
ir_visitor_status
ir_function_inlining_visitor::visit_enter(ir_return *ir)
{
(void) ir;
return visit_continue_with_parent;
}
ir_visitor_status
ir_function_inlining_visitor::visit_enter(ir_texture *ir)
{
(void) ir;
return visit_continue_with_parent;
}
ir_visitor_status
ir_function_inlining_visitor::visit_enter(ir_swizzle *ir)
{
(void) ir;
return visit_continue_with_parent;
}
ir_visitor_status
ir_function_inlining_visitor::visit_enter(ir_call *ir)
{
if (can_inline(ir)) {
/* If the call was part of some tree, then it should have been
* flattened out or we shouldn't have seen it because of a
* visit_continue_with_parent in this visitor.
*/
assert(ir == base_ir);
(void) ir->generate_inline(ir);
ir->remove();
this->progress = true;
}
return visit_continue;
}
ir_visitor_status
ir_function_inlining_visitor::visit_enter(ir_assignment *ir)
{
ir_call *call = ir->rhs->as_call();
if (!call || !can_inline(call))
return visit_continue;
/* generates the parameter setup, function body, and returns the return
* value of the function
*/
ir_rvalue *rhs = call->generate_inline(ir);
assert(rhs);
ir->rhs = rhs;
this->progress = true;
return visit_continue;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2010-2014 Jeremy Lainé
* Contact: https://github.com/jlaine/qdjango
*
* This file is part of the QDjango Library.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* 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.
*/
#include <QDebug>
#include <QLocalServer>
#include <QLocalSocket>
#include <QTcpServer>
#include <QTcpSocket>
#include <QUrl>
#include "QDjangoFastCgiServer.h"
#include "QDjangoFastCgiServer_p.h"
#include "QDjangoHttpController.h"
#include "QDjangoHttpRequest.h"
#include "QDjangoHttpRequest_p.h"
#include "QDjangoHttpResponse.h"
#include "QDjangoHttpResponse_p.h"
#include "QDjangoHttpServer.h"
#include "QDjangoUrlResolver.h"
//#define QDJANGO_DEBUG_FCGI
quint16 FCGI_Header_contentLength(FCGI_Header *header)
{
return (header->contentLengthB1 << 8) | header->contentLengthB0;
}
quint16 FCGI_Header_requestId(FCGI_Header *header)
{
return (header->requestIdB1 << 8) | header->requestIdB0;
}
void FCGI_Header_setContentLength(FCGI_Header *header, quint16 contentLength)
{
header->contentLengthB1 = (contentLength >> 8) & 0xff;
header->contentLengthB0 = (contentLength & 0xff);
}
void FCGI_Header_setRequestId(FCGI_Header *header, quint16 requestId)
{
header->requestIdB1 = (requestId >> 8) & 0xff;
header->requestIdB0 = (requestId & 0xff);
}
#ifdef QDJANGO_DEBUG_FCGI
static void hDebug(FCGI_Header *header, const char *dir)
{
qDebug("--- FCGI Record %s ---", dir);
qDebug("version: %i", header->version);
qDebug("type: %i", header->type);
qDebug("requestId: %i", FCGI_Header_requestId(header));
qDebug("contentLength: %i", FCGI_Header_contentLength(header));
qDebug("paddingLength: %i", header->paddingLength);
}
#endif
/// \cond
QDjangoFastCgiConnection::QDjangoFastCgiConnection(QIODevice *device, QDjangoFastCgiServer *server)
: QObject(server),
m_device(device),
m_inputPos(0),
m_pendingRequest(0),
m_pendingRequestId(0),
m_server(server)
{
bool check;
Q_UNUSED(check);
m_device->setParent(this);
check = connect(m_device, SIGNAL(disconnected()),
this, SIGNAL(closed()));
Q_ASSERT(check);
check = connect(m_device, SIGNAL(bytesWritten(qint64)),
this, SLOT(_q_bytesWritten(qint64)));
Q_ASSERT(check);
check = connect(m_device, SIGNAL(readyRead()),
this, SLOT(_q_readyRead()));
Q_ASSERT(check);
}
QDjangoFastCgiConnection::~QDjangoFastCgiConnection()
{
if (m_pendingRequest)
delete m_pendingRequest;
}
void QDjangoFastCgiConnection::writeResponse(quint16 requestId, QDjangoHttpResponse *response)
{
// serialise HTTP response
QString httpHeader = QString::fromLatin1("Status: %1 %2\r\n").arg(response->d->statusCode).arg(response->d->reasonPhrase);
QList<QPair<QString, QString> >::ConstIterator it = response->d->headers.constBegin();
while (it != response->d->headers.constEnd()) {
httpHeader += (*it).first + QLatin1String(": ") + (*it).second + QLatin1String("\r\n");
++it;
}
const QByteArray data = httpHeader.toUtf8() + "\r\n" + response->d->body;
const char *ptr = data.constData();
FCGI_Header *header = (FCGI_Header*)m_outputBuffer;
memset(header, 0, FCGI_HEADER_LEN);
header->version = 1;
FCGI_Header_setRequestId(header, requestId);
for (qint64 bytesRemaining = data.size(); ; ) {
const quint16 contentLength = qMin(bytesRemaining, qint64(32768));
header->type = FCGI_STDOUT;
FCGI_Header_setContentLength(header, contentLength);
memcpy(m_outputBuffer + FCGI_HEADER_LEN, ptr, contentLength);
m_device->write(m_outputBuffer, FCGI_HEADER_LEN + contentLength);
#ifdef QDJANGO_DEBUG_FCGI
hDebug(header, "sent");
qDebug("[STDOUT]");
#endif
if (contentLength > 0) {
ptr += contentLength;
bytesRemaining -= contentLength;
} else {
break;
}
}
quint16 contentLength = 8;
header->type = FCGI_END_REQUEST;
FCGI_Header_setContentLength(header, contentLength);
memset(m_outputBuffer + FCGI_HEADER_LEN, 0, contentLength);
m_device->write(m_outputBuffer, FCGI_HEADER_LEN + contentLength);
#ifdef QDJANGO_DEBUG_FCGI
hDebug(header, "sent");
qDebug("[END REQUEST]");
#endif
}
/** When bytes have been written, check whether we need to close
* the connection.
*
* @param bytes
*/
void QDjangoFastCgiConnection::_q_bytesWritten(qint64 bytes)
{
Q_UNUSED(bytes);
if (!m_device->bytesToWrite()) {
#ifdef QDJANGO_DEBUG_FCGI
qDebug("Closing connection");
#endif
m_device->close();
emit closed();
}
}
void QDjangoFastCgiConnection::_q_readyRead()
{
while (m_device->bytesAvailable()) {
// read record header
if (m_inputPos < FCGI_HEADER_LEN) {
const qint64 length = m_device->read(m_inputBuffer + m_inputPos, FCGI_HEADER_LEN - m_inputPos);
if (length < 0) {
qWarning("Failed to read header from socket");
m_device->close();
emit closed();
return;
}
m_inputPos += length;
if (m_inputPos < FCGI_HEADER_LEN)
return;
}
// read record body
FCGI_Header *header = (FCGI_Header*)m_inputBuffer;
const quint16 contentLength = FCGI_Header_contentLength(header);
const quint16 bodyLength = contentLength + header->paddingLength;
const qint64 length = m_device->read(m_inputBuffer + m_inputPos, bodyLength + FCGI_HEADER_LEN - m_inputPos);
if (length < 0) {
qWarning("Failed to read body from socket");
m_device->close();
emit closed();
return;
}
m_inputPos += length;
if (m_inputPos < FCGI_HEADER_LEN + bodyLength)
return;
m_inputPos = 0;
// process record
#ifdef QDJANGO_DEBUG_FCGI
hDebug(header, "received");
#endif
if (header->version != 1) {
qWarning("Received FastCGI frame with an invalid version %i", header->version);
m_device->close();
emit closed();
return;
}
const quint16 requestId = FCGI_Header_requestId(header);
if (header->type != FCGI_BEGIN_REQUEST && (!m_pendingRequest || requestId != m_pendingRequestId)) {
qWarning("Received FastCGI frame for an invalid request %i", requestId);
m_device->close();
emit closed();
return;
}
quint8 *d = (quint8*)(m_inputBuffer + FCGI_HEADER_LEN);
switch (header->type) {
case FCGI_BEGIN_REQUEST: {
#ifdef QDJANGO_DEBUG_FCGI
const quint16 role = (d[0] << 8) | d[1];
qDebug("[BEGIN REQUEST]");
qDebug("role: %i", role);
qDebug("flags: %i", d[2]);
#endif
if (m_pendingRequest) {
qWarning("Received FCGI_BEGIN_REQUEST inside a request");
m_device->close();
emit closed();
return;
}
m_pendingRequest = new QDjangoHttpRequest;
m_pendingRequestId = requestId;
break;
}
case FCGI_ABORT_REQUEST:
#ifdef QDJANGO_DEBUG_FCGI
qDebug("[ABORT]");
#endif
m_device->close();
emit closed();
return;
case FCGI_PARAMS:
#ifdef QDJANGO_DEBUG_FCGI
qDebug("[PARAMS]");
#endif
while (d < (quint8*)(m_inputBuffer + FCGI_HEADER_LEN + contentLength)) {
quint32 nameLength;
quint32 valueLength;
if (d[0] >> 7) {
nameLength = ((d[0] & 0x7f) << 24) | (d[1] << 16) | (d[2] << 8) | d[3];
d += 4;
} else {
nameLength = d[0];
d++;
}
if (d[0] >> 7) {
valueLength = ((d[0] & 0x7f) << 24) | (d[1] << 16) | (d[2] << 8) | d[3];
d += 4;
} else {
valueLength = d[0];
d++;
}
const QByteArray name((char*)d, nameLength);
d += nameLength;
const QByteArray value((char*)d, valueLength);
d += valueLength;
#ifdef QDJANGO_DEBUG_FCGI
qDebug() << name << ":" << value;
#endif
if (name == "PATH_INFO") {
m_pendingRequest->d->path = QString::fromUtf8(value);
} else if (name == "REQUEST_URI") {
m_pendingRequest->d->path = QUrl(QString::fromUtf8(value)).path();
} else if (name == "REQUEST_METHOD") {
m_pendingRequest->d->method = QString::fromUtf8(value);
}
m_pendingRequest->d->meta.insert(QString::fromLatin1(name), QString::fromUtf8(value));
}
break;
case FCGI_STDIN:
#ifdef QDJANGO_DEBUG_FCGI
qDebug("[STDIN]");
#endif
if (contentLength) {
m_pendingRequest->d->buffer.append((char*)d, contentLength);
} else {
QDjangoHttpRequest *request = m_pendingRequest;
const quint16 requestId = m_pendingRequestId;
m_pendingRequest = 0;
m_pendingRequestId = 0;
QDjangoHttpResponse *response = m_server->urls()->respond(*request, request->path());
writeResponse(requestId, response);
}
break;
default:
qWarning("Received FastCGI frame with an invalid type %i", header->type);
m_device->close();
emit closed();
return;
}
}
}
/// \endcond
class QDjangoFastCgiServerPrivate
{
public:
QDjangoFastCgiServerPrivate(QDjangoFastCgiServer *qq);
QLocalServer *localServer;
QTcpServer *tcpServer;
QDjangoUrlResolver *urlResolver;
private:
QDjangoFastCgiServer *q;
};
QDjangoFastCgiServerPrivate::QDjangoFastCgiServerPrivate(QDjangoFastCgiServer *qq)
: localServer(0),
tcpServer(0),
q(qq)
{
urlResolver = new QDjangoUrlResolver(q);
}
/** Constructs a new FastCGI server.
*/
QDjangoFastCgiServer::QDjangoFastCgiServer(QObject *parent)
: QObject(parent)
{
d = new QDjangoFastCgiServerPrivate(this);
}
/** Destroys the FastCGI server.
*/
QDjangoFastCgiServer::~QDjangoFastCgiServer()
{
delete d;
}
/** Closes the server. The server will no longer listen for
* incoming connections.
*/
void QDjangoFastCgiServer::close()
{
if (d->localServer)
d->localServer->close();
if (d->tcpServer)
d->tcpServer->close();
}
/** Tells the server to listen for incoming connections on the given
* local socket.
*/
bool QDjangoFastCgiServer::listen(const QString &name)
{
if (!d->localServer) {
bool check;
Q_UNUSED(check);
d->localServer = new QLocalServer(this);
check = connect(d->localServer, SIGNAL(newConnection()),
this, SLOT(_q_newLocalConnection()));
Q_ASSERT(check);
}
return d->localServer->listen(name);
}
/** Tells the server to listen for incoming TCP connections on the given
* \a address and \a port.
*/
bool QDjangoFastCgiServer::listen(const QHostAddress &address, quint16 port)
{
if (!d->tcpServer) {
bool check;
Q_UNUSED(check);
d->tcpServer = new QTcpServer(this);
check = connect(d->tcpServer, SIGNAL(newConnection()),
this, SLOT(_q_newTcpConnection()));
Q_ASSERT(check);
}
return d->tcpServer->listen(address, port);
}
/** Returns the root URL resolver for the server, which dispatches
* requests to handlers.
*/
QDjangoUrlResolver* QDjangoFastCgiServer::urls() const
{
return d->urlResolver;
}
void QDjangoFastCgiServer::_q_newLocalConnection()
{
bool check;
Q_UNUSED(check);
QLocalSocket *socket;
while ((socket = d->localServer->nextPendingConnection()) != 0) {
#ifdef QDJANGO_DEBUG_FCGI
qDebug("New local connection");
#endif
QDjangoFastCgiConnection *connection = new QDjangoFastCgiConnection(socket, this);
check = connect(connection, SIGNAL(closed()),
connection, SLOT(deleteLater()));
Q_ASSERT(check);
}
}
void QDjangoFastCgiServer::_q_newTcpConnection()
{
bool check;
Q_UNUSED(check);
QTcpSocket *socket;
while ((socket = d->tcpServer->nextPendingConnection()) != 0) {
#ifdef QDJANGO_DEBUG_FCGI
qDebug("New TCP connection");
#endif
QDjangoFastCgiConnection *connection = new QDjangoFastCgiConnection(socket, this);
check = connect(connection, SIGNAL(closed()),
connection, SLOT(deleteLater()));
Q_ASSERT(check);
}
}
<commit_msg>improve debug messages<commit_after>/*
* Copyright (C) 2010-2014 Jeremy Lainé
* Contact: https://github.com/jlaine/qdjango
*
* This file is part of the QDjango Library.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* 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.
*/
#include <QDebug>
#include <QLocalServer>
#include <QLocalSocket>
#include <QTcpServer>
#include <QTcpSocket>
#include <QUrl>
#include "QDjangoFastCgiServer.h"
#include "QDjangoFastCgiServer_p.h"
#include "QDjangoHttpController.h"
#include "QDjangoHttpRequest.h"
#include "QDjangoHttpRequest_p.h"
#include "QDjangoHttpResponse.h"
#include "QDjangoHttpResponse_p.h"
#include "QDjangoHttpServer.h"
#include "QDjangoUrlResolver.h"
//#define QDJANGO_DEBUG_FCGI
quint16 FCGI_Header_contentLength(FCGI_Header *header)
{
return (header->contentLengthB1 << 8) | header->contentLengthB0;
}
quint16 FCGI_Header_requestId(FCGI_Header *header)
{
return (header->requestIdB1 << 8) | header->requestIdB0;
}
void FCGI_Header_setContentLength(FCGI_Header *header, quint16 contentLength)
{
header->contentLengthB1 = (contentLength >> 8) & 0xff;
header->contentLengthB0 = (contentLength & 0xff);
}
void FCGI_Header_setRequestId(FCGI_Header *header, quint16 requestId)
{
header->requestIdB1 = (requestId >> 8) & 0xff;
header->requestIdB0 = (requestId & 0xff);
}
#ifdef QDJANGO_DEBUG_FCGI
static void hDebug(FCGI_Header *header, const char *dir)
{
qDebug("--- FCGI Record %s ---", dir);
qDebug("version: %i", header->version);
qDebug("type: %i", header->type);
qDebug("requestId: %i", FCGI_Header_requestId(header));
qDebug("contentLength: %i", FCGI_Header_contentLength(header));
qDebug("paddingLength: %i", header->paddingLength);
}
#endif
/// \cond
QDjangoFastCgiConnection::QDjangoFastCgiConnection(QIODevice *device, QDjangoFastCgiServer *server)
: QObject(server),
m_device(device),
m_inputPos(0),
m_pendingRequest(0),
m_pendingRequestId(0),
m_server(server)
{
bool check;
Q_UNUSED(check);
m_device->setParent(this);
check = connect(m_device, SIGNAL(disconnected()),
this, SIGNAL(closed()));
Q_ASSERT(check);
check = connect(m_device, SIGNAL(bytesWritten(qint64)),
this, SLOT(_q_bytesWritten(qint64)));
Q_ASSERT(check);
check = connect(m_device, SIGNAL(readyRead()),
this, SLOT(_q_readyRead()));
Q_ASSERT(check);
}
QDjangoFastCgiConnection::~QDjangoFastCgiConnection()
{
if (m_pendingRequest)
delete m_pendingRequest;
}
void QDjangoFastCgiConnection::writeResponse(quint16 requestId, QDjangoHttpResponse *response)
{
// serialise HTTP response
QString httpHeader = QString::fromLatin1("Status: %1 %2\r\n").arg(response->d->statusCode).arg(response->d->reasonPhrase);
QList<QPair<QString, QString> >::ConstIterator it = response->d->headers.constBegin();
while (it != response->d->headers.constEnd()) {
httpHeader += (*it).first + QLatin1String(": ") + (*it).second + QLatin1String("\r\n");
++it;
}
const QByteArray data = httpHeader.toUtf8() + "\r\n" + response->d->body;
const char *ptr = data.constData();
FCGI_Header *header = (FCGI_Header*)m_outputBuffer;
memset(header, 0, FCGI_HEADER_LEN);
header->version = 1;
FCGI_Header_setRequestId(header, requestId);
for (qint64 bytesRemaining = data.size(); ; ) {
const quint16 contentLength = qMin(bytesRemaining, qint64(32768));
header->type = FCGI_STDOUT;
FCGI_Header_setContentLength(header, contentLength);
memcpy(m_outputBuffer + FCGI_HEADER_LEN, ptr, contentLength);
m_device->write(m_outputBuffer, FCGI_HEADER_LEN + contentLength);
#ifdef QDJANGO_DEBUG_FCGI
hDebug(header, "sent");
qDebug("[STDOUT]");
#endif
if (contentLength > 0) {
ptr += contentLength;
bytesRemaining -= contentLength;
} else {
break;
}
}
quint16 contentLength = 8;
header->type = FCGI_END_REQUEST;
FCGI_Header_setContentLength(header, contentLength);
memset(m_outputBuffer + FCGI_HEADER_LEN, 0, contentLength);
m_device->write(m_outputBuffer, FCGI_HEADER_LEN + contentLength);
#ifdef QDJANGO_DEBUG_FCGI
hDebug(header, "sent");
qDebug("[END REQUEST]");
#endif
}
/** When bytes have been written, check whether we need to close
* the connection.
*
* @param bytes
*/
void QDjangoFastCgiConnection::_q_bytesWritten(qint64 bytes)
{
Q_UNUSED(bytes);
if (!m_device->bytesToWrite()) {
#ifdef QDJANGO_DEBUG_FCGI
qDebug("Closing connection");
#endif
m_device->close();
emit closed();
}
}
void QDjangoFastCgiConnection::_q_readyRead()
{
while (m_device->bytesAvailable()) {
// read record header
if (m_inputPos < FCGI_HEADER_LEN) {
const qint64 length = m_device->read(m_inputBuffer + m_inputPos, FCGI_HEADER_LEN - m_inputPos);
if (length < 0) {
qWarning("Failed to read FastCGI record header from socket");
m_device->close();
emit closed();
return;
}
m_inputPos += length;
if (m_inputPos < FCGI_HEADER_LEN)
return;
}
// read record body
FCGI_Header *header = (FCGI_Header*)m_inputBuffer;
const quint16 contentLength = FCGI_Header_contentLength(header);
const quint16 bodyLength = contentLength + header->paddingLength;
const qint64 length = m_device->read(m_inputBuffer + m_inputPos, bodyLength + FCGI_HEADER_LEN - m_inputPos);
if (length < 0) {
qWarning("Failed to read FastCGI record body from socket");
m_device->close();
emit closed();
return;
}
m_inputPos += length;
if (m_inputPos < FCGI_HEADER_LEN + bodyLength)
return;
m_inputPos = 0;
// process record
#ifdef QDJANGO_DEBUG_FCGI
hDebug(header, "received");
#endif
if (header->version != 1) {
qWarning("Received FastCGI record with an invalid version %i", header->version);
m_device->close();
emit closed();
return;
}
const quint16 requestId = FCGI_Header_requestId(header);
if (header->type != FCGI_BEGIN_REQUEST && (!m_pendingRequest || requestId != m_pendingRequestId)) {
qWarning("Received FastCGI record for an invalid request %i", requestId);
m_device->close();
emit closed();
return;
}
quint8 *d = (quint8*)(m_inputBuffer + FCGI_HEADER_LEN);
switch (header->type) {
case FCGI_BEGIN_REQUEST: {
#ifdef QDJANGO_DEBUG_FCGI
const quint16 role = (d[0] << 8) | d[1];
qDebug("[BEGIN REQUEST]");
qDebug("role: %i", role);
qDebug("flags: %i", d[2]);
#endif
// we do not support multiplexing
if (m_pendingRequest) {
qWarning("Received new FastCGI request %i while already handling request %i", requestId, m_pendingRequestId);
m_device->close();
emit closed();
return;
}
m_pendingRequest = new QDjangoHttpRequest;
m_pendingRequestId = requestId;
break;
}
case FCGI_ABORT_REQUEST:
#ifdef QDJANGO_DEBUG_FCGI
qDebug("[ABORT]");
#endif
m_device->close();
emit closed();
return;
case FCGI_PARAMS:
#ifdef QDJANGO_DEBUG_FCGI
qDebug("[PARAMS]");
#endif
while (d < (quint8*)(m_inputBuffer + FCGI_HEADER_LEN + contentLength)) {
quint32 nameLength;
quint32 valueLength;
if (d[0] >> 7) {
nameLength = ((d[0] & 0x7f) << 24) | (d[1] << 16) | (d[2] << 8) | d[3];
d += 4;
} else {
nameLength = d[0];
d++;
}
if (d[0] >> 7) {
valueLength = ((d[0] & 0x7f) << 24) | (d[1] << 16) | (d[2] << 8) | d[3];
d += 4;
} else {
valueLength = d[0];
d++;
}
const QByteArray name((char*)d, nameLength);
d += nameLength;
const QByteArray value((char*)d, valueLength);
d += valueLength;
#ifdef QDJANGO_DEBUG_FCGI
qDebug() << name << ":" << value;
#endif
if (name == "PATH_INFO") {
m_pendingRequest->d->path = QString::fromUtf8(value);
} else if (name == "REQUEST_URI") {
m_pendingRequest->d->path = QUrl(QString::fromUtf8(value)).path();
} else if (name == "REQUEST_METHOD") {
m_pendingRequest->d->method = QString::fromUtf8(value);
}
m_pendingRequest->d->meta.insert(QString::fromLatin1(name), QString::fromUtf8(value));
}
break;
case FCGI_STDIN:
#ifdef QDJANGO_DEBUG_FCGI
qDebug("[STDIN]");
#endif
if (contentLength) {
m_pendingRequest->d->buffer.append((char*)d, contentLength);
} else {
// an empty STDIN record signals the end of the request
QDjangoHttpRequest *request = m_pendingRequest;
const quint16 requestId = m_pendingRequestId;
m_pendingRequest = 0;
m_pendingRequestId = 0;
QDjangoHttpResponse *response = m_server->urls()->respond(*request, request->path());
writeResponse(requestId, response);
}
break;
default:
qWarning("Received FastCGI record with an invalid type %i", header->type);
m_device->close();
emit closed();
return;
}
}
}
/// \endcond
class QDjangoFastCgiServerPrivate
{
public:
QDjangoFastCgiServerPrivate(QDjangoFastCgiServer *qq);
QLocalServer *localServer;
QTcpServer *tcpServer;
QDjangoUrlResolver *urlResolver;
private:
QDjangoFastCgiServer *q;
};
QDjangoFastCgiServerPrivate::QDjangoFastCgiServerPrivate(QDjangoFastCgiServer *qq)
: localServer(0),
tcpServer(0),
q(qq)
{
urlResolver = new QDjangoUrlResolver(q);
}
/** Constructs a new FastCGI server.
*/
QDjangoFastCgiServer::QDjangoFastCgiServer(QObject *parent)
: QObject(parent)
{
d = new QDjangoFastCgiServerPrivate(this);
}
/** Destroys the FastCGI server.
*/
QDjangoFastCgiServer::~QDjangoFastCgiServer()
{
delete d;
}
/** Closes the server. The server will no longer listen for
* incoming connections.
*/
void QDjangoFastCgiServer::close()
{
if (d->localServer)
d->localServer->close();
if (d->tcpServer)
d->tcpServer->close();
}
/** Tells the server to listen for incoming connections on the given
* local socket.
*/
bool QDjangoFastCgiServer::listen(const QString &name)
{
if (!d->localServer) {
bool check;
Q_UNUSED(check);
d->localServer = new QLocalServer(this);
check = connect(d->localServer, SIGNAL(newConnection()),
this, SLOT(_q_newLocalConnection()));
Q_ASSERT(check);
}
return d->localServer->listen(name);
}
/** Tells the server to listen for incoming TCP connections on the given
* \a address and \a port.
*/
bool QDjangoFastCgiServer::listen(const QHostAddress &address, quint16 port)
{
if (!d->tcpServer) {
bool check;
Q_UNUSED(check);
d->tcpServer = new QTcpServer(this);
check = connect(d->tcpServer, SIGNAL(newConnection()),
this, SLOT(_q_newTcpConnection()));
Q_ASSERT(check);
}
return d->tcpServer->listen(address, port);
}
/** Returns the root URL resolver for the server, which dispatches
* requests to handlers.
*/
QDjangoUrlResolver* QDjangoFastCgiServer::urls() const
{
return d->urlResolver;
}
void QDjangoFastCgiServer::_q_newLocalConnection()
{
bool check;
Q_UNUSED(check);
QLocalSocket *socket;
while ((socket = d->localServer->nextPendingConnection()) != 0) {
#ifdef QDJANGO_DEBUG_FCGI
qDebug("New local connection");
#endif
QDjangoFastCgiConnection *connection = new QDjangoFastCgiConnection(socket, this);
check = connect(connection, SIGNAL(closed()),
connection, SLOT(deleteLater()));
Q_ASSERT(check);
}
}
void QDjangoFastCgiServer::_q_newTcpConnection()
{
bool check;
Q_UNUSED(check);
QTcpSocket *socket;
while ((socket = d->tcpServer->nextPendingConnection()) != 0) {
#ifdef QDJANGO_DEBUG_FCGI
qDebug("New TCP connection");
#endif
QDjangoFastCgiConnection *connection = new QDjangoFastCgiConnection(socket, this);
check = connect(connection, SIGNAL(closed()),
connection, SLOT(deleteLater()));
Q_ASSERT(check);
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2010 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkJPEGWriteUtility.h"
///////////////////////////////////////////////////////////////////////////////
static void sk_init_destination(j_compress_ptr cinfo) {
skjpeg_destination_mgr* dest = (skjpeg_destination_mgr*)cinfo->dest;
dest->next_output_byte = dest->fBuffer;
dest->free_in_buffer = skjpeg_destination_mgr::kBufferSize;
}
static boolean sk_empty_output_buffer(j_compress_ptr cinfo) {
skjpeg_destination_mgr* dest = (skjpeg_destination_mgr*)cinfo->dest;
// if (!dest->fStream->write(dest->fBuffer, skjpeg_destination_mgr::kBufferSize - dest->free_in_buffer))
if (!dest->fStream->write(dest->fBuffer,
skjpeg_destination_mgr::kBufferSize)) {
ERREXIT(cinfo, JERR_FILE_WRITE);
return false;
}
dest->next_output_byte = dest->fBuffer;
dest->free_in_buffer = skjpeg_destination_mgr::kBufferSize;
return TRUE;
}
static void sk_term_destination (j_compress_ptr cinfo) {
skjpeg_destination_mgr* dest = (skjpeg_destination_mgr*)cinfo->dest;
size_t size = skjpeg_destination_mgr::kBufferSize - dest->free_in_buffer;
if (size > 0) {
if (!dest->fStream->write(dest->fBuffer, size)) {
ERREXIT(cinfo, JERR_FILE_WRITE);
return;
}
}
dest->fStream->flush();
}
skjpeg_destination_mgr::skjpeg_destination_mgr(SkWStream* stream)
: fStream(stream) {
this->init_destination = sk_init_destination;
this->empty_output_buffer = sk_empty_output_buffer;
this->term_destination = sk_term_destination;
}
void skjpeg_error_exit(j_common_ptr cinfo) {
skjpeg_error_mgr* error = (skjpeg_error_mgr*)cinfo->err;
(*error->output_message) (cinfo);
/* Let the memory manager delete any temp files before we die */
jpeg_destroy(cinfo);
if (error->fJmpBufStack.empty()) {
SK_ABORT("JPEG error with no jmp_buf set.");
}
longjmp(*error->fJmpBufStack.back(), -1);
}
<commit_msg>return proper false for jpeg<commit_after>/*
* Copyright 2010 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkJPEGWriteUtility.h"
///////////////////////////////////////////////////////////////////////////////
static void sk_init_destination(j_compress_ptr cinfo) {
skjpeg_destination_mgr* dest = (skjpeg_destination_mgr*)cinfo->dest;
dest->next_output_byte = dest->fBuffer;
dest->free_in_buffer = skjpeg_destination_mgr::kBufferSize;
}
static boolean sk_empty_output_buffer(j_compress_ptr cinfo) {
skjpeg_destination_mgr* dest = (skjpeg_destination_mgr*)cinfo->dest;
// if (!dest->fStream->write(dest->fBuffer, skjpeg_destination_mgr::kBufferSize - dest->free_in_buffer))
if (!dest->fStream->write(dest->fBuffer,
skjpeg_destination_mgr::kBufferSize)) {
ERREXIT(cinfo, JERR_FILE_WRITE);
return FALSE;
}
dest->next_output_byte = dest->fBuffer;
dest->free_in_buffer = skjpeg_destination_mgr::kBufferSize;
return TRUE;
}
static void sk_term_destination (j_compress_ptr cinfo) {
skjpeg_destination_mgr* dest = (skjpeg_destination_mgr*)cinfo->dest;
size_t size = skjpeg_destination_mgr::kBufferSize - dest->free_in_buffer;
if (size > 0) {
if (!dest->fStream->write(dest->fBuffer, size)) {
ERREXIT(cinfo, JERR_FILE_WRITE);
return;
}
}
dest->fStream->flush();
}
skjpeg_destination_mgr::skjpeg_destination_mgr(SkWStream* stream)
: fStream(stream) {
this->init_destination = sk_init_destination;
this->empty_output_buffer = sk_empty_output_buffer;
this->term_destination = sk_term_destination;
}
void skjpeg_error_exit(j_common_ptr cinfo) {
skjpeg_error_mgr* error = (skjpeg_error_mgr*)cinfo->err;
(*error->output_message) (cinfo);
/* Let the memory manager delete any temp files before we die */
jpeg_destroy(cinfo);
if (error->fJmpBufStack.empty()) {
SK_ABORT("JPEG error with no jmp_buf set.");
}
longjmp(*error->fJmpBufStack.back(), -1);
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2011, Paul Tagliamonte <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef _SHIBUYA_HH_
#define _SHIBUYA_HH_ FOO
/* Attr hooks
1 2 3 8 16 32 64 128
BKG BKG BKG BNK FGD FGD FGD BLD
\ \ \ \ \ \ \ \
\ \ \ \ \ \ \ +--- Bold
\ \ \ \ +---+---+------ Foreground
\ \ \ +----------------- Blink
+---+---+-------------------- Background
*/
#define SHIBUYA_ATTR_BOLD 128
#define SHIBUYA_ATTR_FG_MASK 0x70
#define SHIBUYA_ATTR_FG_OFFSET 4
#define SHIBUYA_ATTR_BG_MASK 0x07
#define SHIBUYA_ATTR_BG_OFFSET 0
#define SHIBUYA_ATTR_GET_FG(x) ((x & SHIBUYA_ATTR_FG_MASK) >> \
SHIBUYA_ATTR_FG_OFFSET)
#define SHIBUYA_ATTR_GET_BG(x) ((x & SHIBUYA_ATTR_BG_MASK) >> \
SHIBUYA_ATTR_BG_OFFSET)
#define SHIBUYA_ATTR_HAS_BOLD(x) (x & SHIBUYA_ATTR_BOLD)
#define SHIBUYA_ATTR_HAS_BLINK(x) (x & 8)
/* OK. Done with the bitwise */
#define String std::string
#define SDEBUG std::clog
void init_screen();
void set_clog();
void uninit_screen();
void update_screen();
#endif
<commit_msg>more bitwise stuff<commit_after>/*
* Copyright (C) 2011, Paul Tagliamonte <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef _SHIBUYA_HH_
#define _SHIBUYA_HH_ FOO
/* Attr hooks
1 2 3 8 16 32 64 128
BKG BKG BKG BNK FGD FGD FGD BLD
\ \ \ \ \ \ \ \
\ \ \ \ \ \ \ +--- Bold
\ \ \ \ +---+---+------ Foreground
\ \ \ +----------------- Blink
+---+---+-------------------- Background
*/
// Single bit defs
#define SHIBUYA_ATTR_BOLD 128
#define SHIBUYA_ATTR_BLINK 8
// Bit mask defs
#define SHIBUYA_ATTR_FG_MASK 0x70
#define SHIBUYA_ATTR_FG_OFFSET 4
#define SHIBUYA_ATTR_BG_MASK 0x07
#define SHIBUYA_ATTR_BG_OFFSET 0
// Access macro defs
#define SHIBUYA_ATTR_GET_FG(x) \
((x & SHIBUYA_ATTR_FG_MASK) >> SHIBUYA_ATTR_FG_OFFSET)
#define SHIBUYA_ATTR_GET_BG(x) \
((x & SHIBUYA_ATTR_BG_MASK) >> SHIBUYA_ATTR_BG_OFFSET)
#define SHIBUYA_ATTR_HAS_BOLD(x) (x & SHIBUYA_ATTR_BOLD)
#define SHIBUYA_ATTR_HAS_BLINK(x) (x & SHIBUYA_ATTR_BLINK)
/* OK. Done with the bitwise stuffs */
#define String std::string
#define SDEBUG std::clog
void init_screen();
void set_clog();
void uninit_screen();
void update_screen();
#endif
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2013-2018 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
#include <vector>
#include <string>
#include <map>
#include "module_traits.hpp"
#include "money.hpp"
#include "date.hpp"
#include "writer_fwd.hpp"
#include "filter_iterator.hpp"
namespace budget {
struct assets_module {
void load();
void unload();
void handle(const std::vector<std::string>& args);
};
template<>
struct module_traits<assets_module> {
static constexpr const bool is_default = false;
static constexpr const char* command = "asset";
};
// An asset class
struct asset_class {
size_t id;
std::string guid;
std::string name;
std::map<std::string, std::string> get_params();
};
// An asset
struct asset {
size_t id;
std::string guid;
std::string name;
std::string currency;
bool portfolio;
money portfolio_alloc;
bool share_based;
std::string ticker;
std::vector<std::pair<size_t, money>> classes;
// Legacy fields, to be removed
money int_stocks;
money dom_stocks;
money bonds;
money cash;
std::map<std::string, std::string> get_params();
money total_allocation() const {
return int_stocks + dom_stocks + bonds + cash;
}
bool is_cash() const {
return cash == budget::money(100);
}
};
// Used to set the value of the asset
struct asset_value {
size_t id;
std::string guid;
size_t asset_id;
budget::money amount;
budget::date set_date;
std::map<std::string, std::string> get_params();
};
// Used to indicate purchase of shares
struct asset_share {
size_t id;
std::string guid;
size_t asset_id;
int64_t shares; // The number of shares
budget::money price; // The purchase price
budget::date date; // The purchase date
std::map<std::string, std::string> get_params();
bool is_buy() const {
return shares >= 0;
}
bool is_sell() const {
return shares < 0;
}
};
std::ostream& operator<<(std::ostream& stream, const asset_class& c);
void operator>>(const std::vector<std::string>& parts, asset_class& c);
std::ostream& operator<<(std::ostream& stream, const asset& asset);
void operator>>(const std::vector<std::string>& parts, asset& asset);
std::ostream& operator<<(std::ostream& stream, const asset_value& asset);
void operator>>(const std::vector<std::string>& parts, asset_value& asset);
std::ostream& operator<<(std::ostream& stream, const asset_share& asset);
void operator>>(const std::vector<std::string>& parts, asset_share& asset);
void load_assets();
void save_assets();
void migrate_assets_4_to_5();
void migrate_assets_5_to_6();
void show_assets(budget::writer& w);
void list_asset_values(budget::writer& w);
void small_show_asset_values(budget::writer& w);
void show_asset_values(budget::writer& w);
void show_asset_portfolio(budget::writer& w);
void show_asset_rebalance(budget::writer& w, bool nocash = false);
void list_asset_shares(budget::writer& w);
bool asset_class_exists(const std::string& name);
bool asset_exists(const std::string& asset);
bool share_asset_exists(const std::string& asset);
budget::asset_class& get_asset_class(size_t id);
budget::asset_class& get_asset_class(const std::string & name);
budget::asset& get_asset(size_t id);
budget::asset& get_asset(std::string name);
budget::asset_value& get_asset_value(size_t id);
budget::asset_share& get_asset_share(size_t id);
budget::asset& get_desired_allocation();
std::vector<budget::asset_class>& all_asset_classes();
std::vector<budget::asset>& all_assets();
std::vector<budget::asset_value>& all_asset_values();
std::vector<budget::asset_share>& all_asset_shares();
budget::date asset_start_date();
budget::date asset_start_date(const asset& asset);
void set_asset_class_next_id(size_t next_id);
void set_assets_next_id(size_t next_id);
void set_asset_values_next_id(size_t next_id);
void set_asset_shares_next_id(size_t next_id);
void set_asset_classes_changed();
void set_assets_changed();
void set_asset_values_changed();
void set_asset_shares_changed();
std::string get_default_currency();
void add_asset_class(asset_class&& c);
bool asset_class_exists(size_t id);
void asset_class_delete(size_t id);
asset_class& asset_class_get(size_t id);
void add_asset(asset&& asset);
bool asset_exists(size_t id);
void asset_delete(size_t id);
asset& asset_get(size_t id);
void add_asset_value(asset_value&& asset_value);
bool asset_value_exists(size_t id);
void asset_value_delete(size_t id);
asset_value& asset_value_get(size_t id);
void add_asset_share(asset_share&& asset_share);
bool asset_share_exists(size_t id);
void asset_share_delete(size_t id);
asset_share& asset_share_get(size_t id);
budget::money get_portfolio_value();
budget::money get_net_worth();
budget::money get_net_worth_cash();
budget::money get_net_worth(budget::date d);
// The value of an assert in its own currency
budget::money get_asset_value(budget::asset & asset);
budget::money get_asset_value(budget::asset & asset, budget::date d);
// The value of an assert in the default currency
budget::money get_asset_value_conv(budget::asset & asset);
budget::money get_asset_value_conv(budget::asset & asset, budget::date d);
// The value of an assert in a specific currency
budget::money get_asset_value_conv(budget::asset & asset, const std::string& currency);
budget::money get_asset_value_conv(budget::asset & asset, budget::date d, const std::string& currency);
// Filter functions
inline auto all_user_assets() {
return make_filter_view(begin(all_assets()), end(all_assets()), [=](const asset& a) {
return a.name != "DESIRED";
});
}
} //end of namespace budget
<commit_msg>Update total_allocation<commit_after>//=======================================================================
// Copyright (c) 2013-2018 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
#include <vector>
#include <string>
#include <map>
#include "module_traits.hpp"
#include "money.hpp"
#include "date.hpp"
#include "writer_fwd.hpp"
#include "filter_iterator.hpp"
namespace budget {
struct assets_module {
void load();
void unload();
void handle(const std::vector<std::string>& args);
};
template<>
struct module_traits<assets_module> {
static constexpr const bool is_default = false;
static constexpr const char* command = "asset";
};
// An asset class
struct asset_class {
size_t id;
std::string guid;
std::string name;
std::map<std::string, std::string> get_params();
};
// An asset
struct asset {
size_t id;
std::string guid;
std::string name;
std::string currency;
bool portfolio;
money portfolio_alloc;
bool share_based;
std::string ticker;
std::vector<std::pair<size_t, money>> classes;
// Legacy fields, to be removed
money int_stocks;
money dom_stocks;
money bonds;
money cash;
std::map<std::string, std::string> get_params();
money total_allocation() const {
money total;
for (auto& clas : classes) {
total += clas.second;
}
return total;
}
bool is_cash() const {
return cash == budget::money(100);
}
};
// Used to set the value of the asset
struct asset_value {
size_t id;
std::string guid;
size_t asset_id;
budget::money amount;
budget::date set_date;
std::map<std::string, std::string> get_params();
};
// Used to indicate purchase of shares
struct asset_share {
size_t id;
std::string guid;
size_t asset_id;
int64_t shares; // The number of shares
budget::money price; // The purchase price
budget::date date; // The purchase date
std::map<std::string, std::string> get_params();
bool is_buy() const {
return shares >= 0;
}
bool is_sell() const {
return shares < 0;
}
};
std::ostream& operator<<(std::ostream& stream, const asset_class& c);
void operator>>(const std::vector<std::string>& parts, asset_class& c);
std::ostream& operator<<(std::ostream& stream, const asset& asset);
void operator>>(const std::vector<std::string>& parts, asset& asset);
std::ostream& operator<<(std::ostream& stream, const asset_value& asset);
void operator>>(const std::vector<std::string>& parts, asset_value& asset);
std::ostream& operator<<(std::ostream& stream, const asset_share& asset);
void operator>>(const std::vector<std::string>& parts, asset_share& asset);
void load_assets();
void save_assets();
void migrate_assets_4_to_5();
void migrate_assets_5_to_6();
void show_assets(budget::writer& w);
void list_asset_values(budget::writer& w);
void small_show_asset_values(budget::writer& w);
void show_asset_values(budget::writer& w);
void show_asset_portfolio(budget::writer& w);
void show_asset_rebalance(budget::writer& w, bool nocash = false);
void list_asset_shares(budget::writer& w);
bool asset_class_exists(const std::string& name);
bool asset_exists(const std::string& asset);
bool share_asset_exists(const std::string& asset);
budget::asset_class& get_asset_class(size_t id);
budget::asset_class& get_asset_class(const std::string & name);
budget::asset& get_asset(size_t id);
budget::asset& get_asset(std::string name);
budget::asset_value& get_asset_value(size_t id);
budget::asset_share& get_asset_share(size_t id);
budget::asset& get_desired_allocation();
std::vector<budget::asset_class>& all_asset_classes();
std::vector<budget::asset>& all_assets();
std::vector<budget::asset_value>& all_asset_values();
std::vector<budget::asset_share>& all_asset_shares();
budget::date asset_start_date();
budget::date asset_start_date(const asset& asset);
void set_asset_class_next_id(size_t next_id);
void set_assets_next_id(size_t next_id);
void set_asset_values_next_id(size_t next_id);
void set_asset_shares_next_id(size_t next_id);
void set_asset_classes_changed();
void set_assets_changed();
void set_asset_values_changed();
void set_asset_shares_changed();
std::string get_default_currency();
void add_asset_class(asset_class&& c);
bool asset_class_exists(size_t id);
void asset_class_delete(size_t id);
asset_class& asset_class_get(size_t id);
void add_asset(asset&& asset);
bool asset_exists(size_t id);
void asset_delete(size_t id);
asset& asset_get(size_t id);
void add_asset_value(asset_value&& asset_value);
bool asset_value_exists(size_t id);
void asset_value_delete(size_t id);
asset_value& asset_value_get(size_t id);
void add_asset_share(asset_share&& asset_share);
bool asset_share_exists(size_t id);
void asset_share_delete(size_t id);
asset_share& asset_share_get(size_t id);
budget::money get_portfolio_value();
budget::money get_net_worth();
budget::money get_net_worth_cash();
budget::money get_net_worth(budget::date d);
// The value of an assert in its own currency
budget::money get_asset_value(budget::asset & asset);
budget::money get_asset_value(budget::asset & asset, budget::date d);
// The value of an assert in the default currency
budget::money get_asset_value_conv(budget::asset & asset);
budget::money get_asset_value_conv(budget::asset & asset, budget::date d);
// The value of an assert in a specific currency
budget::money get_asset_value_conv(budget::asset & asset, const std::string& currency);
budget::money get_asset_value_conv(budget::asset & asset, budget::date d, const std::string& currency);
// Filter functions
inline auto all_user_assets() {
return make_filter_view(begin(all_assets()), end(all_assets()), [=](const asset& a) {
return a.name != "DESIRED";
});
}
} //end of namespace budget
<|endoftext|> |
<commit_before>#include <osg/Notify>
#include <osg/Geometry>
#include <osg/AnimationPath>
#include <osgDB/Registry>
#include <osgDB/Input>
#include <osgDB/Output>
using namespace osg;
using namespace osgDB;
// forward declare functions to use later.
bool AnimationPath_readLocalData(osg::Object &obj, osgDB::Input &fr);
bool AnimationPath_writeLocalData(const osg::Object &obj, osgDB::Output &fw);
// register the read and write functions with the osgDB::Registry.
osgDB::RegisterDotOsgWrapperProxy AnimationPath_Proxy
(
new osg::AnimationPath,
"AnimationPath",
"Object AnimationPath",
AnimationPath_readLocalData,
AnimationPath_writeLocalData,
DotOsgWrapper::READ_AND_WRITE
);
bool AnimationPath_readLocalData(osg::Object &obj, osgDB::Input &fr)
{
osg::AnimationPath *ap = dynamic_cast<osg::AnimationPath*>(&obj);
if (!ap) return false;
bool itAdvanced = false;
if (fr[0].matchWord("LoopMode"))
{
if (fr[1].matchWord("SWING"))
{
ap->setLoopMode(AnimationPath::SWING);
fr += 2;
itAdvanced = true;
}
else if (fr[1].matchWord("LOOP"))
{
ap->setLoopMode(AnimationPath::LOOP);
fr += 2;
itAdvanced = true;
}
else if (fr[1].matchWord("NO_LOOPING"))
{
ap->setLoopMode(AnimationPath::NO_LOOPING);
fr += 2;
itAdvanced = true;
}
}
if (fr.matchSequence("ControlPoints {"))
{
int entry = fr[0].getNoNestedBrackets();
fr += 2;
float time;
Vec3 position,scale;
Quat rotation;
while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)
{
if (fr[0].getFloat(time) &&
fr[1].getFloat(position[0]) &&
fr[2].getFloat(position[1]) &&
fr[3].getFloat(position[2]) &&
fr[4].getFloat(rotation[0]) &&
fr[5].getFloat(rotation[1]) &&
fr[6].getFloat(rotation[2]) &&
fr[7].getFloat(rotation[3]) &&
fr[8].getFloat(scale[0]) &&
fr[9].getFloat(scale[1]) &&
fr[10].getFloat(scale[2]))
{
osg::AnimationPath::ControlPoint ctrlPoint;
ctrlPoint._position = position;
ctrlPoint._rotation = rotation;
ctrlPoint._scale = scale;
ap->insert(time, ctrlPoint);
fr+=11;
}
else fr.advanceOverCurrentFieldOrBlock();
}
itAdvanced = true;
}
return itAdvanced;
}
bool AnimationPath_writeLocalData(const osg::Object &obj, osgDB::Output &fw)
{
const osg::AnimationPath* ap = dynamic_cast<const osg::AnimationPath*>(&obj);
if (!ap) return false;
fw.indent() << "LoopMode ";
switch(ap->getLoopMode())
{
case AnimationPath::SWING:
fw << "SWING" <<std::endl;
break;
case AnimationPath::LOOP:
fw << "LOOP"<<std::endl;
break;
case AnimationPath::NO_LOOPING:
fw << "NO_LOOPING"<<std::endl;
break;
}
const AnimationPath::TimeControlPointMap& tcpm = ap->getTimeControlPointMap();
fw.indent() << "ControlPoints {"<< std::endl;
fw.moveIn();
for (AnimationPath::TimeControlPointMap::const_iterator itr=tcpm.begin();
itr!=tcpm.end();
++itr)
{
fw.indent() << itr->first << " " << itr->second._position << " " << itr->second._rotation << " " << itr->second._scale << std::endl;
}
fw.moveOut();
fw.indent() << "}"<< std::endl;
return true;
}
// forward declare functions to use later.
bool AnimationPathCallback_readLocalData(osg::Object &obj, osgDB::Input &fr);
bool AnimationPathCallback_writeLocalData(const osg::Object &obj, osgDB::Output &fw);
// register the read and write functions with the osgDB::Registry.
osgDB::RegisterDotOsgWrapperProxy AnimationPathCallback_Proxy
(
new osg::AnimationPathCallback,
"AnimationPathCallback",
"Object AnimationPathCallback",
AnimationPathCallback_readLocalData,
AnimationPathCallback_writeLocalData,
DotOsgWrapper::READ_AND_WRITE
);
bool AnimationPathCallback_readLocalData(osg::Object &obj, osgDB::Input &fr)
{
osg::AnimationPathCallback *apc = dynamic_cast<osg::AnimationPathCallback*>(&obj);
if (!apc) return false;
bool iteratorAdvanced = false;
if (fr.matchSequence("pivotPoint %f %f %f"))
{
osg::Vec3 pivot;
fr[1].getFloat(pivot[0]);
fr[2].getFloat(pivot[1]);
fr[3].getFloat(pivot[2]);
apc->setPivotPoint(pivot);
fr += 4;
iteratorAdvanced = true;
}
if (fr.matchSequence("timeOffset %f"))
{
fr[1].getFloat(apc->_timeOffset);
fr+=2;
iteratorAdvanced = true;
}
else if(fr.matchSequence("timeMultiplier %f"))
{
fr[1].getFloat(apc->_timeMultiplier);
fr+=2;
iteratorAdvanced = true;
}
static osg::ref_ptr<osg::AnimationPath> s_path = new osg::AnimationPath;
ref_ptr<osg::Object> object = fr.readObjectOfType(*s_path);
if (object.valid())
{
osg::AnimationPath* animpath = dynamic_cast<osg::AnimationPath*>(object.get());
if (animpath) apc->setAnimationPath(animpath);
iteratorAdvanced = true;
}
return iteratorAdvanced;
}
bool AnimationPathCallback_writeLocalData(const osg::Object &obj, osgDB::Output &fw)
{
const osg::AnimationPathCallback* apc = dynamic_cast<const osg::AnimationPathCallback*>(&obj);
if (!apc) return false;
fw.indent() <<"pivotPoint " <<apc->getPivotPoint()<<std::endl;
fw.indent() <<"timeOffset " <<apc->_timeOffset<<std::endl;
fw.indent() <<"timeMultiplier " <<apc->_timeMultiplier << std::endl;
if (apc->getAnimationPath())
{
fw.writeObject(*(apc->getAnimationPath()));
}
return true;
}
<commit_msg>Improved precision of AnimationPath IO.<commit_after>#include <osg/Notify>
#include <osg/Geometry>
#include <osg/AnimationPath>
#include <osgDB/Registry>
#include <osgDB/Input>
#include <osgDB/Output>
using namespace osg;
using namespace osgDB;
// forward declare functions to use later.
bool AnimationPath_readLocalData(osg::Object &obj, osgDB::Input &fr);
bool AnimationPath_writeLocalData(const osg::Object &obj, osgDB::Output &fw);
// register the read and write functions with the osgDB::Registry.
osgDB::RegisterDotOsgWrapperProxy AnimationPath_Proxy
(
new osg::AnimationPath,
"AnimationPath",
"Object AnimationPath",
AnimationPath_readLocalData,
AnimationPath_writeLocalData,
DotOsgWrapper::READ_AND_WRITE
);
bool AnimationPath_readLocalData(osg::Object &obj, osgDB::Input &fr)
{
osg::AnimationPath *ap = dynamic_cast<osg::AnimationPath*>(&obj);
if (!ap) return false;
bool itAdvanced = false;
if (fr[0].matchWord("LoopMode"))
{
if (fr[1].matchWord("SWING"))
{
ap->setLoopMode(AnimationPath::SWING);
fr += 2;
itAdvanced = true;
}
else if (fr[1].matchWord("LOOP"))
{
ap->setLoopMode(AnimationPath::LOOP);
fr += 2;
itAdvanced = true;
}
else if (fr[1].matchWord("NO_LOOPING"))
{
ap->setLoopMode(AnimationPath::NO_LOOPING);
fr += 2;
itAdvanced = true;
}
}
if (fr.matchSequence("ControlPoints {"))
{
int entry = fr[0].getNoNestedBrackets();
fr += 2;
double time;
Vec3d position,scale;
Quat rotation;
while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)
{
if (fr[0].getFloat(time) &&
fr[1].getFloat(position[0]) &&
fr[2].getFloat(position[1]) &&
fr[3].getFloat(position[2]) &&
fr[4].getFloat(rotation[0]) &&
fr[5].getFloat(rotation[1]) &&
fr[6].getFloat(rotation[2]) &&
fr[7].getFloat(rotation[3]) &&
fr[8].getFloat(scale[0]) &&
fr[9].getFloat(scale[1]) &&
fr[10].getFloat(scale[2]))
{
osg::AnimationPath::ControlPoint ctrlPoint;
ctrlPoint._position = position;
ctrlPoint._rotation = rotation;
ctrlPoint._scale = scale;
ap->insert(time, ctrlPoint);
fr+=11;
}
else fr.advanceOverCurrentFieldOrBlock();
}
itAdvanced = true;
}
return itAdvanced;
}
bool AnimationPath_writeLocalData(const osg::Object &obj, osgDB::Output &fw)
{
const osg::AnimationPath* ap = dynamic_cast<const osg::AnimationPath*>(&obj);
if (!ap) return false;
fw.indent() << "LoopMode ";
switch(ap->getLoopMode())
{
case AnimationPath::SWING:
fw << "SWING" <<std::endl;
break;
case AnimationPath::LOOP:
fw << "LOOP"<<std::endl;
break;
case AnimationPath::NO_LOOPING:
fw << "NO_LOOPING"<<std::endl;
break;
}
const AnimationPath::TimeControlPointMap& tcpm = ap->getTimeControlPointMap();
fw.indent() << "ControlPoints {"<< std::endl;
fw.moveIn();
int prec = fw.precision();
fw.precision(15);
for (AnimationPath::TimeControlPointMap::const_iterator itr=tcpm.begin();
itr!=tcpm.end();
++itr)
{
fw.indent() << itr->first << " " << itr->second._position << " " << itr->second._rotation << " " << itr->second._scale << std::endl;
}
fw.precision(prec);
fw.moveOut();
fw.indent() << "}"<< std::endl;
return true;
}
// forward declare functions to use later.
bool AnimationPathCallback_readLocalData(osg::Object &obj, osgDB::Input &fr);
bool AnimationPathCallback_writeLocalData(const osg::Object &obj, osgDB::Output &fw);
// register the read and write functions with the osgDB::Registry.
osgDB::RegisterDotOsgWrapperProxy AnimationPathCallback_Proxy
(
new osg::AnimationPathCallback,
"AnimationPathCallback",
"Object AnimationPathCallback",
AnimationPathCallback_readLocalData,
AnimationPathCallback_writeLocalData,
DotOsgWrapper::READ_AND_WRITE
);
bool AnimationPathCallback_readLocalData(osg::Object &obj, osgDB::Input &fr)
{
osg::AnimationPathCallback *apc = dynamic_cast<osg::AnimationPathCallback*>(&obj);
if (!apc) return false;
bool iteratorAdvanced = false;
if (fr.matchSequence("pivotPoint %f %f %f"))
{
osg::Vec3 pivot;
fr[1].getFloat(pivot[0]);
fr[2].getFloat(pivot[1]);
fr[3].getFloat(pivot[2]);
apc->setPivotPoint(pivot);
fr += 4;
iteratorAdvanced = true;
}
if (fr.matchSequence("timeOffset %f"))
{
fr[1].getFloat(apc->_timeOffset);
fr+=2;
iteratorAdvanced = true;
}
else if(fr.matchSequence("timeMultiplier %f"))
{
fr[1].getFloat(apc->_timeMultiplier);
fr+=2;
iteratorAdvanced = true;
}
static osg::ref_ptr<osg::AnimationPath> s_path = new osg::AnimationPath;
ref_ptr<osg::Object> object = fr.readObjectOfType(*s_path);
if (object.valid())
{
osg::AnimationPath* animpath = dynamic_cast<osg::AnimationPath*>(object.get());
if (animpath) apc->setAnimationPath(animpath);
iteratorAdvanced = true;
}
return iteratorAdvanced;
}
bool AnimationPathCallback_writeLocalData(const osg::Object &obj, osgDB::Output &fw)
{
const osg::AnimationPathCallback* apc = dynamic_cast<const osg::AnimationPathCallback*>(&obj);
if (!apc) return false;
fw.indent() <<"pivotPoint " <<apc->getPivotPoint()<<std::endl;
fw.indent() <<"timeOffset " <<apc->_timeOffset<<std::endl;
fw.indent() <<"timeMultiplier " <<apc->_timeMultiplier << std::endl;
if (apc->getAnimationPath())
{
fw.writeObject(*(apc->getAnimationPath()));
}
return true;
}
<|endoftext|> |
<commit_before>// Copyright (C) 2012 JINMEI Tatuya
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
#include <query_context.h>
#include <query_repository.h>
#include <dispatcher.h>
#include <message_manager.h>
#include <asio_message_manager.h>
#include <util/buffer.h>
#include <exceptions/exceptions.h>
#include <dns/message.h>
#include <dns/rrclass.h>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/foreach.hpp>
#include <algorithm>
#include <istream>
#include <cassert>
#include <list>
#include <netinet/in.h>
using namespace std;
using namespace isc::util;
using namespace isc::dns;
using namespace Queryperf;
using boost::scoped_ptr;
using boost::shared_ptr;
using namespace boost::posix_time;
using boost::posix_time::seconds;
namespace {
class QueryEvent {
typedef boost::function<void(qid_t, const Message*)> RestartCallback;
public:
QueryEvent(MessageManager& mgr, qid_t qid, QueryContext* ctx,
RestartCallback restart_callback) :
ctx_(ctx), qid_(qid), restart_callback_(restart_callback),
timer_(mgr.createMessageTimer(
boost::bind(&QueryEvent::queryTimerCallback, this))),
tcp_sock_(NULL), tcp_rcvbuf_(NULL)
{}
~QueryEvent() {
delete tcp_sock_;
delete ctx_;
delete[] tcp_rcvbuf_;
}
QueryContext::QuerySpec start(qid_t qid, const time_duration& timeout) {
assert(ctx_ != NULL);
qid_ = qid;
timer_->start(timeout);
return (ctx_->start(qid_));
}
void* getTCPBuf() {
if (tcp_rcvbuf_ == NULL) {
tcp_rcvbuf_ = new uint8_t[TCP_RCVBUF_LEN];
}
return (tcp_rcvbuf_);
}
size_t getTCPBufLen() {
return (TCP_RCVBUF_LEN);
}
qid_t getQid() const { return (qid_); }
bool matchResponse(qid_t qid) const { return (qid_ == qid); }
void setTCPSocket(MessageSocket* tcp_sock) {
assert(tcp_sock_ == NULL);
tcp_sock_ = tcp_sock;
}
void clearTCPSocket() {
assert(tcp_sock_ != NULL);
delete tcp_sock_;
tcp_sock_ = NULL;
}
private:
void queryTimerCallback() {
cout << "[Timeout] Query timed out: msg id: " << qid_ << endl;
if (tcp_sock_ != NULL) {
clearTCPSocket();
}
restart_callback_(qid_, NULL);
}
QueryContext* ctx_;
qid_t qid_;
RestartCallback restart_callback_;
shared_ptr<MessageTimer> timer_;
MessageSocket* tcp_sock_;
static const size_t TCP_RCVBUF_LEN = 65535;
uint8_t* tcp_rcvbuf_; // lazily allocated
};
typedef shared_ptr<QueryEvent> QueryEventPtr;
} // unnamed namespace
namespace Queryperf {
struct Dispatcher::DispatcherImpl {
DispatcherImpl(MessageManager& msg_mgr,
QueryContextCreator& ctx_creator) :
msg_mgr_(&msg_mgr), qryctx_creator_(&ctx_creator),
response_(Message::PARSE)
{
initParams();
}
DispatcherImpl(const string& data_file) :
qry_repo_local_(new QueryRepository(data_file)),
msg_mgr_local_(new ASIOMessageManager),
qryctx_creator_local_(new QueryContextCreator(*qry_repo_local_)),
msg_mgr_(msg_mgr_local_.get()),
qryctx_creator_(qryctx_creator_local_.get()),
response_(Message::PARSE)
{
initParams();
}
DispatcherImpl(istream& input_stream) :
qry_repo_local_(new QueryRepository(input_stream)),
msg_mgr_local_(new ASIOMessageManager),
qryctx_creator_local_(new QueryContextCreator(*qry_repo_local_)),
msg_mgr_(msg_mgr_local_.get()),
qryctx_creator_(qryctx_creator_local_.get()),
response_(Message::PARSE)
{
initParams();
}
void initParams() {
keep_sending_ = true;
window_ = DEFAULT_WINDOW;
qid_ = 0;
queries_sent_ = 0;
queries_completed_ = 0;
server_address_ = DEFAULT_SERVER;
server_port_ = DEFAULT_PORT;
test_duration_ = DEFAULT_DURATION;
query_timeout_ = seconds(DEFAULT_QUERY_TIMEOUT);
}
void run();
// Callback from the message manager called when a response to a query is
// delivered.
void responseCallback(const MessageSocket::Event& sockev);
void responseTCPCallback(const MessageSocket::Event& sockev,
QueryEvent* qev);
// Generate next query either due to completion or timeout.
void restartQuery(qid_t qid, const Message* response);
// A subroutine commonly used to send a single query.
void sendQuery(QueryEvent& qev, const QueryContext::QuerySpec& qry_spec) {
if (qry_spec.proto == IPPROTO_UDP) {
udp_socket_->send(qry_spec.data, qry_spec.len);
} else {
MessageSocket* tcp_sock =
msg_mgr_->createMessageSocket(
IPPROTO_TCP, server_address_, server_port_,
qev.getTCPBuf(), qev.getTCPBufLen(),
boost::bind(&DispatcherImpl::responseTCPCallback, this,
_1, &qev));
qev.setTCPSocket(tcp_sock);
tcp_sock->send(qry_spec.data, qry_spec.len);
}
++queries_sent_;
++qid_;
}
// Callback from the message manager on expiration of the session timer.
// Stop sending more queries; only wait for outstanding ones.
void sessionTimerCallback() {
keep_sending_ = false;
}
// These are placeholders for the support class objects when they are
// built within the context.
scoped_ptr<QueryRepository> qry_repo_local_;
scoped_ptr<ASIOMessageManager> msg_mgr_local_;
scoped_ptr<QueryContextCreator> qryctx_creator_local_;
// These are pointers to the objects actually used in the object
MessageManager* msg_mgr_;
QueryContextCreator* qryctx_creator_;
// Note that these should be placed after msg_mgr_local_; in the destructor
// these should be released first.
scoped_ptr<MessageSocket> udp_socket_;
scoped_ptr<MessageTimer> session_timer_;
uint8_t udp_recvbuf_[4096];
// Configurable parameters
string server_address_;
uint16_t server_port_;
size_t test_duration_;
time_duration query_timeout_;
bool keep_sending_; // whether to send next query on getting a response
size_t window_;
qid_t qid_;
Message response_; // placeholder for response messages
list<shared_ptr<QueryEvent> > outstanding_;
// statistics
size_t queries_sent_;
size_t queries_completed_;
ptime start_time_;
ptime end_time_;
};
void
Dispatcher::DispatcherImpl::run() {
// Allocate resources used throughout the test session:
// common UDP socket and the whole session timer.
udp_socket_.reset(msg_mgr_->createMessageSocket(
IPPROTO_UDP, server_address_, server_port_,
udp_recvbuf_, sizeof(udp_recvbuf_),
boost::bind(&DispatcherImpl::responseCallback,
this, _1)));
session_timer_.reset(msg_mgr_->createMessageTimer(
boost::bind(&DispatcherImpl::sessionTimerCallback,
this)));
// Start the session timer.
session_timer_->start(seconds(test_duration_));
// Create a pool of query contexts. Setting QID to 0 for now.
for (size_t i = 0; i < window_; ++i) {
QueryEventPtr qev(new QueryEvent(
*msg_mgr_, 0, qryctx_creator_->create(),
boost::bind(&DispatcherImpl::restartQuery,
this, _1, _2)));
outstanding_.push_back(qev);
}
// Record the start time and dispatch initial queries at once.
start_time_ = microsec_clock::local_time();
BOOST_FOREACH(shared_ptr<QueryEvent>& qev, outstanding_) {
sendQuery(*qev, qev->start(qid_, query_timeout_));
}
// Enter the event loop.
msg_mgr_->run();
}
void
Dispatcher::DispatcherImpl::responseCallback(
const MessageSocket::Event& sockev)
{
// Parse the header of the response
InputBuffer buffer(sockev.data, sockev.datalen);
response_.clear(Message::PARSE);
response_.parseHeader(buffer);
// TODO: catch exception due to bogus response
restartQuery(response_.getQid(), &response_);
}
void
Dispatcher::DispatcherImpl::responseTCPCallback(
const MessageSocket::Event& sockev, QueryEvent* qev)
{
qev->clearTCPSocket();
if (sockev.datalen > 0) {
// Parse the header of the response
InputBuffer buffer(sockev.data, sockev.datalen);
response_.clear(Message::PARSE);
response_.parseHeader(buffer);
} else {
cout << "[Fail] TCP connection terminated unexpectedly" << endl;
}
restartQuery(qev->getQid(), sockev.datalen > 0 ? &response_ : NULL);
}
void
Dispatcher::DispatcherImpl::restartQuery(qid_t qid, const Message* response) {
// Identify the matching query from the outstanding queue.
const list<shared_ptr<QueryEvent> >::iterator qev_it =
find_if(outstanding_.begin(), outstanding_.end(),
boost::bind(&QueryEvent::matchResponse, _1, qid));
if (qev_it != outstanding_.end()) {
if (response != NULL) {
// TODO: let the context check the response further
++queries_completed_;
}
// If necessary, create a new query and dispatch it.
if (keep_sending_) {
sendQuery(**qev_it, (*qev_it)->start(qid_, query_timeout_));
// Move this context to the end of the queue.
outstanding_.splice(qev_it, outstanding_, outstanding_.end());
} else {
outstanding_.erase(qev_it);
if (outstanding_.empty()) {
msg_mgr_->stop();
}
}
} else {
// TODO: record the mismatched response
}
}
Dispatcher::Dispatcher(MessageManager& msg_mgr,
QueryContextCreator& ctx_creator) :
impl_(new DispatcherImpl(msg_mgr, ctx_creator))
{
}
const char* const Dispatcher::DEFAULT_SERVER = "::1";
Dispatcher::Dispatcher(const string& data_file) {
if (data_file == "-") {
impl_ = new DispatcherImpl(cin);
} else {
impl_ = new DispatcherImpl(data_file);
}
}
Dispatcher::Dispatcher(istream& input_stream) :
impl_(new DispatcherImpl(input_stream))
{
}
Dispatcher::~Dispatcher() {
delete impl_;
}
void
Dispatcher::loadQueries() {
// Query preload must be done before running tests.
if (!impl_->start_time_.is_special()) {
throw DispatcherError("query load attempt after run");
}
// Preload can be used (via the dispatcher) only for the internal
// repository.
if (!impl_->qry_repo_local_) {
throw DispatcherError("query load attempt for external repository");
}
impl_->qry_repo_local_->load();
}
void
Dispatcher::setDefaultQueryClass(const std::string& qclass_txt) {
// default qclass must be set before running tests.
if (!impl_->start_time_.is_special()) {
throw DispatcherError("default query class is being set after run");
}
// qclass can be used (via the dispatcher) only for the internal
// repository.
if (!impl_->qry_repo_local_) {
throw DispatcherError("default query class is being set "
"for external repository");
}
try {
impl_->qry_repo_local_->setQueryClass(RRClass(qclass_txt));
} catch (const isc::Exception&) {
throw DispatcherError("invalid query class: " + qclass_txt);
}
}
void
Dispatcher::setDNSSEC(bool on) {
// This must be set before running tests.
if (!impl_->start_time_.is_special()) {
throw DispatcherError("DNSSEC DO bit is being set/reset after run");
}
// DNSSEC bit can be set (via the dispatcher) only for the internal
// repository.
if (!impl_->qry_repo_local_) {
throw DispatcherError("DNSSEC DO bit is being set/reset "
"for external repository");
}
impl_->qry_repo_local_->setDNSSEC(on);
}
void
Dispatcher::setEDNS(bool on) {
// This must be set before running tests.
if (!impl_->start_time_.is_special()) {
throw DispatcherError("EDNS flag is being set/reset after run");
}
// EDNS flag can be set (via the dispatcher) only for the internal
// repository.
if (!impl_->qry_repo_local_) {
throw DispatcherError("EDNS flag bit is being set/reset "
"for external repository");
}
impl_->qry_repo_local_->setEDNS(on);
}
void
Dispatcher::run() {
assert(impl_->udp_socket_ == NULL);
impl_->run();
impl_->end_time_ = microsec_clock::local_time();
}
string
Dispatcher::getServerAddress() const {
return (impl_->server_address_);
}
void
Dispatcher::setServerAddress(const string& address) {
if (!impl_->start_time_.is_special()) {
throw DispatcherError("server address cannot be reset after run()");
}
impl_->server_address_ = address;
}
uint16_t
Dispatcher::getServerPort() const {
return (impl_->server_port_);
}
void
Dispatcher::setServerPort(uint16_t port) {
if (!impl_->start_time_.is_special()) {
throw DispatcherError("server port cannot be reset after run()");
}
impl_->server_port_ = port;
}
void
Dispatcher::setProtocol(int proto) {
// This must be set before running tests.
if (!impl_->start_time_.is_special()) {
throw DispatcherError("Default transport protocol cannot be set "
"after run()");
}
// Default transport protocol can be set (via the dispatcher) only for
// the internal repository.
if (!impl_->qry_repo_local_) {
throw DispatcherError("Default transport protocol cannot be set "
"for external repository");
}
impl_->qry_repo_local_->setProtocol(proto);
}
size_t
Dispatcher::getTestDuration() const {
return (impl_->test_duration_);
}
void
Dispatcher::setTestDuration(size_t duration) {
if (!impl_->start_time_.is_special()) {
throw DispatcherError("test duration cannot be reset after run()");
}
impl_->test_duration_ = duration;
}
size_t
Dispatcher::getQueriesSent() const {
return (impl_->queries_sent_);
}
size_t
Dispatcher::getQueriesCompleted() const {
return (impl_->queries_completed_);
}
const ptime&
Dispatcher::getStartTime() const {
return (impl_->start_time_);
}
const ptime&
Dispatcher::getEndTime() const {
return (impl_->end_time_);
}
} // end of QueryPerf
<commit_msg>fully qualify shared_ptr as it can conflict with the C++11 definition.<commit_after>// Copyright (C) 2012 JINMEI Tatuya
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
#include <query_context.h>
#include <query_repository.h>
#include <dispatcher.h>
#include <message_manager.h>
#include <asio_message_manager.h>
#include <util/buffer.h>
#include <exceptions/exceptions.h>
#include <dns/message.h>
#include <dns/rrclass.h>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/foreach.hpp>
#include <algorithm>
#include <istream>
#include <cassert>
#include <list>
#include <netinet/in.h>
using namespace std;
using namespace isc::util;
using namespace isc::dns;
using namespace Queryperf;
using boost::scoped_ptr;
using namespace boost::posix_time;
using boost::posix_time::seconds;
namespace {
class QueryEvent {
typedef boost::function<void(qid_t, const Message*)> RestartCallback;
public:
QueryEvent(MessageManager& mgr, qid_t qid, QueryContext* ctx,
RestartCallback restart_callback) :
ctx_(ctx), qid_(qid), restart_callback_(restart_callback),
timer_(mgr.createMessageTimer(
boost::bind(&QueryEvent::queryTimerCallback, this))),
tcp_sock_(NULL), tcp_rcvbuf_(NULL)
{}
~QueryEvent() {
delete tcp_sock_;
delete ctx_;
delete[] tcp_rcvbuf_;
}
QueryContext::QuerySpec start(qid_t qid, const time_duration& timeout) {
assert(ctx_ != NULL);
qid_ = qid;
timer_->start(timeout);
return (ctx_->start(qid_));
}
void* getTCPBuf() {
if (tcp_rcvbuf_ == NULL) {
tcp_rcvbuf_ = new uint8_t[TCP_RCVBUF_LEN];
}
return (tcp_rcvbuf_);
}
size_t getTCPBufLen() {
return (TCP_RCVBUF_LEN);
}
qid_t getQid() const { return (qid_); }
bool matchResponse(qid_t qid) const { return (qid_ == qid); }
void setTCPSocket(MessageSocket* tcp_sock) {
assert(tcp_sock_ == NULL);
tcp_sock_ = tcp_sock;
}
void clearTCPSocket() {
assert(tcp_sock_ != NULL);
delete tcp_sock_;
tcp_sock_ = NULL;
}
private:
void queryTimerCallback() {
cout << "[Timeout] Query timed out: msg id: " << qid_ << endl;
if (tcp_sock_ != NULL) {
clearTCPSocket();
}
restart_callback_(qid_, NULL);
}
QueryContext* ctx_;
qid_t qid_;
RestartCallback restart_callback_;
boost::shared_ptr<MessageTimer> timer_;
MessageSocket* tcp_sock_;
static const size_t TCP_RCVBUF_LEN = 65535;
uint8_t* tcp_rcvbuf_; // lazily allocated
};
typedef boost::shared_ptr<QueryEvent> QueryEventPtr;
} // unnamed namespace
namespace Queryperf {
struct Dispatcher::DispatcherImpl {
DispatcherImpl(MessageManager& msg_mgr,
QueryContextCreator& ctx_creator) :
msg_mgr_(&msg_mgr), qryctx_creator_(&ctx_creator),
response_(Message::PARSE)
{
initParams();
}
DispatcherImpl(const string& data_file) :
qry_repo_local_(new QueryRepository(data_file)),
msg_mgr_local_(new ASIOMessageManager),
qryctx_creator_local_(new QueryContextCreator(*qry_repo_local_)),
msg_mgr_(msg_mgr_local_.get()),
qryctx_creator_(qryctx_creator_local_.get()),
response_(Message::PARSE)
{
initParams();
}
DispatcherImpl(istream& input_stream) :
qry_repo_local_(new QueryRepository(input_stream)),
msg_mgr_local_(new ASIOMessageManager),
qryctx_creator_local_(new QueryContextCreator(*qry_repo_local_)),
msg_mgr_(msg_mgr_local_.get()),
qryctx_creator_(qryctx_creator_local_.get()),
response_(Message::PARSE)
{
initParams();
}
void initParams() {
keep_sending_ = true;
window_ = DEFAULT_WINDOW;
qid_ = 0;
queries_sent_ = 0;
queries_completed_ = 0;
server_address_ = DEFAULT_SERVER;
server_port_ = DEFAULT_PORT;
test_duration_ = DEFAULT_DURATION;
query_timeout_ = seconds(DEFAULT_QUERY_TIMEOUT);
}
void run();
// Callback from the message manager called when a response to a query is
// delivered.
void responseCallback(const MessageSocket::Event& sockev);
void responseTCPCallback(const MessageSocket::Event& sockev,
QueryEvent* qev);
// Generate next query either due to completion or timeout.
void restartQuery(qid_t qid, const Message* response);
// A subroutine commonly used to send a single query.
void sendQuery(QueryEvent& qev, const QueryContext::QuerySpec& qry_spec) {
if (qry_spec.proto == IPPROTO_UDP) {
udp_socket_->send(qry_spec.data, qry_spec.len);
} else {
MessageSocket* tcp_sock =
msg_mgr_->createMessageSocket(
IPPROTO_TCP, server_address_, server_port_,
qev.getTCPBuf(), qev.getTCPBufLen(),
boost::bind(&DispatcherImpl::responseTCPCallback, this,
_1, &qev));
qev.setTCPSocket(tcp_sock);
tcp_sock->send(qry_spec.data, qry_spec.len);
}
++queries_sent_;
++qid_;
}
// Callback from the message manager on expiration of the session timer.
// Stop sending more queries; only wait for outstanding ones.
void sessionTimerCallback() {
keep_sending_ = false;
}
// These are placeholders for the support class objects when they are
// built within the context.
scoped_ptr<QueryRepository> qry_repo_local_;
scoped_ptr<ASIOMessageManager> msg_mgr_local_;
scoped_ptr<QueryContextCreator> qryctx_creator_local_;
// These are pointers to the objects actually used in the object
MessageManager* msg_mgr_;
QueryContextCreator* qryctx_creator_;
// Note that these should be placed after msg_mgr_local_; in the destructor
// these should be released first.
scoped_ptr<MessageSocket> udp_socket_;
scoped_ptr<MessageTimer> session_timer_;
uint8_t udp_recvbuf_[4096];
// Configurable parameters
string server_address_;
uint16_t server_port_;
size_t test_duration_;
time_duration query_timeout_;
bool keep_sending_; // whether to send next query on getting a response
size_t window_;
qid_t qid_;
Message response_; // placeholder for response messages
list<boost::shared_ptr<QueryEvent> > outstanding_;
// statistics
size_t queries_sent_;
size_t queries_completed_;
ptime start_time_;
ptime end_time_;
};
void
Dispatcher::DispatcherImpl::run() {
// Allocate resources used throughout the test session:
// common UDP socket and the whole session timer.
udp_socket_.reset(msg_mgr_->createMessageSocket(
IPPROTO_UDP, server_address_, server_port_,
udp_recvbuf_, sizeof(udp_recvbuf_),
boost::bind(&DispatcherImpl::responseCallback,
this, _1)));
session_timer_.reset(msg_mgr_->createMessageTimer(
boost::bind(&DispatcherImpl::sessionTimerCallback,
this)));
// Start the session timer.
session_timer_->start(seconds(test_duration_));
// Create a pool of query contexts. Setting QID to 0 for now.
for (size_t i = 0; i < window_; ++i) {
QueryEventPtr qev(new QueryEvent(
*msg_mgr_, 0, qryctx_creator_->create(),
boost::bind(&DispatcherImpl::restartQuery,
this, _1, _2)));
outstanding_.push_back(qev);
}
// Record the start time and dispatch initial queries at once.
start_time_ = microsec_clock::local_time();
BOOST_FOREACH(boost::shared_ptr<QueryEvent>& qev, outstanding_) {
sendQuery(*qev, qev->start(qid_, query_timeout_));
}
// Enter the event loop.
msg_mgr_->run();
}
void
Dispatcher::DispatcherImpl::responseCallback(
const MessageSocket::Event& sockev)
{
// Parse the header of the response
InputBuffer buffer(sockev.data, sockev.datalen);
response_.clear(Message::PARSE);
response_.parseHeader(buffer);
// TODO: catch exception due to bogus response
restartQuery(response_.getQid(), &response_);
}
void
Dispatcher::DispatcherImpl::responseTCPCallback(
const MessageSocket::Event& sockev, QueryEvent* qev)
{
qev->clearTCPSocket();
if (sockev.datalen > 0) {
// Parse the header of the response
InputBuffer buffer(sockev.data, sockev.datalen);
response_.clear(Message::PARSE);
response_.parseHeader(buffer);
} else {
cout << "[Fail] TCP connection terminated unexpectedly" << endl;
}
restartQuery(qev->getQid(), sockev.datalen > 0 ? &response_ : NULL);
}
void
Dispatcher::DispatcherImpl::restartQuery(qid_t qid, const Message* response) {
// Identify the matching query from the outstanding queue.
const list<boost::shared_ptr<QueryEvent> >::iterator qev_it =
find_if(outstanding_.begin(), outstanding_.end(),
boost::bind(&QueryEvent::matchResponse, _1, qid));
if (qev_it != outstanding_.end()) {
if (response != NULL) {
// TODO: let the context check the response further
++queries_completed_;
}
// If necessary, create a new query and dispatch it.
if (keep_sending_) {
sendQuery(**qev_it, (*qev_it)->start(qid_, query_timeout_));
// Move this context to the end of the queue.
outstanding_.splice(qev_it, outstanding_, outstanding_.end());
} else {
outstanding_.erase(qev_it);
if (outstanding_.empty()) {
msg_mgr_->stop();
}
}
} else {
// TODO: record the mismatched response
}
}
Dispatcher::Dispatcher(MessageManager& msg_mgr,
QueryContextCreator& ctx_creator) :
impl_(new DispatcherImpl(msg_mgr, ctx_creator))
{
}
const char* const Dispatcher::DEFAULT_SERVER = "::1";
Dispatcher::Dispatcher(const string& data_file) {
if (data_file == "-") {
impl_ = new DispatcherImpl(cin);
} else {
impl_ = new DispatcherImpl(data_file);
}
}
Dispatcher::Dispatcher(istream& input_stream) :
impl_(new DispatcherImpl(input_stream))
{
}
Dispatcher::~Dispatcher() {
delete impl_;
}
void
Dispatcher::loadQueries() {
// Query preload must be done before running tests.
if (!impl_->start_time_.is_special()) {
throw DispatcherError("query load attempt after run");
}
// Preload can be used (via the dispatcher) only for the internal
// repository.
if (!impl_->qry_repo_local_) {
throw DispatcherError("query load attempt for external repository");
}
impl_->qry_repo_local_->load();
}
void
Dispatcher::setDefaultQueryClass(const std::string& qclass_txt) {
// default qclass must be set before running tests.
if (!impl_->start_time_.is_special()) {
throw DispatcherError("default query class is being set after run");
}
// qclass can be used (via the dispatcher) only for the internal
// repository.
if (!impl_->qry_repo_local_) {
throw DispatcherError("default query class is being set "
"for external repository");
}
try {
impl_->qry_repo_local_->setQueryClass(RRClass(qclass_txt));
} catch (const isc::Exception&) {
throw DispatcherError("invalid query class: " + qclass_txt);
}
}
void
Dispatcher::setDNSSEC(bool on) {
// This must be set before running tests.
if (!impl_->start_time_.is_special()) {
throw DispatcherError("DNSSEC DO bit is being set/reset after run");
}
// DNSSEC bit can be set (via the dispatcher) only for the internal
// repository.
if (!impl_->qry_repo_local_) {
throw DispatcherError("DNSSEC DO bit is being set/reset "
"for external repository");
}
impl_->qry_repo_local_->setDNSSEC(on);
}
void
Dispatcher::setEDNS(bool on) {
// This must be set before running tests.
if (!impl_->start_time_.is_special()) {
throw DispatcherError("EDNS flag is being set/reset after run");
}
// EDNS flag can be set (via the dispatcher) only for the internal
// repository.
if (!impl_->qry_repo_local_) {
throw DispatcherError("EDNS flag bit is being set/reset "
"for external repository");
}
impl_->qry_repo_local_->setEDNS(on);
}
void
Dispatcher::run() {
assert(impl_->udp_socket_ == NULL);
impl_->run();
impl_->end_time_ = microsec_clock::local_time();
}
string
Dispatcher::getServerAddress() const {
return (impl_->server_address_);
}
void
Dispatcher::setServerAddress(const string& address) {
if (!impl_->start_time_.is_special()) {
throw DispatcherError("server address cannot be reset after run()");
}
impl_->server_address_ = address;
}
uint16_t
Dispatcher::getServerPort() const {
return (impl_->server_port_);
}
void
Dispatcher::setServerPort(uint16_t port) {
if (!impl_->start_time_.is_special()) {
throw DispatcherError("server port cannot be reset after run()");
}
impl_->server_port_ = port;
}
void
Dispatcher::setProtocol(int proto) {
// This must be set before running tests.
if (!impl_->start_time_.is_special()) {
throw DispatcherError("Default transport protocol cannot be set "
"after run()");
}
// Default transport protocol can be set (via the dispatcher) only for
// the internal repository.
if (!impl_->qry_repo_local_) {
throw DispatcherError("Default transport protocol cannot be set "
"for external repository");
}
impl_->qry_repo_local_->setProtocol(proto);
}
size_t
Dispatcher::getTestDuration() const {
return (impl_->test_duration_);
}
void
Dispatcher::setTestDuration(size_t duration) {
if (!impl_->start_time_.is_special()) {
throw DispatcherError("test duration cannot be reset after run()");
}
impl_->test_duration_ = duration;
}
size_t
Dispatcher::getQueriesSent() const {
return (impl_->queries_sent_);
}
size_t
Dispatcher::getQueriesCompleted() const {
return (impl_->queries_completed_);
}
const ptime&
Dispatcher::getStartTime() const {
return (impl_->start_time_);
}
const ptime&
Dispatcher::getEndTime() const {
return (impl_->end_time_);
}
} // end of QueryPerf
<|endoftext|> |
<commit_before>#include "copy.hh"
#include "../stream/copy.hh"
#include "../stream/direct-fd-stream.hh"
namespace mimosa
{
namespace fs
{
bool copyFile(const std::string &src, const std::string &dst)
{
stream::DirectFdStream srcStream;
struct ::stat64 st;
if (::stat64(src.c_str(), &st))
return false;
if (!srcStream.open(src.c_str(), O_RDONLY))
return false;
stream::DirectFdStream dstStream;
if (!dstStream.open(dst.c_str(), O_CREAT | O_TRUNC | O_WRONLY))
return false;
if (st.st_size != stream::copy(srcStream, dstStream)) {
::unlink(dst.c_str());
return false;
}
return true;
}
}
}
<commit_msg>fs/copy: Use struct stat instead of struct stat64<commit_after>#include "copy.hh"
#include "../stream/copy.hh"
#include "../stream/direct-fd-stream.hh"
namespace mimosa
{
namespace fs
{
bool copyFile(const std::string &src, const std::string &dst)
{
stream::DirectFdStream srcStream;
struct ::stat st;
if (::stat(src.c_str(), &st))
return false;
if (!srcStream.open(src.c_str(), O_RDONLY))
return false;
stream::DirectFdStream dstStream;
if (!dstStream.open(dst.c_str(), O_CREAT | O_TRUNC | O_WRONLY))
return false;
if (st.st_size != stream::copy(srcStream, dstStream)) {
::unlink(dst.c_str());
return false;
}
return true;
}
}
}
<|endoftext|> |
<commit_before><commit_msg>tdf#84881: Fix typo in OID string for id-aa-timeStampToken<commit_after><|endoftext|> |
<commit_before>#include "fixie_lib/desktop_gl_impl/gl_version.hpp"
#include "fixie_lib/util.hpp"
#include <regex>
namespace fixie
{
gl_version::gl_version()
: _major(0)
, _minor(0)
, _type(open_gl)
{
}
gl_version::gl_version(const std::string& version_string)
: _major(0)
, _minor(0)
, _type(open_gl)
{
const std::regex version_regex("(OpenGL ES )?(\\d)\\.(\\d)\\.*");
std::smatch match;
if (std::regex_search(version_string.begin(), version_string.end(), match, version_regex))
{
_major = static_cast<GLuint>(std::stoul(match[2].str()));
_minor = static_cast<GLuint>(std::stoul(match[3].str()));
_type = match[1].matched ? open_gl_es : open_gl;
}
}
gl_version::gl_version(GLuint major, GLuint minor, gl_context_type type)
: _major(major)
, _minor(minor)
, _type(type)
{
}
const GLuint& gl_version::major() const
{
return _major;
}
GLuint& gl_version::major()
{
return _major;
}
const GLuint& gl_version::minor() const
{
return _minor;
}
GLuint& gl_version::minor()
{
return _minor;
}
const gl_context_type& gl_version::type() const
{
return _type;
}
gl_context_type& gl_version::type()
{
return _type;
}
std::string gl_version::str() const
{
return format("%s%u.%u", (_type == open_gl_es) ? "ES " : "", _major, _minor);
}
const gl_version gl_3_0 = gl_version(3, 0, open_gl);
const gl_version gl_4_3 = gl_version(4, 3, open_gl);
const gl_version gl_es_3_0 = gl_version(3, 0, open_gl_es);
const gl_version gl_es_2_0 = gl_version(2, 0, open_gl_es);
bool operator==(const gl_version& a, const gl_version& b)
{
return a.major() == b.major() && a.minor() == b.minor() && a.type() == b.type();
}
bool operator!=(const gl_version& a, const gl_version& b)
{
return !(a == b);
}
bool operator>=(const gl_version& a, const gl_version& b)
{
return a.type() == b.type() && ((a.major() != b.major()) ? (a.major() >= b.major()) : (a.minor() >= b.minor()));
}
bool operator>(const gl_version& a, const gl_version& b)
{
return a.type() == b.type() && ((a.major() != b.major()) ? (a.major() > b.major()) : (a.minor() > b.minor()));
}
bool operator<=(const gl_version& a, const gl_version& b)
{
return a.type() == b.type() && ((a.major() != b.major()) ? (a.major() <= b.major()) : (a.minor() <= b.minor()));
}
bool operator<(const gl_version& a, const gl_version& b)
{
return a.type() == b.type() && ((a.major() != b.major()) ? (a.major() < b.major()) : (a.minor() < b.minor()));
}
}
<commit_msg>Simplified the version comparisons.<commit_after>#include "fixie_lib/desktop_gl_impl/gl_version.hpp"
#include "fixie_lib/util.hpp"
#include <regex>
namespace fixie
{
gl_version::gl_version()
: _major(0)
, _minor(0)
, _type(open_gl)
{
}
gl_version::gl_version(const std::string& version_string)
: _major(0)
, _minor(0)
, _type(open_gl)
{
const std::regex version_regex("(OpenGL ES )?(\\d)\\.(\\d)\\.*");
std::smatch match;
if (std::regex_search(version_string.begin(), version_string.end(), match, version_regex))
{
_major = static_cast<GLuint>(std::stoul(match[2].str()));
_minor = static_cast<GLuint>(std::stoul(match[3].str()));
_type = match[1].matched ? open_gl_es : open_gl;
}
}
gl_version::gl_version(GLuint major, GLuint minor, gl_context_type type)
: _major(major)
, _minor(minor)
, _type(type)
{
}
const GLuint& gl_version::major() const
{
return _major;
}
GLuint& gl_version::major()
{
return _major;
}
const GLuint& gl_version::minor() const
{
return _minor;
}
GLuint& gl_version::minor()
{
return _minor;
}
const gl_context_type& gl_version::type() const
{
return _type;
}
gl_context_type& gl_version::type()
{
return _type;
}
std::string gl_version::str() const
{
return format("%s%u.%u", (_type == open_gl_es) ? "ES " : "", _major, _minor);
}
const gl_version gl_3_0 = gl_version(3, 0, open_gl);
const gl_version gl_4_3 = gl_version(4, 3, open_gl);
const gl_version gl_es_3_0 = gl_version(3, 0, open_gl_es);
const gl_version gl_es_2_0 = gl_version(2, 0, open_gl_es);
static size_t get_comparable_version_number(const gl_version& version)
{
return (version.major() * 10) + version.minor();
}
bool operator==(const gl_version& a, const gl_version& b)
{
return a.major() == b.major() && a.minor() == b.minor() && a.type() == b.type();
}
bool operator!=(const gl_version& a, const gl_version& b)
{
return !(a == b);
}
bool operator>=(const gl_version& a, const gl_version& b)
{
return a.type() == b.type() && get_comparable_version_number(a) >= get_comparable_version_number(b);
}
bool operator>(const gl_version& a, const gl_version& b)
{
return a.type() == b.type() && get_comparable_version_number(a) > get_comparable_version_number(b);
}
bool operator<=(const gl_version& a, const gl_version& b)
{
return a.type() == b.type() && get_comparable_version_number(a) <= get_comparable_version_number(b);
}
bool operator<(const gl_version& a, const gl_version& b)
{
return a.type() == b.type() && get_comparable_version_number(a) < get_comparable_version_number(b);
}
}
<|endoftext|> |
<commit_before>/*
* MRustC - Rust Compiler
* - By John Hodge (Mutabah/thePowersGang)
*
* trans/mangling_v2.cpp
* - Name mangling (encoding of rust paths into symbols)
*/
#include <debug.hpp>
#include <string_view.hpp>
#include <hir/hir.hpp> // ABI_RUST
#include <hir/type.hpp>
#include <cctype>
class Mangler
{
::std::ostream& m_os;
public:
Mangler(::std::ostream& os):
m_os(os)
{
}
// Item names:
// - These can have a single '#' in them (either leading or in the middle)
// TODO: Some other invalid characters can appear:
// - '-' (crate names)
void fmt_name(const RcString& s)
{
this->fmt_name(s.c_str());
}
void fmt_name(const char* const s)
{
size_t size = strlen(s);
const char* hash_pos = nullptr;
// - Search the string for the '#' character
for(const auto* p = s; *p; p++)
{
if( p == s ) {
ASSERT_BUG(Span(), !isdigit(*p), "Leading digit not valid in '" << s << "'");
}
if( isalnum(*p) ) {
}
else if( *p == '_' ) {
}
else if( *p == '#' || *p == '-' ) { // HACK: Treat '-' and '#' as the same in encoding
// Multiple hash characters? abort/error
ASSERT_BUG(Span(), hash_pos == nullptr, "Multiple '#' characters in '" << s << "'");
hash_pos = p;
}
else {
BUG(Span(), "Encounteded invalid character '" << *p << "' in '" << s << "'");
}
}
// If there's a hash, then prefix with a letter indicating its location?
// - Using a 3 character overhead currently (but a letter could work really well)
if( hash_pos != nullptr )
{
auto pre_hash_len = static_cast<int>(hash_pos - s);
#if 0
assert(pre_hash_len < 26);
// <posletter> <full_len> <body1> <body2>
m_os << 'a' + pre_hash_len;
m_os << size - 1;
m_os << ::stdx::string_view(s, s + pre_hash_len);
m_os << hash_pos + 1;;
#else
// If the suffix is all digits, then print `H` and the literal contents
if( false && std::isdigit(hash_pos[1]) )
{
for(auto c = hash_pos+1; *c; c++)
ASSERT_BUG(Span(), std::isdigit(*c), "'" << s << "'");
m_os << "H";
m_os << pre_hash_len;
m_os << ::stdx::string_view(s, s + pre_hash_len);
m_os << hash_pos + 1;
}
else
{
// 'h' <len1> <body1> <len2> <body2>
m_os << "h";
m_os << pre_hash_len;
m_os << ::stdx::string_view(s, s + pre_hash_len);
m_os << size - pre_hash_len - 1;
m_os << hash_pos + 1;
}
#endif
}
else
{
m_os << size;
m_os << s;
}
}
// SimplePath : <ncomp> 'c' [<RcString> ...]
void fmt_simple_path(const ::HIR::SimplePath& sp)
{
m_os << sp.m_components.size();
m_os << "c"; // Needed to separate the component count from the crate name
this->fmt_name(sp.m_crate_name);
for(const auto& c : sp.m_components)
{
this->fmt_name(c);
}
}
// PathParams : <ntys> 'g' [<TypeRef> ...]
void fmt_path_params(const ::HIR::PathParams& pp)
{
// Type Parameter count
m_os << pp.m_types.size();
m_os << "g";
for(const auto& ty : pp.m_types)
{
fmt_type(ty);
}
}
// GenericPath : <SimplePath> <PathParams>
void fmt_generic_path(const ::HIR::GenericPath& gp)
{
this->fmt_simple_path(gp.m_path);
this->fmt_path_params(gp.m_params);
}
void fmt_path(const ::HIR::Path& p)
{
// Path type
// - Generic: starts with `G`
// - Inherent: Starts with `I`
// - Trait: Starts with `Q` (qualified)
// - bare type: Starts with `T` (see Trans_MangleType)
TU_MATCH_HDRA( (p.m_data), {)
TU_ARMA(Generic, e) {
m_os << "G";
this->fmt_generic_path(e);
}
TU_ARMA(UfcsInherent, e) {
m_os << "I";
this->fmt_type(e.type);
this->fmt_name(e.item);
this->fmt_path_params(e.params);
}
TU_ARMA(UfcsKnown, e) {
m_os << "Q";
this->fmt_type(e.type);
this->fmt_generic_path(e.trait);
this->fmt_name(e.item);
this->fmt_path_params(e.params);
}
TU_ARMA(UfcsUnknown, e)
BUG(Span(), "Non-encodable path " << p);
}
}
// Type
// - Tuple: 'T' <nelem> [<TypeRef> ...]
// - Slice: 'S' <TypeRef>
// - Array: 'A' <size> <TypeRef>
// - Path: 'N' <Path>
// - TraitObject: 'D' <data:GenericPath> <nmarker> [markers: <GenericPath> ...] <naty> [<TypeRef> ...] TODO: Does this need to include the ATY name?
// - Borrow: 'B' ('s'|'u'|'o') <TypeRef>
// - RawPointer: 'P' ('s'|'u'|'o') <TypeRef>
// - Function: 'F' <abi:RcString> <nargs> [args: <TypeRef> ...] <ret:TypeRef>
// - Primitives::
// - u8 : 'C' 'a'
// - i8 : 'C' 'b'
// - u16 : 'C' 'c'
// - i16 : 'C' 'd'
// - u32 : 'C' 'e'
// - i32 : 'C' 'f'
// - u64 : 'C' 'g'
// - i64 : 'C' 'h'
// - u128: 'C' 'i'
// - i128: 'C' 'j'
// --
// - f32 : 'C' 'n'
// - f64 : 'C' 'o'
// --
// - usize: 'C' 'u'
// - isize: 'C' 'v'
// - bool : 'C' 'x'
// - char : 'C' 'x'
// - str : 'C' 'y'
// - Diverge: 'C' 'z'
void fmt_type(const ::HIR::TypeRef& ty)
{
TU_MATCH_HDRA( (ty.data()), { )
case ::HIR::TypeData::TAG_Infer:
case ::HIR::TypeData::TAG_Generic:
case ::HIR::TypeData::TAG_ErasedType:
case ::HIR::TypeData::TAG_Closure:
case ::HIR::TypeData::TAG_Generator:
BUG(Span(), "Non-encodable type " << ty);
TU_ARMA(Tuple, e) {
m_os << "T" << e.size();
for(const auto& sty : e)
this->fmt_type(sty);
}
TU_ARMA(Slice, e) {
m_os << "S";
this->fmt_type(e.inner);
}
TU_ARMA(Array, e) {
m_os << "A" << e.size.as_Known();
this->fmt_type(e.inner);
}
TU_ARMA(Path, e) {
m_os << "G";
ASSERT_BUG(Span(), e.path.m_data.is_Generic(), "Type path not Generic - " << ty);
this->fmt_generic_path(e.path.m_data.as_Generic());
}
TU_ARMA(TraitObject, e) {
// - TraitObject: 'D' <data:GenericPath> <naty> [<TypeRef> ...] <nmarker> [markers: <GenericPath> ...]
m_os << "D";
this->fmt_generic_path(e.m_trait.m_path);
m_os << e.m_trait.m_type_bounds.size();
// HACK: Assume all TraitObject types have the same aty set (std::map is deterministic)
for(const auto& aty : e.m_trait.m_type_bounds)
this->fmt_type(aty.second.type);
m_os << e.m_markers.size();
for(const auto& p : e.m_markers)
this->fmt_generic_path(p);
}
TU_ARMA(Function, e) {
// - Function: 'F' <abi:RcString> <nargs> [args: <TypeRef> ...] <ret:TypeRef>
m_os << "F";
m_os << (e.is_unsafe ? "u" : ""); // Optional allowed, next is a number
if( e.m_abi != ABI_RUST )
{
m_os << "e";
this->fmt_name(e.m_abi.c_str());
}
m_os << e.m_arg_types.size();
for(const auto& t : e.m_arg_types)
this->fmt_type(t);
this->fmt_type(e.m_rettype);
}
TU_ARMA(Borrow, e) {
m_os << "B";
switch(e.type)
{
case ::HIR::BorrowType::Shared: m_os << "s"; break;
case ::HIR::BorrowType::Unique: m_os << "u"; break;
case ::HIR::BorrowType::Owned: m_os << "o"; break;
}
this->fmt_type(e.inner);
}
TU_ARMA(Pointer, e) {
m_os << "P";
switch(e.type)
{
case ::HIR::BorrowType::Shared: m_os << "s"; break;
case ::HIR::BorrowType::Unique: m_os << "u"; break;
case ::HIR::BorrowType::Owned: m_os << "o"; break;
}
this->fmt_type(e.inner);
}
TU_ARMA(Primitive, e) {
switch(e)
{
case ::HIR::CoreType::U8 : m_os << 'C' << 'a'; break;
case ::HIR::CoreType::I8 : m_os << 'C' << 'b'; break;
case ::HIR::CoreType::U16 : m_os << 'C' << 'c'; break;
case ::HIR::CoreType::I16 : m_os << 'C' << 'd'; break;
case ::HIR::CoreType::U32 : m_os << 'C' << 'e'; break;
case ::HIR::CoreType::I32 : m_os << 'C' << 'f'; break;
case ::HIR::CoreType::U64 : m_os << 'C' << 'g'; break;
case ::HIR::CoreType::I64 : m_os << 'C' << 'h'; break;
case ::HIR::CoreType::U128: m_os << 'C' << 'i'; break;
case ::HIR::CoreType::I128: m_os << 'C' << 'j'; break;
case ::HIR::CoreType::F32 : m_os << 'C' << 'n'; break;
case ::HIR::CoreType::F64 : m_os << 'C' << 'o'; break;
case ::HIR::CoreType::Usize: m_os << 'C' << 'u'; break;
case ::HIR::CoreType::Isize: m_os << 'C' << 'v'; break;
case ::HIR::CoreType::Bool: m_os << 'C' << 'w'; break;
case ::HIR::CoreType::Char: m_os << 'C' << 'x'; break;
case ::HIR::CoreType::Str : m_os << 'C' << 'y'; break;
}
}
TU_ARMA(Diverge, _e) {
m_os << 'C' << 'z';
}
}
}
};
::FmtLambda Trans_ManglePath(const ::HIR::Path& p)
{
return FMT_CB(os, os << "ZR"; Mangler(os).fmt_path(p));
}
::FmtLambda Trans_MangleSimplePath(const ::HIR::SimplePath& p)
{
return FMT_CB(os, os << "ZRG"; Mangler(os).fmt_simple_path(p); Mangler(os).fmt_path_params({}););
}
::FmtLambda Trans_MangleGenericPath(const ::HIR::GenericPath& p)
{
return FMT_CB(os, os << "ZRG"; Mangler(os).fmt_generic_path(p));
}
::FmtLambda Trans_MangleTypeRef(const ::HIR::TypeRef& p)
{
return FMT_CB(os, os << "ZRT"; Mangler(os).fmt_type(p));
}
namespace {
::FmtLambda max_len(::FmtLambda v) {
std::stringstream ss;
ss << v;
auto s = ss.str();
static const size_t MAX_LEN = 128;
if( s.size() > 128 ) {
size_t hash = ::std::hash<std::string>()(s);
ss.str("");
ss << s.substr(0, MAX_LEN-9) << "$" << ::std::hex << hash;
DEBUG("Over-long symbol '" << s << "' -> '" << ss.str() << "'");
s = ss.str();
}
else {
}
return ::FmtLambda([=](::std::ostream& os){
os << s;
});
}
}
// TODO: If the mangled name exceeds a limit, stop emitting the real name and start hashing the rest.
#define DO_MANGLE(ty) ::FmtLambda Trans_Mangle(const ::HIR::ty& v) { \
return max_len(Trans_Mangle##ty(v)); \
}
DO_MANGLE(SimplePath)
DO_MANGLE(GenericPath)
DO_MANGLE(Path)
DO_MANGLE(TypeRef)
<commit_msg>Trans - Add back-references to mangling (for longer identifiers)<commit_after>/*
* MRustC - Rust Compiler
* - By John Hodge (Mutabah/thePowersGang)
*
* trans/mangling_v2.cpp
* - Name mangling (encoding of rust paths into symbols)
*/
#include <debug.hpp>
#include <string_view.hpp>
#include <hir/hir.hpp> // ABI_RUST
#include <hir/type.hpp>
#include <cctype>
class Mangler
{
::std::ostream& m_os;
std::vector<RcString> m_name_cache;
public:
Mangler(::std::ostream& os):
m_os(os)
{
}
// Item names:
// - These can have a single '#' in them (either leading or in the middle)
// TODO: Some other invalid characters can appear:
// - '-' (crate names)
void fmt_name(const RcString& s)
{
// Support back-references to names (if shorter than the literal name)
auto it = std::find(m_name_cache.begin(), m_name_cache.end(), s);
if(it != m_name_cache.end())
{
auto idx = it - m_name_cache.begin();
// Only emit this way if shorter than the formatted name would be.
auto len = 1 + static_cast<int>(std::ceil(std::log10(idx+1)));
if(len < s.size())
{
m_os << "b" << idx;
return ;
}
}
else
{
m_name_cache.push_back(s);
}
this->fmt_name(s.c_str());
}
void fmt_name(const char* const s)
{
size_t size = strlen(s);
const char* hash_pos = nullptr;
// - Search the string for the '#' character
for(const auto* p = s; *p; p++)
{
if( p == s ) {
ASSERT_BUG(Span(), !isdigit(*p), "Leading digit not valid in '" << s << "'");
}
if( isalnum(*p) ) {
}
else if( *p == '_' ) {
}
else if( *p == '#' || *p == '-' ) { // HACK: Treat '-' and '#' as the same in encoding
// Multiple hash characters? abort/error
ASSERT_BUG(Span(), hash_pos == nullptr, "Multiple '#' characters in '" << s << "'");
hash_pos = p;
}
else {
BUG(Span(), "Encounteded invalid character '" << *p << "' in '" << s << "'");
}
}
// If there's a hash, then prefix with a letter indicating its location?
// - Using a 3 character overhead currently (but a letter could work really well)
if( hash_pos != nullptr )
{
auto pre_hash_len = static_cast<int>(hash_pos - s);
#if 0
assert(pre_hash_len < 26);
// <posletter> <full_len> <body1> <body2>
m_os << 'a' + pre_hash_len;
m_os << size - 1;
m_os << ::stdx::string_view(s, s + pre_hash_len);
m_os << hash_pos + 1;;
#else
// If the suffix is all digits, then print `H` and the literal contents
if( false && std::isdigit(hash_pos[1]) )
{
for(auto c = hash_pos+1; *c; c++)
ASSERT_BUG(Span(), std::isdigit(*c), "'" << s << "'");
m_os << "H";
m_os << pre_hash_len;
m_os << ::stdx::string_view(s, s + pre_hash_len);
m_os << hash_pos + 1;
}
else
{
// 'h' <len1> <body1> <len2> <body2>
m_os << "h";
m_os << pre_hash_len;
m_os << ::stdx::string_view(s, s + pre_hash_len);
m_os << size - pre_hash_len - 1;
m_os << hash_pos + 1;
}
#endif
}
else
{
m_os << size;
m_os << s;
}
}
// SimplePath : <ncomp> 'c' [<RcString> ...]
void fmt_simple_path(const ::HIR::SimplePath& sp)
{
m_os << sp.m_components.size();
m_os << "c"; // Needed to separate the component count from the crate name
this->fmt_name(sp.m_crate_name);
for(const auto& c : sp.m_components)
{
this->fmt_name(c);
}
}
// PathParams : <ntys> 'g' [<TypeRef> ...]
void fmt_path_params(const ::HIR::PathParams& pp)
{
// Type Parameter count
m_os << pp.m_types.size();
m_os << "g";
for(const auto& ty : pp.m_types)
{
fmt_type(ty);
}
}
// GenericPath : <SimplePath> <PathParams>
void fmt_generic_path(const ::HIR::GenericPath& gp)
{
this->fmt_simple_path(gp.m_path);
this->fmt_path_params(gp.m_params);
}
void fmt_path(const ::HIR::Path& p)
{
// Path type
// - Generic: starts with `G`
// - Inherent: Starts with `I`
// - Trait: Starts with `Q` (qualified)
// - bare type: Starts with `T` (see Trans_MangleType)
TU_MATCH_HDRA( (p.m_data), {)
TU_ARMA(Generic, e) {
m_os << "G";
this->fmt_generic_path(e);
}
TU_ARMA(UfcsInherent, e) {
m_os << "I";
this->fmt_type(e.type);
this->fmt_name(e.item);
this->fmt_path_params(e.params);
}
TU_ARMA(UfcsKnown, e) {
m_os << "Q";
this->fmt_type(e.type);
this->fmt_generic_path(e.trait);
this->fmt_name(e.item);
this->fmt_path_params(e.params);
}
TU_ARMA(UfcsUnknown, e)
BUG(Span(), "Non-encodable path " << p);
}
}
// Type
// - Tuple: 'T' <nelem> [<TypeRef> ...]
// - Slice: 'S' <TypeRef>
// - Array: 'A' <size> <TypeRef>
// - Path: 'N' <Path>
// - TraitObject: 'D' <data:GenericPath> <nmarker> [markers: <GenericPath> ...] <naty> [<TypeRef> ...] TODO: Does this need to include the ATY name?
// - Borrow: 'B' ('s'|'u'|'o') <TypeRef>
// - RawPointer: 'P' ('s'|'u'|'o') <TypeRef>
// - Function: 'F' <abi:RcString> <nargs> [args: <TypeRef> ...] <ret:TypeRef>
// - Primitives::
// - u8 : 'C' 'a'
// - i8 : 'C' 'b'
// - u16 : 'C' 'c'
// - i16 : 'C' 'd'
// - u32 : 'C' 'e'
// - i32 : 'C' 'f'
// - u64 : 'C' 'g'
// - i64 : 'C' 'h'
// - u128: 'C' 'i'
// - i128: 'C' 'j'
// --
// - f32 : 'C' 'n'
// - f64 : 'C' 'o'
// --
// - usize: 'C' 'u'
// - isize: 'C' 'v'
// - bool : 'C' 'x'
// - char : 'C' 'x'
// - str : 'C' 'y'
// - Diverge: 'C' 'z'
void fmt_type(const ::HIR::TypeRef& ty)
{
TU_MATCH_HDRA( (ty.data()), { )
case ::HIR::TypeData::TAG_Infer:
case ::HIR::TypeData::TAG_Generic:
case ::HIR::TypeData::TAG_ErasedType:
case ::HIR::TypeData::TAG_Closure:
case ::HIR::TypeData::TAG_Generator:
BUG(Span(), "Non-encodable type " << ty);
TU_ARMA(Tuple, e) {
m_os << "T" << e.size();
for(const auto& sty : e)
this->fmt_type(sty);
}
TU_ARMA(Slice, e) {
m_os << "S";
this->fmt_type(e.inner);
}
TU_ARMA(Array, e) {
m_os << "A" << e.size.as_Known();
this->fmt_type(e.inner);
}
TU_ARMA(Path, e) {
m_os << "G";
ASSERT_BUG(Span(), e.path.m_data.is_Generic(), "Type path not Generic - " << ty);
this->fmt_generic_path(e.path.m_data.as_Generic());
}
TU_ARMA(TraitObject, e) {
// - TraitObject: 'D' <data:GenericPath> <naty> [<TypeRef> ...] <nmarker> [markers: <GenericPath> ...]
m_os << "D";
this->fmt_generic_path(e.m_trait.m_path);
m_os << e.m_trait.m_type_bounds.size();
// HACK: Assume all TraitObject types have the same aty set (std::map is deterministic)
for(const auto& aty : e.m_trait.m_type_bounds)
this->fmt_type(aty.second.type);
m_os << e.m_markers.size();
for(const auto& p : e.m_markers)
this->fmt_generic_path(p);
}
TU_ARMA(Function, e) {
// - Function: 'F' <abi:RcString> <nargs> [args: <TypeRef> ...] <ret:TypeRef>
m_os << "F";
m_os << (e.is_unsafe ? "u" : ""); // Optional allowed, next is a number
if( e.m_abi != ABI_RUST )
{
m_os << "e";
this->fmt_name(e.m_abi.c_str());
}
m_os << e.m_arg_types.size();
for(const auto& t : e.m_arg_types)
this->fmt_type(t);
this->fmt_type(e.m_rettype);
}
TU_ARMA(Borrow, e) {
m_os << "B";
switch(e.type)
{
case ::HIR::BorrowType::Shared: m_os << "s"; break;
case ::HIR::BorrowType::Unique: m_os << "u"; break;
case ::HIR::BorrowType::Owned: m_os << "o"; break;
}
this->fmt_type(e.inner);
}
TU_ARMA(Pointer, e) {
m_os << "P";
switch(e.type)
{
case ::HIR::BorrowType::Shared: m_os << "s"; break;
case ::HIR::BorrowType::Unique: m_os << "u"; break;
case ::HIR::BorrowType::Owned: m_os << "o"; break;
}
this->fmt_type(e.inner);
}
TU_ARMA(Primitive, e) {
switch(e)
{
case ::HIR::CoreType::U8 : m_os << 'C' << 'a'; break;
case ::HIR::CoreType::I8 : m_os << 'C' << 'b'; break;
case ::HIR::CoreType::U16 : m_os << 'C' << 'c'; break;
case ::HIR::CoreType::I16 : m_os << 'C' << 'd'; break;
case ::HIR::CoreType::U32 : m_os << 'C' << 'e'; break;
case ::HIR::CoreType::I32 : m_os << 'C' << 'f'; break;
case ::HIR::CoreType::U64 : m_os << 'C' << 'g'; break;
case ::HIR::CoreType::I64 : m_os << 'C' << 'h'; break;
case ::HIR::CoreType::U128: m_os << 'C' << 'i'; break;
case ::HIR::CoreType::I128: m_os << 'C' << 'j'; break;
case ::HIR::CoreType::F32 : m_os << 'C' << 'n'; break;
case ::HIR::CoreType::F64 : m_os << 'C' << 'o'; break;
case ::HIR::CoreType::Usize: m_os << 'C' << 'u'; break;
case ::HIR::CoreType::Isize: m_os << 'C' << 'v'; break;
case ::HIR::CoreType::Bool: m_os << 'C' << 'w'; break;
case ::HIR::CoreType::Char: m_os << 'C' << 'x'; break;
case ::HIR::CoreType::Str : m_os << 'C' << 'y'; break;
}
}
TU_ARMA(Diverge, _e) {
m_os << 'C' << 'z';
}
}
}
};
::FmtLambda Trans_ManglePath(const ::HIR::Path& p)
{
return FMT_CB(os, os << "ZR"; Mangler(os).fmt_path(p));
}
::FmtLambda Trans_MangleSimplePath(const ::HIR::SimplePath& p)
{
return FMT_CB(os, os << "ZRG"; Mangler(os).fmt_simple_path(p); Mangler(os).fmt_path_params({}););
}
::FmtLambda Trans_MangleGenericPath(const ::HIR::GenericPath& p)
{
return FMT_CB(os, os << "ZRG"; Mangler(os).fmt_generic_path(p));
}
::FmtLambda Trans_MangleTypeRef(const ::HIR::TypeRef& p)
{
return FMT_CB(os, os << "ZRT"; Mangler(os).fmt_type(p));
}
namespace {
::FmtLambda max_len(::FmtLambda v) {
std::stringstream ss;
ss << v;
auto s = ss.str();
static const size_t MAX_LEN = 128;
if( s.size() > 128 ) {
size_t hash = ::std::hash<std::string>()(s);
ss.str("");
ss << s.substr(0, MAX_LEN-9) << "$" << ::std::hex << hash;
DEBUG("Over-long symbol '" << s << "' -> '" << ss.str() << "'");
s = ss.str();
}
else {
}
return ::FmtLambda([=](::std::ostream& os){
os << s;
});
}
}
// TODO: If the mangled name exceeds a limit, stop emitting the real name and start hashing the rest.
#define DO_MANGLE(ty) ::FmtLambda Trans_Mangle(const ::HIR::ty& v) { \
return max_len(Trans_Mangle##ty(v)); \
}
DO_MANGLE(SimplePath)
DO_MANGLE(GenericPath)
DO_MANGLE(Path)
DO_MANGLE(TypeRef)
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2021-2021 ArangoDB GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Lars Maier
////////////////////////////////////////////////////////////////////////////////
#include "Replication2/Mocks/FakeReplicatedLog.h"
#include "Replication2/ReplicatedLog/LogCommon.h"
#include "TestHelper.h"
#include <Containers/Enumerate.h>
#include <gtest/gtest.h>
#include <optional>
#include "Replication2/ReplicatedLog/LogCore.h"
#include "Replication2/ReplicatedLog/LogLeader.h"
using namespace arangodb;
using namespace arangodb::replication2;
using namespace arangodb::replication2::replicated_log;
using namespace arangodb::replication2::test;
struct AppendEntriesBatchTest
: ReplicatedLogTest,
::testing::WithParamInterface<std::tuple<ReplicatedLogGlobalSettings, std::vector<LogPayload>>> {
AppendEntriesBatchTest() : _payloads(std::get<1>(GetParam())) {
*_optionsMock = std::get<0>(GetParam());
}
std::vector<LogPayload> const _payloads{};
};
TEST_P(AppendEntriesBatchTest, test_with_sized_batches) {
auto expectedNumRequests = size_t{0};
// AppendEntries CommitIndex
expectedNumRequests++;
// AppendEntries LCI
expectedNumRequests++;
// If the payload has more than one entry, decrement lastAckedIndex to 0
if (_payloads.size() > 1) {
expectedNumRequests += 1;
}
auto leaderLog = std::invoke([&] {
auto persistedLog = makePersistedLog(LogId{1});
for (auto [idx, payload] : enumerate(_payloads)) {
persistedLog->setEntry(LogIndex{idx + 1}, LogTerm{4}, payload);
}
/*
* Compute the number of requests we expect to be generating;
* this is slightly dissatisfying as we're re-implementing the
* algorithm used for batching, but there is no closed formula
* for this
*/
auto it = persistedLog->read(LogIndex{1});
auto numRequests = size_t{0};
auto currentSize = size_t{0};
while (auto log = it->next()) {
currentSize += log->approxByteSize();
if (currentSize >= _optionsMock->_thresholdNetworkBatchSize) {
numRequests += 1;
currentSize = 0;
}
}
{
// Add first entry in term
currentSize += PersistingLogEntry{LogTerm{5}, LogIndex{1}, std::nullopt}.approxByteSize();
if (currentSize >= _optionsMock->_maxNetworkBatchSize) {
numRequests += 1;
currentSize = 0;
}
}
// Some pending entries still need to be submitted
if (currentSize > 0) {
numRequests += 1;
}
expectedNumRequests += numRequests;
return std::make_shared<TestReplicatedLog>(std::make_unique<LogCore>(persistedLog),
_logMetricsMock, _optionsMock,
LoggerContext(Logger::REPLICATION2));
});
auto followerLog = makeReplicatedLog(LogId{1});
auto follower = followerLog->becomeFollower("follower", LogTerm{5}, "leader");
auto leader = leaderLog->becomeLeader("leader", LogTerm{5}, {follower}, 2);
{
if (_payloads.size() > 0) {
auto stats = std::get<LeaderStatus>(leader->getStatus().getVariant());
EXPECT_EQ(stats.local.spearHead,
TermIndexPair(LogTerm{5}, LogIndex{_payloads.size() + 1}));
EXPECT_EQ(stats.local.commitIndex, LogIndex{0});
EXPECT_EQ(stats.follower.at("follower").spearHead.index,
LogIndex{_payloads.size() - 1});
} else {
// TODO:
}
}
{
auto stats = std::get<FollowerStatus>(follower->getStatus().getVariant());
EXPECT_EQ(stats.local.spearHead.index, LogIndex{0});
EXPECT_EQ(stats.local.commitIndex, LogIndex{0});
}
leader->triggerAsyncReplication();
ASSERT_TRUE(follower->hasPendingAppendEntries());
{
std::size_t num_requests = 0;
while (follower->hasPendingAppendEntries()) {
follower->runAsyncAppendEntries();
num_requests += 1;
}
EXPECT_EQ(num_requests, expectedNumRequests);
}
{
auto stats = std::get<LeaderStatus>(leader->getStatus().getVariant());
EXPECT_EQ(stats.local.spearHead.index, LogIndex{_payloads.size() + 1});
EXPECT_EQ(stats.local.commitIndex, LogIndex{_payloads.size() + 1});
}
{
auto stats = std::get<FollowerStatus>(follower->getStatus().getVariant());
EXPECT_EQ(stats.local.spearHead.index, LogIndex{_payloads.size() + 1});
EXPECT_EQ(stats.local.commitIndex, LogIndex{_payloads.size() + 1});
}
}
auto testReplicatedLogOptions =
testing::Values(ReplicatedLogGlobalSettings{5, 5}, ReplicatedLogGlobalSettings{1024, 1024},
ReplicatedLogGlobalSettings{1024 * 1024, 1024 * 1024});
auto testPayloads = testing::Values(
std::vector<LogPayload>{LogPayload::createFromString("a")},
std::vector<LogPayload>{LogPayload::createFromString("a"),
LogPayload::createFromString("b")},
std::vector<LogPayload>{LogPayload::createFromString(std::string(1024, 'a'))},
std::vector<LogPayload>{LogPayload::createFromString("Hello, world"),
LogPayload::createFromString("Bye, world")},
std::vector<LogPayload>(1024, LogPayload::createFromString("")),
std::vector<LogPayload>{LogPayload::createFromString(std::string(1024, 'a')),
LogPayload::createFromString("Hello, world"),
LogPayload::createFromString("Bye, world")},
std::vector<LogPayload>(1024, LogPayload::createFromString(std::string(1024, 'a'))));
// Use a sequence of payload of pre-defined sizes and send them;
// count the number of batches that are created.
INSTANTIATE_TEST_CASE_P(AppendEntriesBatchTestInstance, AppendEntriesBatchTest,
testing::Combine(testReplicatedLogOptions, testPayloads));
<commit_msg>Fix missing rename of _thresholdNetworkBatchSize. (#15170)<commit_after>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2021-2021 ArangoDB GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Lars Maier
////////////////////////////////////////////////////////////////////////////////
#include "Replication2/Mocks/FakeReplicatedLog.h"
#include "Replication2/ReplicatedLog/LogCommon.h"
#include "TestHelper.h"
#include <Containers/Enumerate.h>
#include <gtest/gtest.h>
#include <optional>
#include "Replication2/ReplicatedLog/LogCore.h"
#include "Replication2/ReplicatedLog/LogLeader.h"
using namespace arangodb;
using namespace arangodb::replication2;
using namespace arangodb::replication2::replicated_log;
using namespace arangodb::replication2::test;
struct AppendEntriesBatchTest
: ReplicatedLogTest,
::testing::WithParamInterface<std::tuple<ReplicatedLogGlobalSettings, std::vector<LogPayload>>> {
AppendEntriesBatchTest() : _payloads(std::get<1>(GetParam())) {
*_optionsMock = std::get<0>(GetParam());
}
std::vector<LogPayload> const _payloads{};
};
TEST_P(AppendEntriesBatchTest, test_with_sized_batches) {
auto expectedNumRequests = size_t{0};
// AppendEntries CommitIndex
expectedNumRequests++;
// AppendEntries LCI
expectedNumRequests++;
// If the payload has more than one entry, decrement lastAckedIndex to 0
if (_payloads.size() > 1) {
expectedNumRequests += 1;
}
auto leaderLog = std::invoke([&] {
auto persistedLog = makePersistedLog(LogId{1});
for (auto [idx, payload] : enumerate(_payloads)) {
persistedLog->setEntry(LogIndex{idx + 1}, LogTerm{4}, payload);
}
/*
* Compute the number of requests we expect to be generating;
* this is slightly dissatisfying as we're re-implementing the
* algorithm used for batching, but there is no closed formula
* for this
*/
auto it = persistedLog->read(LogIndex{1});
auto numRequests = size_t{0};
auto currentSize = size_t{0};
while (auto log = it->next()) {
currentSize += log->approxByteSize();
if (currentSize >= _optionsMock->_thresholdNetworkBatchSize) {
numRequests += 1;
currentSize = 0;
}
}
{
// Add first entry in term
currentSize += PersistingLogEntry{LogTerm{5}, LogIndex{1}, std::nullopt}.approxByteSize();
if (currentSize >= _optionsMock->_thresholdNetworkBatchSize) {
numRequests += 1;
currentSize = 0;
}
}
// Some pending entries still need to be submitted
if (currentSize > 0) {
numRequests += 1;
}
expectedNumRequests += numRequests;
return std::make_shared<TestReplicatedLog>(std::make_unique<LogCore>(persistedLog),
_logMetricsMock, _optionsMock,
LoggerContext(Logger::REPLICATION2));
});
auto followerLog = makeReplicatedLog(LogId{1});
auto follower = followerLog->becomeFollower("follower", LogTerm{5}, "leader");
auto leader = leaderLog->becomeLeader("leader", LogTerm{5}, {follower}, 2);
{
if (_payloads.size() > 0) {
auto stats = std::get<LeaderStatus>(leader->getStatus().getVariant());
EXPECT_EQ(stats.local.spearHead,
TermIndexPair(LogTerm{5}, LogIndex{_payloads.size() + 1}));
EXPECT_EQ(stats.local.commitIndex, LogIndex{0});
EXPECT_EQ(stats.follower.at("follower").spearHead.index,
LogIndex{_payloads.size() - 1});
} else {
// TODO:
}
}
{
auto stats = std::get<FollowerStatus>(follower->getStatus().getVariant());
EXPECT_EQ(stats.local.spearHead.index, LogIndex{0});
EXPECT_EQ(stats.local.commitIndex, LogIndex{0});
}
leader->triggerAsyncReplication();
ASSERT_TRUE(follower->hasPendingAppendEntries());
{
std::size_t num_requests = 0;
while (follower->hasPendingAppendEntries()) {
follower->runAsyncAppendEntries();
num_requests += 1;
}
EXPECT_EQ(num_requests, expectedNumRequests);
}
{
auto stats = std::get<LeaderStatus>(leader->getStatus().getVariant());
EXPECT_EQ(stats.local.spearHead.index, LogIndex{_payloads.size() + 1});
EXPECT_EQ(stats.local.commitIndex, LogIndex{_payloads.size() + 1});
}
{
auto stats = std::get<FollowerStatus>(follower->getStatus().getVariant());
EXPECT_EQ(stats.local.spearHead.index, LogIndex{_payloads.size() + 1});
EXPECT_EQ(stats.local.commitIndex, LogIndex{_payloads.size() + 1});
}
}
auto testReplicatedLogOptions =
testing::Values(ReplicatedLogGlobalSettings{5, 5}, ReplicatedLogGlobalSettings{1024, 1024},
ReplicatedLogGlobalSettings{1024 * 1024, 1024 * 1024});
auto testPayloads = testing::Values(
std::vector<LogPayload>{LogPayload::createFromString("a")},
std::vector<LogPayload>{LogPayload::createFromString("a"),
LogPayload::createFromString("b")},
std::vector<LogPayload>{LogPayload::createFromString(std::string(1024, 'a'))},
std::vector<LogPayload>{LogPayload::createFromString("Hello, world"),
LogPayload::createFromString("Bye, world")},
std::vector<LogPayload>(1024, LogPayload::createFromString("")),
std::vector<LogPayload>{LogPayload::createFromString(std::string(1024, 'a')),
LogPayload::createFromString("Hello, world"),
LogPayload::createFromString("Bye, world")},
std::vector<LogPayload>(1024, LogPayload::createFromString(std::string(1024, 'a'))));
// Use a sequence of payload of pre-defined sizes and send them;
// count the number of batches that are created.
INSTANTIATE_TEST_CASE_P(AppendEntriesBatchTestInstance, AppendEntriesBatchTest,
testing::Combine(testReplicatedLogOptions, testPayloads));
<|endoftext|> |
<commit_before>/*
* The MIT License
*
* Copyright 2017-2018 Norwegian University of Technology
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <fmicpp/fmi2/import/CoSimulationSlave.hpp>
#include "AbstractFmuInstance.cpp"
using namespace std;
using namespace fmicpp::fmi2::import;
CoSimulationSlave::CoSimulationSlave(const shared_ptr<CoSimulationModelDescription> modelDescription, const shared_ptr<CoSimulationLibrary> library)
: AbstractFmuInstance<CoSimulationLibrary, CoSimulationModelDescription>(modelDescription, library) {}
fmi2Status CoSimulationSlave::doStep(const double stepSize) {
fmi2Status status = library_->doStep(c_, simulationTime_, stepSize, false);
if (status == fmi2OK) {
simulationTime_ += stepSize;
}
return status;
}
fmi2Status CoSimulationSlave::cancelStep() {
return library_->cancelStep(c_);
}
<commit_msg>remove .cpp include<commit_after>/*
* The MIT License
*
* Copyright 2017-2018 Norwegian University of Technology
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <fmicpp/fmi2/import/CoSimulationSlave.hpp>
using namespace std;
using namespace fmicpp::fmi2::import;
CoSimulationSlave::CoSimulationSlave(const shared_ptr<CoSimulationModelDescription> modelDescription, const shared_ptr<CoSimulationLibrary> library)
: AbstractFmuInstance<CoSimulationLibrary, CoSimulationModelDescription>(modelDescription, library) {}
fmi2Status CoSimulationSlave::doStep(const double stepSize) {
fmi2Status status = library_->doStep(c_, simulationTime_, stepSize, false);
if (status == fmi2OK) {
simulationTime_ += stepSize;
}
return status;
}
fmi2Status CoSimulationSlave::cancelStep() {
return library_->cancelStep(c_);
}
<|endoftext|> |
<commit_before>
extern "C" {
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
}
#include "php_mmseg.h"
#include <sys/stat.h>
using namespace std;
// SegmenterManager
ZEND_DECLARE_MODULE_GLOBALS(mmseg)
/* True global resources - no need for thread safety here */
static int le_mmseg;
/* {{{ mmseg_functions[]
*
* Every user visible function must have an entry in mmseg_functions[].
*/
const zend_function_entry mmseg_functions[] = {
PHP_FE(mmseg_segment, NULL)
PHP_FE(mmseg_open, NULL)
PHP_FE(mmseg_close, NULL)
PHP_FE(mmseg_gendict, NULL)
PHP_FE(mmseg_gensynonyms, NULL)
PHP_FE(mmseg_genthesaurus, NULL)
PHP_FE_END /* Must be the last line in mmseg_functions[] */
};
/* }}} */
/* {{{ mmseg_module_entry
*/
zend_module_entry mmseg_module_entry = {
#if ZEND_MODULE_API_NO >= 20010901
STANDARD_MODULE_HEADER,
#endif
"mmseg",
mmseg_functions,
PHP_MINIT(mmseg),
PHP_MSHUTDOWN(mmseg),
PHP_RINIT(mmseg), /* Replace with NULL if there's nothing to do at request start */
PHP_RSHUTDOWN(mmseg), /* Replace with NULL if there's nothing to do at request end */
PHP_MINFO(mmseg),
#if ZEND_MODULE_API_NO >= 20010901
"0.1", /* Replace with version number for your extension */
#endif
STANDARD_MODULE_PROPERTIES
};
/* }}} */
#ifdef COMPILE_DL_MMSEG
BEGIN_EXTERN_C()
ZEND_GET_MODULE(mmseg)
END_EXTERN_C()
#endif
/* {{{ PHP_INI
*/
PHP_INI_BEGIN()
// setting the path of the dictionary
PHP_INI_ENTRY("mmseg.dict_dir", "/opt/etc", PHP_INI_ALL, NULL)
PHP_INI_ENTRY("mmseg.autoreload", "1", PHP_INI_ALL, NULL)
PHP_INI_END()
/* }}} */
/* {{{ php_mmseg_init_globals
*/
/*
static void php_mmseg_init_globals(zend_mmseg_globals *mmseg_globals)
{
mmseg_globals->dict_dir = NULL;
}
*/
/* }}} */
/* Triggered at the beginning of a thread */
static void php_mmseg_globals_ctor(zend_mmseg_globals *mmseg_globals TSRMLS_DC)
{
struct stat st;
SegmenterManager* mgr = (SegmenterManager*) mmseg_globals->mgr;
mgr = new SegmenterManager();
int nRet = 0;
mmseg_globals->dict_mtime = 0;
nRet = mgr->init(INI_STR("mmseg.dict_dir"));
if (nRet == 0) {
mmseg_globals->mgr = (void*) mgr;
// 记录最后一次字典文件更改的数值
string dict_file_path;
dict_file_path = INI_STR("mmseg.dict_dir");
dict_file_path.append("/uni.lib");
if (stat(dict_file_path.c_str(), &st) == 0) {
mmseg_globals->dict_mtime = st.st_mtime;
MMSEG_LOG(ctime(&st.st_mtime));
}
MMSEG_LOG("minit load dictionary");
return ;
} else {
if (mgr != NULL) {
delete mgr;
mgr = NULL;
}
mmseg_globals->mgr = NULL;
return ;
}
}
/* Triggered at the end of a thread */
static void php_mmseg_globals_dtor(zend_mmseg_globals *mmseg_globals TSRMLS_DC)
{
SegmenterManager* mgr = (SegmenterManager*) mmseg_globals->mgr;
if (mgr != NULL) {
delete mgr;
mgr = NULL;
}
}
// mmseg segmenter manager句柄
static int le_mmseg_descriptor;
// mmseg 句柄的dtor函数
static void php_mmseg_descriptor_dtor(zend_rsrc_list_entry *rsrc TSRMLS_DC)
{
SegmenterManager *mgr = (SegmenterManager*)rsrc->ptr;
if (mgr != NULL) {
delete mgr;
mgr = NULL;
}
}
/* {{{ PHP_MINIT_FUNCTION
*/
PHP_MINIT_FUNCTION(mmseg)
{
REGISTER_INI_ENTRIES();
// 初始化mmseg资源句柄
le_mmseg_descriptor = zend_register_list_destructors_ex(php_mmseg_descriptor_dtor, NULL, PHP_MMSEG_DESCRIPTOR_RES_NAME,module_number);
// 初始化,如果初始化失败,则返回失败信息,(XXX: 未来将改变为如果初始化失败, 可以在程序里面调用init初始化)
#ifdef ZTS
ts_allocate_id(&mmseg_globals_id, sizeof(zend_mmseg_globals),
php_mmseg_globals_ctor, php_mmseg_globals_dtor);
#else
php_mmseg_globals_ctor(&mmseg_globals TSRMLS_CC);
#endif
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MSHUTDOWN_FUNCTION
*/
PHP_MSHUTDOWN_FUNCTION(mmseg)
{
UNREGISTER_INI_ENTRIES();
#ifndef ZTS
php_mmseg_globals_dtor(&mmseg_globals TSRMLS_CC);
#endif
return SUCCESS;
}
/* }}} */
/* Remove if there's nothing to do at request start */
/* {{{ PHP_RINIT_FUNCTION
*/
PHP_RINIT_FUNCTION(mmseg)
{
return SUCCESS;
}
/* }}} */
/* Remove if there's nothing to do at request end */
/* {{{ PHP_RSHUTDOWN_FUNCTION
*/
PHP_RSHUTDOWN_FUNCTION(mmseg)
{
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MINFO_FUNCTION
*/
PHP_MINFO_FUNCTION(mmseg)
{
php_info_print_table_start();
php_info_print_table_header(2, "mmseg support", "enabled");
php_info_print_table_end();
DISPLAY_INI_ENTRIES();
}
/* }}} */
/* The previous line is meant for vim and emacs, so it can correctly fold and
unfold functions in source code. See the corresponding marks just before
function definition, where the functions purpose is also documented. Please
follow this convention for the convenience of others editing your code.
*/
/* {{{ proto array mmseg_segment(string content)
*/
PHP_FUNCTION(mmseg_segment)
{
char *content = NULL;
int argc = ZEND_NUM_ARGS();
int content_len;
SegmenterManager* mgr = NULL;
zval *mmseg_resource;
zend_bool autoreload = INI_BOOL("mmseg.autoreload");
// 判断传入参数的数量
if (argc == 1) {
struct stat st;
if (zend_parse_parameters(argc TSRMLS_CC, "s", &content, &content_len) == FAILURE)
return;
// 如果使用全局的字典文件,在这里看一下是否需要判断文件是否有改变
if (1 == autoreload) {
// 文件名
string dict_file_path;
dict_file_path = INI_STR("mmseg.dict_dir");
dict_file_path.append("/uni.lib");
if (stat(dict_file_path.c_str(), &st) == 0) {
if (st.st_mtime != MMSEG_G(dict_mtime)) {
MMSEG_G(dict_mtime) = st.st_mtime;
SegmenterManager* oldMgr = (SegmenterManager*)MMSEG_G(mgr);
SegmenterManager* newMgr;
newMgr = new SegmenterManager();
int nRet = 0;
nRet = newMgr->init(INI_STR("mmseg.dict_dir"));
if (nRet == 0) {
if (oldMgr) {
MMSEG_LOG("trying to delete old mgr");
delete oldMgr;
oldMgr = NULL;
}
MMSEG_LOG("load dictionary on change");
MMSEG_G(mgr) = newMgr;
} else {
// no change. still use oldMgr
MMSEG_LOG("no change, initialize new dict file failed");
newMgr = NULL;
}
} else {
MMSEG_LOG(ctime(&st.st_mtime));
MMSEG_LOG(ctime(&MMSEG_G(dict_mtime)));
MMSEG_LOG("no change, dict file no change");
// no change, still use old oldMgr
}
} else {
MMSEG_LOG("no change, stat new dict file failed");
}
} else {
MMSEG_LOG("no change, autoreload not set");
}
} else if (argc = 2){
if (zend_parse_parameters(argc TSRMLS_CC, "rs", &mmseg_resource, &content, &content_len) == FAILURE)
return;
ZEND_FETCH_RESOURCE(mgr,SegmenterManager*,&mmseg_resource,-1,PHP_MMSEG_DESCRIPTOR_RES_NAME,le_mmseg_descriptor);
} else {
return;
}
mgr = (SegmenterManager*) MMSEG_G(mgr);
if (mgr == NULL) {
RETURN_NULL();
}
Segmenter* seg = mgr->getSegmenter();
u4 content_length = content_len;
seg->setBuffer((u1*)content, content_length);
array_init(return_value);
while(1)
{
u2 len = 0, symlen = 0;
char* tok = (char*)seg->peekToken(len,symlen);
if(!tok || !*tok || !len){
break;
}
//append new item
add_next_index_stringl(return_value, tok, len, 1);
seg->popToken(len);
}
return ;
}
/* }}} */
PHP_FUNCTION(mmseg_open)
{
char *path = NULL;
int argc = ZEND_NUM_ARGS();
int path_len;
if (zend_parse_parameters(argc TSRMLS_CC, "s", &path, &path_len) == FAILURE)
return;
// 生成新的对象
SegmenterManager* mgr = new SegmenterManager();
int nRet = 0;
nRet = mgr->init(path);
if (nRet == 0) {
// 注册这个资源
ZEND_REGISTER_RESOURCE(return_value,mgr,le_mmseg_descriptor);
} else {
RETURN_NULL();
}
}
PHP_FUNCTION(mmseg_close)
{
zval *mmseg_resource;
SegmenterManager* mgr;
int argc = ZEND_NUM_ARGS();
if (zend_parse_parameters(argc TSRMLS_CC, "r", &mmseg_resource) == FAILURE)
return;
ZEND_FETCH_RESOURCE(mgr,SegmenterManager*,&mmseg_resource,-1,PHP_MMSEG_DESCRIPTOR_RES_NAME,le_mmseg_descriptor);
zend_hash_index_del(&EG(regular_list),Z_RESVAL_P(mmseg_resource));
RETURN_TRUE;
}
// 字典的生成
PHP_FUNCTION(mmseg_gendict)
{
int argc = ZEND_NUM_ARGS();
char *path = NULL;
int path_len;
char *target = NULL;
int target_len;
zend_bool b_plainText = 0;
if (zend_parse_parameters(argc TSRMLS_CC, "ss", &path, &path_len, &target, &target_len) == FAILURE)
return;
UnigramCorpusReader ur;
ur.open(path,b_plainText?"plain":NULL);
UnigramDict ud;
int ret = ud.import(ur);
ud.save(target);
//check
int i = 0;
for(i=0;i<ur.count();i++)
{
UnigramRecord* rec = ur.getAt(i);
if(ud.exactMatch(rec->key.c_str()) == rec->count){
continue;
}else{
RETURN_FALSE;
}
}//end for
RETURN_TRUE;
}
// 特殊短语字典的生成
PHP_FUNCTION(mmseg_gensynonyms)
{
int argc = ZEND_NUM_ARGS();
char *path = NULL;
int path_len;
char *target = NULL;
int target_len;
zend_bool b_plainText = 0;
if (zend_parse_parameters(argc TSRMLS_CC, "ss", &path, &path_len, &target, &target_len) == FAILURE)
return;
SynonymsDict dict;
dict.import(path);
if(target)
dict.save(target);
else
dict.save("synonyms.dat");
RETURN_TRUE;
}
// 同义词词典的生成
PHP_FUNCTION(mmseg_genthesaurus)
{
int argc = ZEND_NUM_ARGS();
char *path = NULL;
int path_len;
char *target = NULL;
int target_len;
zend_bool b_plainText = 0;
if (zend_parse_parameters(argc TSRMLS_CC, "ss", &path, &path_len, &target, &target_len) == FAILURE)
return;
ThesaurusDict tdict;
tdict.import(path, target);
RETURN_TRUE;
}
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
<commit_msg>update verison to 0.2<commit_after>
extern "C" {
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
}
#include "php_mmseg.h"
#include <sys/stat.h>
using namespace std;
// SegmenterManager
ZEND_DECLARE_MODULE_GLOBALS(mmseg)
/* True global resources - no need for thread safety here */
static int le_mmseg;
/* {{{ mmseg_functions[]
*
* Every user visible function must have an entry in mmseg_functions[].
*/
const zend_function_entry mmseg_functions[] = {
PHP_FE(mmseg_segment, NULL)
PHP_FE(mmseg_open, NULL)
PHP_FE(mmseg_close, NULL)
PHP_FE(mmseg_gendict, NULL)
PHP_FE(mmseg_gensynonyms, NULL)
PHP_FE(mmseg_genthesaurus, NULL)
PHP_FE_END /* Must be the last line in mmseg_functions[] */
};
/* }}} */
/* {{{ mmseg_module_entry
*/
zend_module_entry mmseg_module_entry = {
#if ZEND_MODULE_API_NO >= 20010901
STANDARD_MODULE_HEADER,
#endif
"mmseg",
mmseg_functions,
PHP_MINIT(mmseg),
PHP_MSHUTDOWN(mmseg),
PHP_RINIT(mmseg), /* Replace with NULL if there's nothing to do at request start */
PHP_RSHUTDOWN(mmseg), /* Replace with NULL if there's nothing to do at request end */
PHP_MINFO(mmseg),
#if ZEND_MODULE_API_NO >= 20010901
"0.2", /* Replace with version number for your extension */
#endif
STANDARD_MODULE_PROPERTIES
};
/* }}} */
#ifdef COMPILE_DL_MMSEG
BEGIN_EXTERN_C()
ZEND_GET_MODULE(mmseg)
END_EXTERN_C()
#endif
/* {{{ PHP_INI
*/
PHP_INI_BEGIN()
// setting the path of the dictionary
PHP_INI_ENTRY("mmseg.dict_dir", "/opt/etc", PHP_INI_ALL, NULL)
PHP_INI_ENTRY("mmseg.autoreload", "1", PHP_INI_ALL, NULL)
PHP_INI_END()
/* }}} */
/* {{{ php_mmseg_init_globals
*/
/*
static void php_mmseg_init_globals(zend_mmseg_globals *mmseg_globals)
{
mmseg_globals->dict_dir = NULL;
}
*/
/* }}} */
/* Triggered at the beginning of a thread */
static void php_mmseg_globals_ctor(zend_mmseg_globals *mmseg_globals TSRMLS_DC)
{
struct stat st;
SegmenterManager* mgr = (SegmenterManager*) mmseg_globals->mgr;
mgr = new SegmenterManager();
int nRet = 0;
mmseg_globals->dict_mtime = 0;
nRet = mgr->init(INI_STR("mmseg.dict_dir"));
if (nRet == 0) {
mmseg_globals->mgr = (void*) mgr;
// 记录最后一次字典文件更改的数值
string dict_file_path;
dict_file_path = INI_STR("mmseg.dict_dir");
dict_file_path.append("/uni.lib");
if (stat(dict_file_path.c_str(), &st) == 0) {
mmseg_globals->dict_mtime = st.st_mtime;
MMSEG_LOG(ctime(&st.st_mtime));
}
MMSEG_LOG("minit load dictionary");
return ;
} else {
if (mgr != NULL) {
delete mgr;
mgr = NULL;
}
mmseg_globals->mgr = NULL;
return ;
}
}
/* Triggered at the end of a thread */
static void php_mmseg_globals_dtor(zend_mmseg_globals *mmseg_globals TSRMLS_DC)
{
SegmenterManager* mgr = (SegmenterManager*) mmseg_globals->mgr;
if (mgr != NULL) {
delete mgr;
mgr = NULL;
}
}
// mmseg segmenter manager句柄
static int le_mmseg_descriptor;
// mmseg 句柄的dtor函数
static void php_mmseg_descriptor_dtor(zend_rsrc_list_entry *rsrc TSRMLS_DC)
{
SegmenterManager *mgr = (SegmenterManager*)rsrc->ptr;
if (mgr != NULL) {
delete mgr;
mgr = NULL;
}
}
/* {{{ PHP_MINIT_FUNCTION
*/
PHP_MINIT_FUNCTION(mmseg)
{
REGISTER_INI_ENTRIES();
// 初始化mmseg资源句柄
le_mmseg_descriptor = zend_register_list_destructors_ex(php_mmseg_descriptor_dtor, NULL, PHP_MMSEG_DESCRIPTOR_RES_NAME,module_number);
// 初始化,如果初始化失败,则返回失败信息,(XXX: 未来将改变为如果初始化失败, 可以在程序里面调用init初始化)
#ifdef ZTS
ts_allocate_id(&mmseg_globals_id, sizeof(zend_mmseg_globals),
php_mmseg_globals_ctor, php_mmseg_globals_dtor);
#else
php_mmseg_globals_ctor(&mmseg_globals TSRMLS_CC);
#endif
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MSHUTDOWN_FUNCTION
*/
PHP_MSHUTDOWN_FUNCTION(mmseg)
{
UNREGISTER_INI_ENTRIES();
#ifndef ZTS
php_mmseg_globals_dtor(&mmseg_globals TSRMLS_CC);
#endif
return SUCCESS;
}
/* }}} */
/* Remove if there's nothing to do at request start */
/* {{{ PHP_RINIT_FUNCTION
*/
PHP_RINIT_FUNCTION(mmseg)
{
return SUCCESS;
}
/* }}} */
/* Remove if there's nothing to do at request end */
/* {{{ PHP_RSHUTDOWN_FUNCTION
*/
PHP_RSHUTDOWN_FUNCTION(mmseg)
{
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MINFO_FUNCTION
*/
PHP_MINFO_FUNCTION(mmseg)
{
php_info_print_table_start();
php_info_print_table_header(2, "mmseg support", "enabled");
php_info_print_table_end();
DISPLAY_INI_ENTRIES();
}
/* }}} */
/* The previous line is meant for vim and emacs, so it can correctly fold and
unfold functions in source code. See the corresponding marks just before
function definition, where the functions purpose is also documented. Please
follow this convention for the convenience of others editing your code.
*/
/* {{{ proto array mmseg_segment(string content)
*/
PHP_FUNCTION(mmseg_segment)
{
char *content = NULL;
int argc = ZEND_NUM_ARGS();
int content_len;
SegmenterManager* mgr = NULL;
zval *mmseg_resource;
zend_bool autoreload = INI_BOOL("mmseg.autoreload");
// 判断传入参数的数量
if (argc == 1) {
struct stat st;
if (zend_parse_parameters(argc TSRMLS_CC, "s", &content, &content_len) == FAILURE)
return;
// 如果使用全局的字典文件,在这里看一下是否需要判断文件是否有改变
if (1 == autoreload) {
// 文件名
string dict_file_path;
dict_file_path = INI_STR("mmseg.dict_dir");
dict_file_path.append("/uni.lib");
if (stat(dict_file_path.c_str(), &st) == 0) {
if (st.st_mtime != MMSEG_G(dict_mtime)) {
MMSEG_G(dict_mtime) = st.st_mtime;
SegmenterManager* oldMgr = (SegmenterManager*)MMSEG_G(mgr);
SegmenterManager* newMgr;
newMgr = new SegmenterManager();
int nRet = 0;
nRet = newMgr->init(INI_STR("mmseg.dict_dir"));
if (nRet == 0) {
if (oldMgr) {
MMSEG_LOG("trying to delete old mgr");
delete oldMgr;
oldMgr = NULL;
}
MMSEG_LOG("load dictionary on change");
MMSEG_G(mgr) = newMgr;
} else {
// no change. still use oldMgr
MMSEG_LOG("no change, initialize new dict file failed");
newMgr = NULL;
}
} else {
MMSEG_LOG(ctime(&st.st_mtime));
MMSEG_LOG(ctime(&MMSEG_G(dict_mtime)));
MMSEG_LOG("no change, dict file no change");
// no change, still use old oldMgr
}
} else {
MMSEG_LOG("no change, stat new dict file failed");
}
} else {
MMSEG_LOG("no change, autoreload not set");
}
} else if (argc = 2){
if (zend_parse_parameters(argc TSRMLS_CC, "rs", &mmseg_resource, &content, &content_len) == FAILURE)
return;
ZEND_FETCH_RESOURCE(mgr,SegmenterManager*,&mmseg_resource,-1,PHP_MMSEG_DESCRIPTOR_RES_NAME,le_mmseg_descriptor);
} else {
return;
}
mgr = (SegmenterManager*) MMSEG_G(mgr);
if (mgr == NULL) {
RETURN_NULL();
}
Segmenter* seg = mgr->getSegmenter();
u4 content_length = content_len;
seg->setBuffer((u1*)content, content_length);
array_init(return_value);
while(1)
{
u2 len = 0, symlen = 0;
char* tok = (char*)seg->peekToken(len,symlen);
if(!tok || !*tok || !len){
break;
}
//append new item
add_next_index_stringl(return_value, tok, len, 1);
seg->popToken(len);
}
return ;
}
/* }}} */
PHP_FUNCTION(mmseg_open)
{
char *path = NULL;
int argc = ZEND_NUM_ARGS();
int path_len;
if (zend_parse_parameters(argc TSRMLS_CC, "s", &path, &path_len) == FAILURE)
return;
// 生成新的对象
SegmenterManager* mgr = new SegmenterManager();
int nRet = 0;
nRet = mgr->init(path);
if (nRet == 0) {
// 注册这个资源
ZEND_REGISTER_RESOURCE(return_value,mgr,le_mmseg_descriptor);
} else {
RETURN_NULL();
}
}
PHP_FUNCTION(mmseg_close)
{
zval *mmseg_resource;
SegmenterManager* mgr;
int argc = ZEND_NUM_ARGS();
if (zend_parse_parameters(argc TSRMLS_CC, "r", &mmseg_resource) == FAILURE)
return;
ZEND_FETCH_RESOURCE(mgr,SegmenterManager*,&mmseg_resource,-1,PHP_MMSEG_DESCRIPTOR_RES_NAME,le_mmseg_descriptor);
zend_hash_index_del(&EG(regular_list),Z_RESVAL_P(mmseg_resource));
RETURN_TRUE;
}
// 字典的生成
PHP_FUNCTION(mmseg_gendict)
{
int argc = ZEND_NUM_ARGS();
char *path = NULL;
int path_len;
char *target = NULL;
int target_len;
zend_bool b_plainText = 0;
if (zend_parse_parameters(argc TSRMLS_CC, "ss", &path, &path_len, &target, &target_len) == FAILURE)
return;
UnigramCorpusReader ur;
ur.open(path,b_plainText?"plain":NULL);
UnigramDict ud;
int ret = ud.import(ur);
ud.save(target);
//check
int i = 0;
for(i=0;i<ur.count();i++)
{
UnigramRecord* rec = ur.getAt(i);
if(ud.exactMatch(rec->key.c_str()) == rec->count){
continue;
}else{
RETURN_FALSE;
}
}//end for
RETURN_TRUE;
}
// 特殊短语字典的生成
PHP_FUNCTION(mmseg_gensynonyms)
{
int argc = ZEND_NUM_ARGS();
char *path = NULL;
int path_len;
char *target = NULL;
int target_len;
zend_bool b_plainText = 0;
if (zend_parse_parameters(argc TSRMLS_CC, "ss", &path, &path_len, &target, &target_len) == FAILURE)
return;
SynonymsDict dict;
dict.import(path);
if(target)
dict.save(target);
else
dict.save("synonyms.dat");
RETURN_TRUE;
}
// 同义词词典的生成
PHP_FUNCTION(mmseg_genthesaurus)
{
int argc = ZEND_NUM_ARGS();
char *path = NULL;
int path_len;
char *target = NULL;
int target_len;
zend_bool b_plainText = 0;
if (zend_parse_parameters(argc TSRMLS_CC, "ss", &path, &path_len, &target, &target_len) == FAILURE)
return;
ThesaurusDict tdict;
tdict.import(path, target);
RETURN_TRUE;
}
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
<|endoftext|> |
<commit_before>#ifndef ITERBASE_HPP_
#define ITERBASE_HPP_
// This file consists of utilities used for the generic nature of the
// iterable wrapper classes. As such, the contents of this file should be
// considered UNDOCUMENTED and is subject to change without warning. This
// also applies to the name of the file. No user code should include
// this file directly.
#include <utility>
#include <tuple>
#include <iterator>
#include <functional>
#include <memory>
#include <type_traits>
#include <cstddef>
namespace iter {
// iterator_type<C> is the type of C's iterator
template <typename Container>
using iterator_type =
decltype(std::begin(std::declval<Container&>()));
// iterator_deref<C> is the type obtained by dereferencing an iterator
// to an object of type C
template <typename Container>
using iterator_deref =
decltype(*std::declval<iterator_type<Container>&>());
template <typename Container>
using iterator_traits_deref =
std::remove_reference_t<iterator_deref<Container>>;
// iterator_type<C> is the type of C's iterator
template <typename Container>
using reverse_iterator_type =
decltype(std::declval<Container&>().rbegin());
// iterator_deref<C> is the type obtained by dereferencing an iterator
// to an object of type C
template <typename Container>
using reverse_iterator_deref =
decltype(*std::declval<reverse_iterator_type<Container>&>());
template <typename, typename =void>
struct is_random_access_iter : std::false_type { };
template <typename T>
struct is_random_access_iter<T,
std::enable_if_t<
std::is_same<
typename std::iterator_traits<T>::iterator_category,
std::random_access_iterator_tag>::value
>> : std::true_type { };
template <typename T>
using has_random_access_iter = is_random_access_iter<iterator_type<T>>;
// because std::advance assumes a lot and is actually smart, I need a dumb
// version that will work with most things
template <typename InputIt, typename Distance =std::size_t>
void dumb_advance(InputIt& iter, Distance distance=1) {
for (Distance i(0); i < distance; ++i) {
++iter;
}
}
template <typename Iter, typename Distance>
void dumb_advance_impl(Iter& iter, const Iter& end,
Distance distance, std::false_type) {
for (Distance i(0); i < distance && iter != end; ++i) {
++iter;
}
}
template <typename Iter, typename Distance>
void dumb_advance_impl(Iter& iter, const Iter& end,
Distance distance, std::true_type) {
if (static_cast<Distance>(end - iter) < distance) {
iter = end;
} else {
iter += distance;
}
}
// iter will not be incremented past end
template <typename Iter, typename Distance =std::size_t>
void dumb_advance(Iter& iter, const Iter& end, Distance distance=1) {
dumb_advance_impl(iter, end, distance, is_random_access_iter<Iter>{});
}
template <typename ForwardIt, typename Distance =std::size_t>
ForwardIt dumb_next(ForwardIt it, Distance distance=1) {
dumb_advance(it, distance);
return it;
}
template <typename ForwardIt, typename Distance =std::size_t>
ForwardIt dumb_next(
ForwardIt it, const ForwardIt& end, Distance distance=1) {
dumb_advance(it, end, distance);
return it;
}
template <typename Container, typename Distance =std::size_t>
Distance dumb_size(Container&& container) {
Distance d{0};
for (auto it = std::begin(container), end = std::end(container);
it != end;
++it) {
++d;
}
return d;
}
template <typename... Ts>
struct are_same : std::true_type { };
template <typename T, typename U, typename... Ts>
struct are_same<T, U, Ts...>
: std::integral_constant<bool,
std::is_same<T, U>::value && are_same<T, Ts...>::value> { };
namespace detail {
template <typename... Ts>
std::tuple<iterator_type<Ts>...> iterator_tuple_type_helper(
const std::tuple<Ts...>&);
}
// Given a tuple template argument, evaluates to a tuple of iterators
// for the template argument's contained types.
template <typename TupleType>
using iterator_tuple_type =
decltype(detail::iterator_tuple_type_helper(
std::declval<TupleType>()));
namespace detail {
template <typename... Ts>
std::tuple<iterator_deref<Ts>...> iterator_tuple_deref_helper(
const std::tuple<Ts...>&);
}
// Given a tuple template argument, evaluates to a tuple of
// what the iterators for the template argument's contained types
// dereference to
template <typename TupleType>
using iterator_deref_tuple =
decltype(detail::iterator_tuple_deref_helper(
std::declval<TupleType>()));
// ---- Tuple utilities ---- //
// function absorbing all arguments passed to it. used when
// applying a function to a parameter pack but not passing the evaluated
// results anywhere
template <typename... Ts>
void absorb(Ts&&...) { }
namespace detail {
template <typename Func, typename TupleType, std::size_t... Is>
decltype(auto) call_with_tuple_impl(Func&& mf, TupleType&& tup,
std::index_sequence<Is...>) {
return mf(std::get<Is>(tup)...);
}
}
// expand a TupleType into individual arguments when calling a Func
template <typename Func, typename TupleType>
decltype(auto) call_with_tuple(Func&& mf, TupleType&& tup) {
constexpr auto TUP_SIZE = std::tuple_size<
std::decay_t<TupleType>>::value;
return detail::call_with_tuple_impl(
std::forward<Func>(mf),
std::forward<TupleType>(tup),
std::make_index_sequence<TUP_SIZE>{});
}
// DerefHolder holds the value gotten from an iterator dereference
// if the iterate dereferences to an lvalue references, a pointer to the
// element is stored
// if it does not, a value is stored instead
// get() returns a reference to the held item in either case
// pull() should be used when the item is being "pulled out" of the
// DerefHolder. after pull() is called, neither it nor get() can be
// safely called after
// reset() replaces the currently held item and may be called after pull()
template <typename T, typename =void>
class DerefHolder {
private:
static_assert(!std::is_lvalue_reference<T>::value,
"Non-lvalue-ref specialization used for lvalue ref type");
// it could still be an rvalue reference
using TPlain = typename std::remove_reference<T>::type;
std::unique_ptr<TPlain> item_p;
public:
DerefHolder() = default;
DerefHolder(const DerefHolder& other)
: item_p{other.item_p ? new TPlain(*other.item_p) : nullptr}
{ }
DerefHolder& operator=(const DerefHolder& other) {
this->item_p.reset(other.item_p
? new TPlain(*other.item_p) : nullptr);
return *this;
}
DerefHolder(DerefHolder&&) = default;
DerefHolder& operator=(DerefHolder&&) = default;
~DerefHolder() = default;
TPlain& get() {
return *item_p;
}
T pull() {
// NOTE should I reset the unique_ptr to nullptr here
// since its held item is now invalid anyway?
return std::move(*item_p);
}
void reset(T&& item) {
item_p.reset(new TPlain(std::move(item)));
}
explicit operator bool() const {
return this->item_p;
}
};
// Specialization for when T is an lvalue ref. Keep this in mind
// wherever a T appears.
template <typename T>
class DerefHolder<T,
typename std::enable_if<std::is_lvalue_reference<T>::value>::type>
{
private:
static_assert(std::is_lvalue_reference<T>::value,
"lvalue specialization handling non-lvalue-ref type");
typename std::remove_reference<T>::type *item_p =nullptr;
public:
DerefHolder() = default;
T get() {
return *this->item_p;
}
T pull() {
return this->get();
}
void reset(T item) {
this->item_p = &item;
}
explicit operator bool() const {
return this->item_p != nullptr;
}
};
}
#endif
<commit_msg>forwards the tuple elements to the called function<commit_after>#ifndef ITERBASE_HPP_
#define ITERBASE_HPP_
// This file consists of utilities used for the generic nature of the
// iterable wrapper classes. As such, the contents of this file should be
// considered UNDOCUMENTED and is subject to change without warning. This
// also applies to the name of the file. No user code should include
// this file directly.
#include <utility>
#include <tuple>
#include <iterator>
#include <functional>
#include <memory>
#include <type_traits>
#include <cstddef>
namespace iter {
// iterator_type<C> is the type of C's iterator
template <typename Container>
using iterator_type =
decltype(std::begin(std::declval<Container&>()));
// iterator_deref<C> is the type obtained by dereferencing an iterator
// to an object of type C
template <typename Container>
using iterator_deref =
decltype(*std::declval<iterator_type<Container>&>());
template <typename Container>
using iterator_traits_deref =
std::remove_reference_t<iterator_deref<Container>>;
// iterator_type<C> is the type of C's iterator
template <typename Container>
using reverse_iterator_type =
decltype(std::declval<Container&>().rbegin());
// iterator_deref<C> is the type obtained by dereferencing an iterator
// to an object of type C
template <typename Container>
using reverse_iterator_deref =
decltype(*std::declval<reverse_iterator_type<Container>&>());
template <typename, typename =void>
struct is_random_access_iter : std::false_type { };
template <typename T>
struct is_random_access_iter<T,
std::enable_if_t<
std::is_same<
typename std::iterator_traits<T>::iterator_category,
std::random_access_iterator_tag>::value
>> : std::true_type { };
template <typename T>
using has_random_access_iter = is_random_access_iter<iterator_type<T>>;
// because std::advance assumes a lot and is actually smart, I need a dumb
// version that will work with most things
template <typename InputIt, typename Distance =std::size_t>
void dumb_advance(InputIt& iter, Distance distance=1) {
for (Distance i(0); i < distance; ++i) {
++iter;
}
}
template <typename Iter, typename Distance>
void dumb_advance_impl(Iter& iter, const Iter& end,
Distance distance, std::false_type) {
for (Distance i(0); i < distance && iter != end; ++i) {
++iter;
}
}
template <typename Iter, typename Distance>
void dumb_advance_impl(Iter& iter, const Iter& end,
Distance distance, std::true_type) {
if (static_cast<Distance>(end - iter) < distance) {
iter = end;
} else {
iter += distance;
}
}
// iter will not be incremented past end
template <typename Iter, typename Distance =std::size_t>
void dumb_advance(Iter& iter, const Iter& end, Distance distance=1) {
dumb_advance_impl(iter, end, distance, is_random_access_iter<Iter>{});
}
template <typename ForwardIt, typename Distance =std::size_t>
ForwardIt dumb_next(ForwardIt it, Distance distance=1) {
dumb_advance(it, distance);
return it;
}
template <typename ForwardIt, typename Distance =std::size_t>
ForwardIt dumb_next(
ForwardIt it, const ForwardIt& end, Distance distance=1) {
dumb_advance(it, end, distance);
return it;
}
template <typename Container, typename Distance =std::size_t>
Distance dumb_size(Container&& container) {
Distance d{0};
for (auto it = std::begin(container), end = std::end(container);
it != end;
++it) {
++d;
}
return d;
}
template <typename... Ts>
struct are_same : std::true_type { };
template <typename T, typename U, typename... Ts>
struct are_same<T, U, Ts...>
: std::integral_constant<bool,
std::is_same<T, U>::value && are_same<T, Ts...>::value> { };
namespace detail {
template <typename... Ts>
std::tuple<iterator_type<Ts>...> iterator_tuple_type_helper(
const std::tuple<Ts...>&);
}
// Given a tuple template argument, evaluates to a tuple of iterators
// for the template argument's contained types.
template <typename TupleType>
using iterator_tuple_type =
decltype(detail::iterator_tuple_type_helper(
std::declval<TupleType>()));
namespace detail {
template <typename... Ts>
std::tuple<iterator_deref<Ts>...> iterator_tuple_deref_helper(
const std::tuple<Ts...>&);
}
// Given a tuple template argument, evaluates to a tuple of
// what the iterators for the template argument's contained types
// dereference to
template <typename TupleType>
using iterator_deref_tuple =
decltype(detail::iterator_tuple_deref_helper(
std::declval<TupleType>()));
// ---- Tuple utilities ---- //
// function absorbing all arguments passed to it. used when
// applying a function to a parameter pack but not passing the evaluated
// results anywhere
template <typename... Ts>
void absorb(Ts&&...) { }
namespace detail {
template <typename Func, typename TupleType, std::size_t... Is>
decltype(auto) call_with_tuple_impl(Func&& mf, TupleType&& tup,
std::index_sequence<Is...>) {
return mf(std::forward<
std::tuple_element_t<
Is, std::remove_reference_t<TupleType>>
>(std::get<Is>(tup))...);
}
}
// expand a TupleType into individual arguments when calling a Func
template <typename Func, typename TupleType>
decltype(auto) call_with_tuple(Func&& mf, TupleType&& tup) {
constexpr auto TUP_SIZE = std::tuple_size<
std::decay_t<TupleType>>::value;
return detail::call_with_tuple_impl(
std::forward<Func>(mf),
std::forward<TupleType>(tup),
std::make_index_sequence<TUP_SIZE>{});
}
// DerefHolder holds the value gotten from an iterator dereference
// if the iterate dereferences to an lvalue references, a pointer to the
// element is stored
// if it does not, a value is stored instead
// get() returns a reference to the held item in either case
// pull() should be used when the item is being "pulled out" of the
// DerefHolder. after pull() is called, neither it nor get() can be
// safely called after
// reset() replaces the currently held item and may be called after pull()
template <typename T, typename =void>
class DerefHolder {
private:
static_assert(!std::is_lvalue_reference<T>::value,
"Non-lvalue-ref specialization used for lvalue ref type");
// it could still be an rvalue reference
using TPlain = typename std::remove_reference<T>::type;
std::unique_ptr<TPlain> item_p;
public:
DerefHolder() = default;
DerefHolder(const DerefHolder& other)
: item_p{other.item_p ? new TPlain(*other.item_p) : nullptr}
{ }
DerefHolder& operator=(const DerefHolder& other) {
this->item_p.reset(other.item_p
? new TPlain(*other.item_p) : nullptr);
return *this;
}
DerefHolder(DerefHolder&&) = default;
DerefHolder& operator=(DerefHolder&&) = default;
~DerefHolder() = default;
TPlain& get() {
return *item_p;
}
T pull() {
// NOTE should I reset the unique_ptr to nullptr here
// since its held item is now invalid anyway?
return std::move(*item_p);
}
void reset(T&& item) {
item_p.reset(new TPlain(std::move(item)));
}
explicit operator bool() const {
return this->item_p;
}
};
// Specialization for when T is an lvalue ref. Keep this in mind
// wherever a T appears.
template <typename T>
class DerefHolder<T,
typename std::enable_if<std::is_lvalue_reference<T>::value>::type>
{
private:
static_assert(std::is_lvalue_reference<T>::value,
"lvalue specialization handling non-lvalue-ref type");
typename std::remove_reference<T>::type *item_p =nullptr;
public:
DerefHolder() = default;
T get() {
return *this->item_p;
}
T pull() {
return this->get();
}
void reset(T item) {
this->item_p = &item;
}
explicit operator bool() const {
return this->item_p != nullptr;
}
};
}
#endif
<|endoftext|> |
<commit_before>#include <cstdlib>
#include <cstring>
#include <vector>
#include <glog/logging.h>
#include "merkletree/merkle_tree.h"
#include "_cgo_export.h"
#include "merkle_tree_go.h"
extern "C" {
// Some hollow functions to cast the void* types into what they really are,
// they're only really here to provide a little bit of type safety.
// Hopefully these should all be optimized away into oblivion by the compiler.
inline MerkleTree* MT(TREE tree) {
return static_cast<MerkleTree*>(CHECK_NOTNULL(tree));
}
inline Sha256Hasher* H(HASHER hasher) {
return static_cast<Sha256Hasher*>(CHECK_NOTNULL(hasher));
}
inline GoSlice* BS(BYTE_SLICE slice) {
return static_cast<GoSlice*>(CHECK_NOTNULL(slice));
}
HASHER NewSha256Hasher() {
return new Sha256Hasher;
}
TREE NewMerkleTree(HASHER hasher) {
return new MerkleTree(H(hasher));
}
void DeleteMerkleTree(TREE tree) {
delete MT(tree);
}
size_t NodeSize(TREE tree) {
return MT(tree)->NodeSize();
}
size_t LeafCount(TREE tree) {
return MT(tree)->LeafCount();
}
bool LeafHash(TREE tree, BYTE_SLICE out, size_t leaf) {
GoSlice* slice(BS(out));
const MerkleTree* t(MT(tree));
const size_t nodesize(t->NodeSize());
if (slice->data == NULL || slice->cap < nodesize) {
return false;
}
const std::string& hash = t->LeafHash(leaf);
CHECK_EQ(nodesize, hash.size());
memcpy(slice->data, hash.data(), nodesize);
slice->len = nodesize;
return true;
}
size_t LevelCount(TREE tree) {
const MerkleTree* t(MT(tree));
return t->LevelCount();
}
size_t AddLeaf(TREE tree, BYTE_SLICE leaf) {
GoSlice* slice(BS(leaf));
MerkleTree* t(MT(tree));
return t->AddLeaf(std::string(static_cast<char*>(slice->data), slice->len));
}
size_t AddLeafHash(TREE tree, BYTE_SLICE hash) {
GoSlice* slice(BS(hash));
MerkleTree* t(MT(tree));
return t->AddLeafHash(
std::string(static_cast<char*>(slice->data), slice->len));
}
bool CurrentRoot(TREE tree, BYTE_SLICE out) {
GoSlice* slice(BS(out));
MerkleTree *t(MT(tree));
const size_t nodesize(t->NodeSize());
if (slice->data == NULL || slice->len != nodesize) {
return false;
}
const std::string& hash = t->CurrentRoot();
CHECK_EQ(nodesize, hash.size());
memcpy(slice->data, hash.data(), nodesize);
slice->len = nodesize;
return true;
}
bool RootAtSnapshot(TREE tree, BYTE_SLICE out, size_t snapshot) {
GoSlice* slice(BS(out));
MerkleTree *t(MT(tree));
const size_t nodesize(t->NodeSize());
if (slice->data == NULL || slice->len != nodesize) {
return false;
}
const std::string& hash = t->RootAtSnapshot(snapshot);
CHECK_EQ(nodesize, hash.size());
memcpy(slice->data, hash.data(), nodesize);
slice->len = nodesize;
return true;
}
// Copies the fixed-length entries from |path| into the GoSlice pointed to by
// |dst|, one after the other in the same order.
// |num_copied| is set to the number of entries copied.
bool CopyNodesToSlice(const std::vector<std::string>& path, GoSlice* dst,
size_t nodesize, size_t* num_copied) {
CHECK_NOTNULL(dst);
CHECK_NOTNULL(num_copied);
if (dst->cap < path.size() * nodesize) {
*num_copied = 0;
return false;
}
char *e = static_cast<char*>(dst->data);
for (int i = 0; i < path.size(); ++i) {
CHECK_EQ(nodesize, path[i].size());
memcpy(e, path[i].data(), nodesize);
e += nodesize;
}
dst->len = path.size() * nodesize;
*num_copied = path.size();
return true;
}
bool PathToCurrentRoot(TREE tree, BYTE_SLICE out, size_t* num_entries, size_t leaf) {
MerkleTree *t(MT(tree));
const std::vector<std::string> path = t->PathToCurrentRoot(leaf);
return CopyNodesToSlice(path, BS(out), t->NodeSize(), num_entries);
}
bool PathToRootAtSnapshot(TREE tree, BYTE_SLICE out, size_t* num_entries, size_t leaf, size_t snapshot) {
MerkleTree *t(MT(tree));
const std::vector<std::string> path = t->PathToRootAtSnapshot(leaf, snapshot);
return CopyNodesToSlice(path, BS(out), t->NodeSize(), num_entries);
}
bool SnapshotConsistency(TREE tree, BYTE_SLICE out, size_t* num_entries, size_t snapshot1, size_t snapshot2) {
MerkleTree *t(MT(tree));
const std::vector<std::string> path = t->SnapshotConsistency(snapshot1, snapshot2);
return CopyNodesToSlice(path, BS(out), t->NodeSize(), num_entries);
}
} // extern "C"
<commit_msg>Clean up #include ordering and add missing ones.<commit_after>#include "merkletree/merkle_tree.h"
#include <cstdlib>
#include <cstring>
#include <vector>
#include <glog/logging.h>
#include "_cgo_export.h"
#include "merkle_tree_go.h"
extern "C" {
// Some hollow functions to cast the void* types into what they really are,
// they're only really here to provide a little bit of type safety.
// Hopefully these should all be optimized away into oblivion by the compiler.
inline MerkleTree* MT(TREE tree) {
return static_cast<MerkleTree*>(CHECK_NOTNULL(tree));
}
inline Sha256Hasher* H(HASHER hasher) {
return static_cast<Sha256Hasher*>(CHECK_NOTNULL(hasher));
}
inline GoSlice* BS(BYTE_SLICE slice) {
return static_cast<GoSlice*>(CHECK_NOTNULL(slice));
}
HASHER NewSha256Hasher() {
return new Sha256Hasher;
}
TREE NewMerkleTree(HASHER hasher) {
return new MerkleTree(H(hasher));
}
void DeleteMerkleTree(TREE tree) {
delete MT(tree);
}
size_t NodeSize(TREE tree) {
return MT(tree)->NodeSize();
}
size_t LeafCount(TREE tree) {
return MT(tree)->LeafCount();
}
bool LeafHash(TREE tree, BYTE_SLICE out, size_t leaf) {
GoSlice* slice(BS(out));
const MerkleTree* t(MT(tree));
const size_t nodesize(t->NodeSize());
if (slice->data == NULL || slice->cap < nodesize) {
return false;
}
const std::string& hash = t->LeafHash(leaf);
CHECK_EQ(nodesize, hash.size());
memcpy(slice->data, hash.data(), nodesize);
slice->len = nodesize;
return true;
}
size_t LevelCount(TREE tree) {
const MerkleTree* t(MT(tree));
return t->LevelCount();
}
size_t AddLeaf(TREE tree, BYTE_SLICE leaf) {
GoSlice* slice(BS(leaf));
MerkleTree* t(MT(tree));
return t->AddLeaf(std::string(static_cast<char*>(slice->data), slice->len));
}
size_t AddLeafHash(TREE tree, BYTE_SLICE hash) {
GoSlice* slice(BS(hash));
MerkleTree* t(MT(tree));
return t->AddLeafHash(
std::string(static_cast<char*>(slice->data), slice->len));
}
bool CurrentRoot(TREE tree, BYTE_SLICE out) {
GoSlice* slice(BS(out));
MerkleTree *t(MT(tree));
const size_t nodesize(t->NodeSize());
if (slice->data == NULL || slice->len != nodesize) {
return false;
}
const std::string& hash = t->CurrentRoot();
CHECK_EQ(nodesize, hash.size());
memcpy(slice->data, hash.data(), nodesize);
slice->len = nodesize;
return true;
}
bool RootAtSnapshot(TREE tree, BYTE_SLICE out, size_t snapshot) {
GoSlice* slice(BS(out));
MerkleTree *t(MT(tree));
const size_t nodesize(t->NodeSize());
if (slice->data == NULL || slice->len != nodesize) {
return false;
}
const std::string& hash = t->RootAtSnapshot(snapshot);
CHECK_EQ(nodesize, hash.size());
memcpy(slice->data, hash.data(), nodesize);
slice->len = nodesize;
return true;
}
// Copies the fixed-length entries from |path| into the GoSlice pointed to by
// |dst|, one after the other in the same order.
// |num_copied| is set to the number of entries copied.
bool CopyNodesToSlice(const std::vector<std::string>& path, GoSlice* dst,
size_t nodesize, size_t* num_copied) {
CHECK_NOTNULL(dst);
CHECK_NOTNULL(num_copied);
if (dst->cap < path.size() * nodesize) {
*num_copied = 0;
return false;
}
char *e = static_cast<char*>(dst->data);
for (int i = 0; i < path.size(); ++i) {
CHECK_EQ(nodesize, path[i].size());
memcpy(e, path[i].data(), nodesize);
e += nodesize;
}
dst->len = path.size() * nodesize;
*num_copied = path.size();
return true;
}
bool PathToCurrentRoot(TREE tree, BYTE_SLICE out, size_t* num_entries, size_t leaf) {
MerkleTree *t(MT(tree));
const std::vector<std::string> path = t->PathToCurrentRoot(leaf);
return CopyNodesToSlice(path, BS(out), t->NodeSize(), num_entries);
}
bool PathToRootAtSnapshot(TREE tree, BYTE_SLICE out, size_t* num_entries, size_t leaf, size_t snapshot) {
MerkleTree *t(MT(tree));
const std::vector<std::string> path = t->PathToRootAtSnapshot(leaf, snapshot);
return CopyNodesToSlice(path, BS(out), t->NodeSize(), num_entries);
}
bool SnapshotConsistency(TREE tree, BYTE_SLICE out, size_t* num_entries, size_t snapshot1, size_t snapshot2) {
MerkleTree *t(MT(tree));
const std::vector<std::string> path = t->SnapshotConsistency(snapshot1, snapshot2);
return CopyNodesToSlice(path, BS(out), t->NodeSize(), num_entries);
}
} // extern "C"
<|endoftext|> |
<commit_before>// Copyright eeGeo Ltd (2012-2014), All Rights Reserved
#include "AppHost.h"
#include "AndroidWebRequestService.hpp"
#include "AndroidSharedGlContext.h"
#include "LatLongAltitude.h"
#include "EegeoWorld.h"
#include "RenderContext.h"
#include "GlobalLighting.h"
#include "GlobalFogging.h"
#include "AppInterface.h"
#include "JpegLoader.h"
#include "Blitter.h"
#include "EffectHandler.h"
#include "SearchServiceCredentials.h"
#include "AndroidThreadHelper.h"
#include "GlobeCameraController.h"
#include "RenderCamera.h"
#include "CameraHelpers.h"
#include "LoadingScreen.h"
#include "PlatformConfig.h"
#include "AndroidPlatformConfigBuilder.h"
#include "AndroidUrlEncoder.h"
#include "AndroidFileIO.h"
#include "AndroidLocationService.h"
#include "EegeoWorld.h"
#include "EnvironmentFlatteningService.h"
#include "TtyHandler.h"
#include "MenuViewModule.h"
#include "PrimaryMenuModule.h"
#include "SecondaryMenuModule.h"
#include "ModalityModule.h"
#include "ModalBackgroundViewModule.h"
#include "ModalBackgroundNativeViewModule.h"
#include "MenuModel.h"
#include "MenuViewModel.h"
#include "SearchResultMenuModule.h"
#include "MenuOptionsModel.h"
#include "SearchModule.h"
#include "SearchResultOnMapModule.h"
#include "WorldPinsModule.h"
#include "RegularTexturePageLayout.h"
#include "PinsModule.h"
#include "SearchResultRepository.h"
#include "LatLongAltitude.h"
#include "SearchResultPoiModule.h"
#include "AndroidPlatformAbstractionModule.h"
#include "FlattenButtonModule.h"
#include "FlattenButtonViewModule.h"
#include "SearchResultPoiViewModule.h"
#include "SearchResultOnMapViewModule.h"
#include "PlaceJumpsModule.h"
#include "IPlaceJumpController.h"
#include "SecondaryMenuViewModule.h"
#include "SearchMenuViewModule.h"
#include "CompassViewModule.h"
#include "CompassModule.h"
#include "AboutPageViewModule.h"
#include "AndroidInitialExperienceModule.h"
#include "ViewControllerUpdaterModule.h"
#include "ViewControllerUpdaterModel.h"
#include "IMenuViewController.h"
#include "CategorySearchModule.h"
#include "ScreenProperties.h"
#include "Logger.h"
#include "AndroidAppThreadAssertionMacros.h"
#include "SearchResultRepositoryObserver.h"
using namespace Eegeo::Android;
using namespace Eegeo::Android::Input;
AppHost::AppHost(
AndroidNativeState& nativeState,
float displayWidth,
float displayHeight,
EGLDisplay display,
EGLSurface shareSurface,
EGLContext resourceBuildShareContext
)
:m_isPaused(false)
,m_pJpegLoader(NULL)
,m_pScreenProperties(NULL)
,m_pAndroidLocationService(NULL)
,m_nativeState(nativeState)
,m_androidInputBoxFactory(&nativeState)
,m_androidKeyboardInputFactory(&nativeState, m_inputHandler)
,m_androidAlertBoxFactory(&nativeState)
,m_androidNativeUIFactories(m_androidAlertBoxFactory, m_androidInputBoxFactory, m_androidKeyboardInputFactory)
,m_pInputProcessor(NULL)
,m_pAndroidPlatformAbstractionModule(NULL)
,m_pPrimaryMenuViewModule(NULL)
,m_pSecondaryMenuViewModule(NULL)
,m_pSearchResultMenuViewModule(NULL)
,m_pModalBackgroundViewModule(NULL)
,m_pFlattenButtonViewModule(NULL)
,m_pSearchResultPoiViewModule(NULL)
,m_pSearchResultOnMapViewModule(NULL)
,m_pCompassViewModule(NULL)
,m_pApp(NULL)
,m_androidPersistentSettingsModel(nativeState)
,m_createdUIModules(false)
,m_requestedApplicationInitialiseViewState(false)
,m_uiCreatedMessageReceivedOnNativeThread(false)
,m_pViewControllerUpdaterModule(NULL)
{
ASSERT_NATIVE_THREAD
Eegeo_ASSERT(resourceBuildShareContext != EGL_NO_CONTEXT);
Eegeo::TtyHandler::TtyEnabled = true;
Eegeo::AssertHandler::BreakOnAssert = true;
m_pAndroidLocationService = Eegeo_NEW(AndroidLocationService)(&nativeState);
m_pScreenProperties = Eegeo_NEW(Eegeo::Rendering::ScreenProperties)(displayWidth, displayHeight, 1.0f, nativeState.deviceDpi);
m_pJpegLoader = Eegeo_NEW(Eegeo::Helpers::Jpeg::JpegLoader)();
std::set<std::string> customApplicationAssetDirectories;
customApplicationAssetDirectories.insert("SearchResultOnMap");
m_pAndroidPlatformAbstractionModule = Eegeo_NEW(Eegeo::Android::AndroidPlatformAbstractionModule)(
nativeState,
*m_pJpegLoader,
display,
resourceBuildShareContext,
shareSurface,
customApplicationAssetDirectories);
Eegeo::EffectHandler::Initialise();
std::string deviceModel = std::string(nativeState.deviceModel, strlen(nativeState.deviceModel));
Eegeo::Config::PlatformConfig platformConfig = Eegeo::Android::AndroidPlatformConfigBuilder(deviceModel).Build();
m_pInputProcessor = Eegeo_NEW(Eegeo::Android::Input::AndroidInputProcessor)(&m_inputHandler, m_pScreenProperties->GetScreenWidth(), m_pScreenProperties->GetScreenHeight());
m_pInitialExperienceModule = Eegeo_NEW(ExampleApp::InitialExperience::AndroidInitialExperienceModule)(
m_nativeState,
m_androidPersistentSettingsModel
);
m_pApp = Eegeo_NEW(ExampleApp::MobileExampleApp)(*m_pAndroidPlatformAbstractionModule,
*m_pScreenProperties,
*m_pAndroidLocationService,
m_androidNativeUIFactories,
platformConfig,
*m_pJpegLoader,
*m_pInitialExperienceModule,
m_uiToNativeMessageBus,
m_nativeToUiMessageBus);
m_pModalBackgroundNativeViewModule = Eegeo_NEW(ExampleApp::ModalBackground::ModalBackgroundNativeViewModule)(
m_pApp->World().GetRenderingModule(),
m_uiToNativeMessageBus
);
m_pAndroidPlatformAbstractionModule->SetWebRequestServiceWorkPool(m_pApp->World().GetWorkPool());
m_pAppInputDelegate = Eegeo_NEW(AppInputDelegate)(*m_pApp);
m_inputHandler.AddDelegateInputHandler(m_pAppInputDelegate);
}
AppHost::~AppHost()
{
ASSERT_NATIVE_THREAD
m_inputHandler.RemoveDelegateInputHandler(m_pAppInputDelegate);
Eegeo_DELETE m_pAppInputDelegate;
m_pAppInputDelegate = NULL;
Eegeo_DELETE m_pApp;
m_pApp = NULL;
Eegeo::EffectHandler::Reset();
Eegeo::EffectHandler::Shutdown();
Eegeo_DELETE m_pAndroidPlatformAbstractionModule;
m_pAndroidPlatformAbstractionModule = NULL;
Eegeo_DELETE m_pJpegLoader;
m_pJpegLoader = NULL;
Eegeo_DELETE m_pScreenProperties;
m_pScreenProperties = NULL;
Eegeo_DELETE m_pAndroidLocationService;
m_pAndroidLocationService = NULL;
}
void AppHost::OnResume()
{
ASSERT_NATIVE_THREAD
m_pApp->OnResume();
m_isPaused = false;
}
void AppHost::OnPause()
{
ASSERT_NATIVE_THREAD
m_isPaused = true;
m_pApp->OnPause();
m_pAndroidLocationService->StopListening();
}
void AppHost::SetSharedSurface(EGLSurface sharedSurface)
{
ASSERT_NATIVE_THREAD
m_pAndroidPlatformAbstractionModule->UpdateSurface(sharedSurface);
}
void AppHost::SetViewportOffset(float x, float y)
{
ASSERT_NATIVE_THREAD
m_inputHandler.SetViewportOffset(x, y);
}
void AppHost::HandleTouchInputEvent(const Eegeo::Android::Input::TouchInputEvent& event)
{
ASSERT_NATIVE_THREAD
m_pInputProcessor->HandleInput(event);
}
void AppHost::Update(float dt)
{
ASSERT_NATIVE_THREAD
if(m_isPaused)
{
return;
}
m_uiToNativeMessageBus.Flush();
m_pApp->Update(dt);
if(m_pApp->IsLoadingScreenComplete() && !m_requestedApplicationInitialiseViewState)
{
m_requestedApplicationInitialiseViewState = true;
DispatchRevealUiMessageToUiThreadFromNativeThread();
}
}
void AppHost::Draw(float dt)
{
ASSERT_NATIVE_THREAD
if(m_isPaused)
{
return;
}
m_pApp->Draw(dt);
m_pInputProcessor->Update(dt);
}
void AppHost::HandleApplicationUiCreatedOnNativeThread()
{
ASSERT_NATIVE_THREAD
m_uiCreatedMessageReceivedOnNativeThread = true;
}
void AppHost::DispatchRevealUiMessageToUiThreadFromNativeThread()
{
ASSERT_NATIVE_THREAD
AndroidSafeNativeThreadAttachment attached(m_nativeState);
JNIEnv* env = attached.envForThread;
jmethodID dispatchRevealUiMessageToUiThreadFromNativeThread = env->GetMethodID(m_nativeState.activityClass, "dispatchRevealUiMessageToUiThreadFromNativeThread", "(J)V");
env->CallVoidMethod(m_nativeState.activity, dispatchRevealUiMessageToUiThreadFromNativeThread, (jlong)(this));
}
void AppHost::DispatchUiCreatedMessageToNativeThreadFromUiThread()
{
ASSERT_UI_THREAD
AndroidSafeNativeThreadAttachment attached(m_nativeState);
JNIEnv* env = attached.envForThread;
jmethodID dispatchUiCreatedMessageToNativeThreadFromUiThread = env->GetMethodID(m_nativeState.activityClass, "dispatchUiCreatedMessageToNativeThreadFromUiThread", "(J)V");
env->CallVoidMethod(m_nativeState.activity, dispatchUiCreatedMessageToNativeThreadFromUiThread, (jlong)(this));
}
void AppHost::RevealUiFromUiThread()
{
ASSERT_UI_THREAD
m_pApp->InitialiseApplicationViewState();
}
void AppHost::CreateUiFromUiThread()
{
ASSERT_UI_THREAD
Eegeo_ASSERT(!m_createdUIModules);
CreateApplicationViewModulesFromUiThread();
DispatchUiCreatedMessageToNativeThreadFromUiThread();
}
void AppHost::UpdateUiViewsFromUiThread(float dt)
{
ASSERT_UI_THREAD
m_nativeToUiMessageBus.Flush();
if(m_createdUIModules)
{
m_pViewControllerUpdaterModule->GetViewControllerUpdaterModel().UpdateObjectsUiThread(dt);
}
else
{
CreateUiFromUiThread();
}
}
void AppHost::DestroyUiFromUiThread()
{
ASSERT_UI_THREAD
DestroyApplicationViewModulesFromUiThread();
}
void AppHost::CreateApplicationViewModulesFromUiThread()
{
ASSERT_UI_THREAD
m_createdUIModules = true;
ExampleApp::MobileExampleApp& app = *m_pApp;
// 3d map view layer.
m_pSearchResultOnMapViewModule = Eegeo_NEW(ExampleApp::SearchResultOnMap::SearchResultOnMapViewModule)(
m_nativeState,
app.SearchResultOnMapModule().GetSearchResultOnMapInFocusViewModel(),
app.SearchResultOnMapModule().GetScreenControlViewModel(),
app.SearchResultPoiModule().GetSearchResultPoiViewModel(),
app.PinDiameter()
);
// HUD behind modal background layer.
m_pFlattenButtonViewModule = Eegeo_NEW(ExampleApp::FlattenButton::FlattenButtonViewModule)(
m_nativeState,
app.FlattenButtonModule().GetFlattenButtonViewModel(),
m_uiToNativeMessageBus,
m_nativeToUiMessageBus
);
m_pCompassViewModule = Eegeo_NEW(ExampleApp::Compass::CompassViewModule)(
m_nativeState,
app.CompassModule().GetCompassViewModel(),
m_uiToNativeMessageBus,
m_nativeToUiMessageBus
);
// Modal background layer.
m_pModalBackgroundViewModule = Eegeo_NEW(ExampleApp::ModalBackground::ModalBackgroundViewModule)(
m_nativeState,
app.ModalityModule().GetModalityModel()
);
// Menus & HUD layer.
m_pPrimaryMenuViewModule = Eegeo_NEW(ExampleApp::Menu::MenuViewModule)(
"com/eegeo/primarymenu/PrimaryMenuView",
m_nativeState,
app.PrimaryMenuModule().GetPrimaryMenuModel(),
app.PrimaryMenuModule().GetPrimaryMenuViewModel()
);
m_pSecondaryMenuViewModule = Eegeo_NEW(ExampleApp::SecondaryMenu::SecondaryMenuViewModule)(
"com/eegeo/secondarymenu/SecondaryMenuView",
m_nativeState,
app.SecondaryMenuModule().GetSecondaryMenuModel(),
app.SecondaryMenuModule().GetSecondaryMenuViewModel(),
m_uiToNativeMessageBus,
m_nativeToUiMessageBus
);
m_pSearchResultMenuViewModule = Eegeo_NEW(ExampleApp::SearchMenu::SearchMenuViewModule)(
"com/eegeo/searchmenu/SearchMenuView",
m_nativeState,
app.SearchResultMenuModule().GetSearchResultMenuModel(),
app.SearchResultMenuModule().GetMenuViewModel(),
app.CategorySearchModule().GetCategorySearchRepository(),
app.SearchResultMenuModule().GetSearchResultMenuViewModel(),
m_uiToNativeMessageBus,
m_nativeToUiMessageBus
);
// Pop-up layer.
m_pSearchResultPoiViewModule = Eegeo_NEW(ExampleApp::SearchResultPoi::SearchResultPoiViewModule)(
m_nativeState,
app.SearchResultPoiModule().GetSearchResultPoiViewModel()
);
m_pAboutPageViewModule = Eegeo_NEW(ExampleApp::AboutPage::AboutPageViewModule)(
m_nativeState,
app.AboutPageModule().GetAboutPageModel(),
app.AboutPageModule().GetAboutPageViewModel()
);
m_pViewControllerUpdaterModule = Eegeo_NEW(ExampleApp::ViewControllerUpdater::ViewControllerUpdaterModule);
ExampleApp::ViewControllerUpdater::IViewControllerUpdaterModel& viewControllerUpdaterModel = m_pViewControllerUpdaterModule->GetViewControllerUpdaterModel();
viewControllerUpdaterModel.AddUpdateableObject(m_pPrimaryMenuViewModule->GetMenuViewController());
viewControllerUpdaterModel.AddUpdateableObject(m_pSecondaryMenuViewModule->GetMenuViewController());
viewControllerUpdaterModel.AddUpdateableObject(m_pSearchResultMenuViewModule->GetMenuViewController());
}
void AppHost::DestroyApplicationViewModulesFromUiThread()
{
ASSERT_UI_THREAD
if(m_createdUIModules)
{
Eegeo_DELETE m_pViewControllerUpdaterModule;
Eegeo_DELETE m_pFlattenButtonViewModule;
Eegeo_DELETE m_pAboutPageViewModule;
Eegeo_DELETE m_pSearchResultOnMapViewModule;
Eegeo_DELETE m_pSearchResultPoiViewModule;
Eegeo_DELETE m_pModalBackgroundViewModule;
Eegeo_DELETE m_pSearchResultMenuViewModule;
Eegeo_DELETE m_pSecondaryMenuViewModule;
Eegeo_DELETE m_pPrimaryMenuViewModule;
Eegeo_DELETE m_pCompassViewModule;
}
m_createdUIModules = false;
}
<commit_msg>Fix up Android wiring of MobileExampleApp<commit_after>// Copyright eeGeo Ltd (2012-2014), All Rights Reserved
#include "AppHost.h"
#include "AndroidWebRequestService.hpp"
#include "AndroidSharedGlContext.h"
#include "LatLongAltitude.h"
#include "EegeoWorld.h"
#include "RenderContext.h"
#include "GlobalLighting.h"
#include "GlobalFogging.h"
#include "AppInterface.h"
#include "JpegLoader.h"
#include "Blitter.h"
#include "EffectHandler.h"
#include "SearchServiceCredentials.h"
#include "AndroidThreadHelper.h"
#include "GlobeCameraController.h"
#include "RenderCamera.h"
#include "CameraHelpers.h"
#include "LoadingScreen.h"
#include "PlatformConfig.h"
#include "AndroidPlatformConfigBuilder.h"
#include "AndroidUrlEncoder.h"
#include "AndroidFileIO.h"
#include "AndroidLocationService.h"
#include "EegeoWorld.h"
#include "EnvironmentFlatteningService.h"
#include "TtyHandler.h"
#include "MenuViewModule.h"
#include "PrimaryMenuModule.h"
#include "SecondaryMenuModule.h"
#include "ModalityModule.h"
#include "ModalBackgroundViewModule.h"
#include "ModalBackgroundNativeViewModule.h"
#include "MenuModel.h"
#include "MenuViewModel.h"
#include "SearchResultMenuModule.h"
#include "MenuOptionsModel.h"
#include "SearchModule.h"
#include "SearchResultOnMapModule.h"
#include "WorldPinsModule.h"
#include "RegularTexturePageLayout.h"
#include "PinsModule.h"
#include "SearchResultRepository.h"
#include "LatLongAltitude.h"
#include "SearchResultPoiModule.h"
#include "AndroidPlatformAbstractionModule.h"
#include "FlattenButtonModule.h"
#include "FlattenButtonViewModule.h"
#include "SearchResultPoiViewModule.h"
#include "SearchResultOnMapViewModule.h"
#include "PlaceJumpsModule.h"
#include "IPlaceJumpController.h"
#include "SecondaryMenuViewModule.h"
#include "SearchMenuViewModule.h"
#include "CompassViewModule.h"
#include "CompassModule.h"
#include "AboutPageViewModule.h"
#include "AndroidInitialExperienceModule.h"
#include "ViewControllerUpdaterModule.h"
#include "ViewControllerUpdaterModel.h"
#include "IMenuViewController.h"
#include "CategorySearchModule.h"
#include "ScreenProperties.h"
#include "Logger.h"
#include "AndroidAppThreadAssertionMacros.h"
#include "SearchResultRepositoryObserver.h"
using namespace Eegeo::Android;
using namespace Eegeo::Android::Input;
AppHost::AppHost(
AndroidNativeState& nativeState,
float displayWidth,
float displayHeight,
EGLDisplay display,
EGLSurface shareSurface,
EGLContext resourceBuildShareContext
)
:m_isPaused(false)
,m_pJpegLoader(NULL)
,m_pScreenProperties(NULL)
,m_pAndroidLocationService(NULL)
,m_nativeState(nativeState)
,m_androidInputBoxFactory(&nativeState)
,m_androidKeyboardInputFactory(&nativeState, m_inputHandler)
,m_androidAlertBoxFactory(&nativeState)
,m_androidNativeUIFactories(m_androidAlertBoxFactory, m_androidInputBoxFactory, m_androidKeyboardInputFactory)
,m_pInputProcessor(NULL)
,m_pAndroidPlatformAbstractionModule(NULL)
,m_pPrimaryMenuViewModule(NULL)
,m_pSecondaryMenuViewModule(NULL)
,m_pSearchResultMenuViewModule(NULL)
,m_pModalBackgroundViewModule(NULL)
,m_pFlattenButtonViewModule(NULL)
,m_pSearchResultPoiViewModule(NULL)
,m_pSearchResultOnMapViewModule(NULL)
,m_pCompassViewModule(NULL)
,m_pApp(NULL)
,m_androidPersistentSettingsModel(nativeState)
,m_createdUIModules(false)
,m_requestedApplicationInitialiseViewState(false)
,m_uiCreatedMessageReceivedOnNativeThread(false)
,m_pViewControllerUpdaterModule(NULL)
{
ASSERT_NATIVE_THREAD
Eegeo_ASSERT(resourceBuildShareContext != EGL_NO_CONTEXT);
Eegeo::TtyHandler::TtyEnabled = true;
Eegeo::AssertHandler::BreakOnAssert = true;
m_pAndroidLocationService = Eegeo_NEW(AndroidLocationService)(&nativeState);
m_pScreenProperties = Eegeo_NEW(Eegeo::Rendering::ScreenProperties)(displayWidth, displayHeight, 1.0f, nativeState.deviceDpi);
m_pJpegLoader = Eegeo_NEW(Eegeo::Helpers::Jpeg::JpegLoader)();
std::set<std::string> customApplicationAssetDirectories;
customApplicationAssetDirectories.insert("SearchResultOnMap");
m_pAndroidPlatformAbstractionModule = Eegeo_NEW(Eegeo::Android::AndroidPlatformAbstractionModule)(
nativeState,
*m_pJpegLoader,
display,
resourceBuildShareContext,
shareSurface,
customApplicationAssetDirectories);
Eegeo::EffectHandler::Initialise();
std::string deviceModel = std::string(nativeState.deviceModel, strlen(nativeState.deviceModel));
Eegeo::Config::PlatformConfig platformConfig = Eegeo::Android::AndroidPlatformConfigBuilder(deviceModel).Build();
m_pInputProcessor = Eegeo_NEW(Eegeo::Android::Input::AndroidInputProcessor)(&m_inputHandler, m_pScreenProperties->GetScreenWidth(), m_pScreenProperties->GetScreenHeight());
m_pInitialExperienceModule = Eegeo_NEW(ExampleApp::InitialExperience::AndroidInitialExperienceModule)(
m_nativeState,
m_androidPersistentSettingsModel
);
m_pApp = Eegeo_NEW(ExampleApp::MobileExampleApp)(*m_pAndroidPlatformAbstractionModule,
*m_pScreenProperties,
*m_pAndroidLocationService,
m_androidNativeUIFactories,
platformConfig,
*m_pJpegLoader,
*m_pInitialExperienceModule,
m_androidPersistentSettingsModel,
m_uiToNativeMessageBus,
m_nativeToUiMessageBus);
m_pModalBackgroundNativeViewModule = Eegeo_NEW(ExampleApp::ModalBackground::ModalBackgroundNativeViewModule)(
m_pApp->World().GetRenderingModule(),
m_uiToNativeMessageBus
);
m_pAndroidPlatformAbstractionModule->SetWebRequestServiceWorkPool(m_pApp->World().GetWorkPool());
m_pAppInputDelegate = Eegeo_NEW(AppInputDelegate)(*m_pApp);
m_inputHandler.AddDelegateInputHandler(m_pAppInputDelegate);
}
AppHost::~AppHost()
{
ASSERT_NATIVE_THREAD
m_inputHandler.RemoveDelegateInputHandler(m_pAppInputDelegate);
Eegeo_DELETE m_pAppInputDelegate;
m_pAppInputDelegate = NULL;
Eegeo_DELETE m_pApp;
m_pApp = NULL;
Eegeo::EffectHandler::Reset();
Eegeo::EffectHandler::Shutdown();
Eegeo_DELETE m_pAndroidPlatformAbstractionModule;
m_pAndroidPlatformAbstractionModule = NULL;
Eegeo_DELETE m_pJpegLoader;
m_pJpegLoader = NULL;
Eegeo_DELETE m_pScreenProperties;
m_pScreenProperties = NULL;
Eegeo_DELETE m_pAndroidLocationService;
m_pAndroidLocationService = NULL;
}
void AppHost::OnResume()
{
ASSERT_NATIVE_THREAD
m_pApp->OnResume();
m_isPaused = false;
}
void AppHost::OnPause()
{
ASSERT_NATIVE_THREAD
m_isPaused = true;
m_pApp->OnPause();
m_pAndroidLocationService->StopListening();
}
void AppHost::SetSharedSurface(EGLSurface sharedSurface)
{
ASSERT_NATIVE_THREAD
m_pAndroidPlatformAbstractionModule->UpdateSurface(sharedSurface);
}
void AppHost::SetViewportOffset(float x, float y)
{
ASSERT_NATIVE_THREAD
m_inputHandler.SetViewportOffset(x, y);
}
void AppHost::HandleTouchInputEvent(const Eegeo::Android::Input::TouchInputEvent& event)
{
ASSERT_NATIVE_THREAD
m_pInputProcessor->HandleInput(event);
}
void AppHost::Update(float dt)
{
ASSERT_NATIVE_THREAD
if(m_isPaused)
{
return;
}
m_uiToNativeMessageBus.Flush();
m_pApp->Update(dt);
if(m_pApp->IsLoadingScreenComplete() && !m_requestedApplicationInitialiseViewState)
{
m_requestedApplicationInitialiseViewState = true;
DispatchRevealUiMessageToUiThreadFromNativeThread();
}
}
void AppHost::Draw(float dt)
{
ASSERT_NATIVE_THREAD
if(m_isPaused)
{
return;
}
m_pApp->Draw(dt);
m_pInputProcessor->Update(dt);
}
void AppHost::HandleApplicationUiCreatedOnNativeThread()
{
ASSERT_NATIVE_THREAD
m_uiCreatedMessageReceivedOnNativeThread = true;
}
void AppHost::DispatchRevealUiMessageToUiThreadFromNativeThread()
{
ASSERT_NATIVE_THREAD
AndroidSafeNativeThreadAttachment attached(m_nativeState);
JNIEnv* env = attached.envForThread;
jmethodID dispatchRevealUiMessageToUiThreadFromNativeThread = env->GetMethodID(m_nativeState.activityClass, "dispatchRevealUiMessageToUiThreadFromNativeThread", "(J)V");
env->CallVoidMethod(m_nativeState.activity, dispatchRevealUiMessageToUiThreadFromNativeThread, (jlong)(this));
}
void AppHost::DispatchUiCreatedMessageToNativeThreadFromUiThread()
{
ASSERT_UI_THREAD
AndroidSafeNativeThreadAttachment attached(m_nativeState);
JNIEnv* env = attached.envForThread;
jmethodID dispatchUiCreatedMessageToNativeThreadFromUiThread = env->GetMethodID(m_nativeState.activityClass, "dispatchUiCreatedMessageToNativeThreadFromUiThread", "(J)V");
env->CallVoidMethod(m_nativeState.activity, dispatchUiCreatedMessageToNativeThreadFromUiThread, (jlong)(this));
}
void AppHost::RevealUiFromUiThread()
{
ASSERT_UI_THREAD
m_pApp->InitialiseApplicationViewState();
}
void AppHost::CreateUiFromUiThread()
{
ASSERT_UI_THREAD
Eegeo_ASSERT(!m_createdUIModules);
CreateApplicationViewModulesFromUiThread();
DispatchUiCreatedMessageToNativeThreadFromUiThread();
}
void AppHost::UpdateUiViewsFromUiThread(float dt)
{
ASSERT_UI_THREAD
m_nativeToUiMessageBus.Flush();
if(m_createdUIModules)
{
m_pViewControllerUpdaterModule->GetViewControllerUpdaterModel().UpdateObjectsUiThread(dt);
}
else
{
CreateUiFromUiThread();
}
}
void AppHost::DestroyUiFromUiThread()
{
ASSERT_UI_THREAD
DestroyApplicationViewModulesFromUiThread();
}
void AppHost::CreateApplicationViewModulesFromUiThread()
{
ASSERT_UI_THREAD
m_createdUIModules = true;
ExampleApp::MobileExampleApp& app = *m_pApp;
// 3d map view layer.
m_pSearchResultOnMapViewModule = Eegeo_NEW(ExampleApp::SearchResultOnMap::SearchResultOnMapViewModule)(
m_nativeState,
app.SearchResultOnMapModule().GetSearchResultOnMapInFocusViewModel(),
app.SearchResultOnMapModule().GetScreenControlViewModel(),
app.SearchResultPoiModule().GetSearchResultPoiViewModel(),
app.PinDiameter()
);
// HUD behind modal background layer.
m_pFlattenButtonViewModule = Eegeo_NEW(ExampleApp::FlattenButton::FlattenButtonViewModule)(
m_nativeState,
app.FlattenButtonModule().GetFlattenButtonViewModel(),
m_uiToNativeMessageBus,
m_nativeToUiMessageBus
);
m_pCompassViewModule = Eegeo_NEW(ExampleApp::Compass::CompassViewModule)(
m_nativeState,
app.CompassModule().GetCompassViewModel(),
m_uiToNativeMessageBus,
m_nativeToUiMessageBus
);
// Modal background layer.
m_pModalBackgroundViewModule = Eegeo_NEW(ExampleApp::ModalBackground::ModalBackgroundViewModule)(
m_nativeState,
app.ModalityModule().GetModalityModel()
);
// Menus & HUD layer.
m_pPrimaryMenuViewModule = Eegeo_NEW(ExampleApp::Menu::MenuViewModule)(
"com/eegeo/primarymenu/PrimaryMenuView",
m_nativeState,
app.PrimaryMenuModule().GetPrimaryMenuModel(),
app.PrimaryMenuModule().GetPrimaryMenuViewModel()
);
m_pSecondaryMenuViewModule = Eegeo_NEW(ExampleApp::SecondaryMenu::SecondaryMenuViewModule)(
"com/eegeo/secondarymenu/SecondaryMenuView",
m_nativeState,
app.SecondaryMenuModule().GetSecondaryMenuModel(),
app.SecondaryMenuModule().GetSecondaryMenuViewModel(),
m_uiToNativeMessageBus,
m_nativeToUiMessageBus
);
m_pSearchResultMenuViewModule = Eegeo_NEW(ExampleApp::SearchMenu::SearchMenuViewModule)(
"com/eegeo/searchmenu/SearchMenuView",
m_nativeState,
app.SearchResultMenuModule().GetSearchResultMenuModel(),
app.SearchResultMenuModule().GetMenuViewModel(),
app.CategorySearchModule().GetCategorySearchRepository(),
app.SearchResultMenuModule().GetSearchResultMenuViewModel(),
m_uiToNativeMessageBus,
m_nativeToUiMessageBus
);
// Pop-up layer.
m_pSearchResultPoiViewModule = Eegeo_NEW(ExampleApp::SearchResultPoi::SearchResultPoiViewModule)(
m_nativeState,
app.SearchResultPoiModule().GetSearchResultPoiViewModel()
);
m_pAboutPageViewModule = Eegeo_NEW(ExampleApp::AboutPage::AboutPageViewModule)(
m_nativeState,
app.AboutPageModule().GetAboutPageModel(),
app.AboutPageModule().GetAboutPageViewModel()
);
m_pViewControllerUpdaterModule = Eegeo_NEW(ExampleApp::ViewControllerUpdater::ViewControllerUpdaterModule);
ExampleApp::ViewControllerUpdater::IViewControllerUpdaterModel& viewControllerUpdaterModel = m_pViewControllerUpdaterModule->GetViewControllerUpdaterModel();
viewControllerUpdaterModel.AddUpdateableObject(m_pPrimaryMenuViewModule->GetMenuViewController());
viewControllerUpdaterModel.AddUpdateableObject(m_pSecondaryMenuViewModule->GetMenuViewController());
viewControllerUpdaterModel.AddUpdateableObject(m_pSearchResultMenuViewModule->GetMenuViewController());
}
void AppHost::DestroyApplicationViewModulesFromUiThread()
{
ASSERT_UI_THREAD
if(m_createdUIModules)
{
Eegeo_DELETE m_pViewControllerUpdaterModule;
Eegeo_DELETE m_pFlattenButtonViewModule;
Eegeo_DELETE m_pAboutPageViewModule;
Eegeo_DELETE m_pSearchResultOnMapViewModule;
Eegeo_DELETE m_pSearchResultPoiViewModule;
Eegeo_DELETE m_pModalBackgroundViewModule;
Eegeo_DELETE m_pSearchResultMenuViewModule;
Eegeo_DELETE m_pSecondaryMenuViewModule;
Eegeo_DELETE m_pPrimaryMenuViewModule;
Eegeo_DELETE m_pCompassViewModule;
}
m_createdUIModules = false;
}
<|endoftext|> |
<commit_before>/*
* Copyright © 2010 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
/**
* \file lower_if_to_cond_assign.cpp
*
* This attempts to flatten if-statements to conditional assignments for
* GPUs with limited or no flow control support.
*
* It can't handle other control flow being inside of its block, such
* as calls or loops. Hopefully loop unrolling and inlining will take
* care of those.
*
* Drivers for GPUs with no control flow support should simply call
*
* lower_if_to_cond_assign(instructions)
*
* to attempt to flatten all if-statements.
*
* Some GPUs (such as i965 prior to gen6) do support control flow, but have a
* maximum nesting depth N. Drivers for such hardware can call
*
* lower_if_to_cond_assign(instructions, N)
*
* to attempt to flatten any if-statements appearing at depth > N.
*/
#include "glsl_types.h"
#include "ir.h"
#include "program/hash_table.h"
class ir_if_to_cond_assign_visitor : public ir_hierarchical_visitor {
public:
ir_if_to_cond_assign_visitor(unsigned max_depth)
{
this->progress = false;
this->max_depth = max_depth;
this->depth = 0;
this->condition_variables = hash_table_ctor(0, hash_table_pointer_hash,
hash_table_pointer_compare);
}
~ir_if_to_cond_assign_visitor()
{
hash_table_dtor(this->condition_variables);
}
ir_visitor_status visit_enter(ir_if *);
ir_visitor_status visit_leave(ir_if *);
bool progress;
unsigned max_depth;
unsigned depth;
struct hash_table *condition_variables;
};
bool
lower_if_to_cond_assign(exec_list *instructions, unsigned max_depth)
{
ir_if_to_cond_assign_visitor v(max_depth);
visit_list_elements(&v, instructions);
return v.progress;
}
void
check_control_flow(ir_instruction *ir, void *data)
{
bool *found_control_flow = (bool *)data;
switch (ir->ir_type) {
case ir_type_call:
case ir_type_discard:
case ir_type_loop:
case ir_type_loop_jump:
case ir_type_return:
*found_control_flow = true;
break;
default:
break;
}
}
void
move_block_to_cond_assign(void *mem_ctx,
ir_if *if_ir, ir_rvalue *cond_expr,
exec_list *instructions,
struct hash_table *ht)
{
foreach_list_safe(node, instructions) {
ir_instruction *ir = (ir_instruction *) node;
if (ir->ir_type == ir_type_assignment) {
ir_assignment *assign = (ir_assignment *)ir;
if (hash_table_find(ht, assign) == NULL) {
hash_table_insert(ht, assign, assign);
/* If the LHS of the assignment is a condition variable that was
* previously added, insert an additional assignment of false to
* the variable.
*/
const bool assign_to_cv =
hash_table_find(ht, assign->lhs->variable_referenced()) != NULL;
if (!assign->condition) {
if (assign_to_cv) {
assign->rhs =
new(mem_ctx) ir_expression(ir_binop_logic_and,
glsl_type::bool_type,
cond_expr->clone(mem_ctx, NULL),
assign->rhs);
} else {
assign->condition = cond_expr->clone(mem_ctx, NULL);
}
} else {
assign->condition =
new(mem_ctx) ir_expression(ir_binop_logic_and,
glsl_type::bool_type,
cond_expr->clone(mem_ctx, NULL),
assign->condition);
}
}
}
/* Now, move from the if block to the block surrounding it. */
ir->remove();
if_ir->insert_before(ir);
}
}
ir_visitor_status
ir_if_to_cond_assign_visitor::visit_enter(ir_if *ir)
{
(void) ir;
this->depth++;
return visit_continue;
}
ir_visitor_status
ir_if_to_cond_assign_visitor::visit_leave(ir_if *ir)
{
/* Only flatten when beyond the GPU's maximum supported nesting depth. */
if (this->depth-- <= this->max_depth)
return visit_continue;
bool found_control_flow = false;
ir_assignment *assign;
ir_dereference_variable *deref;
/* Check that both blocks don't contain anything we can't support. */
foreach_iter(exec_list_iterator, then_iter, ir->then_instructions) {
ir_instruction *then_ir = (ir_instruction *)then_iter.get();
visit_tree(then_ir, check_control_flow, &found_control_flow);
}
foreach_iter(exec_list_iterator, else_iter, ir->else_instructions) {
ir_instruction *else_ir = (ir_instruction *)else_iter.get();
visit_tree(else_ir, check_control_flow, &found_control_flow);
}
if (found_control_flow)
return visit_continue;
void *mem_ctx = ralloc_parent(ir);
/* Store the condition to a variable. Move all of the instructions from
* the then-clause of the if-statement. Use the condition variable as a
* condition for all assignments.
*/
ir_variable *const then_var =
new(mem_ctx) ir_variable(glsl_type::bool_type,
"if_to_cond_assign_then",
ir_var_temporary);
ir->insert_before(then_var);
ir_dereference_variable *then_cond =
new(mem_ctx) ir_dereference_variable(then_var);
assign = new(mem_ctx) ir_assignment(then_cond, ir->condition);
ir->insert_before(assign);
move_block_to_cond_assign(mem_ctx, ir, then_cond,
&ir->then_instructions,
this->condition_variables);
/* Add the new condition variable to the hash table. This allows us to
* find this variable when lowering other (enclosing) if-statements.
*/
hash_table_insert(this->condition_variables, then_var, then_var);
/* If there are instructions in the else-clause, store the inverse of the
* condition to a variable. Move all of the instructions from the
* else-clause if the if-statement. Use the (inverse) condition variable
* as a condition for all assignments.
*/
if (!ir->else_instructions.is_empty()) {
ir_variable *const else_var =
new(mem_ctx) ir_variable(glsl_type::bool_type,
"if_to_cond_assign_else",
ir_var_temporary);
ir->insert_before(else_var);
ir_dereference_variable *else_cond =
new(mem_ctx) ir_dereference_variable(else_var);
ir_rvalue *inverse =
new(mem_ctx) ir_expression(ir_unop_logic_not,
then_cond->clone(mem_ctx, NULL));
assign = new(mem_ctx) ir_assignment(else_cond, inverse);
ir->insert_before(assign);
move_block_to_cond_assign(mem_ctx, ir, else_cond,
&ir->else_instructions,
this->condition_variables);
/* Add the new condition variable to the hash table. This allows us to
* find this variable when lowering other (enclosing) if-statements.
*/
hash_table_insert(this->condition_variables, else_var, else_var);
}
ir->remove();
this->progress = true;
return visit_continue;
}
<commit_msg>glsl: Remove unused variable.<commit_after>/*
* Copyright © 2010 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
/**
* \file lower_if_to_cond_assign.cpp
*
* This attempts to flatten if-statements to conditional assignments for
* GPUs with limited or no flow control support.
*
* It can't handle other control flow being inside of its block, such
* as calls or loops. Hopefully loop unrolling and inlining will take
* care of those.
*
* Drivers for GPUs with no control flow support should simply call
*
* lower_if_to_cond_assign(instructions)
*
* to attempt to flatten all if-statements.
*
* Some GPUs (such as i965 prior to gen6) do support control flow, but have a
* maximum nesting depth N. Drivers for such hardware can call
*
* lower_if_to_cond_assign(instructions, N)
*
* to attempt to flatten any if-statements appearing at depth > N.
*/
#include "glsl_types.h"
#include "ir.h"
#include "program/hash_table.h"
class ir_if_to_cond_assign_visitor : public ir_hierarchical_visitor {
public:
ir_if_to_cond_assign_visitor(unsigned max_depth)
{
this->progress = false;
this->max_depth = max_depth;
this->depth = 0;
this->condition_variables = hash_table_ctor(0, hash_table_pointer_hash,
hash_table_pointer_compare);
}
~ir_if_to_cond_assign_visitor()
{
hash_table_dtor(this->condition_variables);
}
ir_visitor_status visit_enter(ir_if *);
ir_visitor_status visit_leave(ir_if *);
bool progress;
unsigned max_depth;
unsigned depth;
struct hash_table *condition_variables;
};
bool
lower_if_to_cond_assign(exec_list *instructions, unsigned max_depth)
{
ir_if_to_cond_assign_visitor v(max_depth);
visit_list_elements(&v, instructions);
return v.progress;
}
void
check_control_flow(ir_instruction *ir, void *data)
{
bool *found_control_flow = (bool *)data;
switch (ir->ir_type) {
case ir_type_call:
case ir_type_discard:
case ir_type_loop:
case ir_type_loop_jump:
case ir_type_return:
*found_control_flow = true;
break;
default:
break;
}
}
void
move_block_to_cond_assign(void *mem_ctx,
ir_if *if_ir, ir_rvalue *cond_expr,
exec_list *instructions,
struct hash_table *ht)
{
foreach_list_safe(node, instructions) {
ir_instruction *ir = (ir_instruction *) node;
if (ir->ir_type == ir_type_assignment) {
ir_assignment *assign = (ir_assignment *)ir;
if (hash_table_find(ht, assign) == NULL) {
hash_table_insert(ht, assign, assign);
/* If the LHS of the assignment is a condition variable that was
* previously added, insert an additional assignment of false to
* the variable.
*/
const bool assign_to_cv =
hash_table_find(ht, assign->lhs->variable_referenced()) != NULL;
if (!assign->condition) {
if (assign_to_cv) {
assign->rhs =
new(mem_ctx) ir_expression(ir_binop_logic_and,
glsl_type::bool_type,
cond_expr->clone(mem_ctx, NULL),
assign->rhs);
} else {
assign->condition = cond_expr->clone(mem_ctx, NULL);
}
} else {
assign->condition =
new(mem_ctx) ir_expression(ir_binop_logic_and,
glsl_type::bool_type,
cond_expr->clone(mem_ctx, NULL),
assign->condition);
}
}
}
/* Now, move from the if block to the block surrounding it. */
ir->remove();
if_ir->insert_before(ir);
}
}
ir_visitor_status
ir_if_to_cond_assign_visitor::visit_enter(ir_if *ir)
{
(void) ir;
this->depth++;
return visit_continue;
}
ir_visitor_status
ir_if_to_cond_assign_visitor::visit_leave(ir_if *ir)
{
/* Only flatten when beyond the GPU's maximum supported nesting depth. */
if (this->depth-- <= this->max_depth)
return visit_continue;
bool found_control_flow = false;
ir_assignment *assign;
/* Check that both blocks don't contain anything we can't support. */
foreach_iter(exec_list_iterator, then_iter, ir->then_instructions) {
ir_instruction *then_ir = (ir_instruction *)then_iter.get();
visit_tree(then_ir, check_control_flow, &found_control_flow);
}
foreach_iter(exec_list_iterator, else_iter, ir->else_instructions) {
ir_instruction *else_ir = (ir_instruction *)else_iter.get();
visit_tree(else_ir, check_control_flow, &found_control_flow);
}
if (found_control_flow)
return visit_continue;
void *mem_ctx = ralloc_parent(ir);
/* Store the condition to a variable. Move all of the instructions from
* the then-clause of the if-statement. Use the condition variable as a
* condition for all assignments.
*/
ir_variable *const then_var =
new(mem_ctx) ir_variable(glsl_type::bool_type,
"if_to_cond_assign_then",
ir_var_temporary);
ir->insert_before(then_var);
ir_dereference_variable *then_cond =
new(mem_ctx) ir_dereference_variable(then_var);
assign = new(mem_ctx) ir_assignment(then_cond, ir->condition);
ir->insert_before(assign);
move_block_to_cond_assign(mem_ctx, ir, then_cond,
&ir->then_instructions,
this->condition_variables);
/* Add the new condition variable to the hash table. This allows us to
* find this variable when lowering other (enclosing) if-statements.
*/
hash_table_insert(this->condition_variables, then_var, then_var);
/* If there are instructions in the else-clause, store the inverse of the
* condition to a variable. Move all of the instructions from the
* else-clause if the if-statement. Use the (inverse) condition variable
* as a condition for all assignments.
*/
if (!ir->else_instructions.is_empty()) {
ir_variable *const else_var =
new(mem_ctx) ir_variable(glsl_type::bool_type,
"if_to_cond_assign_else",
ir_var_temporary);
ir->insert_before(else_var);
ir_dereference_variable *else_cond =
new(mem_ctx) ir_dereference_variable(else_var);
ir_rvalue *inverse =
new(mem_ctx) ir_expression(ir_unop_logic_not,
then_cond->clone(mem_ctx, NULL));
assign = new(mem_ctx) ir_assignment(else_cond, inverse);
ir->insert_before(assign);
move_block_to_cond_assign(mem_ctx, ir, else_cond,
&ir->else_instructions,
this->condition_variables);
/* Add the new condition variable to the hash table. This allows us to
* find this variable when lowering other (enclosing) if-statements.
*/
hash_table_insert(this->condition_variables, else_var, else_var);
}
ir->remove();
this->progress = true;
return visit_continue;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ColumnLineChartTypeTemplate.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: vg $ $Date: 2007-09-18 15:05:32 $
*
* 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 "ColumnLineChartTypeTemplate.hxx"
#include "macros.hxx"
#include "CommonConverters.hxx"
#include "DiagramHelper.hxx"
#include "DataSeriesHelper.hxx"
#include "servicenames_charttypes.hxx"
#include "ColumnLineDataInterpreter.hxx"
#include "ContainerHelper.hxx"
#ifndef CHART_PROPERTYHELPER_HXX
#include "PropertyHelper.hxx"
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_XCHARTTYPECONTAINER_HPP_
#include <com/sun/star/chart2/XChartTypeContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_XDATASERIESCONTAINER_HPP_
#include <com/sun/star/chart2/XDataSeriesContainer.hpp>
#endif
#include <algorithm>
using namespace ::com::sun::star::chart2;
using namespace ::com::sun::star;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::rtl::OUString;
using ::com::sun::star::beans::Property;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Any;
using ::osl::MutexGuard;
namespace
{
static const ::rtl::OUString lcl_aServiceName(
RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.chart2.ColumnLineChartTypeTemplate" ));
enum
{
PROP_COL_LINE_NUMBER_OF_LINES
};
void lcl_AddPropertiesToVector(
::std::vector< Property > & rOutProperties )
{
rOutProperties.push_back(
Property( C2U( "NumberOfLines" ),
PROP_COL_LINE_NUMBER_OF_LINES,
::getCppuType( reinterpret_cast< const sal_Int32 * >(0)),
beans::PropertyAttribute::BOUND
| beans::PropertyAttribute::MAYBEDEFAULT ));
}
void lcl_AddDefaultsToMap(
::chart::tPropertyValueMap & rOutMap )
{
::chart::PropertyHelper::setPropertyValueDefault< sal_Int32 >( rOutMap, PROP_COL_LINE_NUMBER_OF_LINES, 1 );
}
const uno::Sequence< Property > & lcl_GetPropertySequence()
{
static uno::Sequence< Property > aPropSeq;
// /--
MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if( 0 == aPropSeq.getLength() )
{
// get properties
::std::vector< ::com::sun::star::beans::Property > aProperties;
lcl_AddPropertiesToVector( aProperties );
// and sort them for access via bsearch
::std::sort( aProperties.begin(), aProperties.end(),
::chart::PropertyNameLess() );
// transfer result to static Sequence
aPropSeq = ::chart::ContainerHelper::ContainerToSequence( aProperties );
}
return aPropSeq;
}
::cppu::IPropertyArrayHelper & lcl_getInfoHelper()
{
static ::cppu::OPropertyArrayHelper aArrayHelper(
lcl_GetPropertySequence(),
/* bSorted = */ sal_True );
return aArrayHelper;
}
} // anonymous namespace
namespace chart
{
ColumnLineChartTypeTemplate::ColumnLineChartTypeTemplate(
Reference<
uno::XComponentContext > const & xContext,
const ::rtl::OUString & rServiceName,
StackMode eStackMode,
sal_Int32 nNumberOfLines ) :
ChartTypeTemplate( xContext, rServiceName ),
::property::OPropertySet( m_aMutex ),
m_eStackMode( eStackMode )
{
setFastPropertyValue_NoBroadcast( PROP_COL_LINE_NUMBER_OF_LINES, uno::makeAny( nNumberOfLines ));
}
ColumnLineChartTypeTemplate::~ColumnLineChartTypeTemplate()
{}
// ____ OPropertySet ____
uno::Any ColumnLineChartTypeTemplate::GetDefaultValue( sal_Int32 nHandle ) const
throw(beans::UnknownPropertyException)
{
static tPropertyValueMap aStaticDefaults;
// /--
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if( 0 == aStaticDefaults.size() )
{
// initialize defaults
lcl_AddDefaultsToMap( aStaticDefaults );
}
tPropertyValueMap::const_iterator aFound(
aStaticDefaults.find( nHandle ));
if( aFound == aStaticDefaults.end())
return uno::Any();
return (*aFound).second;
// \--
}
::cppu::IPropertyArrayHelper & SAL_CALL ColumnLineChartTypeTemplate::getInfoHelper()
{
return lcl_getInfoHelper();
}
// ____ XPropertySet ____
uno::Reference< beans::XPropertySetInfo > SAL_CALL
ColumnLineChartTypeTemplate::getPropertySetInfo()
throw (uno::RuntimeException)
{
static uno::Reference< beans::XPropertySetInfo > xInfo;
// /--
MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if( !xInfo.is())
{
xInfo = ::cppu::OPropertySetHelper::createPropertySetInfo(
getInfoHelper());
}
return xInfo;
// \--
}
void ColumnLineChartTypeTemplate::createChartTypes(
const Sequence< Sequence< Reference< XDataSeries > > > & aSeriesSeq,
const Sequence< Reference< XCoordinateSystem > > & rCoordSys,
const Sequence< Reference< XChartType > >& aOldChartTypesSeq )
{
if( rCoordSys.getLength() == 0 ||
! rCoordSys[0].is() )
return;
try
{
Reference< lang::XMultiServiceFactory > xFact(
GetComponentContext()->getServiceManager(), uno::UNO_QUERY_THROW );
Sequence< Reference< XDataSeries > > aFlatSeriesSeq( FlattenSequence( aSeriesSeq ));
sal_Int32 nNumberOfSeries = aFlatSeriesSeq.getLength();
sal_Int32 nNumberOfLines = 0;
sal_Int32 nNumberOfColumns = 0;
getFastPropertyValue( PROP_COL_LINE_NUMBER_OF_LINES ) >>= nNumberOfLines;
OSL_ENSURE( nNumberOfLines>=0, "number of lines should be not negative" );
if( nNumberOfLines < 0 )
nNumberOfLines = 0;
if( nNumberOfLines >= nNumberOfSeries )
{
if( nNumberOfSeries > 0 )
{
nNumberOfLines = nNumberOfSeries - 1;
nNumberOfColumns = 1;
}
else
nNumberOfLines = 0;
}
else
nNumberOfColumns = nNumberOfSeries - nNumberOfLines;
// Columns
// -------
Reference< XChartType > xCT(
xFact->createInstance( CHART2_SERVICE_NAME_CHARTTYPE_COLUMN ), uno::UNO_QUERY_THROW );
ChartTypeTemplate::copyPropertiesFromOldToNewCoordianteSystem( aOldChartTypesSeq, xCT );
Reference< XChartTypeContainer > xCTCnt( rCoordSys[ 0 ], uno::UNO_QUERY_THROW );
xCTCnt->setChartTypes( Sequence< Reference< chart2::XChartType > >( &xCT, 1 ));
if( nNumberOfColumns > 0 )
{
Reference< XDataSeriesContainer > xDSCnt( xCT, uno::UNO_QUERY_THROW );
Sequence< Reference< XDataSeries > > aColumnSeq( nNumberOfColumns );
::std::copy( aFlatSeriesSeq.getConstArray(),
aFlatSeriesSeq.getConstArray() + nNumberOfColumns,
aColumnSeq.getArray());
xDSCnt->setDataSeries( aColumnSeq );
}
// Lines
// -----
xCT.set( xFact->createInstance( CHART2_SERVICE_NAME_CHARTTYPE_LINE ), uno::UNO_QUERY_THROW );
xCTCnt.set( rCoordSys[ 0 ], uno::UNO_QUERY_THROW );
xCTCnt->addChartType( xCT );
if( nNumberOfLines > 0 )
{
Reference< XDataSeriesContainer > xDSCnt( xCT, uno::UNO_QUERY_THROW );
Sequence< Reference< XDataSeries > > aLineSeq( nNumberOfLines );
::std::copy( aFlatSeriesSeq.getConstArray() + nNumberOfColumns,
aFlatSeriesSeq.getConstArray() + aFlatSeriesSeq.getLength(),
aLineSeq.getArray());
xDSCnt->setDataSeries( aLineSeq );
}
}
catch( uno::Exception & ex )
{
ASSERT_EXCEPTION( ex );
}
}
StackMode ColumnLineChartTypeTemplate::getStackMode( sal_Int32 nChartTypeIndex ) const
{
if( nChartTypeIndex == 0 )
return m_eStackMode;
return StackMode_NONE;
}
// ____ XChartTypeTemplate ____
sal_Bool SAL_CALL ColumnLineChartTypeTemplate::matchesTemplate(
const uno::Reference< XDiagram >& xDiagram,
sal_Bool bAdaptProperties )
throw (uno::RuntimeException)
{
sal_Bool bResult = sal_False;
if( ! xDiagram.is())
return bResult;
try
{
Reference< chart2::XChartType > xColumnChartType;
Reference< XCoordinateSystem > xColumnChartCooSys;
Reference< chart2::XChartType > xLineChartType;
sal_Int32 nNumberOfChartTypes = 0;
Reference< XCoordinateSystemContainer > xCooSysCnt(
xDiagram, uno::UNO_QUERY_THROW );
Sequence< Reference< XCoordinateSystem > > aCooSysSeq(
xCooSysCnt->getCoordinateSystems());
for( sal_Int32 i=0; i<aCooSysSeq.getLength(); ++i )
{
Reference< XChartTypeContainer > xCTCnt( aCooSysSeq[i], uno::UNO_QUERY_THROW );
Sequence< Reference< XChartType > > aChartTypeSeq( xCTCnt->getChartTypes());
for( sal_Int32 j=0; j<aChartTypeSeq.getLength(); ++j )
{
if( aChartTypeSeq[j].is())
{
++nNumberOfChartTypes;
if( nNumberOfChartTypes > 2 )
break;
OUString aCTService = aChartTypeSeq[j]->getChartType();
if( aCTService.equals( CHART2_SERVICE_NAME_CHARTTYPE_COLUMN ))
{
xColumnChartType.set( aChartTypeSeq[j] );
xColumnChartCooSys.set( aCooSysSeq[i] );
}
else if( aCTService.equals( CHART2_SERVICE_NAME_CHARTTYPE_LINE ))
xLineChartType.set( aChartTypeSeq[j] );
}
}
if( nNumberOfChartTypes > 2 )
break;
}
if( nNumberOfChartTypes == 2 &&
xColumnChartType.is() &&
xLineChartType.is())
{
OSL_ASSERT( xColumnChartCooSys.is());
// check stackmode of bars
bResult = (xColumnChartCooSys->getDimension() == getDimension());
if( bResult )
{
bResult = ( DiagramHelper::getStackModeFromChartType(
xColumnChartType,
xColumnChartCooSys )
== getStackMode( 0 ) );
if( bResult && bAdaptProperties )
{
Reference< XDataSeriesContainer > xSeriesContainer( xLineChartType, uno::UNO_QUERY );
if( xSeriesContainer.is() )
{
sal_Int32 nNumberOfLines = xSeriesContainer->getDataSeries().getLength();
setFastPropertyValue_NoBroadcast( PROP_COL_LINE_NUMBER_OF_LINES, uno::makeAny( nNumberOfLines ));
}
}
}
}
}
catch( uno::Exception & ex )
{
ASSERT_EXCEPTION( ex );
}
return bResult;
}
Reference< XChartType > SAL_CALL ColumnLineChartTypeTemplate::getChartTypeForNewSeries(
const uno::Sequence< Reference< chart2::XChartType > >& aFormerlyUsedChartTypes )
throw (uno::RuntimeException)
{
Reference< chart2::XChartType > xResult;
try
{
Reference< lang::XMultiServiceFactory > xFact(
GetComponentContext()->getServiceManager(), uno::UNO_QUERY_THROW );
xResult.set( xFact->createInstance(
CHART2_SERVICE_NAME_CHARTTYPE_LINE ), uno::UNO_QUERY_THROW );
ChartTypeTemplate::copyPropertiesFromOldToNewCoordianteSystem( aFormerlyUsedChartTypes, xResult );
}
catch( uno::Exception & ex )
{
ASSERT_EXCEPTION( ex );
}
return xResult;
}
Reference< XDataInterpreter > SAL_CALL ColumnLineChartTypeTemplate::getDataInterpreter()
throw (uno::RuntimeException)
{
if( ! m_xDataInterpreter.is())
{
sal_Int32 nNumberOfLines = 1;
getFastPropertyValue( PROP_COL_LINE_NUMBER_OF_LINES ) >>= nNumberOfLines;
m_xDataInterpreter.set( new ColumnLineDataInterpreter( nNumberOfLines, GetComponentContext() ) );
}
else
{
//todo...
OSL_ENSURE( false, "number of lines may not be valid anymore in the datainterpreter" );
}
return m_xDataInterpreter;
}
// ----------------------------------------
uno::Sequence< ::rtl::OUString > ColumnLineChartTypeTemplate::getSupportedServiceNames_Static()
{
uno::Sequence< ::rtl::OUString > aServices( 2 );
aServices[ 0 ] = lcl_aServiceName;
aServices[ 1 ] = C2U( "com.sun.star.chart2.ChartTypeTemplate" );
return aServices;
}
// implement XServiceInfo methods basing upon getSupportedServiceNames_Static
APPHELPER_XSERVICEINFO_IMPL( ColumnLineChartTypeTemplate, lcl_aServiceName );
IMPLEMENT_FORWARD_XINTERFACE2( ColumnLineChartTypeTemplate, ChartTypeTemplate, OPropertySet )
IMPLEMENT_FORWARD_XTYPEPROVIDER2( ColumnLineChartTypeTemplate, ChartTypeTemplate, OPropertySet )
} // namespace chart
<commit_msg>INTEGRATION: CWS chart17 (1.9.4); FILE MERGED 2007/11/05 14:09:10 iha 1.9.4.1: #i63857#, #i4039# more flexible placement of data point labels, best fit for pie labels<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ColumnLineChartTypeTemplate.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: ihi $ $Date: 2007-11-23 12:01: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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "ColumnLineChartTypeTemplate.hxx"
#include "macros.hxx"
#include "CommonConverters.hxx"
#include "DiagramHelper.hxx"
#include "DataSeriesHelper.hxx"
#include "servicenames_charttypes.hxx"
#include "ColumnLineDataInterpreter.hxx"
#include "ContainerHelper.hxx"
#ifndef CHART_PROPERTYHELPER_HXX
#include "PropertyHelper.hxx"
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_XCHARTTYPECONTAINER_HPP_
#include <com/sun/star/chart2/XChartTypeContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_XDATASERIESCONTAINER_HPP_
#include <com/sun/star/chart2/XDataSeriesContainer.hpp>
#endif
#include <algorithm>
using namespace ::com::sun::star::chart2;
using namespace ::com::sun::star;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::rtl::OUString;
using ::com::sun::star::beans::Property;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Any;
using ::osl::MutexGuard;
namespace
{
static const ::rtl::OUString lcl_aServiceName(
RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.chart2.ColumnLineChartTypeTemplate" ));
enum
{
PROP_COL_LINE_NUMBER_OF_LINES
};
void lcl_AddPropertiesToVector(
::std::vector< Property > & rOutProperties )
{
rOutProperties.push_back(
Property( C2U( "NumberOfLines" ),
PROP_COL_LINE_NUMBER_OF_LINES,
::getCppuType( reinterpret_cast< const sal_Int32 * >(0)),
beans::PropertyAttribute::BOUND
| beans::PropertyAttribute::MAYBEDEFAULT ));
}
void lcl_AddDefaultsToMap(
::chart::tPropertyValueMap & rOutMap )
{
::chart::PropertyHelper::setPropertyValueDefault< sal_Int32 >( rOutMap, PROP_COL_LINE_NUMBER_OF_LINES, 1 );
}
const uno::Sequence< Property > & lcl_GetPropertySequence()
{
static uno::Sequence< Property > aPropSeq;
// /--
MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if( 0 == aPropSeq.getLength() )
{
// get properties
::std::vector< ::com::sun::star::beans::Property > aProperties;
lcl_AddPropertiesToVector( aProperties );
// and sort them for access via bsearch
::std::sort( aProperties.begin(), aProperties.end(),
::chart::PropertyNameLess() );
// transfer result to static Sequence
aPropSeq = ::chart::ContainerHelper::ContainerToSequence( aProperties );
}
return aPropSeq;
}
::cppu::IPropertyArrayHelper & lcl_getInfoHelper()
{
static ::cppu::OPropertyArrayHelper aArrayHelper(
lcl_GetPropertySequence(),
/* bSorted = */ sal_True );
return aArrayHelper;
}
} // anonymous namespace
namespace chart
{
ColumnLineChartTypeTemplate::ColumnLineChartTypeTemplate(
Reference<
uno::XComponentContext > const & xContext,
const ::rtl::OUString & rServiceName,
StackMode eStackMode,
sal_Int32 nNumberOfLines ) :
ChartTypeTemplate( xContext, rServiceName ),
::property::OPropertySet( m_aMutex ),
m_eStackMode( eStackMode )
{
setFastPropertyValue_NoBroadcast( PROP_COL_LINE_NUMBER_OF_LINES, uno::makeAny( nNumberOfLines ));
}
ColumnLineChartTypeTemplate::~ColumnLineChartTypeTemplate()
{}
// ____ OPropertySet ____
uno::Any ColumnLineChartTypeTemplate::GetDefaultValue( sal_Int32 nHandle ) const
throw(beans::UnknownPropertyException)
{
static tPropertyValueMap aStaticDefaults;
// /--
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if( 0 == aStaticDefaults.size() )
{
// initialize defaults
lcl_AddDefaultsToMap( aStaticDefaults );
}
tPropertyValueMap::const_iterator aFound(
aStaticDefaults.find( nHandle ));
if( aFound == aStaticDefaults.end())
return uno::Any();
return (*aFound).second;
// \--
}
::cppu::IPropertyArrayHelper & SAL_CALL ColumnLineChartTypeTemplate::getInfoHelper()
{
return lcl_getInfoHelper();
}
// ____ XPropertySet ____
uno::Reference< beans::XPropertySetInfo > SAL_CALL
ColumnLineChartTypeTemplate::getPropertySetInfo()
throw (uno::RuntimeException)
{
static uno::Reference< beans::XPropertySetInfo > xInfo;
// /--
MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if( !xInfo.is())
{
xInfo = ::cppu::OPropertySetHelper::createPropertySetInfo(
getInfoHelper());
}
return xInfo;
// \--
}
void ColumnLineChartTypeTemplate::createChartTypes(
const Sequence< Sequence< Reference< XDataSeries > > > & aSeriesSeq,
const Sequence< Reference< XCoordinateSystem > > & rCoordSys,
const Sequence< Reference< XChartType > >& aOldChartTypesSeq )
{
if( rCoordSys.getLength() == 0 ||
! rCoordSys[0].is() )
return;
try
{
Reference< lang::XMultiServiceFactory > xFact(
GetComponentContext()->getServiceManager(), uno::UNO_QUERY_THROW );
Sequence< Reference< XDataSeries > > aFlatSeriesSeq( FlattenSequence( aSeriesSeq ));
sal_Int32 nNumberOfSeries = aFlatSeriesSeq.getLength();
sal_Int32 nNumberOfLines = 0;
sal_Int32 nNumberOfColumns = 0;
getFastPropertyValue( PROP_COL_LINE_NUMBER_OF_LINES ) >>= nNumberOfLines;
OSL_ENSURE( nNumberOfLines>=0, "number of lines should be not negative" );
if( nNumberOfLines < 0 )
nNumberOfLines = 0;
if( nNumberOfLines >= nNumberOfSeries )
{
if( nNumberOfSeries > 0 )
{
nNumberOfLines = nNumberOfSeries - 1;
nNumberOfColumns = 1;
}
else
nNumberOfLines = 0;
}
else
nNumberOfColumns = nNumberOfSeries - nNumberOfLines;
// Columns
// -------
Reference< XChartType > xCT(
xFact->createInstance( CHART2_SERVICE_NAME_CHARTTYPE_COLUMN ), uno::UNO_QUERY_THROW );
ChartTypeTemplate::copyPropertiesFromOldToNewCoordianteSystem( aOldChartTypesSeq, xCT );
Reference< XChartTypeContainer > xCTCnt( rCoordSys[ 0 ], uno::UNO_QUERY_THROW );
xCTCnt->setChartTypes( Sequence< Reference< chart2::XChartType > >( &xCT, 1 ));
if( nNumberOfColumns > 0 )
{
Reference< XDataSeriesContainer > xDSCnt( xCT, uno::UNO_QUERY_THROW );
Sequence< Reference< XDataSeries > > aColumnSeq( nNumberOfColumns );
::std::copy( aFlatSeriesSeq.getConstArray(),
aFlatSeriesSeq.getConstArray() + nNumberOfColumns,
aColumnSeq.getArray());
xDSCnt->setDataSeries( aColumnSeq );
}
// Lines
// -----
xCT.set( xFact->createInstance( CHART2_SERVICE_NAME_CHARTTYPE_LINE ), uno::UNO_QUERY_THROW );
xCTCnt.set( rCoordSys[ 0 ], uno::UNO_QUERY_THROW );
xCTCnt->addChartType( xCT );
if( nNumberOfLines > 0 )
{
Reference< XDataSeriesContainer > xDSCnt( xCT, uno::UNO_QUERY_THROW );
Sequence< Reference< XDataSeries > > aLineSeq( nNumberOfLines );
::std::copy( aFlatSeriesSeq.getConstArray() + nNumberOfColumns,
aFlatSeriesSeq.getConstArray() + aFlatSeriesSeq.getLength(),
aLineSeq.getArray());
xDSCnt->setDataSeries( aLineSeq );
}
}
catch( uno::Exception & ex )
{
ASSERT_EXCEPTION( ex );
}
}
StackMode ColumnLineChartTypeTemplate::getStackMode( sal_Int32 nChartTypeIndex ) const
{
if( nChartTypeIndex == 0 )
return m_eStackMode;
return StackMode_NONE;
}
// ____ XChartTypeTemplate ____
sal_Bool SAL_CALL ColumnLineChartTypeTemplate::matchesTemplate(
const uno::Reference< XDiagram >& xDiagram,
sal_Bool bAdaptProperties )
throw (uno::RuntimeException)
{
sal_Bool bResult = sal_False;
if( ! xDiagram.is())
return bResult;
try
{
Reference< chart2::XChartType > xColumnChartType;
Reference< XCoordinateSystem > xColumnChartCooSys;
Reference< chart2::XChartType > xLineChartType;
sal_Int32 nNumberOfChartTypes = 0;
Reference< XCoordinateSystemContainer > xCooSysCnt(
xDiagram, uno::UNO_QUERY_THROW );
Sequence< Reference< XCoordinateSystem > > aCooSysSeq(
xCooSysCnt->getCoordinateSystems());
for( sal_Int32 i=0; i<aCooSysSeq.getLength(); ++i )
{
Reference< XChartTypeContainer > xCTCnt( aCooSysSeq[i], uno::UNO_QUERY_THROW );
Sequence< Reference< XChartType > > aChartTypeSeq( xCTCnt->getChartTypes());
for( sal_Int32 j=0; j<aChartTypeSeq.getLength(); ++j )
{
if( aChartTypeSeq[j].is())
{
++nNumberOfChartTypes;
if( nNumberOfChartTypes > 2 )
break;
OUString aCTService = aChartTypeSeq[j]->getChartType();
if( aCTService.equals( CHART2_SERVICE_NAME_CHARTTYPE_COLUMN ))
{
xColumnChartType.set( aChartTypeSeq[j] );
xColumnChartCooSys.set( aCooSysSeq[i] );
}
else if( aCTService.equals( CHART2_SERVICE_NAME_CHARTTYPE_LINE ))
xLineChartType.set( aChartTypeSeq[j] );
}
}
if( nNumberOfChartTypes > 2 )
break;
}
if( nNumberOfChartTypes == 2 &&
xColumnChartType.is() &&
xLineChartType.is())
{
OSL_ASSERT( xColumnChartCooSys.is());
// check stackmode of bars
bResult = (xColumnChartCooSys->getDimension() == getDimension());
if( bResult )
{
bResult = ( DiagramHelper::getStackModeFromChartType(
xColumnChartType,
xColumnChartCooSys )
== getStackMode( 0 ) );
if( bResult && bAdaptProperties )
{
Reference< XDataSeriesContainer > xSeriesContainer( xLineChartType, uno::UNO_QUERY );
if( xSeriesContainer.is() )
{
sal_Int32 nNumberOfLines = xSeriesContainer->getDataSeries().getLength();
setFastPropertyValue_NoBroadcast( PROP_COL_LINE_NUMBER_OF_LINES, uno::makeAny( nNumberOfLines ));
}
}
}
}
}
catch( uno::Exception & ex )
{
ASSERT_EXCEPTION( ex );
}
return bResult;
}
Reference< chart2::XChartType > ColumnLineChartTypeTemplate::getChartTypeForIndex( sal_Int32 nChartTypeIndex )
{
Reference< chart2::XChartType > xCT;
Reference< lang::XMultiServiceFactory > xFact(
GetComponentContext()->getServiceManager(), uno::UNO_QUERY );
if(xFact.is())
{
if( nChartTypeIndex == 0 )
xCT.set( xFact->createInstance( CHART2_SERVICE_NAME_CHARTTYPE_COLUMN ), uno::UNO_QUERY );
else
xCT.set( xFact->createInstance( CHART2_SERVICE_NAME_CHARTTYPE_LINE ), uno::UNO_QUERY );
}
return xCT;
}
Reference< XChartType > SAL_CALL ColumnLineChartTypeTemplate::getChartTypeForNewSeries(
const uno::Sequence< Reference< chart2::XChartType > >& aFormerlyUsedChartTypes )
throw (uno::RuntimeException)
{
Reference< chart2::XChartType > xResult;
try
{
Reference< lang::XMultiServiceFactory > xFact(
GetComponentContext()->getServiceManager(), uno::UNO_QUERY_THROW );
xResult.set( xFact->createInstance(
CHART2_SERVICE_NAME_CHARTTYPE_LINE ), uno::UNO_QUERY_THROW );
ChartTypeTemplate::copyPropertiesFromOldToNewCoordianteSystem( aFormerlyUsedChartTypes, xResult );
}
catch( uno::Exception & ex )
{
ASSERT_EXCEPTION( ex );
}
return xResult;
}
Reference< XDataInterpreter > SAL_CALL ColumnLineChartTypeTemplate::getDataInterpreter()
throw (uno::RuntimeException)
{
if( ! m_xDataInterpreter.is())
{
sal_Int32 nNumberOfLines = 1;
getFastPropertyValue( PROP_COL_LINE_NUMBER_OF_LINES ) >>= nNumberOfLines;
m_xDataInterpreter.set( new ColumnLineDataInterpreter( nNumberOfLines, GetComponentContext() ) );
}
else
{
//todo...
OSL_ENSURE( false, "number of lines may not be valid anymore in the datainterpreter" );
}
return m_xDataInterpreter;
}
// ----------------------------------------
uno::Sequence< ::rtl::OUString > ColumnLineChartTypeTemplate::getSupportedServiceNames_Static()
{
uno::Sequence< ::rtl::OUString > aServices( 2 );
aServices[ 0 ] = lcl_aServiceName;
aServices[ 1 ] = C2U( "com.sun.star.chart2.ChartTypeTemplate" );
return aServices;
}
// implement XServiceInfo methods basing upon getSupportedServiceNames_Static
APPHELPER_XSERVICEINFO_IMPL( ColumnLineChartTypeTemplate, lcl_aServiceName );
IMPLEMENT_FORWARD_XINTERFACE2( ColumnLineChartTypeTemplate, ChartTypeTemplate, OPropertySet )
IMPLEMENT_FORWARD_XTYPEPROVIDER2( ColumnLineChartTypeTemplate, ChartTypeTemplate, OPropertySet )
} // namespace chart
<|endoftext|> |
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/nacl_host/pnacl_translation_cache.h"
#include "base/files/file_path.h"
#include "base/files/scoped_temp_dir.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "components/nacl/common/pnacl_types.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "net/base/io_buffer.h"
#include "net/base/test_completion_callback.h"
#include "testing/gtest/include/gtest/gtest.h"
using content::BrowserThread;
using base::FilePath;
namespace pnacl {
class PnaclTranslationCacheTest : public testing::Test {
protected:
PnaclTranslationCacheTest()
: thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP) {}
virtual ~PnaclTranslationCacheTest() {}
virtual void SetUp() { cache_ = new PnaclTranslationCache(); }
virtual void TearDown() {
// The destructor of PnaclTranslationCacheWriteEntry posts a task to the IO
// thread to close the backend cache entry. We want to make sure the entries
// are closed before we delete the backend (and in particular the destructor
// for the memory backend has a DCHECK to verify this), so we run the loop
// here to ensure the task gets processed.
base::RunLoop().RunUntilIdle();
delete cache_;
}
void InitBackend(bool in_mem);
void StoreNexe(const std::string& key, const std::string& nexe);
std::string GetNexe(const std::string& key);
PnaclTranslationCache* cache_;
content::TestBrowserThreadBundle thread_bundle_;
base::ScopedTempDir temp_dir_;
};
void PnaclTranslationCacheTest::InitBackend(bool in_mem) {
net::TestCompletionCallback init_cb;
if (!in_mem) {
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
}
int rv = cache_->InitCache(temp_dir_.path(), in_mem, init_cb.callback());
if (in_mem)
ASSERT_EQ(net::OK, rv);
ASSERT_EQ(net::OK, init_cb.GetResult(rv));
ASSERT_EQ(0, cache_->Size());
}
void PnaclTranslationCacheTest::StoreNexe(const std::string& key,
const std::string& nexe) {
net::TestCompletionCallback store_cb;
scoped_refptr<net::DrainableIOBuffer> nexe_buf(
new net::DrainableIOBuffer(new net::StringIOBuffer(nexe), nexe.size()));
cache_->StoreNexe(key, nexe_buf, store_cb.callback());
// Using ERR_IO_PENDING here causes the callback to wait for the result
// which should be harmless even if it returns OK immediately. This is because
// we don't plumb the intermediate writing stages all the way out.
EXPECT_EQ(net::OK, store_cb.GetResult(net::ERR_IO_PENDING));
}
// Inspired by net::TestCompletionCallback. Instantiate a TestNexeCallback and
// pass the GetNexeCallback returned by the callback() method to GetNexe.
// Then call GetResult, which will pump the message loop until it gets a result,
// return the resulting IOBuffer and fill in the return value
class TestNexeCallback {
public:
TestNexeCallback()
: have_result_(false),
result_(-1),
cb_(base::Bind(&TestNexeCallback::SetResult, base::Unretained(this))) {}
GetNexeCallback callback() { return cb_; }
net::DrainableIOBuffer* GetResult(int* result) {
while (!have_result_)
base::RunLoop().RunUntilIdle();
have_result_ = false;
*result = result_;
return buf_.get();
}
private:
void SetResult(int rv, scoped_refptr<net::DrainableIOBuffer> buf) {
have_result_ = true;
result_ = rv;
buf_ = buf;
}
bool have_result_;
int result_;
scoped_refptr<net::DrainableIOBuffer> buf_;
const GetNexeCallback cb_;
};
std::string PnaclTranslationCacheTest::GetNexe(const std::string& key) {
TestNexeCallback load_cb;
cache_->GetNexe(key, load_cb.callback());
int rv;
scoped_refptr<net::DrainableIOBuffer> buf(load_cb.GetResult(&rv));
EXPECT_EQ(net::OK, rv);
std::string nexe(buf->data(), buf->size());
return nexe;
}
static const std::string test_key("1");
static const std::string test_store_val("testnexe");
static const int kLargeNexeSize = 16 * 1024 * 1024;
TEST(PnaclTranslationCacheKeyTest, CacheKeyTest) {
nacl::PnaclCacheInfo info;
info.pexe_url = GURL("http://www.google.com");
info.abi_version = 0;
info.opt_level = 0;
std::string test_time("Wed, 15 Nov 1995 06:25:24 GMT");
base::Time::FromString(test_time.c_str(), &info.last_modified);
// Basic check for URL and time components
EXPECT_EQ("ABI:0;opt:0;URL:http://www.google.com/;"
"modified:1995:11:15:6:25:24:0:UTC;etag:",
PnaclTranslationCache::GetKey(info));
// Check that query portion of URL is not stripped
info.pexe_url = GURL("http://www.google.com/?foo=bar");
EXPECT_EQ("ABI:0;opt:0;URL:http://www.google.com/?foo=bar;"
"modified:1995:11:15:6:25:24:0:UTC;etag:",
PnaclTranslationCache::GetKey(info));
// Check that username, password, and normal port are stripped
info.pexe_url = GURL("https://user:[email protected]:443/");
EXPECT_EQ("ABI:0;opt:0;URL:https://www.google.com/;"
"modified:1995:11:15:6:25:24:0:UTC;etag:",
PnaclTranslationCache::GetKey(info));
// Check that unusual port is not stripped but ref is stripped
info.pexe_url = GURL("https://www.google.com:444/#foo");
EXPECT_EQ("ABI:0;opt:0;URL:https://www.google.com:444/;"
"modified:1995:11:15:6:25:24:0:UTC;etag:",
PnaclTranslationCache::GetKey(info));
// Check chrome-extesnsion scheme
info.pexe_url = GURL("chrome-extension://ljacajndfccfgnfohlgkdphmbnpkjflk/");
EXPECT_EQ("ABI:0;opt:0;"
"URL:chrome-extension://ljacajndfccfgnfohlgkdphmbnpkjflk/;"
"modified:1995:11:15:6:25:24:0:UTC;etag:",
PnaclTranslationCache::GetKey(info));
// Check that ABI version, opt level, and etag are in the key
info.pexe_url = GURL("http://www.google.com/");
info.abi_version = 2;
EXPECT_EQ("ABI:2;opt:0;URL:http://www.google.com/;"
"modified:1995:11:15:6:25:24:0:UTC;etag:",
PnaclTranslationCache::GetKey(info));
info.opt_level = 2;
EXPECT_EQ("ABI:2;opt:2;URL:http://www.google.com/;"
"modified:1995:11:15:6:25:24:0:UTC;etag:",
PnaclTranslationCache::GetKey(info));
info.etag = std::string("etag");
EXPECT_EQ("ABI:2;opt:2;URL:http://www.google.com/;"
"modified:1995:11:15:6:25:24:0:UTC;etag:etag",
PnaclTranslationCache::GetKey(info));
// Check for all the time components, and null time
info.last_modified = base::Time();
EXPECT_EQ("ABI:2;opt:2;URL:http://www.google.com/;"
"modified:0:0:0:0:0:0:0:UTC;etag:etag",
PnaclTranslationCache::GetKey(info));
test_time.assign("Fri, 29 Feb 2008 13:04:12 GMT");
base::Time::FromString(test_time.c_str(), &info.last_modified);
EXPECT_EQ("ABI:2;opt:2;URL:http://www.google.com/;"
"modified:2008:2:29:13:4:12:0:UTC;etag:etag",
PnaclTranslationCache::GetKey(info));
}
TEST_F(PnaclTranslationCacheTest, StoreSmallInMem) {
// Test that a single store puts something in the mem backend
InitBackend(true);
StoreNexe(test_key, test_store_val);
EXPECT_EQ(1, cache_->Size());
}
TEST_F(PnaclTranslationCacheTest, StoreSmallOnDisk) {
// Test that a single store puts something in the disk backend
InitBackend(false);
StoreNexe(test_key, test_store_val);
EXPECT_EQ(1, cache_->Size());
}
TEST_F(PnaclTranslationCacheTest, StoreLargeOnDisk) {
// Test a value too large(?) for a single I/O operation
InitBackend(false);
const std::string large_buffer(kLargeNexeSize, 'a');
StoreNexe(test_key, large_buffer);
EXPECT_EQ(1, cache_->Size());
}
TEST_F(PnaclTranslationCacheTest, InMemSizeLimit) {
InitBackend(true);
scoped_refptr<net::DrainableIOBuffer> large_buffer(new net::DrainableIOBuffer(
new net::StringIOBuffer(std::string(kMaxMemCacheSize + 1, 'a')),
kMaxMemCacheSize + 1));
net::TestCompletionCallback store_cb;
cache_->StoreNexe(test_key, large_buffer, store_cb.callback());
EXPECT_EQ(net::ERR_FAILED, store_cb.GetResult(net::ERR_IO_PENDING));
base::RunLoop().RunUntilIdle(); // Ensure the entry is closed.
EXPECT_EQ(0, cache_->Size());
}
TEST_F(PnaclTranslationCacheTest, GetOneInMem) {
InitBackend(true);
StoreNexe(test_key, test_store_val);
EXPECT_EQ(1, cache_->Size());
EXPECT_EQ(0, GetNexe(test_key).compare(test_store_val));
}
TEST_F(PnaclTranslationCacheTest, GetOneOnDisk) {
InitBackend(false);
StoreNexe(test_key, test_store_val);
EXPECT_EQ(1, cache_->Size());
EXPECT_EQ(0, GetNexe(test_key).compare(test_store_val));
}
TEST_F(PnaclTranslationCacheTest, GetLargeOnDisk) {
InitBackend(false);
const std::string large_buffer(kLargeNexeSize, 'a');
StoreNexe(test_key, large_buffer);
EXPECT_EQ(1, cache_->Size());
EXPECT_EQ(0, GetNexe(test_key).compare(large_buffer));
}
TEST_F(PnaclTranslationCacheTest, StoreTwice) {
// Test that storing twice with the same key overwrites
InitBackend(true);
StoreNexe(test_key, test_store_val);
StoreNexe(test_key, test_store_val + "aaa");
EXPECT_EQ(1, cache_->Size());
EXPECT_EQ(0, GetNexe(test_key).compare(test_store_val + "aaa"));
}
TEST_F(PnaclTranslationCacheTest, StoreTwo) {
InitBackend(true);
StoreNexe(test_key, test_store_val);
StoreNexe(test_key + "a", test_store_val + "aaa");
EXPECT_EQ(2, cache_->Size());
EXPECT_EQ(0, GetNexe(test_key).compare(test_store_val));
EXPECT_EQ(0, GetNexe(test_key + "a").compare(test_store_val + "aaa"));
}
TEST_F(PnaclTranslationCacheTest, GetMiss) {
InitBackend(true);
StoreNexe(test_key, test_store_val);
TestNexeCallback load_cb;
std::string nexe;
cache_->GetNexe(test_key + "a", load_cb.callback());
int rv;
scoped_refptr<net::DrainableIOBuffer> buf(load_cb.GetResult(&rv));
EXPECT_EQ(net::ERR_FAILED, rv);
}
} // namespace pnacl
<commit_msg>Disable Store/GetLargeOnDisk tests for linux.<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/nacl_host/pnacl_translation_cache.h"
#include "base/files/file_path.h"
#include "base/files/scoped_temp_dir.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "components/nacl/common/pnacl_types.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "net/base/io_buffer.h"
#include "net/base/test_completion_callback.h"
#include "testing/gtest/include/gtest/gtest.h"
using content::BrowserThread;
using base::FilePath;
namespace pnacl {
class PnaclTranslationCacheTest : public testing::Test {
protected:
PnaclTranslationCacheTest()
: thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP) {}
virtual ~PnaclTranslationCacheTest() {}
virtual void SetUp() { cache_ = new PnaclTranslationCache(); }
virtual void TearDown() {
// The destructor of PnaclTranslationCacheWriteEntry posts a task to the IO
// thread to close the backend cache entry. We want to make sure the entries
// are closed before we delete the backend (and in particular the destructor
// for the memory backend has a DCHECK to verify this), so we run the loop
// here to ensure the task gets processed.
base::RunLoop().RunUntilIdle();
delete cache_;
}
void InitBackend(bool in_mem);
void StoreNexe(const std::string& key, const std::string& nexe);
std::string GetNexe(const std::string& key);
PnaclTranslationCache* cache_;
content::TestBrowserThreadBundle thread_bundle_;
base::ScopedTempDir temp_dir_;
};
void PnaclTranslationCacheTest::InitBackend(bool in_mem) {
net::TestCompletionCallback init_cb;
if (!in_mem) {
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
}
int rv = cache_->InitCache(temp_dir_.path(), in_mem, init_cb.callback());
if (in_mem)
ASSERT_EQ(net::OK, rv);
ASSERT_EQ(net::OK, init_cb.GetResult(rv));
ASSERT_EQ(0, cache_->Size());
}
void PnaclTranslationCacheTest::StoreNexe(const std::string& key,
const std::string& nexe) {
net::TestCompletionCallback store_cb;
scoped_refptr<net::DrainableIOBuffer> nexe_buf(
new net::DrainableIOBuffer(new net::StringIOBuffer(nexe), nexe.size()));
cache_->StoreNexe(key, nexe_buf, store_cb.callback());
// Using ERR_IO_PENDING here causes the callback to wait for the result
// which should be harmless even if it returns OK immediately. This is because
// we don't plumb the intermediate writing stages all the way out.
EXPECT_EQ(net::OK, store_cb.GetResult(net::ERR_IO_PENDING));
}
// Inspired by net::TestCompletionCallback. Instantiate a TestNexeCallback and
// pass the GetNexeCallback returned by the callback() method to GetNexe.
// Then call GetResult, which will pump the message loop until it gets a result,
// return the resulting IOBuffer and fill in the return value
class TestNexeCallback {
public:
TestNexeCallback()
: have_result_(false),
result_(-1),
cb_(base::Bind(&TestNexeCallback::SetResult, base::Unretained(this))) {}
GetNexeCallback callback() { return cb_; }
net::DrainableIOBuffer* GetResult(int* result) {
while (!have_result_)
base::RunLoop().RunUntilIdle();
have_result_ = false;
*result = result_;
return buf_.get();
}
private:
void SetResult(int rv, scoped_refptr<net::DrainableIOBuffer> buf) {
have_result_ = true;
result_ = rv;
buf_ = buf;
}
bool have_result_;
int result_;
scoped_refptr<net::DrainableIOBuffer> buf_;
const GetNexeCallback cb_;
};
std::string PnaclTranslationCacheTest::GetNexe(const std::string& key) {
TestNexeCallback load_cb;
cache_->GetNexe(key, load_cb.callback());
int rv;
scoped_refptr<net::DrainableIOBuffer> buf(load_cb.GetResult(&rv));
EXPECT_EQ(net::OK, rv);
std::string nexe(buf->data(), buf->size());
return nexe;
}
static const std::string test_key("1");
static const std::string test_store_val("testnexe");
static const int kLargeNexeSize = 16 * 1024 * 1024;
TEST(PnaclTranslationCacheKeyTest, CacheKeyTest) {
nacl::PnaclCacheInfo info;
info.pexe_url = GURL("http://www.google.com");
info.abi_version = 0;
info.opt_level = 0;
std::string test_time("Wed, 15 Nov 1995 06:25:24 GMT");
base::Time::FromString(test_time.c_str(), &info.last_modified);
// Basic check for URL and time components
EXPECT_EQ("ABI:0;opt:0;URL:http://www.google.com/;"
"modified:1995:11:15:6:25:24:0:UTC;etag:",
PnaclTranslationCache::GetKey(info));
// Check that query portion of URL is not stripped
info.pexe_url = GURL("http://www.google.com/?foo=bar");
EXPECT_EQ("ABI:0;opt:0;URL:http://www.google.com/?foo=bar;"
"modified:1995:11:15:6:25:24:0:UTC;etag:",
PnaclTranslationCache::GetKey(info));
// Check that username, password, and normal port are stripped
info.pexe_url = GURL("https://user:[email protected]:443/");
EXPECT_EQ("ABI:0;opt:0;URL:https://www.google.com/;"
"modified:1995:11:15:6:25:24:0:UTC;etag:",
PnaclTranslationCache::GetKey(info));
// Check that unusual port is not stripped but ref is stripped
info.pexe_url = GURL("https://www.google.com:444/#foo");
EXPECT_EQ("ABI:0;opt:0;URL:https://www.google.com:444/;"
"modified:1995:11:15:6:25:24:0:UTC;etag:",
PnaclTranslationCache::GetKey(info));
// Check chrome-extesnsion scheme
info.pexe_url = GURL("chrome-extension://ljacajndfccfgnfohlgkdphmbnpkjflk/");
EXPECT_EQ("ABI:0;opt:0;"
"URL:chrome-extension://ljacajndfccfgnfohlgkdphmbnpkjflk/;"
"modified:1995:11:15:6:25:24:0:UTC;etag:",
PnaclTranslationCache::GetKey(info));
// Check that ABI version, opt level, and etag are in the key
info.pexe_url = GURL("http://www.google.com/");
info.abi_version = 2;
EXPECT_EQ("ABI:2;opt:0;URL:http://www.google.com/;"
"modified:1995:11:15:6:25:24:0:UTC;etag:",
PnaclTranslationCache::GetKey(info));
info.opt_level = 2;
EXPECT_EQ("ABI:2;opt:2;URL:http://www.google.com/;"
"modified:1995:11:15:6:25:24:0:UTC;etag:",
PnaclTranslationCache::GetKey(info));
info.etag = std::string("etag");
EXPECT_EQ("ABI:2;opt:2;URL:http://www.google.com/;"
"modified:1995:11:15:6:25:24:0:UTC;etag:etag",
PnaclTranslationCache::GetKey(info));
// Check for all the time components, and null time
info.last_modified = base::Time();
EXPECT_EQ("ABI:2;opt:2;URL:http://www.google.com/;"
"modified:0:0:0:0:0:0:0:UTC;etag:etag",
PnaclTranslationCache::GetKey(info));
test_time.assign("Fri, 29 Feb 2008 13:04:12 GMT");
base::Time::FromString(test_time.c_str(), &info.last_modified);
EXPECT_EQ("ABI:2;opt:2;URL:http://www.google.com/;"
"modified:2008:2:29:13:4:12:0:UTC;etag:etag",
PnaclTranslationCache::GetKey(info));
}
TEST_F(PnaclTranslationCacheTest, StoreSmallInMem) {
// Test that a single store puts something in the mem backend
InitBackend(true);
StoreNexe(test_key, test_store_val);
EXPECT_EQ(1, cache_->Size());
}
TEST_F(PnaclTranslationCacheTest, StoreSmallOnDisk) {
// Test that a single store puts something in the disk backend
InitBackend(false);
StoreNexe(test_key, test_store_val);
EXPECT_EQ(1, cache_->Size());
}
#if defined(OS_LINUX)
TEST_F(PnaclTranslationCacheTest, DISABLED_StoreLargeOnDisk) {
#else
TEST_F(PnaclTranslationCacheTest, StoreLargeOnDisk) {
#endif
// Test a value too large(?) for a single I/O operation
InitBackend(false);
const std::string large_buffer(kLargeNexeSize, 'a');
StoreNexe(test_key, large_buffer);
EXPECT_EQ(1, cache_->Size());
}
TEST_F(PnaclTranslationCacheTest, InMemSizeLimit) {
InitBackend(true);
scoped_refptr<net::DrainableIOBuffer> large_buffer(new net::DrainableIOBuffer(
new net::StringIOBuffer(std::string(kMaxMemCacheSize + 1, 'a')),
kMaxMemCacheSize + 1));
net::TestCompletionCallback store_cb;
cache_->StoreNexe(test_key, large_buffer, store_cb.callback());
EXPECT_EQ(net::ERR_FAILED, store_cb.GetResult(net::ERR_IO_PENDING));
base::RunLoop().RunUntilIdle(); // Ensure the entry is closed.
EXPECT_EQ(0, cache_->Size());
}
TEST_F(PnaclTranslationCacheTest, GetOneInMem) {
InitBackend(true);
StoreNexe(test_key, test_store_val);
EXPECT_EQ(1, cache_->Size());
EXPECT_EQ(0, GetNexe(test_key).compare(test_store_val));
}
TEST_F(PnaclTranslationCacheTest, GetOneOnDisk) {
InitBackend(false);
StoreNexe(test_key, test_store_val);
EXPECT_EQ(1, cache_->Size());
EXPECT_EQ(0, GetNexe(test_key).compare(test_store_val));
}
#if defined(OS_LINUX)
TEST_F(PnaclTranslationCacheTest, DISABLED_GetLargeOnDisk) {
#else
TEST_F(PnaclTranslationCacheTest, GetLargeOnDisk) {
#endif
InitBackend(false);
const std::string large_buffer(kLargeNexeSize, 'a');
StoreNexe(test_key, large_buffer);
EXPECT_EQ(1, cache_->Size());
EXPECT_EQ(0, GetNexe(test_key).compare(large_buffer));
}
TEST_F(PnaclTranslationCacheTest, StoreTwice) {
// Test that storing twice with the same key overwrites
InitBackend(true);
StoreNexe(test_key, test_store_val);
StoreNexe(test_key, test_store_val + "aaa");
EXPECT_EQ(1, cache_->Size());
EXPECT_EQ(0, GetNexe(test_key).compare(test_store_val + "aaa"));
}
TEST_F(PnaclTranslationCacheTest, StoreTwo) {
InitBackend(true);
StoreNexe(test_key, test_store_val);
StoreNexe(test_key + "a", test_store_val + "aaa");
EXPECT_EQ(2, cache_->Size());
EXPECT_EQ(0, GetNexe(test_key).compare(test_store_val));
EXPECT_EQ(0, GetNexe(test_key + "a").compare(test_store_val + "aaa"));
}
TEST_F(PnaclTranslationCacheTest, GetMiss) {
InitBackend(true);
StoreNexe(test_key, test_store_val);
TestNexeCallback load_cb;
std::string nexe;
cache_->GetNexe(test_key + "a", load_cb.callback());
int rv;
scoped_refptr<net::DrainableIOBuffer> buf(load_cb.GetResult(&rv));
EXPECT_EQ(net::ERR_FAILED, rv);
}
} // namespace pnacl
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <math.h>
#include <sapi.h>
#include "base/memory/singleton.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "base/win/scoped_comptr.h"
#include "chrome/browser/speech/extension_api/tts_extension_api_controller.h"
#include "chrome/browser/speech/extension_api/tts_extension_api_platform.h"
class ExtensionTtsPlatformImplWin : public ExtensionTtsPlatformImpl {
public:
virtual bool PlatformImplAvailable() {
return true;
}
virtual bool Speak(
int utterance_id,
const std::string& utterance,
const std::string& lang,
const UtteranceContinuousParameters& params);
virtual bool StopSpeaking();
virtual bool IsSpeaking();
virtual bool SendsEvent(TtsEventType event_type);
// Get the single instance of this class.
static ExtensionTtsPlatformImplWin* GetInstance();
static void __stdcall SpeechEventCallback(WPARAM w_param, LPARAM l_param);
private:
ExtensionTtsPlatformImplWin();
virtual ~ExtensionTtsPlatformImplWin() {}
void OnSpeechEvent();
base::win::ScopedComPtr<ISpVoice> speech_synthesizer_;
// These apply to the current utterance only.
std::wstring utterance_;
int utterance_id_;
int prefix_len_;
ULONG stream_number_;
int char_position_;
friend struct DefaultSingletonTraits<ExtensionTtsPlatformImplWin>;
DISALLOW_COPY_AND_ASSIGN(ExtensionTtsPlatformImplWin);
};
// static
ExtensionTtsPlatformImpl* ExtensionTtsPlatformImpl::GetInstance() {
return ExtensionTtsPlatformImplWin::GetInstance();
}
bool ExtensionTtsPlatformImplWin::Speak(
int utterance_id,
const std::string& src_utterance,
const std::string& lang,
const UtteranceContinuousParameters& params) {
std::wstring prefix;
std::wstring suffix;
if (!speech_synthesizer_)
return false;
// TODO(dmazzoni): support languages other than the default: crbug.com/88059
if (params.rate >= 0.0) {
// Map our multiplicative range of 0.1x to 10.0x onto Microsoft's
// linear range of -10 to 10:
// 0.1 -> -10
// 1.0 -> 0
// 10.0 -> 10
speech_synthesizer_->SetRate(static_cast<int32>(10 * log10(params.rate)));
}
if (params.pitch >= 0.0) {
// The TTS api allows a range of -10 to 10 for speech pitch.
// TODO(dtseng): cleanup if we ever use any other properties that
// require xml.
std::wstring pitch_value =
base::IntToString16(static_cast<int>(params.pitch * 10 - 10));
prefix = L"<pitch absmiddle=\"" + pitch_value + L"\">";
suffix = L"</pitch>";
}
if (params.volume >= 0.0) {
// The TTS api allows a range of 0 to 100 for speech volume.
speech_synthesizer_->SetVolume(static_cast<uint16>(params.volume * 100));
}
// TODO(dmazzoni): convert SSML to SAPI xml. http://crbug.com/88072
utterance_ = UTF8ToWide(src_utterance);
utterance_id_ = utterance_id;
char_position_ = 0;
std::wstring merged_utterance = prefix + utterance_ + suffix;
prefix_len_ = prefix.size();
HRESULT result = speech_synthesizer_->Speak(
merged_utterance.c_str(),
SPF_ASYNC,
&stream_number_);
return (result == S_OK);
}
bool ExtensionTtsPlatformImplWin::StopSpeaking() {
if (speech_synthesizer_) {
// Clear the stream number so that any further events relating to this
// utterance are ignored.
stream_number_ = 0;
if (IsSpeaking()) {
// Stop speech by speaking the empty string with the purge flag.
speech_synthesizer_->Speak(L"", SPF_ASYNC | SPF_PURGEBEFORESPEAK, NULL);
}
}
return true;
}
bool ExtensionTtsPlatformImplWin::IsSpeaking() {
if (speech_synthesizer_) {
SPVOICESTATUS status;
HRESULT result = speech_synthesizer_->GetStatus(&status, NULL);
if (result == S_OK) {
if (status.dwRunningState == 0 || // 0 == waiting to speak
status.dwRunningState == SPRS_IS_SPEAKING) {
return true;
}
}
}
return false;
}
bool ExtensionTtsPlatformImplWin::SendsEvent(TtsEventType event_type) {
return (event_type == TTS_EVENT_START ||
event_type == TTS_EVENT_END ||
event_type == TTS_EVENT_MARKER ||
event_type == TTS_EVENT_WORD ||
event_type == TTS_EVENT_SENTENCE);
}
void ExtensionTtsPlatformImplWin::OnSpeechEvent() {
ExtensionTtsController* controller = ExtensionTtsController::GetInstance();
SPEVENT event;
while (S_OK == speech_synthesizer_->GetEvents(1, &event, NULL)) {
if (event.ulStreamNum != stream_number_)
continue;
switch (event.eEventId) {
case SPEI_START_INPUT_STREAM:
controller->OnTtsEvent(
utterance_id_, TTS_EVENT_START, 0, std::string());
break;
case SPEI_END_INPUT_STREAM:
char_position_ = utterance_.size();
controller->OnTtsEvent(
utterance_id_, TTS_EVENT_END, char_position_, std::string());
break;
case SPEI_TTS_BOOKMARK:
controller->OnTtsEvent(
utterance_id_, TTS_EVENT_MARKER, char_position_, std::string());
break;
case SPEI_WORD_BOUNDARY:
char_position_ = static_cast<ULONG>(event.lParam) - prefix_len_;
controller->OnTtsEvent(
utterance_id_, TTS_EVENT_WORD, char_position_,
std::string());
break;
case SPEI_SENTENCE_BOUNDARY:
char_position_ = static_cast<ULONG>(event.lParam) - prefix_len_;
controller->OnTtsEvent(
utterance_id_, TTS_EVENT_SENTENCE, char_position_,
std::string());
break;
}
}
}
ExtensionTtsPlatformImplWin::ExtensionTtsPlatformImplWin()
: speech_synthesizer_(NULL),
utterance_id_(0),
prefix_len_(0),
stream_number_(0),
char_position_(0) {
CoCreateInstance(
CLSID_SpVoice,
NULL,
CLSCTX_SERVER,
IID_ISpVoice,
reinterpret_cast<void**>(&speech_synthesizer_));
if (speech_synthesizer_) {
ULONGLONG event_mask =
SPFEI(SPEI_START_INPUT_STREAM) |
SPFEI(SPEI_TTS_BOOKMARK) |
SPFEI(SPEI_WORD_BOUNDARY) |
SPFEI(SPEI_SENTENCE_BOUNDARY) |
SPFEI(SPEI_END_INPUT_STREAM);
speech_synthesizer_->SetInterest(event_mask, event_mask);
speech_synthesizer_->SetNotifyCallbackFunction(
ExtensionTtsPlatformImplWin::SpeechEventCallback, 0, 0);
}
}
// static
ExtensionTtsPlatformImplWin* ExtensionTtsPlatformImplWin::GetInstance() {
return Singleton<ExtensionTtsPlatformImplWin>::get();
}
// static
void ExtensionTtsPlatformImplWin::SpeechEventCallback(
WPARAM w_param, LPARAM l_param) {
GetInstance()->OnSpeechEvent();
}
<commit_msg>Fix use of ScopedComPtr that caused crash in destructor<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <math.h>
#include <sapi.h>
#include "base/memory/singleton.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "base/win/scoped_comptr.h"
#include "chrome/browser/speech/extension_api/tts_extension_api_controller.h"
#include "chrome/browser/speech/extension_api/tts_extension_api_platform.h"
class ExtensionTtsPlatformImplWin : public ExtensionTtsPlatformImpl {
public:
virtual bool PlatformImplAvailable() {
return true;
}
virtual bool Speak(
int utterance_id,
const std::string& utterance,
const std::string& lang,
const UtteranceContinuousParameters& params);
virtual bool StopSpeaking();
virtual bool IsSpeaking();
virtual bool SendsEvent(TtsEventType event_type);
// Get the single instance of this class.
static ExtensionTtsPlatformImplWin* GetInstance();
static void __stdcall SpeechEventCallback(WPARAM w_param, LPARAM l_param);
private:
ExtensionTtsPlatformImplWin();
virtual ~ExtensionTtsPlatformImplWin() {}
void OnSpeechEvent();
base::win::ScopedComPtr<ISpVoice> speech_synthesizer_;
// These apply to the current utterance only.
std::wstring utterance_;
int utterance_id_;
int prefix_len_;
ULONG stream_number_;
int char_position_;
friend struct DefaultSingletonTraits<ExtensionTtsPlatformImplWin>;
DISALLOW_COPY_AND_ASSIGN(ExtensionTtsPlatformImplWin);
};
// static
ExtensionTtsPlatformImpl* ExtensionTtsPlatformImpl::GetInstance() {
return ExtensionTtsPlatformImplWin::GetInstance();
}
bool ExtensionTtsPlatformImplWin::Speak(
int utterance_id,
const std::string& src_utterance,
const std::string& lang,
const UtteranceContinuousParameters& params) {
std::wstring prefix;
std::wstring suffix;
if (!speech_synthesizer_.get())
return false;
// TODO(dmazzoni): support languages other than the default: crbug.com/88059
if (params.rate >= 0.0) {
// Map our multiplicative range of 0.1x to 10.0x onto Microsoft's
// linear range of -10 to 10:
// 0.1 -> -10
// 1.0 -> 0
// 10.0 -> 10
speech_synthesizer_->SetRate(static_cast<int32>(10 * log10(params.rate)));
}
if (params.pitch >= 0.0) {
// The TTS api allows a range of -10 to 10 for speech pitch.
// TODO(dtseng): cleanup if we ever use any other properties that
// require xml.
std::wstring pitch_value =
base::IntToString16(static_cast<int>(params.pitch * 10 - 10));
prefix = L"<pitch absmiddle=\"" + pitch_value + L"\">";
suffix = L"</pitch>";
}
if (params.volume >= 0.0) {
// The TTS api allows a range of 0 to 100 for speech volume.
speech_synthesizer_->SetVolume(static_cast<uint16>(params.volume * 100));
}
// TODO(dmazzoni): convert SSML to SAPI xml. http://crbug.com/88072
utterance_ = UTF8ToWide(src_utterance);
utterance_id_ = utterance_id;
char_position_ = 0;
std::wstring merged_utterance = prefix + utterance_ + suffix;
prefix_len_ = prefix.size();
HRESULT result = speech_synthesizer_->Speak(
merged_utterance.c_str(),
SPF_ASYNC,
&stream_number_);
return (result == S_OK);
}
bool ExtensionTtsPlatformImplWin::StopSpeaking() {
if (speech_synthesizer_.get()) {
// Clear the stream number so that any further events relating to this
// utterance are ignored.
stream_number_ = 0;
if (IsSpeaking()) {
// Stop speech by speaking the empty string with the purge flag.
speech_synthesizer_->Speak(L"", SPF_ASYNC | SPF_PURGEBEFORESPEAK, NULL);
}
}
return true;
}
bool ExtensionTtsPlatformImplWin::IsSpeaking() {
if (speech_synthesizer_.get()) {
SPVOICESTATUS status;
HRESULT result = speech_synthesizer_->GetStatus(&status, NULL);
if (result == S_OK) {
if (status.dwRunningState == 0 || // 0 == waiting to speak
status.dwRunningState == SPRS_IS_SPEAKING) {
return true;
}
}
}
return false;
}
bool ExtensionTtsPlatformImplWin::SendsEvent(TtsEventType event_type) {
return (event_type == TTS_EVENT_START ||
event_type == TTS_EVENT_END ||
event_type == TTS_EVENT_MARKER ||
event_type == TTS_EVENT_WORD ||
event_type == TTS_EVENT_SENTENCE);
}
void ExtensionTtsPlatformImplWin::OnSpeechEvent() {
ExtensionTtsController* controller = ExtensionTtsController::GetInstance();
SPEVENT event;
while (S_OK == speech_synthesizer_->GetEvents(1, &event, NULL)) {
if (event.ulStreamNum != stream_number_)
continue;
switch (event.eEventId) {
case SPEI_START_INPUT_STREAM:
controller->OnTtsEvent(
utterance_id_, TTS_EVENT_START, 0, std::string());
break;
case SPEI_END_INPUT_STREAM:
char_position_ = utterance_.size();
controller->OnTtsEvent(
utterance_id_, TTS_EVENT_END, char_position_, std::string());
break;
case SPEI_TTS_BOOKMARK:
controller->OnTtsEvent(
utterance_id_, TTS_EVENT_MARKER, char_position_, std::string());
break;
case SPEI_WORD_BOUNDARY:
char_position_ = static_cast<ULONG>(event.lParam) - prefix_len_;
controller->OnTtsEvent(
utterance_id_, TTS_EVENT_WORD, char_position_,
std::string());
break;
case SPEI_SENTENCE_BOUNDARY:
char_position_ = static_cast<ULONG>(event.lParam) - prefix_len_;
controller->OnTtsEvent(
utterance_id_, TTS_EVENT_SENTENCE, char_position_,
std::string());
break;
}
}
}
ExtensionTtsPlatformImplWin::ExtensionTtsPlatformImplWin()
: utterance_id_(0),
prefix_len_(0),
stream_number_(0),
char_position_(0) {
speech_synthesizer_.CreateInstance(CLSID_SpVoice);
if (speech_synthesizer_.get()) {
ULONGLONG event_mask =
SPFEI(SPEI_START_INPUT_STREAM) |
SPFEI(SPEI_TTS_BOOKMARK) |
SPFEI(SPEI_WORD_BOUNDARY) |
SPFEI(SPEI_SENTENCE_BOUNDARY) |
SPFEI(SPEI_END_INPUT_STREAM);
speech_synthesizer_->SetInterest(event_mask, event_mask);
speech_synthesizer_->SetNotifyCallbackFunction(
ExtensionTtsPlatformImplWin::SpeechEventCallback, 0, 0);
}
}
// static
ExtensionTtsPlatformImplWin* ExtensionTtsPlatformImplWin::GetInstance() {
return Singleton<ExtensionTtsPlatformImplWin>::get();
}
// static
void ExtensionTtsPlatformImplWin::SpeechEventCallback(
WPARAM w_param, LPARAM l_param) {
GetInstance()->OnSpeechEvent();
}
<|endoftext|> |
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/service_worker/service_worker_controllee_request_handler.h"
#include "base/debug/trace_event.h"
#include "content/browser/service_worker/service_worker_context_core.h"
#include "content/browser/service_worker/service_worker_metrics.h"
#include "content/browser/service_worker/service_worker_provider_host.h"
#include "content/browser/service_worker/service_worker_registration.h"
#include "content/browser/service_worker/service_worker_url_request_job.h"
#include "content/browser/service_worker/service_worker_utils.h"
#include "content/common/resource_request_body.h"
#include "content/common/service_worker/service_worker_types.h"
#include "net/base/load_flags.h"
#include "net/base/net_util.h"
#include "net/url_request/url_request.h"
namespace content {
ServiceWorkerControlleeRequestHandler::ServiceWorkerControlleeRequestHandler(
base::WeakPtr<ServiceWorkerContextCore> context,
base::WeakPtr<ServiceWorkerProviderHost> provider_host,
base::WeakPtr<storage::BlobStorageContext> blob_storage_context,
ResourceType resource_type,
scoped_refptr<ResourceRequestBody> body)
: ServiceWorkerRequestHandler(context,
provider_host,
blob_storage_context,
resource_type),
is_main_resource_load_(
ServiceWorkerUtils::IsMainResourceType(resource_type)),
body_(body),
weak_factory_(this) {
}
ServiceWorkerControlleeRequestHandler::
~ServiceWorkerControlleeRequestHandler() {
// Navigation triggers an update to occur shortly after the page and
// its initial subresources load.
if (provider_host_ && provider_host_->active_version()) {
if (is_main_resource_load_)
provider_host_->active_version()->ScheduleUpdate();
else
provider_host_->active_version()->DeferScheduledUpdate();
}
if (is_main_resource_load_ && provider_host_)
provider_host_->SetAllowAssociation(true);
}
net::URLRequestJob* ServiceWorkerControlleeRequestHandler::MaybeCreateJob(
net::URLRequest* request,
net::NetworkDelegate* network_delegate) {
if (!context_ || !provider_host_) {
// We can't do anything other than to fall back to network.
job_ = NULL;
return NULL;
}
// This may get called multiple times for original and redirect requests:
// A. original request case: job_ is null, no previous location info.
// B. redirect or restarted request case:
// a) job_ is non-null if the previous location was forwarded to SW.
// b) job_ is null if the previous location was fallback.
// c) job_ is non-null if additional restart was required to fall back.
// We've come here by restart, we already have original request and it
// tells we should fallback to network. (Case B-c)
if (job_.get() && job_->ShouldFallbackToNetwork()) {
job_ = NULL;
return NULL;
}
// It's for original request (A) or redirect case (B-a or B-b).
DCHECK(!job_.get() || job_->ShouldForwardToServiceWorker());
job_ = new ServiceWorkerURLRequestJob(
request, network_delegate, provider_host_, blob_storage_context_, body_);
if (is_main_resource_load_)
PrepareForMainResource(request->url());
else
PrepareForSubResource();
if (job_->ShouldFallbackToNetwork()) {
// If we know we can fallback to network at this point (in case
// the storage lookup returned immediately), just return NULL here to
// fallback to network.
job_ = NULL;
return NULL;
}
return job_.get();
}
void ServiceWorkerControlleeRequestHandler::GetExtraResponseInfo(
bool* was_fetched_via_service_worker,
GURL* original_url_via_service_worker) const {
if (!job_.get()) {
*was_fetched_via_service_worker = false;
*original_url_via_service_worker = GURL();
return;
}
job_->GetExtraResponseInfo(was_fetched_via_service_worker,
original_url_via_service_worker);
}
void ServiceWorkerControlleeRequestHandler::PrepareForMainResource(
const GURL& url) {
DCHECK(job_.get());
DCHECK(context_);
TRACE_EVENT_ASYNC_BEGIN1(
"ServiceWorker",
"ServiceWorkerControlleeRequestHandler::PrepareForMainResource",
job_.get(),
"URL", url.spec());
// The corresponding provider_host may already have associated a registration
// in redirect case, unassociate it now.
provider_host_->DisassociateRegistration();
// Also prevent a registrater job for establishing an association to a new
// registration while we're finding an existing registration.
provider_host_->SetAllowAssociation(false);
GURL stripped_url = net::SimplifyUrlForRequest(url);
provider_host_->SetDocumentUrl(stripped_url);
context_->storage()->FindRegistrationForDocument(
stripped_url,
base::Bind(&self::DidLookupRegistrationForMainResource,
weak_factory_.GetWeakPtr()));
}
void
ServiceWorkerControlleeRequestHandler::DidLookupRegistrationForMainResource(
ServiceWorkerStatusCode status,
const scoped_refptr<ServiceWorkerRegistration>& registration) {
DCHECK(job_.get());
provider_host_->SetAllowAssociation(true);
if (status != SERVICE_WORKER_OK) {
job_->FallbackToNetwork();
TRACE_EVENT_ASYNC_END1(
"ServiceWorker",
"ServiceWorkerControlleeRequestHandler::PrepareForMainResource",
job_.get(),
"Status", status);
return;
}
DCHECK(registration.get());
ServiceWorkerMetrics::CountControlledPageLoad();
// Initiate activation of a waiting version.
// Usually a register job initiates activation but that
// doesn't happen if the browser exits prior to activation
// having occurred. This check handles that case.
if (registration->waiting_version())
registration->ActivateWaitingVersionWhenReady();
scoped_refptr<ServiceWorkerVersion> active_version =
registration->active_version();
// Wait until it's activated before firing fetch events.
if (active_version.get() &&
active_version->status() == ServiceWorkerVersion::ACTIVATING) {
provider_host_->SetAllowAssociation(false);
registration->active_version()->RegisterStatusChangeCallback(
base::Bind(&self::OnVersionStatusChanged,
weak_factory_.GetWeakPtr(),
registration,
active_version));
TRACE_EVENT_ASYNC_END2(
"ServiceWorker",
"ServiceWorkerControlleeRequestHandler::PrepareForMainResource",
job_.get(),
"Status", status,
"Info", "Wait until finished SW activation");
return;
}
if (!active_version.get() ||
active_version->status() != ServiceWorkerVersion::ACTIVATED) {
job_->FallbackToNetwork();
TRACE_EVENT_ASYNC_END2(
"ServiceWorker",
"ServiceWorkerControlleeRequestHandler::PrepareForMainResource",
job_.get(),
"Status", status,
"Info",
"ServiceWorkerVersion is not available, so falling back to network");
return;
}
provider_host_->AssociateRegistration(registration.get());
job_->ForwardToServiceWorker();
TRACE_EVENT_ASYNC_END2(
"ServiceWorker",
"ServiceWorkerControlleeRequestHandler::PrepareForMainResource",
job_.get(),
"Status", status,
"Info",
"Forwarded to the ServiceWorker");
}
void ServiceWorkerControlleeRequestHandler::OnVersionStatusChanged(
ServiceWorkerRegistration* registration,
ServiceWorkerVersion* version) {
provider_host_->SetAllowAssociation(true);
if (version != registration->active_version() ||
version->status() != ServiceWorkerVersion::ACTIVATED) {
job_->FallbackToNetwork();
return;
}
provider_host_->AssociateRegistration(registration);
job_->ForwardToServiceWorker();
}
void ServiceWorkerControlleeRequestHandler::PrepareForSubResource() {
DCHECK(job_.get());
DCHECK(context_);
DCHECK(provider_host_->active_version());
job_->ForwardToServiceWorker();
}
} // namespace content
<commit_msg>ServiceWorker: Move tracking code to count only pages controlled by SW<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/service_worker/service_worker_controllee_request_handler.h"
#include "base/debug/trace_event.h"
#include "content/browser/service_worker/service_worker_context_core.h"
#include "content/browser/service_worker/service_worker_metrics.h"
#include "content/browser/service_worker/service_worker_provider_host.h"
#include "content/browser/service_worker/service_worker_registration.h"
#include "content/browser/service_worker/service_worker_url_request_job.h"
#include "content/browser/service_worker/service_worker_utils.h"
#include "content/common/resource_request_body.h"
#include "content/common/service_worker/service_worker_types.h"
#include "net/base/load_flags.h"
#include "net/base/net_util.h"
#include "net/url_request/url_request.h"
namespace content {
ServiceWorkerControlleeRequestHandler::ServiceWorkerControlleeRequestHandler(
base::WeakPtr<ServiceWorkerContextCore> context,
base::WeakPtr<ServiceWorkerProviderHost> provider_host,
base::WeakPtr<storage::BlobStorageContext> blob_storage_context,
ResourceType resource_type,
scoped_refptr<ResourceRequestBody> body)
: ServiceWorkerRequestHandler(context,
provider_host,
blob_storage_context,
resource_type),
is_main_resource_load_(
ServiceWorkerUtils::IsMainResourceType(resource_type)),
body_(body),
weak_factory_(this) {
}
ServiceWorkerControlleeRequestHandler::
~ServiceWorkerControlleeRequestHandler() {
// Navigation triggers an update to occur shortly after the page and
// its initial subresources load.
if (provider_host_ && provider_host_->active_version()) {
if (is_main_resource_load_)
provider_host_->active_version()->ScheduleUpdate();
else
provider_host_->active_version()->DeferScheduledUpdate();
}
if (is_main_resource_load_ && provider_host_)
provider_host_->SetAllowAssociation(true);
}
net::URLRequestJob* ServiceWorkerControlleeRequestHandler::MaybeCreateJob(
net::URLRequest* request,
net::NetworkDelegate* network_delegate) {
if (!context_ || !provider_host_) {
// We can't do anything other than to fall back to network.
job_ = NULL;
return NULL;
}
// This may get called multiple times for original and redirect requests:
// A. original request case: job_ is null, no previous location info.
// B. redirect or restarted request case:
// a) job_ is non-null if the previous location was forwarded to SW.
// b) job_ is null if the previous location was fallback.
// c) job_ is non-null if additional restart was required to fall back.
// We've come here by restart, we already have original request and it
// tells we should fallback to network. (Case B-c)
if (job_.get() && job_->ShouldFallbackToNetwork()) {
job_ = NULL;
return NULL;
}
// It's for original request (A) or redirect case (B-a or B-b).
DCHECK(!job_.get() || job_->ShouldForwardToServiceWorker());
job_ = new ServiceWorkerURLRequestJob(
request, network_delegate, provider_host_, blob_storage_context_, body_);
if (is_main_resource_load_)
PrepareForMainResource(request->url());
else
PrepareForSubResource();
if (job_->ShouldFallbackToNetwork()) {
// If we know we can fallback to network at this point (in case
// the storage lookup returned immediately), just return NULL here to
// fallback to network.
job_ = NULL;
return NULL;
}
return job_.get();
}
void ServiceWorkerControlleeRequestHandler::GetExtraResponseInfo(
bool* was_fetched_via_service_worker,
GURL* original_url_via_service_worker) const {
if (!job_.get()) {
*was_fetched_via_service_worker = false;
*original_url_via_service_worker = GURL();
return;
}
job_->GetExtraResponseInfo(was_fetched_via_service_worker,
original_url_via_service_worker);
}
void ServiceWorkerControlleeRequestHandler::PrepareForMainResource(
const GURL& url) {
DCHECK(job_.get());
DCHECK(context_);
TRACE_EVENT_ASYNC_BEGIN1(
"ServiceWorker",
"ServiceWorkerControlleeRequestHandler::PrepareForMainResource",
job_.get(),
"URL", url.spec());
// The corresponding provider_host may already have associated a registration
// in redirect case, unassociate it now.
provider_host_->DisassociateRegistration();
// Also prevent a registrater job for establishing an association to a new
// registration while we're finding an existing registration.
provider_host_->SetAllowAssociation(false);
GURL stripped_url = net::SimplifyUrlForRequest(url);
provider_host_->SetDocumentUrl(stripped_url);
context_->storage()->FindRegistrationForDocument(
stripped_url,
base::Bind(&self::DidLookupRegistrationForMainResource,
weak_factory_.GetWeakPtr()));
}
void
ServiceWorkerControlleeRequestHandler::DidLookupRegistrationForMainResource(
ServiceWorkerStatusCode status,
const scoped_refptr<ServiceWorkerRegistration>& registration) {
DCHECK(job_.get());
provider_host_->SetAllowAssociation(true);
if (status != SERVICE_WORKER_OK) {
job_->FallbackToNetwork();
TRACE_EVENT_ASYNC_END1(
"ServiceWorker",
"ServiceWorkerControlleeRequestHandler::PrepareForMainResource",
job_.get(),
"Status", status);
return;
}
DCHECK(registration.get());
// Initiate activation of a waiting version.
// Usually a register job initiates activation but that
// doesn't happen if the browser exits prior to activation
// having occurred. This check handles that case.
if (registration->waiting_version())
registration->ActivateWaitingVersionWhenReady();
scoped_refptr<ServiceWorkerVersion> active_version =
registration->active_version();
// Wait until it's activated before firing fetch events.
if (active_version.get() &&
active_version->status() == ServiceWorkerVersion::ACTIVATING) {
provider_host_->SetAllowAssociation(false);
registration->active_version()->RegisterStatusChangeCallback(
base::Bind(&self::OnVersionStatusChanged,
weak_factory_.GetWeakPtr(),
registration,
active_version));
TRACE_EVENT_ASYNC_END2(
"ServiceWorker",
"ServiceWorkerControlleeRequestHandler::PrepareForMainResource",
job_.get(),
"Status", status,
"Info", "Wait until finished SW activation");
return;
}
if (!active_version.get() ||
active_version->status() != ServiceWorkerVersion::ACTIVATED) {
job_->FallbackToNetwork();
TRACE_EVENT_ASYNC_END2(
"ServiceWorker",
"ServiceWorkerControlleeRequestHandler::PrepareForMainResource",
job_.get(),
"Status", status,
"Info",
"ServiceWorkerVersion is not available, so falling back to network");
return;
}
ServiceWorkerMetrics::CountControlledPageLoad();
provider_host_->AssociateRegistration(registration.get());
job_->ForwardToServiceWorker();
TRACE_EVENT_ASYNC_END2(
"ServiceWorker",
"ServiceWorkerControlleeRequestHandler::PrepareForMainResource",
job_.get(),
"Status", status,
"Info",
"Forwarded to the ServiceWorker");
}
void ServiceWorkerControlleeRequestHandler::OnVersionStatusChanged(
ServiceWorkerRegistration* registration,
ServiceWorkerVersion* version) {
provider_host_->SetAllowAssociation(true);
if (version != registration->active_version() ||
version->status() != ServiceWorkerVersion::ACTIVATED) {
job_->FallbackToNetwork();
return;
}
ServiceWorkerMetrics::CountControlledPageLoad();
provider_host_->AssociateRegistration(registration);
job_->ForwardToServiceWorker();
}
void ServiceWorkerControlleeRequestHandler::PrepareForSubResource() {
DCHECK(job_.get());
DCHECK(context_);
DCHECK(provider_host_->active_version());
job_->ForwardToServiceWorker();
}
} // namespace content
<|endoftext|> |
<commit_before>#ifndef HASHTABLE_HH
#define HASHTABLE_HH
#include <fstream>
#include <string>
#include "khmer.hh"
#include "storage.hh"
namespace khmer {
class Hashtable {
protected:
const WordLength _ksize;
const HashIntoType _tablesize;
BoundedCounterType * _counts;
void _allocate_counters() {
_counts = new BoundedCounterType[_tablesize];
memset(_counts, 0, _tablesize * sizeof(BoundedCounterType));
}
public:
Hashtable(WordLength ksize, HashIntoType tablesize) :
_ksize(ksize), _tablesize(tablesize) {
_allocate_counters();
}
~Hashtable() {
if (_counts) { delete _counts; _counts = NULL; }
}
// accessor to get 'k'
const WordLength ksize() const { return _ksize; }
// accessors to get table info
const HashIntoType n_entries() const { return _tablesize; }
// count number of occupied bins
const HashIntoType n_occupied(HashIntoType start=0,
HashIntoType stop=0) const {
HashIntoType n = 0;
if (stop == 0) { stop = _tablesize; }
for (HashIntoType i = start; i < stop; i++) {
if (_counts[i]) {
n++;
}
}
return n;
}
void count(const char * kmer) {
HashIntoType bin = _hash(kmer, _ksize) % _tablesize;
if (_counts[bin] == MAX_COUNT) { return; }
_counts[bin]++;
}
void count(HashIntoType khash) {
HashIntoType bin = khash % _tablesize;
if (_counts[bin] == MAX_COUNT) { return; }
_counts[bin]++;
}
// get the count for the given k-mer.
const BoundedCounterType get_count(const char * kmer) const {
HashIntoType bin = _hash(kmer, _ksize) % _tablesize;
return _counts[bin];
}
// get the count for the given k-mer hash.
const BoundedCounterType get_count(HashIntoType khash) const {
HashIntoType bin = khash % _tablesize;
return _counts[bin];
}
// count every k-mer in the string.
unsigned int consume_string(const std::string &s,
HashIntoType lower_bound = 0,
HashIntoType upper_bound = 0);
// checks each read for non-ACGT characters
unsigned int check_and_process_read(const std::string &read,
bool &is_valid,
HashIntoType lower_bound = 0,
HashIntoType upper_bound = 0);
// count every k-mer in the FASTA file.
void consume_fasta(const std::string &filename,
unsigned int &total_reads,
unsigned long long &n_consumed,
HashIntoType lower_bound = 0,
HashIntoType upper_bound = 0,
ReadMaskTable ** readmask = NULL,
bool update_readmask = true,
CallbackFn callback = NULL,
void * callback_data = NULL);
MinMaxTable * fasta_file_to_minmax(const std::string &inputfile,
unsigned int total_reads,
ReadMaskTable * readmask = NULL,
CallbackFn callback = NULL,
void * callback_data = NULL);
ReadMaskTable * filter_fasta_file_any(MinMaxTable &minmax,
BoundedCounterType threshold,
ReadMaskTable * readmask = NULL,
CallbackFn callback = NULL,
void * callback_data = NULL);
ReadMaskTable * filter_fasta_file_all(MinMaxTable &minmax,
BoundedCounterType threshold,
ReadMaskTable * readmask = NULL,
CallbackFn callback = NULL,
void * callback_data = NULL);
ReadMaskTable * filter_fasta_file_run(const std::string &inputfile,
unsigned int total_reads,
BoundedCounterType threshold,
unsigned int runlength,
ReadMaskTable * old_readmask = NULL,
CallbackFn callback = NULL,
void * callback_data = NULL);
void output_fasta_kmer_pos_freq(const std::string &inputfile,
const std::string &outputfile);
BoundedCounterType get_min_count(const std::string &s,
HashIntoType lower_bound = 0,
HashIntoType upper_bound = 0);
BoundedCounterType get_max_count(const std::string &s,
HashIntoType lower_bound = 0,
HashIntoType upper_bound = 0);
HashIntoType * abundance_distribution() const;
HashIntoType * fasta_count_kmers_by_position(const std::string &inputfile,
const unsigned int max_read_len,
ReadMaskTable * old_readmask = NULL,
BoundedCounterType limit_by_count=0,
CallbackFn callback = NULL,
void * callback_data = NULL);
void fasta_dump_kmers_by_abundance(const std::string &inputfile,
ReadMaskTable * readmask,
BoundedCounterType limit_by_count,
CallbackFn callback = NULL,
void * callback_data = NULL);
void mark_connected_graph(const std::string& kmer) const;
void empty_bins(bool empty_marked=false);
void dump_kmers_and_counts() const {
for (HashIntoType i = 0; i < _tablesize; i++) {
if (_counts[i]) {
std::cout << _revhash(i, _ksize) << " " << _counts[i] << std::endl;
}
}
}
};
class HashtableIntersect {
protected:
khmer::Hashtable * _kh1;
khmer::Hashtable * _kh2;
public:
HashtableIntersect(WordLength ksize,
HashIntoType tablesize1, HashIntoType tablesize2)
{
_kh1 = new Hashtable(ksize, tablesize1);
_kh2 = new Hashtable(ksize, tablesize2);
}
~HashtableIntersect()
{
delete _kh1;
delete _kh2;
}
// count every k-mer in the string.
void consume_string(const std::string &s)
{
_kh1->consume_string(s);
_kh2->consume_string(s);
}
BoundedCounterType get_min_count(const std::string &s)
{
BoundedCounterType kh1Min = _kh1->get_min_count(s);
BoundedCounterType kh2Min = _kh2->get_min_count(s);
if (kh1Min < kh2Min) {
return kh1Min;
} else {
return kh2Min;
}
}
BoundedCounterType get_max_count(const std::string &s)
{
BoundedCounterType kh1Max = _kh1->get_max_count(s);
BoundedCounterType kh2Max = _kh2->get_max_count(s);
if (kh1Max > kh2Max) {
return kh1Max;
} else {
return kh2Max;
}
}
};
};
#endif // HASHTABLE_HH
<commit_msg>added in callback fn<commit_after>#ifndef HASHTABLE_HH
#define HASHTABLE_HH
#include <fstream>
#include <string>
#include "khmer.hh"
#include "storage.hh"
namespace khmer {
class Hashtable {
protected:
const WordLength _ksize;
const HashIntoType _tablesize;
BoundedCounterType * _counts;
void _allocate_counters() {
_counts = new BoundedCounterType[_tablesize];
memset(_counts, 0, _tablesize * sizeof(BoundedCounterType));
}
public:
Hashtable(WordLength ksize, HashIntoType tablesize) :
_ksize(ksize), _tablesize(tablesize) {
_allocate_counters();
}
~Hashtable() {
if (_counts) { delete _counts; _counts = NULL; }
}
// accessor to get 'k'
const WordLength ksize() const { return _ksize; }
// accessors to get table info
const HashIntoType n_entries() const { return _tablesize; }
// count number of occupied bins
const HashIntoType n_occupied(HashIntoType start=0,
HashIntoType stop=0) const {
HashIntoType n = 0;
if (stop == 0) { stop = _tablesize; }
for (HashIntoType i = start; i < stop; i++) {
if (_counts[i]) {
n++;
}
}
return n;
}
void count(const char * kmer) {
HashIntoType bin = _hash(kmer, _ksize) % _tablesize;
if (_counts[bin] == MAX_COUNT) { return; }
_counts[bin]++;
}
void count(HashIntoType khash) {
HashIntoType bin = khash % _tablesize;
if (_counts[bin] == MAX_COUNT) { return; }
_counts[bin]++;
}
// get the count for the given k-mer.
const BoundedCounterType get_count(const char * kmer) const {
HashIntoType bin = _hash(kmer, _ksize) % _tablesize;
return _counts[bin];
}
// get the count for the given k-mer hash.
const BoundedCounterType get_count(HashIntoType khash) const {
HashIntoType bin = khash % _tablesize;
return _counts[bin];
}
// count every k-mer in the string.
unsigned int consume_string(const std::string &s,
HashIntoType lower_bound = 0,
HashIntoType upper_bound = 0);
// checks each read for non-ACGT characters
unsigned int check_and_process_read(const std::string &read,
bool &is_valid,
HashIntoType lower_bound = 0,
HashIntoType upper_bound = 0);
// count every k-mer in the FASTA file.
void consume_fasta(const std::string &filename,
unsigned int &total_reads,
unsigned long long &n_consumed,
HashIntoType lower_bound = 0,
HashIntoType upper_bound = 0,
ReadMaskTable ** readmask = NULL,
bool update_readmask = true,
CallbackFn callback = NULL,
void * callback_data = NULL);
MinMaxTable * fasta_file_to_minmax(const std::string &inputfile,
unsigned int total_reads,
ReadMaskTable * readmask = NULL,
CallbackFn callback = NULL,
void * callback_data = NULL);
ReadMaskTable * filter_fasta_file_any(MinMaxTable &minmax,
BoundedCounterType threshold,
ReadMaskTable * readmask = NULL,
CallbackFn callback = NULL,
void * callback_data = NULL);
ReadMaskTable * filter_fasta_file_all(MinMaxTable &minmax,
BoundedCounterType threshold,
ReadMaskTable * readmask = NULL,
CallbackFn callback = NULL,
void * callback_data = NULL);
ReadMaskTable * filter_fasta_file_run(const std::string &inputfile,
unsigned int total_reads,
BoundedCounterType threshold,
unsigned int runlength,
ReadMaskTable * old_readmask = NULL,
CallbackFn callback = NULL,
void * callback_data = NULL);
void output_fasta_kmer_pos_freq(const std::string &inputfile,
const std::string &outputfile);
BoundedCounterType get_min_count(const std::string &s,
HashIntoType lower_bound = 0,
HashIntoType upper_bound = 0);
BoundedCounterType get_max_count(const std::string &s,
HashIntoType lower_bound = 0,
HashIntoType upper_bound = 0);
HashIntoType * abundance_distribution() const;
HashIntoType * fasta_count_kmers_by_position(const std::string &inputfile,
const unsigned int max_read_len,
ReadMaskTable * old_readmask = NULL,
BoundedCounterType limit_by_count=0,
CallbackFn callback = NULL,
void * callback_data = NULL);
void fasta_dump_kmers_by_abundance(const std::string &inputfile,
ReadMaskTable * readmask,
BoundedCounterType limit_by_count,
CallbackFn callback = NULL,
void * callback_data = NULL);
void mark_connected_graph(const std::string& kmer) const;
void empty_bins(bool empty_marked=false);
typedef void (*kmer_cb)(const char * k, unsigned int n_reads, void *data);
void dump_kmers_and_counts(kmer_cb cb_fn = NULL, void * data = NULL) const {
for (HashIntoType i = 0; i < _tablesize; i++) {
if (_counts[i]) {
if (cb_fn) {
cb_fn(_revhash(i, _ksize).c_str(), _counts[i], data);
} else{
std::cout << _revhash(i, _ksize) << " " << _counts[i] << std::endl;
}
}
}
}
};
class HashtableIntersect {
protected:
khmer::Hashtable * _kh1;
khmer::Hashtable * _kh2;
public:
HashtableIntersect(WordLength ksize,
HashIntoType tablesize1, HashIntoType tablesize2)
{
_kh1 = new Hashtable(ksize, tablesize1);
_kh2 = new Hashtable(ksize, tablesize2);
}
~HashtableIntersect()
{
delete _kh1;
delete _kh2;
}
// count every k-mer in the string.
void consume_string(const std::string &s)
{
_kh1->consume_string(s);
_kh2->consume_string(s);
}
BoundedCounterType get_min_count(const std::string &s)
{
BoundedCounterType kh1Min = _kh1->get_min_count(s);
BoundedCounterType kh2Min = _kh2->get_min_count(s);
if (kh1Min < kh2Min) {
return kh1Min;
} else {
return kh2Min;
}
}
BoundedCounterType get_max_count(const std::string &s)
{
BoundedCounterType kh1Max = _kh1->get_max_count(s);
BoundedCounterType kh2Max = _kh2->get_max_count(s);
if (kh1Max > kh2Max) {
return kh1Max;
} else {
return kh2Max;
}
}
};
};
#endif // HASHTABLE_HH
<|endoftext|> |
<commit_before>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2011 Ulrich von Zadow
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// 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
//
// Current versions can be found at www.libavg.de
//
#include "BitmapManagerThread.h"
#include "Bitmap.h"
#include "BitmapLoader.h"
#include "../base/Exception.h"
#include "../base/ScopeTimer.h"
#include "../base/TimeSource.h"
#include <stdio.h>
#include <stdlib.h>
namespace avg {
BitmapManagerThread::BitmapManagerThread(CQueue& cmdQ, BitmapManagerMsgQueue& MsgQueue)
: WorkerThread<BitmapManagerThread>("BitmapManager", cmdQ),
m_MsgQueue(MsgQueue),
m_TotalLatency(0),
m_NumBmpsLoaded(0)
{
}
bool BitmapManagerThread::work()
{
waitForCommand();
return true;
}
void BitmapManagerThread::deinit()
{
AVG_TRACE(Logger::category::PROFILE, Logger::severity::INFO,
"Average latency for async bitmap loads: " << m_TotalLatency/m_NumBmpsLoaded
<< " ms");
}
static ProfilingZoneID LoaderProfilingZone("loadBitmap", true);
void BitmapManagerThread::loadBitmap(BitmapManagerMsgPtr pRequest)
{
BitmapPtr pBmp;
ScopeTimer timer(LoaderProfilingZone);
float startTime = pRequest->getStartTime();
try {
pBmp = avg::loadBitmap(pRequest->getFilename());
pRequest->setBitmap(pBmp);
} catch (const Exception& ex) {
pRequest->setError(ex);
}
m_MsgQueue.push(pRequest);
m_NumBmpsLoaded++;
float curLatency = TimeSource::get()->getCurrentMicrosecs()/1000 - startTime;
m_TotalLatency += curLatency;
ThreadProfiler::get()->reset();
}
}
<commit_msg>Added documentation for BitmapManager::setNumThreads().<commit_after>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2011 Ulrich von Zadow
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// 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
//
// Current versions can be found at www.libavg.de
//
#include "BitmapManagerThread.h"
#include "Bitmap.h"
#include "BitmapLoader.h"
#include "../base/Exception.h"
#include "../base/ScopeTimer.h"
#include "../base/TimeSource.h"
#include <stdio.h>
#include <stdlib.h>
namespace avg {
BitmapManagerThread::BitmapManagerThread(CQueue& cmdQ, BitmapManagerMsgQueue& MsgQueue)
: WorkerThread<BitmapManagerThread>("BitmapManager", cmdQ),
m_MsgQueue(MsgQueue),
m_TotalLatency(0),
m_NumBmpsLoaded(0)
{
}
bool BitmapManagerThread::work()
{
waitForCommand();
return true;
}
void BitmapManagerThread::deinit()
{
if (m_NumBmpsLoaded > 0) {
AVG_TRACE(Logger::category::PROFILE, Logger::severity::INFO,
"Average latency for async bitmap loads: " << m_TotalLatency/m_NumBmpsLoaded
<< " ms");
}
}
static ProfilingZoneID LoaderProfilingZone("loadBitmap", true);
void BitmapManagerThread::loadBitmap(BitmapManagerMsgPtr pRequest)
{
BitmapPtr pBmp;
ScopeTimer timer(LoaderProfilingZone);
float startTime = pRequest->getStartTime();
try {
pBmp = avg::loadBitmap(pRequest->getFilename());
pRequest->setBitmap(pBmp);
} catch (const Exception& ex) {
pRequest->setError(ex);
}
m_MsgQueue.push(pRequest);
m_NumBmpsLoaded++;
float curLatency = TimeSource::get()->getCurrentMicrosecs()/1000 - startTime;
m_TotalLatency += curLatency;
ThreadProfiler::get()->reset();
}
}
<|endoftext|> |
<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include <QObject>
#include <QDBusAbstractInterface>
#include <QDBusConnection>
#include "ut_mservicefwbaseif.h"
QString Ut_MServiceFwBaseIf::serviceFwService;
class EmailServiceIfProxy : public QDBusAbstractInterface
{
public:
static inline const char *staticInterfaceName() {
return "com.nokia.EmailServiceIf";
}
public:
EmailServiceIfProxy() : QDBusAbstractInterface(QString(), QString(), EmailServiceIfProxy::staticInterfaceName(), QDBusConnection::sessionBus(), 0) {
};
virtual ~EmailServiceIfProxy() {};
Q_SIGNALS: // SIGNALS
void messageSent(const QString &message);
};
class MyServiceFwIf : public MServiceFwBaseIf
{
public:
MyServiceFwIf(QDBusAbstractInterface *ifProxy) :
MServiceFwBaseIf("com.nokia.TextProcessorIf", 0) {
setInterfaceProxy(ifProxy);
};
virtual ~MyServiceFwIf() {
};
virtual void setService(const QString &service) {
setServiceName(service);
};
};
void Ut_MServiceFwBaseIf::init()
{
Ut_MServiceFwBaseIf::serviceFwService = "";
m_subject = new MyServiceFwIf(new EmailServiceIfProxy());
// no point in testing these
m_subject->isValid();
m_subject->serviceNames("com.nokia.TextProcessorIf");
m_subject->serviceName();
m_subject->serviceFwProxy();
}
void Ut_MServiceFwBaseIf::cleanup()
{
delete m_subject;
m_subject = 0;
}
void Ut_MServiceFwBaseIf::initTestCase()
{
}
void Ut_MServiceFwBaseIf::cleanupTestCase()
{
}
// no current service; new service for other if
// should not get signal:serviceAvailable
// should not get signal:serviceChanged
void Ut_MServiceFwBaseIf::testHandleServiceAvailable0()
{
QSignalSpy serviceAvailableSpy(m_subject,
SIGNAL(serviceAvailable(QString)));
QSignalSpy serviceChangedSpy(m_subject,
SIGNAL(serviceChanged(QString)));
m_subject->setService("");
m_subject->handleServiceAvailable("com.google.TextProcessor", "com.google.TexrProcessorIf");
QCOMPARE(serviceAvailableSpy.count(), 0);
QCOMPARE(serviceChangedSpy.count(), 0);
}
// no current service; new service for this if
// should get signal:serviceAvailable
// should get signal:serviceChanged
void Ut_MServiceFwBaseIf::testHandleServiceAvailable1()
{
QSignalSpy serviceAvailableSpy(m_subject,
SIGNAL(serviceAvailable(QString)));
QSignalSpy serviceChangedSpy(m_subject,
SIGNAL(serviceChanged(QString)));
m_subject->setService("");
QString thisService = "org.maemo.TextProcessor";
serviceFwService = thisService;
m_subject->handleServiceAvailable(thisService, m_subject->interfaceName());
QCOMPARE(serviceAvailableSpy.count(), 1);
QCOMPARE(serviceChangedSpy.count(), 1);
}
// current service; new preferred service for other if
// should not get signal:serviceAvilable
// should not get signal:serviceChanged
void Ut_MServiceFwBaseIf::testHandleServiceAvailable2()
{
QSignalSpy serviceAvailableSpy(m_subject,
SIGNAL(serviceAvailable(QString)));
QSignalSpy serviceChangedSpy(m_subject,
SIGNAL(serviceChanged(QString)));
m_subject->setService("org.maemo.TextProcessor");
QString thisService = "com.nokia.TextProcessor";
serviceFwService = thisService;
m_subject->handleServiceAvailable(thisService, "org.maemo.MailService");
QCOMPARE(serviceAvailableSpy.count(), 0);
QCOMPARE(serviceChangedSpy.count(), 0);
}
// current service; new preferred service for this if
// should not get signal:serviceAvilable
// should get signal:serviceChanged
void Ut_MServiceFwBaseIf::testHandleServiceAvailable3()
{
QSignalSpy serviceAvailableSpy(m_subject,
SIGNAL(serviceAvailable(QString)));
QSignalSpy serviceChangedSpy(m_subject,
SIGNAL(serviceChanged(QString)));
m_subject->setService("org.maemo.TextProcessor");
QString thisService = "com.nokia.TextProcessor";
serviceFwService = thisService;
m_subject->handleServiceAvailable(thisService, m_subject->interfaceName());
QCOMPARE(serviceAvailableSpy.count(), 0);
QCOMPARE(serviceChangedSpy.count(), 1);
}
// no current service; dead service is for other if
// should not get serviceUnavailable
// should not get serviceChanged
void Ut_MServiceFwBaseIf::testHandleServiceUnavailable0()
{
QSignalSpy serviceUnavailableSpy(m_subject,
SIGNAL(serviceUnavailable(QString)));
QSignalSpy serviceChangedSpy(m_subject,
SIGNAL(serviceChanged(QString)));
m_subject->setService("");
QString thisService = "com.nokia.TextProcessor";
serviceFwService = "";
m_subject->handleServiceUnavailable(thisService);
QCOMPARE(serviceUnavailableSpy.count(), 0);
QCOMPARE(serviceChangedSpy.count(), 0);
}
// current service; dead service is for other if
// should not get serviceUnavailable
// should not get serviceChanged
void Ut_MServiceFwBaseIf::testHandleServiceUnavailable1()
{
QSignalSpy serviceUnavailableSpy(m_subject,
SIGNAL(serviceUnavailable(QString)));
QSignalSpy serviceChangedSpy(m_subject,
SIGNAL(serviceChanged(QString)));
m_subject->setService("com.nokia.TextProcessor");
serviceFwService = m_subject->serviceName();
m_subject->handleServiceUnavailable("com.nokia.EmailService");
QCOMPARE(serviceUnavailableSpy.count(), 0);
QCOMPARE(serviceChangedSpy.count(), 0);
}
// current service; dead service is not last for this if
// should not get serviceUnavailable
// should get serviceChanged
void Ut_MServiceFwBaseIf::testHandleServiceUnavailable2()
{
QSignalSpy serviceUnavailableSpy(m_subject,
SIGNAL(serviceUnavailable(QString)));
QSignalSpy serviceChangedSpy(m_subject,
SIGNAL(serviceChanged(QString)));
m_subject->setService("com.nokia.TextProcessor");
serviceFwService = "org.maemo.TextProcessor";
m_subject->handleServiceUnavailable(m_subject->serviceName());
QCOMPARE(serviceUnavailableSpy.count(), 0);
QCOMPARE(serviceChangedSpy.count(), 1);
}
// current service; dead service is last for this if
// should get serviceUnavailable
// should not get serviceChanged
void Ut_MServiceFwBaseIf::testHandleServiceUnavailable3()
{
QSignalSpy serviceUnavailableSpy(m_subject,
SIGNAL(serviceUnavailable(QString)));
QSignalSpy serviceChangedSpy(m_subject,
SIGNAL(serviceChanged(QString)));
m_subject->setService("com.nokia.TextProcessor");
serviceFwService = "";
m_subject->handleServiceUnavailable(m_subject->serviceName());
QCOMPARE(serviceUnavailableSpy.count(), 1);
QCOMPARE(serviceChangedSpy.count(), 0);
}
void Ut_MServiceFwBaseIf::testResolveServiceName()
{
serviceFwService = "com.nokia.TextProcessor";
QString thisService = m_subject->resolveServiceName("com.nokia.TextProcessorIf", "");
QCOMPARE(thisService, serviceFwService);
thisService = m_subject->resolveServiceName("com.nokia.TextProcessorIf", "org.maemo.TextProcessor");
QCOMPARE(thisService, QString("org.maemo.TextProcessor"));
}
QTEST_APPLESS_MAIN(Ut_MServiceFwBaseIf)
<commit_msg>Changes: added a call to improve coverage stats<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include <QObject>
#include <QDBusAbstractInterface>
#include <QDBusConnection>
#include "ut_mservicefwbaseif.h"
QString Ut_MServiceFwBaseIf::serviceFwService;
class EmailServiceIfProxy : public QDBusAbstractInterface
{
public:
static inline const char *staticInterfaceName() {
return "com.nokia.EmailServiceIf";
}
public:
EmailServiceIfProxy() : QDBusAbstractInterface(QString(), QString(), EmailServiceIfProxy::staticInterfaceName(), QDBusConnection::sessionBus(), 0) {
};
virtual ~EmailServiceIfProxy() {};
Q_SIGNALS: // SIGNALS
void messageSent(const QString &message);
};
class MyServiceFwIf : public MServiceFwBaseIf
{
public:
MyServiceFwIf(QDBusAbstractInterface *ifProxy) :
MServiceFwBaseIf("com.nokia.TextProcessorIf", 0) {
setInterfaceProxy(ifProxy);
};
virtual ~MyServiceFwIf() {
};
virtual void setService(const QString &service) {
setServiceName(service);
};
};
void Ut_MServiceFwBaseIf::init()
{
Ut_MServiceFwBaseIf::serviceFwService = "";
m_subject = new MyServiceFwIf(new EmailServiceIfProxy());
// no point in testing these
m_subject->isValid();
m_subject->serviceNames("com.nokia.TextProcessorIf");
m_subject->serviceName();
m_subject->serviceFwProxy();
// purely for coverage stats - useless otherwise
m_subject->serviceFwProxy()->servicePath("com.nokia.TextProcessorIf");
}
void Ut_MServiceFwBaseIf::cleanup()
{
delete m_subject;
m_subject = 0;
}
void Ut_MServiceFwBaseIf::initTestCase()
{
}
void Ut_MServiceFwBaseIf::cleanupTestCase()
{
}
// no current service; new service for other if
// should not get signal:serviceAvailable
// should not get signal:serviceChanged
void Ut_MServiceFwBaseIf::testHandleServiceAvailable0()
{
QSignalSpy serviceAvailableSpy(m_subject,
SIGNAL(serviceAvailable(QString)));
QSignalSpy serviceChangedSpy(m_subject,
SIGNAL(serviceChanged(QString)));
m_subject->setService("");
m_subject->handleServiceAvailable("com.google.TextProcessor", "com.google.TexrProcessorIf");
QCOMPARE(serviceAvailableSpy.count(), 0);
QCOMPARE(serviceChangedSpy.count(), 0);
}
// no current service; new service for this if
// should get signal:serviceAvailable
// should get signal:serviceChanged
void Ut_MServiceFwBaseIf::testHandleServiceAvailable1()
{
QSignalSpy serviceAvailableSpy(m_subject,
SIGNAL(serviceAvailable(QString)));
QSignalSpy serviceChangedSpy(m_subject,
SIGNAL(serviceChanged(QString)));
m_subject->setService("");
QString thisService = "org.maemo.TextProcessor";
serviceFwService = thisService;
m_subject->handleServiceAvailable(thisService, m_subject->interfaceName());
QCOMPARE(serviceAvailableSpy.count(), 1);
QCOMPARE(serviceChangedSpy.count(), 1);
}
// current service; new preferred service for other if
// should not get signal:serviceAvilable
// should not get signal:serviceChanged
void Ut_MServiceFwBaseIf::testHandleServiceAvailable2()
{
QSignalSpy serviceAvailableSpy(m_subject,
SIGNAL(serviceAvailable(QString)));
QSignalSpy serviceChangedSpy(m_subject,
SIGNAL(serviceChanged(QString)));
m_subject->setService("org.maemo.TextProcessor");
QString thisService = "com.nokia.TextProcessor";
serviceFwService = thisService;
m_subject->handleServiceAvailable(thisService, "org.maemo.MailService");
QCOMPARE(serviceAvailableSpy.count(), 0);
QCOMPARE(serviceChangedSpy.count(), 0);
}
// current service; new preferred service for this if
// should not get signal:serviceAvilable
// should get signal:serviceChanged
void Ut_MServiceFwBaseIf::testHandleServiceAvailable3()
{
QSignalSpy serviceAvailableSpy(m_subject,
SIGNAL(serviceAvailable(QString)));
QSignalSpy serviceChangedSpy(m_subject,
SIGNAL(serviceChanged(QString)));
m_subject->setService("org.maemo.TextProcessor");
QString thisService = "com.nokia.TextProcessor";
serviceFwService = thisService;
m_subject->handleServiceAvailable(thisService, m_subject->interfaceName());
QCOMPARE(serviceAvailableSpy.count(), 0);
QCOMPARE(serviceChangedSpy.count(), 1);
}
// no current service; dead service is for other if
// should not get serviceUnavailable
// should not get serviceChanged
void Ut_MServiceFwBaseIf::testHandleServiceUnavailable0()
{
QSignalSpy serviceUnavailableSpy(m_subject,
SIGNAL(serviceUnavailable(QString)));
QSignalSpy serviceChangedSpy(m_subject,
SIGNAL(serviceChanged(QString)));
m_subject->setService("");
QString thisService = "com.nokia.TextProcessor";
serviceFwService = "";
m_subject->handleServiceUnavailable(thisService);
QCOMPARE(serviceUnavailableSpy.count(), 0);
QCOMPARE(serviceChangedSpy.count(), 0);
}
// current service; dead service is for other if
// should not get serviceUnavailable
// should not get serviceChanged
void Ut_MServiceFwBaseIf::testHandleServiceUnavailable1()
{
QSignalSpy serviceUnavailableSpy(m_subject,
SIGNAL(serviceUnavailable(QString)));
QSignalSpy serviceChangedSpy(m_subject,
SIGNAL(serviceChanged(QString)));
m_subject->setService("com.nokia.TextProcessor");
serviceFwService = m_subject->serviceName();
m_subject->handleServiceUnavailable("com.nokia.EmailService");
QCOMPARE(serviceUnavailableSpy.count(), 0);
QCOMPARE(serviceChangedSpy.count(), 0);
}
// current service; dead service is not last for this if
// should not get serviceUnavailable
// should get serviceChanged
void Ut_MServiceFwBaseIf::testHandleServiceUnavailable2()
{
QSignalSpy serviceUnavailableSpy(m_subject,
SIGNAL(serviceUnavailable(QString)));
QSignalSpy serviceChangedSpy(m_subject,
SIGNAL(serviceChanged(QString)));
m_subject->setService("com.nokia.TextProcessor");
serviceFwService = "org.maemo.TextProcessor";
m_subject->handleServiceUnavailable(m_subject->serviceName());
QCOMPARE(serviceUnavailableSpy.count(), 0);
QCOMPARE(serviceChangedSpy.count(), 1);
}
// current service; dead service is last for this if
// should get serviceUnavailable
// should not get serviceChanged
void Ut_MServiceFwBaseIf::testHandleServiceUnavailable3()
{
QSignalSpy serviceUnavailableSpy(m_subject,
SIGNAL(serviceUnavailable(QString)));
QSignalSpy serviceChangedSpy(m_subject,
SIGNAL(serviceChanged(QString)));
m_subject->setService("com.nokia.TextProcessor");
serviceFwService = "";
m_subject->handleServiceUnavailable(m_subject->serviceName());
QCOMPARE(serviceUnavailableSpy.count(), 1);
QCOMPARE(serviceChangedSpy.count(), 0);
}
void Ut_MServiceFwBaseIf::testResolveServiceName()
{
serviceFwService = "com.nokia.TextProcessor";
QString thisService = m_subject->resolveServiceName("com.nokia.TextProcessorIf", "");
QCOMPARE(thisService, serviceFwService);
thisService = m_subject->resolveServiceName("com.nokia.TextProcessorIf", "org.maemo.TextProcessor");
QCOMPARE(thisService, QString("org.maemo.TextProcessor"));
}
QTEST_APPLESS_MAIN(Ut_MServiceFwBaseIf)
<|endoftext|> |
<commit_before>#include "StdAfx.h"
#include "DuiObject.h"
// DUIIDԶɱDUIID1000ʼɣDUIؼIDԶɵʼֵĶIDDzһģ
static int g_nDuiObjlId = 1000;
CDuiObject::CDuiObject(void)
{
m_uID = g_nDuiObjlId++;
m_strName = _T("");
m_pDuiHandler = NULL;
SetRect(CRect(0,0,0,0));
}
CDuiObject::~CDuiObject(void)
{
}
// жǷ˶
BOOL CDuiObject::IsThisObject(UINT uID, CString strName)
{
if(uID == 0 || strName == _T(""))
{
return FALSE;
}
if(uID == m_uID || strName == m_strName)
{
return TRUE;
}
return FALSE;
}
// ע¼
BOOL CDuiObject::RegisterHandler(CDuiHandler* pDuiHandler)
{
if(pDuiHandler == NULL)
{
return FALSE;
}
m_pDuiHandler = pDuiHandler;
m_pDuiHandler->SetDuiObject(this);
return TRUE;
}
// öԵĻIDnameԵ
HRESULT CDuiObject::SetAttribute(CString strAttribName, CString strValue, BOOL bLoading)
{
HRESULT hRet = E_FAIL;
if (_T("id") == strAttribName)
{
m_uID = ::StrToInt(strValue);
hRet = S_FALSE;
}else
if (_T("name") == strAttribName)
{
m_strName = strValue;
hRet = S_FALSE;
}else
return E_FAIL;
return hRet;
}
// XMLڵ㣬ڵеϢõǰؼ
BOOL CDuiObject::Load(DuiXmlNode pXmlElem, BOOL bLoadSubControl)
{
// posҪ,,ЩԻܵӰ,ȷijʼ
CString strPosValue = _T("");
for (DuiXmlAttribute pAttrib = pXmlElem.first_attribute(); pAttrib; pAttrib = pAttrib.next_attribute())
{
CString strName = pAttrib.name();
if(strName == _T("pos"))
{
strPosValue = pAttrib.value();
}else
{
SetAttribute(pAttrib.name(), pAttrib.value(), TRUE);
}
}
if(!strPosValue.IsEmpty())
{
SetAttribute(_T("pos"), strPosValue, TRUE);
}
return TRUE;
}
// ַ滻е滻
void CDuiObject::ParseDuiString(CString& strString)
{
DuiSystem::Instance()->ParseDuiString(strString);
}
ULONG CDuiObject::HexStringToULong(LPCTSTR lpszValue, int nSize)
{
int ret=0;
StrToIntEx(lpszValue,STIF_SUPPORT_HEX,&ret);
return ret;
/*
LPCTSTR pchValue = lpszValue;
ULONG ulValue = 0;
while (*pchValue && nSize != 0)
{
ulValue <<= 4;
if ('a' <= *pchValue && 'f' >= *pchValue)
ulValue |= (*pchValue - 'a' + 10);
else if ('A' <= *pchValue && 'F' >= *pchValue)
ulValue |= (*pchValue - 'A' + 10);
else if ('0' <= *pchValue && '9' >= *pchValue)
ulValue |= (*pchValue - '0');
else
return 0;
++ pchValue;
-- nSize;
}
return ulValue;
*/
}
// 16ַתΪColor
Color CDuiObject::HexStringToColor(LPCTSTR lpszValue)
{
return Color(
(BYTE)HexStringToULong(lpszValue, 2),
(BYTE)HexStringToULong(lpszValue + 2, 2),
(BYTE)HexStringToULong(lpszValue + 4, 2)
);
}
// 10ƶŷַָתΪColor
Color CDuiObject::StringToColor(LPCTSTR lpszValue)
{
CStringA strValue;
strValue = lpszValue;
BYTE c1,c2,c3,c4;
CStringA s1 = "";
CStringA s2 = "";
CStringA s3 = "";
CStringA s4 = "";
int nPos = strValue.Find(",");
if(nPos != -1)
{
s1 = strValue.Left(nPos);
strValue.Delete(0, nPos+1);
nPos = strValue.Find(",");
if(nPos != -1)
{
s2 = strValue.Left(nPos);
strValue.Delete(0, nPos+1);
nPos = strValue.Find(",");
if(nPos != -1)
{
s3 = strValue.Left(nPos);
strValue.Delete(0, nPos+1);
s4 = strValue;
}else
{
s3 = strValue;
}
}
}
c1 = atoi(s1);
c2 = atoi(s2);
c3 = atoi(s3);
c4 = atoi(s4);
if(s4.IsEmpty())
{
return Color(c1, c2, c3);
}else
{
return Color(c1, c2, c3, c4);
}
}
// 16ַתRGBɫ
COLORREF CDuiObject::HexStringToRGBColor(LPCTSTR lpszValue)
{
return RGB(
HexStringToULong(lpszValue, 2),
HexStringToULong(lpszValue + 2, 2),
HexStringToULong(lpszValue + 4, 2)
);
}
// ַȡ
void CDuiObject::ParseKeyCode(LPCTSTR lpszValue, UINT& nChar, UINT& nFlag)
{
CStringA strValue;
strValue = lpszValue;
nChar = 0;
nFlag = 0;
strValue.Trim();
strValue.MakeUpper();
CStringA strFlag = "";
CStringA strChar = strValue;
int nPos = strValue.Find("+");
if(nPos != -1)
{
strFlag = strValue.Left(nPos);
strValue.Delete(0, nPos+1);
strChar = strValue;
strFlag.Trim();
strChar.Trim();
}
if(strChar.IsEmpty())
{
return;
}
if(strFlag == "CTRL")
{
nFlag |= VK_CONTROL;
}else
if(strFlag == "ALT")
{
nFlag |= VK_MENU;
}else
if(strFlag == "SHIFT")
{
nFlag |= VK_SHIFT;
}
if(strChar == "RETURN")
{
nChar = VK_RETURN;
}else
if(strChar == "ESC")
{
nChar = VK_ESCAPE;
}else
if(strChar == "BACK")
{
nChar = VK_BACK;
}else
if(strChar == "TAB")
{
nChar = VK_TAB;
}else
if(strChar == "SPACE")
{
nChar = VK_SPACE;
}else
if(strChar == "PRIOR")
{
nChar = VK_PRIOR;
}else
if(strChar == "NEXT")
{
nChar = VK_NEXT;
}else
if(strChar == "END")
{
nChar = VK_END;
}else
if(strChar == "HOME")
{
nChar = VK_HOME;
}else
if(strChar == "LEFT")
{
nChar = VK_LEFT;
}else
if(strChar == "UP")
{
nChar = VK_UP;
}else
if(strChar == "RIGHT")
{
nChar = VK_RIGHT;
}else
if(strChar == "DOWN")
{
nChar = VK_DOWN;
}else
if(strChar == "SELECT")
{
nChar = VK_SELECT;
}else
if(strChar == "PRINT")
{
nChar = VK_PRINT;
}else
if(strChar == "INSERT")
{
nChar = VK_INSERT;
}else
if(strChar == "DELETE")
{
nChar = VK_DELETE;
}else
if(strChar == "F1")
{
nChar = VK_F1;
}else
if(strChar == "F2")
{
nChar = VK_F2;
}else
if(strChar == "F3")
{
nChar = VK_F3;
}else
if(strChar == "F4")
{
nChar = VK_F4;
}else
if(strChar == "F5")
{
nChar = VK_F5;
}else
if(strChar == "F6")
{
nChar = VK_F6;
}else
if(strChar == "F7")
{
nChar = VK_F7;
}else
if(strChar == "F8")
{
nChar = VK_F8;
}else
if(strChar == "F9")
{
nChar = VK_F9;
}else
if(strChar == "F10")
{
nChar = VK_F10;
}else
if(strChar == "F11")
{
nChar = VK_F11;
}else
if(strChar == "F12")
{
nChar = VK_F12;
}else
{
char ch = strChar[0];
if(((ch >= '0') && (ch < '9')) || ((ch >= 'A') && (ch < 'Z')))
{
nChar = ch;
}
}
}<commit_msg>修改HexStringToColor<commit_after>#include "StdAfx.h"
#include "DuiObject.h"
// DUIIDԶɱDUIID1000ʼɣDUIؼIDԶɵʼֵĶIDDzһģ
static int g_nDuiObjlId = 1000;
CDuiObject::CDuiObject(void)
{
m_uID = g_nDuiObjlId++;
m_strName = _T("");
m_pDuiHandler = NULL;
SetRect(CRect(0,0,0,0));
}
CDuiObject::~CDuiObject(void)
{
}
// жǷ˶
BOOL CDuiObject::IsThisObject(UINT uID, CString strName)
{
if(uID == 0 || strName == _T(""))
{
return FALSE;
}
if(uID == m_uID || strName == m_strName)
{
return TRUE;
}
return FALSE;
}
// ע¼
BOOL CDuiObject::RegisterHandler(CDuiHandler* pDuiHandler)
{
if(pDuiHandler == NULL)
{
return FALSE;
}
m_pDuiHandler = pDuiHandler;
m_pDuiHandler->SetDuiObject(this);
return TRUE;
}
// öԵĻIDnameԵ
HRESULT CDuiObject::SetAttribute(CString strAttribName, CString strValue, BOOL bLoading)
{
HRESULT hRet = E_FAIL;
if (_T("id") == strAttribName)
{
m_uID = ::StrToInt(strValue);
hRet = S_FALSE;
}else
if (_T("name") == strAttribName)
{
m_strName = strValue;
hRet = S_FALSE;
}else
return E_FAIL;
return hRet;
}
// XMLڵ㣬ڵеϢõǰؼ
BOOL CDuiObject::Load(DuiXmlNode pXmlElem, BOOL bLoadSubControl)
{
// posҪ,,ЩԻܵӰ,ȷijʼ
CString strPosValue = _T("");
for (DuiXmlAttribute pAttrib = pXmlElem.first_attribute(); pAttrib; pAttrib = pAttrib.next_attribute())
{
CString strName = pAttrib.name();
if(strName == _T("pos"))
{
strPosValue = pAttrib.value();
}else
{
SetAttribute(pAttrib.name(), pAttrib.value(), TRUE);
}
}
if(!strPosValue.IsEmpty())
{
SetAttribute(_T("pos"), strPosValue, TRUE);
}
return TRUE;
}
// ַ滻е滻
void CDuiObject::ParseDuiString(CString& strString)
{
DuiSystem::Instance()->ParseDuiString(strString);
}
ULONG CDuiObject::HexStringToULong(LPCTSTR lpszValue, int nSize)
{
/*
std::wstring ws = lpszValue;
ULONG value;
std::wistringstream iss(ws);
iss >> std::hex >> value;
return value;
*/
/*
ULONG ret=0;
CString strValue;
strValue.Format(_T("0X%s"),lpszValue);
StrToIntEx(strValue,STIF_SUPPORT_HEX,&ret);
return ret;
*/
CStringA strValueA;
strValueA = lpszValue;
LPCSTR pchValue = strValueA.GetBuffer();;
ULONG ulValue = 0;
while (*pchValue && nSize != 0)
{
ulValue <<= 4;
if ('a' <= *pchValue && 'f' >= *pchValue)
ulValue |= (*pchValue - 'a' + 10);
else if ('A' <= *pchValue && 'F' >= *pchValue)
ulValue |= (*pchValue - 'A' + 10);
else if ('0' <= *pchValue && '9' >= *pchValue)
ulValue |= (*pchValue - '0');
else
return 0;
++ pchValue;
-- nSize;
}
return ulValue;
*/
}
// 16ַתΪColor
Color CDuiObject::HexStringToColor(LPCTSTR lpszValue)
{
return Color(
(BYTE)HexStringToULong(lpszValue, 2),
(BYTE)HexStringToULong(lpszValue + 2, 2),
(BYTE)HexStringToULong(lpszValue + 4, 2)
);
}
// 10ƶŷַָתΪColor
Color CDuiObject::StringToColor(LPCTSTR lpszValue)
{
CStringA strValue;
strValue = lpszValue;
BYTE c1,c2,c3,c4;
CStringA s1 = "";
CStringA s2 = "";
CStringA s3 = "";
CStringA s4 = "";
int nPos = strValue.Find(",");
if(nPos != -1)
{
s1 = strValue.Left(nPos);
strValue.Delete(0, nPos+1);
nPos = strValue.Find(",");
if(nPos != -1)
{
s2 = strValue.Left(nPos);
strValue.Delete(0, nPos+1);
nPos = strValue.Find(",");
if(nPos != -1)
{
s3 = strValue.Left(nPos);
strValue.Delete(0, nPos+1);
s4 = strValue;
}else
{
s3 = strValue;
}
}
}
c1 = atoi(s1);
c2 = atoi(s2);
c3 = atoi(s3);
c4 = atoi(s4);
if(s4.IsEmpty())
{
return Color(c1, c2, c3);
}else
{
return Color(c1, c2, c3, c4);
}
}
// 16ַתRGBɫ
COLORREF CDuiObject::HexStringToRGBColor(LPCTSTR lpszValue)
{
return RGB(
HexStringToULong(lpszValue, 2),
HexStringToULong(lpszValue + 2, 2),
HexStringToULong(lpszValue + 4, 2)
);
}
// ַȡ
void CDuiObject::ParseKeyCode(LPCTSTR lpszValue, UINT& nChar, UINT& nFlag)
{
CStringA strValue;
strValue = lpszValue;
nChar = 0;
nFlag = 0;
strValue.Trim();
strValue.MakeUpper();
CStringA strFlag = "";
CStringA strChar = strValue;
int nPos = strValue.Find("+");
if(nPos != -1)
{
strFlag = strValue.Left(nPos);
strValue.Delete(0, nPos+1);
strChar = strValue;
strFlag.Trim();
strChar.Trim();
}
if(strChar.IsEmpty())
{
return;
}
if(strFlag == "CTRL")
{
nFlag |= VK_CONTROL;
}else
if(strFlag == "ALT")
{
nFlag |= VK_MENU;
}else
if(strFlag == "SHIFT")
{
nFlag |= VK_SHIFT;
}
if(strChar == "RETURN")
{
nChar = VK_RETURN;
}else
if(strChar == "ESC")
{
nChar = VK_ESCAPE;
}else
if(strChar == "BACK")
{
nChar = VK_BACK;
}else
if(strChar == "TAB")
{
nChar = VK_TAB;
}else
if(strChar == "SPACE")
{
nChar = VK_SPACE;
}else
if(strChar == "PRIOR")
{
nChar = VK_PRIOR;
}else
if(strChar == "NEXT")
{
nChar = VK_NEXT;
}else
if(strChar == "END")
{
nChar = VK_END;
}else
if(strChar == "HOME")
{
nChar = VK_HOME;
}else
if(strChar == "LEFT")
{
nChar = VK_LEFT;
}else
if(strChar == "UP")
{
nChar = VK_UP;
}else
if(strChar == "RIGHT")
{
nChar = VK_RIGHT;
}else
if(strChar == "DOWN")
{
nChar = VK_DOWN;
}else
if(strChar == "SELECT")
{
nChar = VK_SELECT;
}else
if(strChar == "PRINT")
{
nChar = VK_PRINT;
}else
if(strChar == "INSERT")
{
nChar = VK_INSERT;
}else
if(strChar == "DELETE")
{
nChar = VK_DELETE;
}else
if(strChar == "F1")
{
nChar = VK_F1;
}else
if(strChar == "F2")
{
nChar = VK_F2;
}else
if(strChar == "F3")
{
nChar = VK_F3;
}else
if(strChar == "F4")
{
nChar = VK_F4;
}else
if(strChar == "F5")
{
nChar = VK_F5;
}else
if(strChar == "F6")
{
nChar = VK_F6;
}else
if(strChar == "F7")
{
nChar = VK_F7;
}else
if(strChar == "F8")
{
nChar = VK_F8;
}else
if(strChar == "F9")
{
nChar = VK_F9;
}else
if(strChar == "F10")
{
nChar = VK_F10;
}else
if(strChar == "F11")
{
nChar = VK_F11;
}else
if(strChar == "F12")
{
nChar = VK_F12;
}else
{
char ch = strChar[0];
if(((ch >= '0') && (ch < '9')) || ((ch >= 'A') && (ch < 'Z')))
{
nChar = ch;
}
}
}<|endoftext|> |
<commit_before>/*
RawSpeed - RAW file decoder.
Copyright (C) 2009-2014 Klaus Post
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "io/FileReader.h"
#include "common/Common.h" // for make_unique
#include "io/Buffer.h" // for Buffer
#include "io/FileIOException.h" // for FileIOException (ptr only), ThrowFIE
#include <algorithm> // for move
#include <cstdio> // for fclose, fseek, fopen, fread, ftell
#include <fcntl.h> // for SEEK_END, SEEK_SET
#include <limits> // for numeric_limits
#include <memory> // for unique_ptr
#if !defined(__unix__) && !defined(__APPLE__)
#include <io.h>
#include <tchar.h>
#include <windows.h>
#endif // !defined(__unix__) && !defined(__APPLE__)
namespace rawspeed {
FileReader::FileReader(const char *_filename) : mFilename(_filename) {}
std::unique_ptr<Buffer> FileReader::readFile() {
#if defined(__unix__) || defined(__APPLE__)
int bytes_read = 0;
FILE *file;
long size;
file = fopen(mFilename, "rb");
if (file == nullptr)
ThrowFIE("Could not open file.");
fseek(file, 0, SEEK_END);
size = ftell(file);
if (size > std::numeric_limits<Buffer::size_type>::max()) {
fclose(file);
ThrowFIE("File is too big.");
}
if (size <= 0) {
fclose(file);
ThrowFIE("File is 0 bytes.");
}
fseek(file, 0, SEEK_SET);
auto dest = Buffer::Create(size);
bytes_read = fread(dest.get(), 1, size, file);
fclose(file);
if (size != bytes_read)
ThrowFIE("Could not read file.");
auto fileData = make_unique<Buffer>(move(dest), size);
#else // __unix__
HANDLE file_h; // File handle
file_h = CreateFile(mFilename, GENERIC_READ, FILE_SHARE_READ, nullptr,
OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, nullptr);
if (file_h == INVALID_HANDLE_VALUE) {
ThrowFIE("Could not open file.");
}
LARGE_INTEGER f_size;
GetFileSizeEx(file_h , &f_size);
static_assert(
std::numeric_limits<Buffer::size_type>::max() ==
std::numeric_limits<decltype(f_size.LowPart)>::max(),
"once Buffer migrates to 64-bit index, this needs to be updated.");
if (HighPart > 0)
ThrowFIE("File is too big.");
if (f_size.LowPart <= 0)
ThrowFIE("File is 0 bytes.");
auto dest = Buffer::Create(f_size.LowPart);
DWORD bytes_read;
if (!ReadFile(file_h, dest.get(), f_size.LowPart, &bytes_read, nullptr)) {
CloseHandle(file_h);
ThrowFIE("Could not read file.");
}
CloseHandle(file_h);
if (f_size.LowPart != bytes_read)
ThrowFIE("Could not read file.");
auto fileData = make_unique<Buffer>(move(dest), f_size.LowPart);
#endif // __unix__
return fileData;
}
} // namespace rawspeed
<commit_msg>FileReader: ugh, maybe now fix win build?<commit_after>/*
RawSpeed - RAW file decoder.
Copyright (C) 2009-2014 Klaus Post
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "io/FileReader.h"
#include "common/Common.h" // for make_unique
#include "io/Buffer.h" // for Buffer
#include "io/FileIOException.h" // for FileIOException (ptr only), ThrowFIE
#include <algorithm> // for move
#include <cstdio> // for fclose, fseek, fopen, fread, ftell
#include <fcntl.h> // for SEEK_END, SEEK_SET
#include <limits> // for numeric_limits
#include <memory> // for unique_ptr
#if !defined(__unix__) && !defined(__APPLE__)
#include <io.h>
#include <tchar.h>
#include <windows.h>
#endif // !defined(__unix__) && !defined(__APPLE__)
namespace rawspeed {
FileReader::FileReader(const char *_filename) : mFilename(_filename) {}
std::unique_ptr<Buffer> FileReader::readFile() {
#if defined(__unix__) || defined(__APPLE__)
int bytes_read = 0;
FILE *file;
long size;
file = fopen(mFilename, "rb");
if (file == nullptr)
ThrowFIE("Could not open file.");
fseek(file, 0, SEEK_END);
size = ftell(file);
if (size > std::numeric_limits<Buffer::size_type>::max()) {
fclose(file);
ThrowFIE("File is too big.");
}
if (size <= 0) {
fclose(file);
ThrowFIE("File is 0 bytes.");
}
fseek(file, 0, SEEK_SET);
auto dest = Buffer::Create(size);
bytes_read = fread(dest.get(), 1, size, file);
fclose(file);
if (size != bytes_read)
ThrowFIE("Could not read file.");
auto fileData = make_unique<Buffer>(move(dest), size);
#else // __unix__
HANDLE file_h; // File handle
file_h = CreateFile(mFilename, GENERIC_READ, FILE_SHARE_READ, nullptr,
OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, nullptr);
if (file_h == INVALID_HANDLE_VALUE) {
ThrowFIE("Could not open file.");
}
LARGE_INTEGER f_size;
GetFileSizeEx(file_h , &f_size);
static_assert(
std::numeric_limits<Buffer::size_type>::max() ==
std::numeric_limits<decltype(f_size.LowPart)>::max(),
"once Buffer migrates to 64-bit index, this needs to be updated.");
if (f_size.HighPart > 0)
ThrowFIE("File is too big.");
if (f_size.LowPart <= 0)
ThrowFIE("File is 0 bytes.");
auto dest = Buffer::Create(f_size.LowPart);
DWORD bytes_read;
if (!ReadFile(file_h, dest.get(), f_size.LowPart, &bytes_read, nullptr)) {
CloseHandle(file_h);
ThrowFIE("Could not read file.");
}
CloseHandle(file_h);
if (f_size.LowPart != bytes_read)
ThrowFIE("Could not read file.");
auto fileData = make_unique<Buffer>(move(dest), f_size.LowPart);
#endif // __unix__
return fileData;
}
} // namespace rawspeed
<|endoftext|> |
<commit_before>/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrConfigConversionEffect.h"
#include "gl/GrGLProgramStage.h"
class GrGLConfigConversionEffect : public GrGLProgramStage {
public:
GrGLConfigConversionEffect(const GrProgramStageFactory& factory,
const GrCustomStage& s) : INHERITED (factory) {
const GrConfigConversionEffect& stage = static_cast<const GrConfigConversionEffect&>(s);
fSwapRedAndBlue = stage.swapsRedAndBlue();
fPMConversion = stage.pmConversion();
}
virtual void emitVS(GrGLShaderBuilder* builder,
const char* vertexCoords) SK_OVERRIDE { }
virtual void emitFS(GrGLShaderBuilder* builder,
const char* outputColor,
const char* inputColor,
const char* samplerName) SK_OVERRIDE {
builder->fFSCode.append("\tvec4 tempColor;\n");
builder->emitDefaultFetch("tempColor", samplerName);
if (GrConfigConversionEffect::kNone_PMConversion == fPMConversion) {
GrAssert(fSwapRedAndBlue);
builder->fFSCode.appendf("\t%s = tempColor.bgra;\n", outputColor);
} else {
const char* swiz = fSwapRedAndBlue ? "bgr" : "rgb";
switch (fPMConversion) {
case GrConfigConversionEffect::kMulByAlpha_RoundUp_PMConversion:
builder->fFSCode.appendf(
"\t%s = vec4(ceil(tempColor.%s*tempColor.a*255.0)/255.0, tempColor.a);\n",
outputColor, swiz);
break;
case GrConfigConversionEffect::kMulByAlpha_RoundDown_PMConversion:
builder->fFSCode.appendf(
"\t%s = vec4(floor(tempColor.%s*tempColor.a*255.0)/255.0, tempColor.a);\n",
outputColor, swiz);
break;
case GrConfigConversionEffect::kDivByAlpha_RoundUp_PMConversion:
builder->fFSCode.appendf("\t%s = tempColor.a <= 0.0 ? vec4(0,0,0,0) : vec4(ceil(tempColor.%s / tempColor.a * 255.0)/255.0, tempColor.a);\n",
outputColor, swiz);
break;
case GrConfigConversionEffect::kDivByAlpha_RoundDown_PMConversion:
builder->fFSCode.appendf("\t%s = tempColor.a <= 0.0 ? vec4(0,0,0,0) : vec4(floor(tempColor.%s / tempColor.a * 255.0)/255.0, tempColor.a);\n",
outputColor, swiz);
break;
}
}
}
static inline StageKey GenKey(const GrCustomStage& s, const GrGLCaps&) {
const GrConfigConversionEffect& stage = static_cast<const GrConfigConversionEffect&>(s);
return static_cast<int>(stage.swapsRedAndBlue()) | (stage.pmConversion() << 1);
}
private:
bool fSwapRedAndBlue;
GrConfigConversionEffect::PMConversion fPMConversion;
typedef GrGLProgramStage INHERITED;
};
///////////////////////////////////////////////////////////////////////////////
GrConfigConversionEffect::GrConfigConversionEffect(GrTexture* texture,
bool swapRedAndBlue,
PMConversion pmConversion)
: GrSingleTextureEffect(texture)
, fSwapRedAndBlue(swapRedAndBlue)
, fPMConversion(pmConversion) {
GrAssert(kRGBA_8888_GrPixelConfig == texture->config() ||
kBGRA_8888_GrPixelConfig == texture->config());
// Why did we pollute our texture cache instead of using a GrSingleTextureEffect?
GrAssert(swapRedAndBlue || kNone_PMConversion != pmConversion);
}
const GrProgramStageFactory& GrConfigConversionEffect::getFactory() const {
return GrTProgramStageFactory<GrConfigConversionEffect>::getInstance();
}
bool GrConfigConversionEffect::isEqual(const GrCustomStage& s) const {
const GrConfigConversionEffect& other = static_cast<const GrConfigConversionEffect&>(s);
return other.fSwapRedAndBlue == fSwapRedAndBlue && other.fPMConversion == fPMConversion;
}
///////////////////////////////////////////////////////////////////////////////
GR_DEFINE_CUSTOM_STAGE_TEST(GrConfigConversionEffect);
GrCustomStage* GrConfigConversionEffect::TestCreate(SkRandom* random,
GrContext* context,
GrTexture* textures[]) {
PMConversion pmConv = static_cast<PMConversion>(random->nextULessThan(kPMConversionCnt));
bool swapRB;
if (kNone_PMConversion == pmConv) {
swapRB = true;
} else {
swapRB = random->nextBool();
}
return SkNEW_ARGS(GrConfigConversionEffect,
(textures[GrCustomStageUnitTest::kSkiaPMTextureIdx], swapRB, pmConv));
}
///////////////////////////////////////////////////////////////////////////////
void GrConfigConversionEffect::TestForPreservingPMConversions(GrContext* context,
PMConversion* pmToUPMRule,
PMConversion* upmToPMRule) {
*pmToUPMRule = kNone_PMConversion;
*upmToPMRule = kNone_PMConversion;
SkAutoTMalloc<uint32_t> data(256 * 256 * 3);
uint32_t* srcData = data.get();
uint32_t* firstRead = data.get() + 256 * 256;
uint32_t* secondRead = data.get() + 2 * 256 * 256;
// Fill with every possible premultiplied A, color channel value. There will be 256-y duplicate
// values in row y. We set r,g, and b to the same value since they are handled identically.
for (int y = 0; y < 256; ++y) {
for (int x = 0; x < 256; ++x) {
uint8_t* color = reinterpret_cast<uint8_t*>(&srcData[256*y + x]);
color[3] = y;
color[2] = GrMin(x, y);
color[1] = GrMin(x, y);
color[0] = GrMin(x, y);
}
}
GrTextureDesc desc;
desc.fFlags = kRenderTarget_GrTextureFlagBit |
kNoStencil_GrTextureFlagBit;
desc.fWidth = 256;
desc.fHeight = 256;
desc.fConfig = kRGBA_8888_GrPixelConfig;
SkAutoTUnref<GrTexture> readTex(context->createUncachedTexture(desc, NULL, 0));
if (!readTex.get()) {
return;
}
SkAutoTUnref<GrTexture> tempTex(context->createUncachedTexture(desc, NULL, 0));
if (!tempTex.get()) {
return;
}
desc.fFlags = kNone_GrTextureFlags;
SkAutoTUnref<GrTexture> dataTex(context->createUncachedTexture(desc, data, 0));
if (!dataTex.get()) {
return;
}
static const PMConversion kConversionRules[][2] = {
{kDivByAlpha_RoundDown_PMConversion, kMulByAlpha_RoundUp_PMConversion},
{kDivByAlpha_RoundUp_PMConversion, kMulByAlpha_RoundDown_PMConversion},
};
GrContext::AutoWideOpenIdentityDraw awoid(context, NULL);
bool failed = true;
for (size_t i = 0; i < GR_ARRAY_COUNT(kConversionRules) && failed; ++i) {
*pmToUPMRule = kConversionRules[i][0];
*upmToPMRule = kConversionRules[i][1];
static const GrRect kDstRect = GrRect::MakeWH(GrIntToScalar(256), GrIntToScalar(256));
static const GrRect kSrcRect = GrRect::MakeWH(GR_Scalar1, GR_Scalar1);
// We do a PM->UPM draw from dataTex to readTex and read the data. Then we do a UPM->PM draw
// from readTex to tempTex followed by a PM->UPM draw to readTex and finally read the data.
// We then verify that two reads produced the same values.
GrPaint paint;
paint.reset();
SkAutoTUnref<GrCustomStage> pmToUPMStage1(SkNEW_ARGS(GrConfigConversionEffect,
(dataTex, false, *pmToUPMRule)));
SkAutoTUnref<GrCustomStage> upmToPMStage(SkNEW_ARGS(GrConfigConversionEffect,
(readTex, false, *upmToPMRule)));
SkAutoTUnref<GrCustomStage> pmToUPMStage2(SkNEW_ARGS(GrConfigConversionEffect,
(tempTex, false, *pmToUPMRule)));
context->setRenderTarget(readTex->asRenderTarget());
paint.textureSampler(0)->setCustomStage(pmToUPMStage1);
context->drawRectToRect(paint, kDstRect, kSrcRect);
readTex->readPixels(0, 0, 256, 256, kRGBA_8888_GrPixelConfig, firstRead);
context->setRenderTarget(tempTex->asRenderTarget());
paint.textureSampler(0)->setCustomStage(upmToPMStage);
context->drawRectToRect(paint, kDstRect, kSrcRect);
context->setRenderTarget(readTex->asRenderTarget());
paint.textureSampler(0)->setCustomStage(pmToUPMStage2);
context->drawRectToRect(paint, kDstRect, kSrcRect);
readTex->readPixels(0, 0, 256, 256, kRGBA_8888_GrPixelConfig, secondRead);
failed = false;
for (int y = 0; y < 256 && !failed; ++y) {
for (int x = 0; x <= y; ++x) {
if (firstRead[256 * y + x] != secondRead[256 * y + x]) {
failed = true;
break;
}
}
}
}
if (failed) {
*pmToUPMRule = kNone_PMConversion;
*upmToPMRule = kNone_PMConversion;
}
}
GrCustomStage* GrConfigConversionEffect::Create(GrTexture* texture,
bool swapRedAndBlue,
PMConversion pmConversion) {
if (!swapRedAndBlue && kNone_PMConversion == pmConversion) {
// If we returned a GrConfigConversionEffect that was equivalent to a GrSingleTextureEffect
// then we may pollute our texture cache with redundant shaders. So in the case that no
// conversions were requested we instead return a GrSingleTextureEffect.
return SkNEW_ARGS(GrSingleTextureEffect, (texture));
} else {
if (kRGBA_8888_GrPixelConfig != texture->config() &&
kBGRA_8888_GrPixelConfig != texture->config() &&
kNone_PMConversion != pmConversion) {
// The PM conversions assume colors are 0..255
return NULL;
}
return SkNEW_ARGS(GrConfigConversionEffect, (texture, swapRedAndBlue, pmConversion));
}
}
<commit_msg>Added default to switch to stop compiler failure in Chrome (unreviewed)<commit_after>/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrConfigConversionEffect.h"
#include "gl/GrGLProgramStage.h"
class GrGLConfigConversionEffect : public GrGLProgramStage {
public:
GrGLConfigConversionEffect(const GrProgramStageFactory& factory,
const GrCustomStage& s) : INHERITED (factory) {
const GrConfigConversionEffect& stage = static_cast<const GrConfigConversionEffect&>(s);
fSwapRedAndBlue = stage.swapsRedAndBlue();
fPMConversion = stage.pmConversion();
}
virtual void emitVS(GrGLShaderBuilder* builder,
const char* vertexCoords) SK_OVERRIDE { }
virtual void emitFS(GrGLShaderBuilder* builder,
const char* outputColor,
const char* inputColor,
const char* samplerName) SK_OVERRIDE {
builder->fFSCode.append("\tvec4 tempColor;\n");
builder->emitDefaultFetch("tempColor", samplerName);
if (GrConfigConversionEffect::kNone_PMConversion == fPMConversion) {
GrAssert(fSwapRedAndBlue);
builder->fFSCode.appendf("\t%s = tempColor.bgra;\n", outputColor);
} else {
const char* swiz = fSwapRedAndBlue ? "bgr" : "rgb";
switch (fPMConversion) {
case GrConfigConversionEffect::kMulByAlpha_RoundUp_PMConversion:
builder->fFSCode.appendf(
"\t%s = vec4(ceil(tempColor.%s*tempColor.a*255.0)/255.0, tempColor.a);\n",
outputColor, swiz);
break;
case GrConfigConversionEffect::kMulByAlpha_RoundDown_PMConversion:
builder->fFSCode.appendf(
"\t%s = vec4(floor(tempColor.%s*tempColor.a*255.0)/255.0, tempColor.a);\n",
outputColor, swiz);
break;
case GrConfigConversionEffect::kDivByAlpha_RoundUp_PMConversion:
builder->fFSCode.appendf("\t%s = tempColor.a <= 0.0 ? vec4(0,0,0,0) : vec4(ceil(tempColor.%s / tempColor.a * 255.0)/255.0, tempColor.a);\n",
outputColor, swiz);
break;
case GrConfigConversionEffect::kDivByAlpha_RoundDown_PMConversion:
builder->fFSCode.appendf("\t%s = tempColor.a <= 0.0 ? vec4(0,0,0,0) : vec4(floor(tempColor.%s / tempColor.a * 255.0)/255.0, tempColor.a);\n",
outputColor, swiz);
break;
default:
GrCrash("Unknown conversion op.");
break;
}
}
}
static inline StageKey GenKey(const GrCustomStage& s, const GrGLCaps&) {
const GrConfigConversionEffect& stage = static_cast<const GrConfigConversionEffect&>(s);
return static_cast<int>(stage.swapsRedAndBlue()) | (stage.pmConversion() << 1);
}
private:
bool fSwapRedAndBlue;
GrConfigConversionEffect::PMConversion fPMConversion;
typedef GrGLProgramStage INHERITED;
};
///////////////////////////////////////////////////////////////////////////////
GrConfigConversionEffect::GrConfigConversionEffect(GrTexture* texture,
bool swapRedAndBlue,
PMConversion pmConversion)
: GrSingleTextureEffect(texture)
, fSwapRedAndBlue(swapRedAndBlue)
, fPMConversion(pmConversion) {
GrAssert(kRGBA_8888_GrPixelConfig == texture->config() ||
kBGRA_8888_GrPixelConfig == texture->config());
// Why did we pollute our texture cache instead of using a GrSingleTextureEffect?
GrAssert(swapRedAndBlue || kNone_PMConversion != pmConversion);
}
const GrProgramStageFactory& GrConfigConversionEffect::getFactory() const {
return GrTProgramStageFactory<GrConfigConversionEffect>::getInstance();
}
bool GrConfigConversionEffect::isEqual(const GrCustomStage& s) const {
const GrConfigConversionEffect& other = static_cast<const GrConfigConversionEffect&>(s);
return other.fSwapRedAndBlue == fSwapRedAndBlue && other.fPMConversion == fPMConversion;
}
///////////////////////////////////////////////////////////////////////////////
GR_DEFINE_CUSTOM_STAGE_TEST(GrConfigConversionEffect);
GrCustomStage* GrConfigConversionEffect::TestCreate(SkRandom* random,
GrContext* context,
GrTexture* textures[]) {
PMConversion pmConv = static_cast<PMConversion>(random->nextULessThan(kPMConversionCnt));
bool swapRB;
if (kNone_PMConversion == pmConv) {
swapRB = true;
} else {
swapRB = random->nextBool();
}
return SkNEW_ARGS(GrConfigConversionEffect,
(textures[GrCustomStageUnitTest::kSkiaPMTextureIdx], swapRB, pmConv));
}
///////////////////////////////////////////////////////////////////////////////
void GrConfigConversionEffect::TestForPreservingPMConversions(GrContext* context,
PMConversion* pmToUPMRule,
PMConversion* upmToPMRule) {
*pmToUPMRule = kNone_PMConversion;
*upmToPMRule = kNone_PMConversion;
SkAutoTMalloc<uint32_t> data(256 * 256 * 3);
uint32_t* srcData = data.get();
uint32_t* firstRead = data.get() + 256 * 256;
uint32_t* secondRead = data.get() + 2 * 256 * 256;
// Fill with every possible premultiplied A, color channel value. There will be 256-y duplicate
// values in row y. We set r,g, and b to the same value since they are handled identically.
for (int y = 0; y < 256; ++y) {
for (int x = 0; x < 256; ++x) {
uint8_t* color = reinterpret_cast<uint8_t*>(&srcData[256*y + x]);
color[3] = y;
color[2] = GrMin(x, y);
color[1] = GrMin(x, y);
color[0] = GrMin(x, y);
}
}
GrTextureDesc desc;
desc.fFlags = kRenderTarget_GrTextureFlagBit |
kNoStencil_GrTextureFlagBit;
desc.fWidth = 256;
desc.fHeight = 256;
desc.fConfig = kRGBA_8888_GrPixelConfig;
SkAutoTUnref<GrTexture> readTex(context->createUncachedTexture(desc, NULL, 0));
if (!readTex.get()) {
return;
}
SkAutoTUnref<GrTexture> tempTex(context->createUncachedTexture(desc, NULL, 0));
if (!tempTex.get()) {
return;
}
desc.fFlags = kNone_GrTextureFlags;
SkAutoTUnref<GrTexture> dataTex(context->createUncachedTexture(desc, data, 0));
if (!dataTex.get()) {
return;
}
static const PMConversion kConversionRules[][2] = {
{kDivByAlpha_RoundDown_PMConversion, kMulByAlpha_RoundUp_PMConversion},
{kDivByAlpha_RoundUp_PMConversion, kMulByAlpha_RoundDown_PMConversion},
};
GrContext::AutoWideOpenIdentityDraw awoid(context, NULL);
bool failed = true;
for (size_t i = 0; i < GR_ARRAY_COUNT(kConversionRules) && failed; ++i) {
*pmToUPMRule = kConversionRules[i][0];
*upmToPMRule = kConversionRules[i][1];
static const GrRect kDstRect = GrRect::MakeWH(GrIntToScalar(256), GrIntToScalar(256));
static const GrRect kSrcRect = GrRect::MakeWH(GR_Scalar1, GR_Scalar1);
// We do a PM->UPM draw from dataTex to readTex and read the data. Then we do a UPM->PM draw
// from readTex to tempTex followed by a PM->UPM draw to readTex and finally read the data.
// We then verify that two reads produced the same values.
GrPaint paint;
paint.reset();
SkAutoTUnref<GrCustomStage> pmToUPMStage1(SkNEW_ARGS(GrConfigConversionEffect,
(dataTex, false, *pmToUPMRule)));
SkAutoTUnref<GrCustomStage> upmToPMStage(SkNEW_ARGS(GrConfigConversionEffect,
(readTex, false, *upmToPMRule)));
SkAutoTUnref<GrCustomStage> pmToUPMStage2(SkNEW_ARGS(GrConfigConversionEffect,
(tempTex, false, *pmToUPMRule)));
context->setRenderTarget(readTex->asRenderTarget());
paint.textureSampler(0)->setCustomStage(pmToUPMStage1);
context->drawRectToRect(paint, kDstRect, kSrcRect);
readTex->readPixels(0, 0, 256, 256, kRGBA_8888_GrPixelConfig, firstRead);
context->setRenderTarget(tempTex->asRenderTarget());
paint.textureSampler(0)->setCustomStage(upmToPMStage);
context->drawRectToRect(paint, kDstRect, kSrcRect);
context->setRenderTarget(readTex->asRenderTarget());
paint.textureSampler(0)->setCustomStage(pmToUPMStage2);
context->drawRectToRect(paint, kDstRect, kSrcRect);
readTex->readPixels(0, 0, 256, 256, kRGBA_8888_GrPixelConfig, secondRead);
failed = false;
for (int y = 0; y < 256 && !failed; ++y) {
for (int x = 0; x <= y; ++x) {
if (firstRead[256 * y + x] != secondRead[256 * y + x]) {
failed = true;
break;
}
}
}
}
if (failed) {
*pmToUPMRule = kNone_PMConversion;
*upmToPMRule = kNone_PMConversion;
}
}
GrCustomStage* GrConfigConversionEffect::Create(GrTexture* texture,
bool swapRedAndBlue,
PMConversion pmConversion) {
if (!swapRedAndBlue && kNone_PMConversion == pmConversion) {
// If we returned a GrConfigConversionEffect that was equivalent to a GrSingleTextureEffect
// then we may pollute our texture cache with redundant shaders. So in the case that no
// conversions were requested we instead return a GrSingleTextureEffect.
return SkNEW_ARGS(GrSingleTextureEffect, (texture));
} else {
if (kRGBA_8888_GrPixelConfig != texture->config() &&
kBGRA_8888_GrPixelConfig != texture->config() &&
kNone_PMConversion != pmConversion) {
// The PM conversions assume colors are 0..255
return NULL;
}
return SkNEW_ARGS(GrConfigConversionEffect, (texture, swapRedAndBlue, pmConversion));
}
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the QtLocation module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "tilecache.h"
#include "tile.h"
#include "tilespec.h"
#include "qgeomappingmanager.h"
#include <QDir>
#include <QRegExp>
#include <QThread>
#include <QMetaType>
#include <QDebug>
#include <Qt3D/qgltexture2d.h>
#include <Qt3D/qglscenenode.h>
Q_DECLARE_METATYPE(QList<TileSpec>)
QT_BEGIN_NAMESPACE
class TileDisk
{
public:
~TileDisk()
{
// qWarning() << "evicting (disk) " << spec;
// cache->evictFromDiskCache(this);
}
TileSpec spec;
QString filename;
TileCache *cache;
};
class TileMemory
{
public:
~TileMemory()
{
// qWarning() << "evicting (memory) " << spec;
cache->evictFromMemoryCache(this);
}
TileSpec spec;
QPixmap pixmap;
TileCache *cache;
};
class TileTexture {
public:
~TileTexture()
{
// qWarning() << "evicting (texture) " << spec;
cache->evictFromTextureCache(this);
}
TileSpec spec;
bool bound;
QGLTexture2D *texture;
QGLSceneNode *node;
TileCache *cache;
};
TileCache::TileCache(const QString &directory, QObject *parent)
: QObject(parent), directory_(directory), manager_(0)
{
qRegisterMetaType<TileSpec>();
qRegisterMetaType<QList<TileSpec> >();
if (directory_.isEmpty()) {
QString dirname = QLatin1String(".tilecache");
QDir home = QDir::home();
if (!home.exists(dirname))
home.mkdir(dirname);
directory_ = home.filePath(dirname);
}
qDebug() << __FUNCTION__ << directory_;
diskCache_.setMaxCost(100 * 1024 * 1024);
memoryCache_.setMaxCost(50 * 1024 * 1024);
textureCache_.setMaxCost(100 * 1024 * 1024);
loadTiles();
}
TileCache::~TileCache()
{
delete manager_;
}
void TileCache::setMappingManager(QGeoMappingManager *manager)
{
manager_ = manager;
connect(manager_,
SIGNAL(tileFinished(TileSpec,QByteArray)),
this,
SLOT(insert(TileSpec,QByteArray)));
connect(manager_,
SIGNAL(tileError(TileSpec,QString)),
this,
SLOT(handleError(TileSpec,QString)));
connect(manager_,
SIGNAL(queueFinished()),
this,
SIGNAL(prefetchingFinished()));
}
void TileCache::setMaxDiskUsage(int diskUsage)
{
diskCache_.setMaxCost(diskUsage);
}
int TileCache::maxDiskUsage() const
{
return diskCache_.maxCost();
}
int TileCache::diskUsage() const
{
return diskCache_.totalCost();
}
void TileCache::setMaxMemoryUsage(int memoryUsage)
{
memoryCache_.setMaxCost(memoryUsage);
}
int TileCache::maxMemoryUsage() const
{
return memoryCache_.maxCost();
}
int TileCache::memoryUsage() const
{
return memoryCache_.totalCost();
}
void TileCache::setMaxTextureUsage(int textureUsage)
{
textureCache_.setMaxCost(textureUsage);
}
int TileCache::maxTextureUsage() const
{
return textureCache_.maxCost();
}
int TileCache::textureUsage() const
{
return textureCache_.totalCost();
}
void TileCache::prefetch(const QList<TileSpec> &tiles)
{
if (!manager_)
return;
manager_->requestTiles(tiles);
}
void TileCache::GLContextAvailable(QGLSceneNode *parentNode)
{
int size = cleanupList_.size();
for (int i = 0; i < size; ++i) {
Tile t = cleanupList_.at(i);
QGLSceneNode *node = t.sceneNode();
if (node) {
parentNode->removeNode(node);
delete node;
}
QGLTexture2D *texture = t.texture();
if (texture) {
texture->release();
delete texture;
}
}
cleanupList_.clear();
}
bool TileCache::contains(const TileSpec &spec) const
{
return keys_.contains(spec);
}
Tile TileCache::get(const TileSpec &spec)
{
if (textureCache_.contains(spec)) {
TileTexture *tt = textureCache_.object(spec);
Tile t = Tile(tt->spec);
t.setTexture(tt->texture);
t.setSceneNode(tt->node);
t.setBound(tt->bound);
return t;
}
// if (memoryCache_.contains(spec)) {
// TileMemory *tm = memoryCache_.object(spec);
// TileTexture *tt = addToTextureCache(tm->spec, tm->pixmap);
// Tile t = Tile(tt->spec);
// t.setTexture(tt->texture);
// t.setSceneNode(tt->node);
// t.setBound(tt->bound);
// return t;
// }
if (diskCache_.contains(spec)) {
TileDisk *td = diskCache_.object(spec);
// TileMemory *tm = addToMemoryCache(td->spec, QPixmap(td->filename));
// TileTexture *tt = addToTextureCache(tm->spec, tm->pixmap);
TileTexture *tt = addToTextureCache(td->spec, QPixmap(td->filename));
Tile t = Tile(tt->spec);
t.setTexture(tt->texture);
t.setSceneNode(tt->node);
t.setBound(tt->bound);
return t;
}
return Tile();
}
// TODO rename so this is less strange
// OR do node creation in here somehow
void TileCache::update(const TileSpec &spec, const Tile &tile)
{
TileTexture *tt = textureCache_.object(spec);
if (tt) {
tt->node = tile.sceneNode();
tt->texture = tile.texture();
tt->bound = tile.isBound();
}
}
void TileCache::insert(const TileSpec &spec, const QByteArray &bytes)
{
keys_.insert(spec);
QString filename = tileSpecToFilename(spec, directory_);
QPixmap pixmap;
if (!pixmap.loadFromData(bytes)) {
handleError(spec, QLatin1String("Problem with tile image"));
return;
}
QFile file(filename);
file.open(QIODevice::WriteOnly);
file.write(bytes);
file.close();
addToDiskCache(spec, filename);
// addToMemoryCache(spec, pixmap);
addToTextureCache(spec, pixmap);
emit tileFetched(spec);
}
void TileCache::evictFromDiskCache(TileDisk *td)
{
keys_.remove(td->spec);
QFile::remove(td->filename);
}
void TileCache::evictFromMemoryCache(TileMemory */*tm*/)
{
}
void TileCache::evictFromTextureCache(TileTexture *tt)
{
Tile t(tt->spec);
t.setTexture(tt->texture);
t.setSceneNode(tt->node);
cleanupList_ << t;
}
TileDisk* TileCache::addToDiskCache(const TileSpec &spec, const QString &filename)
{
keys_.insert(spec);
// qWarning() << "adding (disk) " << spec;
TileDisk *td = new TileDisk;
td->spec = spec;
td->filename = filename;
td->cache = this;
QFileInfo fi(filename);
int diskCost = fi.size();
diskCache_.insert(spec,
td,
diskCost);
return td;
}
TileMemory* TileCache::addToMemoryCache(const TileSpec &spec, const QPixmap &pixmap)
{
keys_.insert(spec);
// qWarning() << "adding (memory) " << spec;
TileMemory *tm = new TileMemory;
tm->spec = spec;
tm->pixmap = pixmap;
tm->cache = this;
int memoryCost = pixmap.width() * pixmap.height() * pixmap.depth() / 8;
memoryCache_.insert(spec,
tm,
memoryCost);
return tm;
}
TileTexture* TileCache::addToTextureCache(const TileSpec &spec, const QPixmap &pixmap)
{
keys_.insert(spec);
// qWarning() << "adding (texture) " << spec;
TileTexture *tt = new TileTexture;
tt->spec = spec;
tt->texture = new QGLTexture2D();
tt->texture->setPixmap(pixmap);
tt->texture->setHorizontalWrap(QGL::ClampToEdge);
tt->texture->setVerticalWrap(QGL::ClampToEdge);
// tt->texture->bind();
// tt->texture->clearImage();
tt->node = 0;
tt->cache = this;
int textureCost = pixmap.width() * pixmap.height() * pixmap.depth() / 8;;
textureCache_.insert(spec,
tt,
textureCost);
return tt;
}
void TileCache::handleError(const TileSpec &, const QString &error)
{
qWarning() << "tile request error " << error;
}
void TileCache::loadTiles()
{
QStringList formats;
formats << QLatin1String("*.png");
QDir dir(directory_);
//QStringList files = dir.entryList(formats, QDir::Files, QDir::Time | QDir::Reversed);
QStringList files = dir.entryList(formats, QDir::Files);
int tiles = 0;
for (int i = 0; i < files.size(); ++i) {
TileSpec spec = filenameToTileSpec(files.at(i));
if (spec.zoom() == -1)
continue;
QString filename = dir.filePath(files.at(i));
addToDiskCache(spec, filename);
tiles++;
}
qDebug() << __FUNCTION__ << " loaded this many map tiles to cache: " << tiles;
}
QString TileCache::tileSpecToFilename(const TileSpec &spec, const QString &directory)
{
QString filename = QString::number(spec.mapId());
filename += QLatin1String("-");
filename += QString::number(spec.zoom());
filename += QLatin1String("-");
filename += QString::number(spec.x());
filename += QLatin1String("-");
filename += QString::number(spec.y());
filename += QLatin1String(".png");
QDir dir = QDir(directory);
return dir.filePath(filename);
}
TileSpec TileCache::filenameToTileSpec(const QString &filename)
{
TileSpec spec;
QRegExp r(QLatin1String("(\\d+)-(\\d+)-(\\d+)-(\\d+).png"));
int index = r.indexIn(filename);
if (index != -1) {
bool ok = false;
int mapId = r.cap(1).toInt(&ok);
if (!ok)
return spec;
int zoom = r.cap(2).toInt(&ok);
if (!ok)
return spec;
ok = false;
int x = r.cap(3).toInt(&ok);
if (!ok)
return spec;
ok = false;
int y = r.cap(4).toInt(&ok);
if (!ok)
return spec;
spec.setMapId(mapId);
spec.setZoom(zoom);
spec.setX(x);
spec.setY(y);
}
return spec;
}
QT_END_NAMESPACE
<commit_msg>QtLocation: Fix MSVC warning about commented-out parameter.<commit_after>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the QtLocation module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "tilecache.h"
#include "tile.h"
#include "tilespec.h"
#include "qgeomappingmanager.h"
#include <QDir>
#include <QRegExp>
#include <QThread>
#include <QMetaType>
#include <QDebug>
#include <Qt3D/qgltexture2d.h>
#include <Qt3D/qglscenenode.h>
Q_DECLARE_METATYPE(QList<TileSpec>)
QT_BEGIN_NAMESPACE
class TileDisk
{
public:
~TileDisk()
{
// qWarning() << "evicting (disk) " << spec;
// cache->evictFromDiskCache(this);
}
TileSpec spec;
QString filename;
TileCache *cache;
};
class TileMemory
{
public:
~TileMemory()
{
// qWarning() << "evicting (memory) " << spec;
cache->evictFromMemoryCache(this);
}
TileSpec spec;
QPixmap pixmap;
TileCache *cache;
};
class TileTexture {
public:
~TileTexture()
{
// qWarning() << "evicting (texture) " << spec;
cache->evictFromTextureCache(this);
}
TileSpec spec;
bool bound;
QGLTexture2D *texture;
QGLSceneNode *node;
TileCache *cache;
};
TileCache::TileCache(const QString &directory, QObject *parent)
: QObject(parent), directory_(directory), manager_(0)
{
qRegisterMetaType<TileSpec>();
qRegisterMetaType<QList<TileSpec> >();
if (directory_.isEmpty()) {
QString dirname = QLatin1String(".tilecache");
QDir home = QDir::home();
if (!home.exists(dirname))
home.mkdir(dirname);
directory_ = home.filePath(dirname);
}
qDebug() << __FUNCTION__ << directory_;
diskCache_.setMaxCost(100 * 1024 * 1024);
memoryCache_.setMaxCost(50 * 1024 * 1024);
textureCache_.setMaxCost(100 * 1024 * 1024);
loadTiles();
}
TileCache::~TileCache()
{
delete manager_;
}
void TileCache::setMappingManager(QGeoMappingManager *manager)
{
manager_ = manager;
connect(manager_,
SIGNAL(tileFinished(TileSpec,QByteArray)),
this,
SLOT(insert(TileSpec,QByteArray)));
connect(manager_,
SIGNAL(tileError(TileSpec,QString)),
this,
SLOT(handleError(TileSpec,QString)));
connect(manager_,
SIGNAL(queueFinished()),
this,
SIGNAL(prefetchingFinished()));
}
void TileCache::setMaxDiskUsage(int diskUsage)
{
diskCache_.setMaxCost(diskUsage);
}
int TileCache::maxDiskUsage() const
{
return diskCache_.maxCost();
}
int TileCache::diskUsage() const
{
return diskCache_.totalCost();
}
void TileCache::setMaxMemoryUsage(int memoryUsage)
{
memoryCache_.setMaxCost(memoryUsage);
}
int TileCache::maxMemoryUsage() const
{
return memoryCache_.maxCost();
}
int TileCache::memoryUsage() const
{
return memoryCache_.totalCost();
}
void TileCache::setMaxTextureUsage(int textureUsage)
{
textureCache_.setMaxCost(textureUsage);
}
int TileCache::maxTextureUsage() const
{
return textureCache_.maxCost();
}
int TileCache::textureUsage() const
{
return textureCache_.totalCost();
}
void TileCache::prefetch(const QList<TileSpec> &tiles)
{
if (!manager_)
return;
manager_->requestTiles(tiles);
}
void TileCache::GLContextAvailable(QGLSceneNode *parentNode)
{
int size = cleanupList_.size();
for (int i = 0; i < size; ++i) {
Tile t = cleanupList_.at(i);
QGLSceneNode *node = t.sceneNode();
if (node) {
parentNode->removeNode(node);
delete node;
}
QGLTexture2D *texture = t.texture();
if (texture) {
texture->release();
delete texture;
}
}
cleanupList_.clear();
}
bool TileCache::contains(const TileSpec &spec) const
{
return keys_.contains(spec);
}
Tile TileCache::get(const TileSpec &spec)
{
if (textureCache_.contains(spec)) {
TileTexture *tt = textureCache_.object(spec);
Tile t = Tile(tt->spec);
t.setTexture(tt->texture);
t.setSceneNode(tt->node);
t.setBound(tt->bound);
return t;
}
// if (memoryCache_.contains(spec)) {
// TileMemory *tm = memoryCache_.object(spec);
// TileTexture *tt = addToTextureCache(tm->spec, tm->pixmap);
// Tile t = Tile(tt->spec);
// t.setTexture(tt->texture);
// t.setSceneNode(tt->node);
// t.setBound(tt->bound);
// return t;
// }
if (diskCache_.contains(spec)) {
TileDisk *td = diskCache_.object(spec);
// TileMemory *tm = addToMemoryCache(td->spec, QPixmap(td->filename));
// TileTexture *tt = addToTextureCache(tm->spec, tm->pixmap);
TileTexture *tt = addToTextureCache(td->spec, QPixmap(td->filename));
Tile t = Tile(tt->spec);
t.setTexture(tt->texture);
t.setSceneNode(tt->node);
t.setBound(tt->bound);
return t;
}
return Tile();
}
// TODO rename so this is less strange
// OR do node creation in here somehow
void TileCache::update(const TileSpec &spec, const Tile &tile)
{
TileTexture *tt = textureCache_.object(spec);
if (tt) {
tt->node = tile.sceneNode();
tt->texture = tile.texture();
tt->bound = tile.isBound();
}
}
void TileCache::insert(const TileSpec &spec, const QByteArray &bytes)
{
keys_.insert(spec);
QString filename = tileSpecToFilename(spec, directory_);
QPixmap pixmap;
if (!pixmap.loadFromData(bytes)) {
handleError(spec, QLatin1String("Problem with tile image"));
return;
}
QFile file(filename);
file.open(QIODevice::WriteOnly);
file.write(bytes);
file.close();
addToDiskCache(spec, filename);
// addToMemoryCache(spec, pixmap);
addToTextureCache(spec, pixmap);
emit tileFetched(spec);
}
void TileCache::evictFromDiskCache(TileDisk *td)
{
keys_.remove(td->spec);
QFile::remove(td->filename);
}
void TileCache::evictFromMemoryCache(TileMemory * /* tm */)
{
}
void TileCache::evictFromTextureCache(TileTexture *tt)
{
Tile t(tt->spec);
t.setTexture(tt->texture);
t.setSceneNode(tt->node);
cleanupList_ << t;
}
TileDisk* TileCache::addToDiskCache(const TileSpec &spec, const QString &filename)
{
keys_.insert(spec);
// qWarning() << "adding (disk) " << spec;
TileDisk *td = new TileDisk;
td->spec = spec;
td->filename = filename;
td->cache = this;
QFileInfo fi(filename);
int diskCost = fi.size();
diskCache_.insert(spec,
td,
diskCost);
return td;
}
TileMemory* TileCache::addToMemoryCache(const TileSpec &spec, const QPixmap &pixmap)
{
keys_.insert(spec);
// qWarning() << "adding (memory) " << spec;
TileMemory *tm = new TileMemory;
tm->spec = spec;
tm->pixmap = pixmap;
tm->cache = this;
int memoryCost = pixmap.width() * pixmap.height() * pixmap.depth() / 8;
memoryCache_.insert(spec,
tm,
memoryCost);
return tm;
}
TileTexture* TileCache::addToTextureCache(const TileSpec &spec, const QPixmap &pixmap)
{
keys_.insert(spec);
// qWarning() << "adding (texture) " << spec;
TileTexture *tt = new TileTexture;
tt->spec = spec;
tt->texture = new QGLTexture2D();
tt->texture->setPixmap(pixmap);
tt->texture->setHorizontalWrap(QGL::ClampToEdge);
tt->texture->setVerticalWrap(QGL::ClampToEdge);
// tt->texture->bind();
// tt->texture->clearImage();
tt->node = 0;
tt->cache = this;
int textureCost = pixmap.width() * pixmap.height() * pixmap.depth() / 8;;
textureCache_.insert(spec,
tt,
textureCost);
return tt;
}
void TileCache::handleError(const TileSpec &, const QString &error)
{
qWarning() << "tile request error " << error;
}
void TileCache::loadTiles()
{
QStringList formats;
formats << QLatin1String("*.png");
QDir dir(directory_);
//QStringList files = dir.entryList(formats, QDir::Files, QDir::Time | QDir::Reversed);
QStringList files = dir.entryList(formats, QDir::Files);
int tiles = 0;
for (int i = 0; i < files.size(); ++i) {
TileSpec spec = filenameToTileSpec(files.at(i));
if (spec.zoom() == -1)
continue;
QString filename = dir.filePath(files.at(i));
addToDiskCache(spec, filename);
tiles++;
}
qDebug() << __FUNCTION__ << " loaded this many map tiles to cache: " << tiles;
}
QString TileCache::tileSpecToFilename(const TileSpec &spec, const QString &directory)
{
QString filename = QString::number(spec.mapId());
filename += QLatin1String("-");
filename += QString::number(spec.zoom());
filename += QLatin1String("-");
filename += QString::number(spec.x());
filename += QLatin1String("-");
filename += QString::number(spec.y());
filename += QLatin1String(".png");
QDir dir = QDir(directory);
return dir.filePath(filename);
}
TileSpec TileCache::filenameToTileSpec(const QString &filename)
{
TileSpec spec;
QRegExp r(QLatin1String("(\\d+)-(\\d+)-(\\d+)-(\\d+).png"));
int index = r.indexIn(filename);
if (index != -1) {
bool ok = false;
int mapId = r.cap(1).toInt(&ok);
if (!ok)
return spec;
int zoom = r.cap(2).toInt(&ok);
if (!ok)
return spec;
ok = false;
int x = r.cap(3).toInt(&ok);
if (!ok)
return spec;
ok = false;
int y = r.cap(4).toInt(&ok);
if (!ok)
return spec;
spec.setMapId(mapId);
spec.setZoom(zoom);
spec.setX(x);
spec.setY(y);
}
return spec;
}
QT_END_NAMESPACE
<|endoftext|> |
<commit_before>// Author: Enrico Guiraud CERN 09/2020
/*************************************************************************
* Copyright (C) 1995-2020, 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_RDF_COLUMNREADERUTILS
#define ROOT_RDF_COLUMNREADERUTILS
#include "RColumnReaderBase.hxx"
#include "RDefineBase.hxx"
#include "RDefineReader.hxx"
#include "RDSColumnReader.hxx"
#include "RTreeColumnReader.hxx"
#include <ROOT/RDataSource.hxx>
#include <ROOT/TypeTraits.hxx>
#include <TTreeReader.h>
#include <array>
#include <map>
#include <memory>
#include <string>
#include <typeinfo> // for typeid
#include <vector>
namespace ROOT {
namespace Internal {
namespace RDF {
using namespace ROOT::TypeTraits;
namespace RDFDetail = ROOT::Detail::RDF;
template <typename T>
std::unique_ptr<RDFDetail::RColumnReaderBase>
MakeColumnReader(unsigned int slot, RDFDetail::RDefineBase *define, TTreeReader *r, ROOT::RDF::RDataSource *ds,
const std::vector<void *> *DSValuePtrsPtr, const std::string &colName)
{
using Ret_t = std::unique_ptr<RDFDetail::RColumnReaderBase>;
// this check must come first!
// so that Redefine'd columns have precedence over the original columns
if (define != nullptr)
return Ret_t(new RDefineReader(slot, *define, typeid(T)));
if (DSValuePtrsPtr != nullptr) {
// reading from a RDataSource with the old column reader interface
auto &DSValuePtrs = *DSValuePtrsPtr;
return Ret_t(new RDSColumnReader<T>(DSValuePtrs[slot]));
}
if (ds != nullptr) {
// reading from a RDataSource with the new column reader interface
return ds->GetColumnReaders(slot, colName, typeid(T));
}
// reading from a TTree
return Ret_t(new RTreeColumnReader<T>(*r, colName));
}
template <typename T>
std::unique_ptr<RDFDetail::RColumnReaderBase>
MakeColumnReadersHelper(unsigned int slot, RDFDetail::RDefineBase *define,
const std::map<std::string, std::vector<void *>> &DSValuePtrsMap, TTreeReader *r,
ROOT::RDF::RDataSource *ds, const std::string &colName)
{
const auto DSValuePtrsIt = DSValuePtrsMap.find(colName);
const std::vector<void *> *DSValuePtrsPtr = DSValuePtrsIt != DSValuePtrsMap.end() ? &DSValuePtrsIt->second : nullptr;
assert(define != nullptr || r != nullptr || DSValuePtrsPtr != nullptr || ds != nullptr);
return MakeColumnReader<T>(slot, define, r, ds, DSValuePtrsPtr, colName);
}
/// This type aggregates some of the arguments passed to MakeColumnReaders.
/// We need to pass a single RColumnReadersInfo object rather than each argument separately because with too many
/// arguments passed, gcc 7.5.0 and cling disagree on the ABI, which leads to the last function argument being read
/// incorrectly from a compiled MakeColumnReaders symbols when invoked from a jitted symbol.
struct RColumnReadersInfo {
const std::vector<std::string> &fColNames;
const RBookedDefines &fCustomCols;
const bool *fIsDefine;
const std::map<std::string, std::vector<void *>> &fDSValuePtrsMap;
ROOT::RDF::RDataSource *fDataSource;
};
/// Create a group of column readers, one per type in the parameter pack.
/// colInfo.fColNames and colInfo.fIsDefine are expected to have size equal to the parameter pack, and elements ordered
/// accordingly, i.e. fIsDefine[0] refers to fColNames[0] which is of type "ColTypes[0]".
template <typename... ColTypes>
std::array<std::unique_ptr<RDFDetail::RColumnReaderBase>, sizeof...(ColTypes)>
MakeColumnReaders(unsigned int slot, TTreeReader *r, TypeList<ColTypes...>, const RColumnReadersInfo &colInfo)
{
// see RColumnReadersInfo for why we pass these arguments like this rather than directly as function arguments
const auto &colNames = colInfo.fColNames;
const auto &customCols = colInfo.fCustomCols;
const bool *isDefine = colInfo.fIsDefine;
const auto &DSValuePtrsMap = colInfo.fDSValuePtrsMap;
auto *ds = colInfo.fDataSource;
const auto &customColMap = customCols.GetColumns();
int i = -1;
std::array<std::unique_ptr<RDFDetail::RColumnReaderBase>, sizeof...(ColTypes)> ret{
{{(++i, MakeColumnReadersHelper<ColTypes>(slot, isDefine[i] ? customColMap.at(colNames[i]).get() : nullptr,
DSValuePtrsMap, r, ds, colNames[i]))}...}};
return ret;
// avoid bogus "unused variable" warnings
(void)ds;
(void)slot;
(void)r;
}
} // namespace RDF
} // namespace Internal
} // namespace ROOT
#endif // ROOT_RDF_COLUMNREADERS
<commit_msg>[DF] Simplify MakeColumnReaders<commit_after>// Author: Enrico Guiraud CERN 09/2020
/*************************************************************************
* Copyright (C) 1995-2020, 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_RDF_COLUMNREADERUTILS
#define ROOT_RDF_COLUMNREADERUTILS
#include "RColumnReaderBase.hxx"
#include "RBookedDefines.hxx"
#include "RDefineBase.hxx"
#include "RDefineReader.hxx"
#include "RDSColumnReader.hxx"
#include "RTreeColumnReader.hxx"
#include <ROOT/RDataSource.hxx>
#include <ROOT/TypeTraits.hxx>
#include <TTreeReader.h>
#include <array>
#include <cassert>
#include <map>
#include <memory>
#include <string>
#include <typeinfo> // for typeid
#include <vector>
namespace ROOT {
namespace Internal {
namespace RDF {
using namespace ROOT::TypeTraits;
namespace RDFDetail = ROOT::Detail::RDF;
template <typename T>
std::unique_ptr<RDFDetail::RColumnReaderBase>
MakeColumnReader(unsigned int slot, RDefineBase *define,
const std::map<std::string, std::vector<void *>> &DSValuePtrsMap, TTreeReader *r,
ROOT::RDF::RDataSource *ds, const std::string &colName)
{
using Ret_t = std::unique_ptr<RDFDetail::RColumnReaderBase>;
// this check must come first!
// so that Redefine'd columns have precedence over the original columns
if (define != nullptr)
return Ret_t{new RDefineReader(slot, *define, typeid(T))};
const auto DSValuePtrsIt = DSValuePtrsMap.find(colName);
if (DSValuePtrsIt != DSValuePtrsMap.end()) {
// reading from a RDataSource with the old column reader interface
const std::vector<void *> &DSValuePtrs = DSValuePtrsIt->second;
return Ret_t(new RDSColumnReader<T>(DSValuePtrs[slot]));
}
if (ds != nullptr) {
// reading from a RDataSource with the new column reader interface
return ds->GetColumnReaders(slot, colName, typeid(T));
}
assert(r != nullptr && "We could not find a reader for this column, this should never happen at this point.");
// reading from a TTree
return Ret_t{new RTreeColumnReader<T>(*r, colName)};
}
/// This type aggregates some of the arguments passed to MakeColumnReaders.
/// We need to pass a single RColumnReadersInfo object rather than each argument separately because with too many
/// arguments passed, gcc 7.5.0 and cling disagree on the ABI, which leads to the last function argument being read
/// incorrectly from a compiled MakeColumnReaders symbols when invoked from a jitted symbol.
struct RColumnReadersInfo {
const std::vector<std::string> &fColNames;
const RBookedDefines &fCustomCols;
const bool *fIsDefine;
const std::map<std::string, std::vector<void *>> &fDSValuePtrsMap;
ROOT::RDF::RDataSource *fDataSource;
};
/// Create a group of column readers, one per type in the parameter pack.
/// colInfo.fColNames and colInfo.fIsDefine are expected to have size equal to the parameter pack, and elements ordered
/// accordingly, i.e. fIsDefine[0] refers to fColNames[0] which is of type "ColTypes[0]".
template <typename... ColTypes>
std::array<std::unique_ptr<RDFDetail::RColumnReaderBase>, sizeof...(ColTypes)>
MakeColumnReaders(unsigned int slot, TTreeReader *r, TypeList<ColTypes...>, const RColumnReadersInfo &colInfo)
{
// see RColumnReadersInfo for why we pass these arguments like this rather than directly as function arguments
const auto &colNames = colInfo.fColNames;
const auto &defines = colInfo.fCustomCols.GetColumns();
const bool *isDefine = colInfo.fIsDefine;
const auto &DSValuePtrsMap = colInfo.fDSValuePtrsMap;
auto *ds = colInfo.fDataSource;
int i = -1;
std::array<std::unique_ptr<RDFDetail::RColumnReaderBase>, sizeof...(ColTypes)> ret{
{{(++i, MakeColumnReader<ColTypes>(slot, isDefine[i] ? defines.at(colNames[i]).get() : nullptr, DSValuePtrsMap, r,
ds, colNames[i]))}...}};
return ret;
// avoid bogus "unused variable" warnings
(void)ds;
(void)slot;
(void)r;
}
} // namespace RDF
} // namespace Internal
} // namespace ROOT
#endif // ROOT_RDF_COLUMNREADERS
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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.
*
*=========================================================================*/
#ifdef _MFC_VER
#pragma warning(disable:4996)
#endif
#include "sitkImageSeriesReader.h"
#include <itkImageIOBase.h>
#include <itkImageSeriesReader.h>
#include "itkGDCMSeriesFileNames.h"
namespace itk {
namespace simple {
Image ReadImage ( const std::vector<std::string> &filenames, PixelIDValueEnum outputPixelType )
{
ImageSeriesReader reader;
return reader.SetFileNames ( filenames ).SetOutputPixelType(outputPixelType).Execute();
}
std::vector<std::string> ImageSeriesReader::GetGDCMSeriesFileNames( const std::string &directory,
const std::string &seriesID,
bool useSeriesDetails,
bool recursive,
bool loadSequences )
{
GDCMSeriesFileNames::Pointer gdcmSeries = GDCMSeriesFileNames::New();
gdcmSeries->SetInputDirectory( directory );
gdcmSeries->SetUseSeriesDetails( useSeriesDetails );
gdcmSeries->SetRecursive( recursive );
gdcmSeries->SetLoadSequences( loadSequences );
//Skip private tags. Loading DICOM files is faster when private tags are not needed.
gdcmSeries->SetLoadPrivateTags( false );
gdcmSeries->Update();
return gdcmSeries->GetFileNames(seriesID);
}
std::vector<std::string> ImageSeriesReader::GetGDCMSeriesIDs( const std::string &directory )
{
GDCMSeriesFileNames::Pointer gdcmSeries = GDCMSeriesFileNames::New();
gdcmSeries->SetInputDirectory( directory );
return gdcmSeries->GetSeriesUIDs();
}
ImageSeriesReader::ImageSeriesReader()
:
m_Filter(NULL),
m_MetaDataDictionaryArrayUpdate(false)
{
// list of pixel types supported
typedef NonLabelPixelIDTypeList PixelIDTypeList;
this->m_MemberFactory.reset( new detail::MemberFunctionFactory<MemberFunctionType>( this ) );
this->m_MemberFactory->RegisterMemberFunctions< PixelIDTypeList, 3 > ();
this->m_MemberFactory->RegisterMemberFunctions< PixelIDTypeList, 2 > ();
}
ImageSeriesReader::~ImageSeriesReader()
{
if (this->m_Filter != NULL)
{
m_Filter->UnRegister();
}
}
std::string ImageSeriesReader::ToString() const {
std::ostringstream out;
out << "itk::simple::ImageSeriesReader";
out << std::endl;
out << " FileNames:" << std::endl;
std::vector<std::string>::const_iterator iter = m_FileNames.begin();
while( iter != m_FileNames.end() )
{
std::cout << " \"" << *iter << "\"" << std::endl;
++iter;
}
out << ImageReaderBase::ToString();
return out.str();
}
ImageSeriesReader& ImageSeriesReader::SetFileNames ( const std::vector<std::string> &filenames )
{
this->m_FileNames = filenames;
return *this;
}
const std::vector<std::string> &ImageSeriesReader::GetFileNames() const
{
return this->m_FileNames;
}
Image ImageSeriesReader::Execute ()
{
if( this->m_FileNames.empty() )
{
sitkExceptionMacro( "File names information is empty. Cannot read series." );
}
PixelIDValueType type = this->GetOutputPixelType();
unsigned int dimension = 0;
itk::ImageIOBase::Pointer imageio = this->GetImageIOBase( this->m_FileNames.front() );
if (type == sitkUnknown)
{
this->GetPixelIDFromImageIO( imageio, type, dimension );
}
else
{
PixelIDValueType unused;
this->GetPixelIDFromImageIO( imageio, unused, dimension );
}
// increment for series
++dimension;
if (dimension == 4)
{
unsigned int size = this->GetDimensionFromImageIO( imageio, 2);
if (size == 1)
{
--dimension;
}
}
if ( dimension != 2 && dimension != 3 )
{
sitkExceptionMacro( "The file in the series have unsupported " << dimension - 1 << " dimensions." );
}
if ( !this->m_MemberFactory->HasMemberFunction( type, dimension ) )
{
sitkExceptionMacro( << "PixelType is not supported!" << std::endl
<< "Pixel Type: "
<< GetPixelIDValueAsString( type ) << std::endl
<< "Refusing to load! " << std::endl );
}
return this->m_MemberFactory->GetMemberFunction( type, dimension )(imageio);
}
//
// Custom Casts
//
namespace {
template<typename FilterType>
struct GetMetaDataKeysCustomCast
{
static std::vector<std::string> CustomCast( const FilterType *f, int i)
{
const typename FilterType::DictionaryArrayType &mda = *f->GetMetaDataDictionaryArray();
return mda.at(i)->GetKeys();
}
};
template<typename FilterType>
struct HasMetaDataKeyCustomCast
{
static bool CustomCast( const FilterType *f, int i, const std::string &k)
{
const typename FilterType::DictionaryArrayType &mda = *f->GetMetaDataDictionaryArray();
return mda.at(i)->HasKey(k);
}
};
template<typename FilterType>
struct GetMetaDataCustomCast
{
static std::string CustomCast( const FilterType *f, int i, const std::string &k)
{
const typename FilterType::DictionaryArrayType &mda = *f->GetMetaDataDictionaryArray();
std::string value;
if (ExposeMetaData(*mda.at(i), k, value))
{
return value;
}
std::ostringstream ss;
mda.at(i)->Get(k)->Print(ss);
return ss.str();
}
};
}
template <class TImageType> Image
ImageSeriesReader::ExecuteInternal( itk::ImageIOBase* imageio )
{
typedef TImageType ImageType;
typedef itk::ImageSeriesReader<ImageType> Reader;
// if the IsInstantiated is correctly implemented this should
// not occur
assert( ImageTypeToPixelIDValue<ImageType>::Result != (int)sitkUnknown );
assert( imageio != SITK_NULLPTR );
typename Reader::Pointer reader = Reader::New();
reader->SetImageIO( imageio );
reader->SetFileNames( this->m_FileNames );
// save some computation by not updating this unneeded data-structure
reader->SetMetaDataDictionaryArrayUpdate(m_MetaDataDictionaryArrayUpdate);
// release the old filter ( and output data )
if ( this->m_Filter != NULL)
{
this->m_pfGetMetaDataKeys = SITK_NULL_PTR;
this->m_pfHasMetaDataKey = SITK_NULL_PTR;
this->m_pfGetMetaData = SITK_NULL_PTR;
this->m_Filter->UnRegister();
this->m_Filter = NULL;
}
this->m_Filter = reader;
this->m_Filter->Register();
this->PreUpdate( reader.GetPointer() );
this->m_pfGetMetaDataKeys = nsstd::bind(&GetMetaDataKeysCustomCast<Reader>::CustomCast, reader.GetPointer(), nsstd::placeholders::_1 );
this->m_pfHasMetaDataKey = nsstd::bind(&HasMetaDataKeyCustomCast<Reader>::CustomCast, reader.GetPointer(), nsstd::placeholders::_1, nsstd::placeholders::_2 );
this->m_pfGetMetaData = nsstd::bind(&GetMetaDataCustomCast<Reader>::CustomCast, reader.GetPointer(), nsstd::placeholders::_1, nsstd::placeholders::_2 );
reader->Update();
return Image( reader->GetOutput() );
}
}
}
<commit_msg>Only set the meta data dictionary array call back if data is updated<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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.
*
*=========================================================================*/
#ifdef _MFC_VER
#pragma warning(disable:4996)
#endif
#include "sitkImageSeriesReader.h"
#include <itkImageIOBase.h>
#include <itkImageSeriesReader.h>
#include "itkGDCMSeriesFileNames.h"
namespace itk {
namespace simple {
Image ReadImage ( const std::vector<std::string> &filenames, PixelIDValueEnum outputPixelType )
{
ImageSeriesReader reader;
return reader.SetFileNames ( filenames ).SetOutputPixelType(outputPixelType).Execute();
}
std::vector<std::string> ImageSeriesReader::GetGDCMSeriesFileNames( const std::string &directory,
const std::string &seriesID,
bool useSeriesDetails,
bool recursive,
bool loadSequences )
{
GDCMSeriesFileNames::Pointer gdcmSeries = GDCMSeriesFileNames::New();
gdcmSeries->SetInputDirectory( directory );
gdcmSeries->SetUseSeriesDetails( useSeriesDetails );
gdcmSeries->SetRecursive( recursive );
gdcmSeries->SetLoadSequences( loadSequences );
//Skip private tags. Loading DICOM files is faster when private tags are not needed.
gdcmSeries->SetLoadPrivateTags( false );
gdcmSeries->Update();
return gdcmSeries->GetFileNames(seriesID);
}
std::vector<std::string> ImageSeriesReader::GetGDCMSeriesIDs( const std::string &directory )
{
GDCMSeriesFileNames::Pointer gdcmSeries = GDCMSeriesFileNames::New();
gdcmSeries->SetInputDirectory( directory );
return gdcmSeries->GetSeriesUIDs();
}
ImageSeriesReader::ImageSeriesReader()
:
m_Filter(NULL),
m_MetaDataDictionaryArrayUpdate(false)
{
// list of pixel types supported
typedef NonLabelPixelIDTypeList PixelIDTypeList;
this->m_MemberFactory.reset( new detail::MemberFunctionFactory<MemberFunctionType>( this ) );
this->m_MemberFactory->RegisterMemberFunctions< PixelIDTypeList, 3 > ();
this->m_MemberFactory->RegisterMemberFunctions< PixelIDTypeList, 2 > ();
}
ImageSeriesReader::~ImageSeriesReader()
{
if (this->m_Filter != NULL)
{
m_Filter->UnRegister();
}
}
std::string ImageSeriesReader::ToString() const {
std::ostringstream out;
out << "itk::simple::ImageSeriesReader";
out << std::endl;
out << " FileNames:" << std::endl;
std::vector<std::string>::const_iterator iter = m_FileNames.begin();
while( iter != m_FileNames.end() )
{
std::cout << " \"" << *iter << "\"" << std::endl;
++iter;
}
out << ImageReaderBase::ToString();
return out.str();
}
ImageSeriesReader& ImageSeriesReader::SetFileNames ( const std::vector<std::string> &filenames )
{
this->m_FileNames = filenames;
return *this;
}
const std::vector<std::string> &ImageSeriesReader::GetFileNames() const
{
return this->m_FileNames;
}
Image ImageSeriesReader::Execute ()
{
if( this->m_FileNames.empty() )
{
sitkExceptionMacro( "File names information is empty. Cannot read series." );
}
PixelIDValueType type = this->GetOutputPixelType();
unsigned int dimension = 0;
itk::ImageIOBase::Pointer imageio = this->GetImageIOBase( this->m_FileNames.front() );
if (type == sitkUnknown)
{
this->GetPixelIDFromImageIO( imageio, type, dimension );
}
else
{
PixelIDValueType unused;
this->GetPixelIDFromImageIO( imageio, unused, dimension );
}
// increment for series
++dimension;
if (dimension == 4)
{
unsigned int size = this->GetDimensionFromImageIO( imageio, 2);
if (size == 1)
{
--dimension;
}
}
if ( dimension != 2 && dimension != 3 )
{
sitkExceptionMacro( "The file in the series have unsupported " << dimension - 1 << " dimensions." );
}
if ( !this->m_MemberFactory->HasMemberFunction( type, dimension ) )
{
sitkExceptionMacro( << "PixelType is not supported!" << std::endl
<< "Pixel Type: "
<< GetPixelIDValueAsString( type ) << std::endl
<< "Refusing to load! " << std::endl );
}
return this->m_MemberFactory->GetMemberFunction( type, dimension )(imageio);
}
//
// Custom Casts
//
namespace {
template<typename FilterType>
struct GetMetaDataKeysCustomCast
{
static std::vector<std::string> CustomCast( const FilterType *f, int i)
{
const typename FilterType::DictionaryArrayType &mda = *f->GetMetaDataDictionaryArray();
return mda.at(i)->GetKeys();
}
};
template<typename FilterType>
struct HasMetaDataKeyCustomCast
{
static bool CustomCast( const FilterType *f, int i, const std::string &k)
{
const typename FilterType::DictionaryArrayType &mda = *f->GetMetaDataDictionaryArray();
return mda.at(i)->HasKey(k);
}
};
template<typename FilterType>
struct GetMetaDataCustomCast
{
static std::string CustomCast( const FilterType *f, int i, const std::string &k)
{
const typename FilterType::DictionaryArrayType &mda = *f->GetMetaDataDictionaryArray();
std::string value;
if (ExposeMetaData(*mda.at(i), k, value))
{
return value;
}
std::ostringstream ss;
mda.at(i)->Get(k)->Print(ss);
return ss.str();
}
};
}
template <class TImageType> Image
ImageSeriesReader::ExecuteInternal( itk::ImageIOBase* imageio )
{
typedef TImageType ImageType;
typedef itk::ImageSeriesReader<ImageType> Reader;
// if the IsInstantiated is correctly implemented this should
// not occur
assert( ImageTypeToPixelIDValue<ImageType>::Result != (int)sitkUnknown );
assert( imageio != SITK_NULLPTR );
typename Reader::Pointer reader = Reader::New();
reader->SetImageIO( imageio );
reader->SetFileNames( this->m_FileNames );
// save some computation by not updating this unneeded data-structure
reader->SetMetaDataDictionaryArrayUpdate(m_MetaDataDictionaryArrayUpdate);
// release the old filter ( and output data )
if ( this->m_Filter != NULL)
{
this->m_pfGetMetaDataKeys = SITK_NULLPTR;
this->m_pfHasMetaDataKey = SITK_NULLPTR;
this->m_pfGetMetaData = SITK_NULLPTR;
this->m_Filter->UnRegister();
this->m_Filter = NULL;
}
this->PreUpdate( reader.GetPointer() );
if (m_MetaDataDictionaryArrayUpdate)
{
this->m_Filter = reader;
this->m_Filter->Register();
this->m_pfGetMetaDataKeys = nsstd::bind(&GetMetaDataKeysCustomCast<Reader>::CustomCast, reader.GetPointer(), nsstd::placeholders::_1 );
this->m_pfHasMetaDataKey = nsstd::bind(&HasMetaDataKeyCustomCast<Reader>::CustomCast, reader.GetPointer(), nsstd::placeholders::_1, nsstd::placeholders::_2 );
this->m_pfGetMetaData = nsstd::bind(&GetMetaDataCustomCast<Reader>::CustomCast, reader.GetPointer(), nsstd::placeholders::_1, nsstd::placeholders::_2 );
}
reader->Update();
return Image( reader->GetOutput() );
}
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2017 German Aerospace Center (DLR/SC)
*
* Created: 2017 Martin Siggel <[email protected]>
*
* 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 "CTiglCurveNetworkSorter.h"
#include "CTiglError.h"
#include <utility>
#include <cassert>
namespace
{
// returns the column index if the maximum of i-th row
size_t maxRowIndex(const math_Matrix& m, size_t irow)
{
double max = DBL_MIN;
size_t jmax = 0;
for (Standard_Integer jcol = 0; jcol < m.ColNumber(); ++jcol) {
if (m(static_cast<Standard_Integer>(irow), jcol) > max) {
max = m(static_cast<Standard_Integer>(irow), jcol);
jmax = static_cast<size_t>(jcol);
}
}
return jmax;
}
// returns the row index if the maximum of i-th col
size_t maxColIndex(const math_Matrix& m, size_t jcol)
{
double max = DBL_MIN;
size_t imax = 0;
for (Standard_Integer irow = 0; irow < m.RowNumber(); ++irow) {
if (m(irow, static_cast<Standard_Integer>(jcol)) > max) {
max = m(irow, static_cast<Standard_Integer>(jcol));
imax = static_cast<size_t>(irow);
}
}
return imax;
}
// returns the column index if the minimum of i-th row
size_t minRowIndex(const math_Matrix& m, size_t irow)
{
double min = DBL_MAX;
size_t jmin = 0;
for (Standard_Integer jcol = 0; jcol < m.ColNumber(); ++jcol) {
if (m(static_cast<Standard_Integer>(irow), jcol) < min) {
min = m(static_cast<Standard_Integer>(irow), jcol);
jmin = static_cast<size_t>(jcol);
}
}
return jmin;
}
// returns the column index if the minimum of i-th row
size_t minColIndex(const math_Matrix& m, size_t jcol)
{
double min = DBL_MAX;
size_t imin = 0;
for (Standard_Integer irow = 0; irow < m.RowNumber(); ++irow) {
if (m(irow, static_cast<Standard_Integer>(jcol)) < min) {
min = m(irow, static_cast<Standard_Integer>(jcol));
imin = static_cast<size_t>(irow);
}
}
return imin;
}
}
namespace tigl
{
CTiglCurveNetworkSorter::CTiglCurveNetworkSorter(const std::vector<Handle (Geom_Curve)> &profiles,
const std::vector<Handle (Geom_Curve)> &guides,
const math_Matrix &parmsIntersProfiles,
const math_Matrix &parmsIntersGuides)
: m_profiles(profiles)
, m_guides(guides)
, m_parmsIntersProfiles(parmsIntersProfiles)
, m_parmsIntersGuides(parmsIntersGuides)
, m_hasPerformed(false)
{
// check consistency of input data
size_t n_profiles = profiles.size();
size_t n_guides = guides.size();
if (n_profiles != m_parmsIntersProfiles.RowNumber()) {
throw CTiglError("Invalid row size of parmsIntersProfiles matrix.");
}
if (n_profiles != m_parmsIntersGuides.RowNumber()) {
throw CTiglError("Invalid row size of parmsIntersGuides matrix.");
}
if (n_guides != m_parmsIntersProfiles.ColNumber()) {
throw CTiglError("Invalid col size of parmsIntersProfiles matrix.");
}
if (n_guides != m_parmsIntersGuides.ColNumber()) {
throw CTiglError("Invalid col size of parmsIntersGuides matrix.");
}
assert(m_parmsIntersGuides.UpperRow() == n_profiles - 1);
assert(m_parmsIntersProfiles.UpperRow() == n_profiles - 1);
assert(m_parmsIntersGuides.UpperCol() == n_guides - 1);
assert(m_parmsIntersProfiles.UpperCol() == n_guides - 1);
// create helper vectors with indices
for (int i = 0; i < n_profiles; ++i) {
std::stringstream str;
str << i;
m_profIdx.push_back(str.str());
}
for (int i = 0; i < n_guides; ++i) {
std::stringstream str;
str << i;
m_guidIdx.push_back(str.str());
}
}
void CTiglCurveNetworkSorter::swapProfiles(size_t idx1, size_t idx2)
{
if (idx1 == idx2) {
return;
}
std::iter_swap(m_profiles.begin() + idx1, m_profiles.begin() + idx2);
std::iter_swap(m_profIdx.begin() + idx1, m_profIdx.begin() + idx2);
m_parmsIntersGuides.SwapRow(static_cast<Standard_Integer>(idx1), static_cast<Standard_Integer>(idx2));
m_parmsIntersProfiles.SwapRow(static_cast<Standard_Integer>(idx1), static_cast<Standard_Integer>(idx2));
}
void CTiglCurveNetworkSorter::swapGuides(size_t idx1, size_t idx2)
{
if (idx1 == idx2) {
return;
}
std::iter_swap(m_guides.begin() + idx1, m_guides.begin() + idx2);
std::iter_swap(m_guidIdx.begin() + idx1, m_guidIdx.begin() + idx2);
m_parmsIntersGuides.SwapCol(static_cast<Standard_Integer>(idx1), static_cast<Standard_Integer>(idx2));
m_parmsIntersProfiles.SwapCol(static_cast<Standard_Integer>(idx1), static_cast<Standard_Integer>(idx2));
}
void CTiglCurveNetworkSorter::GetStartCurveIndices(size_t &prof_idx, size_t &guid_idx, bool &guideMustBeReversed) const
{
// find curves, that begin at the same point (have the smallest parameter at their intersection)
for (size_t irow = 0; irow < NProfiles(); ++irow) {
size_t jmin = minRowIndex(m_parmsIntersProfiles, irow);
size_t imin = minColIndex(m_parmsIntersGuides, jmin);
if (imin == irow) {
// we found the start curves
prof_idx = imin;
guid_idx = jmin;
guideMustBeReversed = false;
return;
}
}
// there are situtation (a loop) when the previous situation does not exist
// find curves were the start of a profile hits the end of a guide
for (size_t irow = 0; irow < NProfiles(); ++irow) {
size_t jmin = minRowIndex(m_parmsIntersProfiles, irow);
size_t imax = maxColIndex(m_parmsIntersGuides, jmin);
if (imax == irow) {
// we found the start curves
prof_idx = imax;
guid_idx = jmin;
guideMustBeReversed = true;
return;
}
}
// we have not found the starting curve. The network seems invalid
throw CTiglError("Cannot find starting curves of curve network.");
}
void CTiglCurveNetworkSorter::Perform()
{
if (m_hasPerformed) {
return;
}
size_t prof_start = 0, guide_start = 0;
Standard_Integer nGuid = static_cast<Standard_Integer>(NGuides());
Standard_Integer nProf = static_cast<Standard_Integer>(NProfiles());
bool guideMustBeReversed = false;
GetStartCurveIndices(prof_start, guide_start, guideMustBeReversed);
// put start curves first in array
swapProfiles(0, prof_start);
swapGuides(0, guide_start);
if (guideMustBeReversed) {
reverseGuide(0);
}
// perform a bubble sort for the guides,
// such that the guides intersection of the first profile are ascending
for (int n = nGuid; n > 1; n = n - 1) {
for (int j = 1; j < n - 1; ++j) {
if (m_parmsIntersProfiles(0, j) > m_parmsIntersProfiles(0, j + 1)) {
swapGuides(j, j + 1);
}
}
}
// perform a bubble sort of the profiles,
// such that the profiles are in ascending order of the first guide
for (int n = nProf; n > 1; n = n - 1) {
for (int i = 1; i < n - 1; ++i) {
if (m_parmsIntersGuides(i, 0) > m_parmsIntersGuides(i + 1, 0)) {
swapProfiles(i, i + 1);
}
}
}
// reverse profiles, if necessary
for (Standard_Integer iProf = 1; iProf < nProf; ++iProf) {
if (m_parmsIntersProfiles(iProf, 0) > m_parmsIntersProfiles(iProf, nGuid - 1)) {
reverseProfile(iProf);
}
}
// reverse guide, if necessary
for (Standard_Integer iGuid = 1; iGuid < nGuid; ++iGuid) {
if (m_parmsIntersGuides(0, iGuid) > m_parmsIntersGuides(nProf - 1, iGuid)) {
reverseGuide(iGuid);
}
}
m_hasPerformed = true;
}
size_t CTiglCurveNetworkSorter::NProfiles() const
{
return m_profiles.size();
}
size_t CTiglCurveNetworkSorter::NGuides() const
{
return m_guides.size();
}
const std::vector<std::string> &CTiglCurveNetworkSorter::ProfileIndices() const
{
return m_profIdx;
}
const std::vector<std::string> &CTiglCurveNetworkSorter::GuideIndices() const
{
return m_guidIdx;
}
void CTiglCurveNetworkSorter::reverseProfile(size_t profileIdx)
{
Standard_Integer pIdx = static_cast<Standard_Integer>(profileIdx);
Handle(Geom_Curve) profile = m_profiles[profileIdx];
Standard_Real lastParm = !profile.IsNull() ?
profile->LastParameter() :
m_parmsIntersProfiles(pIdx, static_cast<Standard_Integer>(maxRowIndex(m_parmsIntersProfiles, pIdx)));
Standard_Real firstParm = !profile.IsNull() ?
profile->FirstParameter() :
m_parmsIntersProfiles(pIdx, static_cast<Standard_Integer>(minRowIndex(m_parmsIntersProfiles, pIdx)));
// compute new parameters
for (int icol = 0; icol < NGuides(); ++icol) {
m_parmsIntersProfiles(pIdx, icol) = -m_parmsIntersProfiles(pIdx, icol) + firstParm + lastParm;
}
if (!profile.IsNull()) {
profile->Reverse();
}
m_profIdx[profileIdx] = "-" + m_profIdx[profileIdx];
}
void CTiglCurveNetworkSorter::reverseGuide(size_t guideIdx)
{
Standard_Integer gIdx = static_cast<Standard_Integer>(guideIdx);
Handle(Geom_Curve) guide = m_guides[guideIdx];
Standard_Real lastParm = !guide.IsNull() ?
guide->LastParameter() :
m_parmsIntersGuides(static_cast<Standard_Integer>(maxColIndex(m_parmsIntersGuides, gIdx)), gIdx);
Standard_Real firstParm = !guide.IsNull() ?
guide->FirstParameter() :
m_parmsIntersGuides(static_cast<Standard_Integer>(minColIndex(m_parmsIntersGuides, gIdx)), gIdx);
// compute new parameter
for (int irow = 0; irow < NProfiles(); ++irow) {
m_parmsIntersGuides(irow, gIdx) = -m_parmsIntersGuides(irow, gIdx) + firstParm + lastParm;
}
if (!guide.IsNull()) {
guide->Reverse();
}
m_guidIdx[guideIdx] = "-" + m_guidIdx[guideIdx];
}
} // namespace tigl
<commit_msg>Replaced iter_swap with swap to be compilable on VC2008<commit_after>/*
* Copyright (C) 2017 German Aerospace Center (DLR/SC)
*
* Created: 2017 Martin Siggel <[email protected]>
*
* 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 "CTiglCurveNetworkSorter.h"
#include "CTiglError.h"
#include <utility>
#include <cassert>
namespace
{
// returns the column index if the maximum of i-th row
size_t maxRowIndex(const math_Matrix& m, size_t irow)
{
double max = DBL_MIN;
size_t jmax = 0;
for (Standard_Integer jcol = 0; jcol < m.ColNumber(); ++jcol) {
if (m(static_cast<Standard_Integer>(irow), jcol) > max) {
max = m(static_cast<Standard_Integer>(irow), jcol);
jmax = static_cast<size_t>(jcol);
}
}
return jmax;
}
// returns the row index if the maximum of i-th col
size_t maxColIndex(const math_Matrix& m, size_t jcol)
{
double max = DBL_MIN;
size_t imax = 0;
for (Standard_Integer irow = 0; irow < m.RowNumber(); ++irow) {
if (m(irow, static_cast<Standard_Integer>(jcol)) > max) {
max = m(irow, static_cast<Standard_Integer>(jcol));
imax = static_cast<size_t>(irow);
}
}
return imax;
}
// returns the column index if the minimum of i-th row
size_t minRowIndex(const math_Matrix& m, size_t irow)
{
double min = DBL_MAX;
size_t jmin = 0;
for (Standard_Integer jcol = 0; jcol < m.ColNumber(); ++jcol) {
if (m(static_cast<Standard_Integer>(irow), jcol) < min) {
min = m(static_cast<Standard_Integer>(irow), jcol);
jmin = static_cast<size_t>(jcol);
}
}
return jmin;
}
// returns the column index if the minimum of i-th row
size_t minColIndex(const math_Matrix& m, size_t jcol)
{
double min = DBL_MAX;
size_t imin = 0;
for (Standard_Integer irow = 0; irow < m.RowNumber(); ++irow) {
if (m(irow, static_cast<Standard_Integer>(jcol)) < min) {
min = m(irow, static_cast<Standard_Integer>(jcol));
imin = static_cast<size_t>(irow);
}
}
return imin;
}
}
namespace tigl
{
CTiglCurveNetworkSorter::CTiglCurveNetworkSorter(const std::vector<Handle (Geom_Curve)> &profiles,
const std::vector<Handle (Geom_Curve)> &guides,
const math_Matrix &parmsIntersProfiles,
const math_Matrix &parmsIntersGuides)
: m_profiles(profiles)
, m_guides(guides)
, m_parmsIntersProfiles(parmsIntersProfiles)
, m_parmsIntersGuides(parmsIntersGuides)
, m_hasPerformed(false)
{
// check consistency of input data
size_t n_profiles = profiles.size();
size_t n_guides = guides.size();
if (n_profiles != m_parmsIntersProfiles.RowNumber()) {
throw CTiglError("Invalid row size of parmsIntersProfiles matrix.");
}
if (n_profiles != m_parmsIntersGuides.RowNumber()) {
throw CTiglError("Invalid row size of parmsIntersGuides matrix.");
}
if (n_guides != m_parmsIntersProfiles.ColNumber()) {
throw CTiglError("Invalid col size of parmsIntersProfiles matrix.");
}
if (n_guides != m_parmsIntersGuides.ColNumber()) {
throw CTiglError("Invalid col size of parmsIntersGuides matrix.");
}
assert(m_parmsIntersGuides.UpperRow() == n_profiles - 1);
assert(m_parmsIntersProfiles.UpperRow() == n_profiles - 1);
assert(m_parmsIntersGuides.UpperCol() == n_guides - 1);
assert(m_parmsIntersProfiles.UpperCol() == n_guides - 1);
// create helper vectors with indices
for (int i = 0; i < n_profiles; ++i) {
std::stringstream str;
str << i;
m_profIdx.push_back(str.str());
}
for (int i = 0; i < n_guides; ++i) {
std::stringstream str;
str << i;
m_guidIdx.push_back(str.str());
}
}
void CTiglCurveNetworkSorter::swapProfiles(size_t idx1, size_t idx2)
{
if (idx1 == idx2) {
return;
}
std::swap(m_profiles[idx1], m_profiles[idx2]);
std::swap(m_profIdx[idx1], m_profIdx[idx2]);
m_parmsIntersGuides.SwapRow(static_cast<Standard_Integer>(idx1), static_cast<Standard_Integer>(idx2));
m_parmsIntersProfiles.SwapRow(static_cast<Standard_Integer>(idx1), static_cast<Standard_Integer>(idx2));
}
void CTiglCurveNetworkSorter::swapGuides(size_t idx1, size_t idx2)
{
if (idx1 == idx2) {
return;
}
std::swap(m_guides[idx1], m_guides[idx2]);
std::swap(m_guidIdx[idx1], m_guidIdx[idx2]);
m_parmsIntersGuides.SwapCol(static_cast<Standard_Integer>(idx1), static_cast<Standard_Integer>(idx2));
m_parmsIntersProfiles.SwapCol(static_cast<Standard_Integer>(idx1), static_cast<Standard_Integer>(idx2));
}
void CTiglCurveNetworkSorter::GetStartCurveIndices(size_t &prof_idx, size_t &guid_idx, bool &guideMustBeReversed) const
{
// find curves, that begin at the same point (have the smallest parameter at their intersection)
for (size_t irow = 0; irow < NProfiles(); ++irow) {
size_t jmin = minRowIndex(m_parmsIntersProfiles, irow);
size_t imin = minColIndex(m_parmsIntersGuides, jmin);
if (imin == irow) {
// we found the start curves
prof_idx = imin;
guid_idx = jmin;
guideMustBeReversed = false;
return;
}
}
// there are situtation (a loop) when the previous situation does not exist
// find curves were the start of a profile hits the end of a guide
for (size_t irow = 0; irow < NProfiles(); ++irow) {
size_t jmin = minRowIndex(m_parmsIntersProfiles, irow);
size_t imax = maxColIndex(m_parmsIntersGuides, jmin);
if (imax == irow) {
// we found the start curves
prof_idx = imax;
guid_idx = jmin;
guideMustBeReversed = true;
return;
}
}
// we have not found the starting curve. The network seems invalid
throw CTiglError("Cannot find starting curves of curve network.");
}
void CTiglCurveNetworkSorter::Perform()
{
if (m_hasPerformed) {
return;
}
size_t prof_start = 0, guide_start = 0;
Standard_Integer nGuid = static_cast<Standard_Integer>(NGuides());
Standard_Integer nProf = static_cast<Standard_Integer>(NProfiles());
bool guideMustBeReversed = false;
GetStartCurveIndices(prof_start, guide_start, guideMustBeReversed);
// put start curves first in array
swapProfiles(0, prof_start);
swapGuides(0, guide_start);
if (guideMustBeReversed) {
reverseGuide(0);
}
// perform a bubble sort for the guides,
// such that the guides intersection of the first profile are ascending
for (int n = nGuid; n > 1; n = n - 1) {
for (int j = 1; j < n - 1; ++j) {
if (m_parmsIntersProfiles(0, j) > m_parmsIntersProfiles(0, j + 1)) {
swapGuides(j, j + 1);
}
}
}
// perform a bubble sort of the profiles,
// such that the profiles are in ascending order of the first guide
for (int n = nProf; n > 1; n = n - 1) {
for (int i = 1; i < n - 1; ++i) {
if (m_parmsIntersGuides(i, 0) > m_parmsIntersGuides(i + 1, 0)) {
swapProfiles(i, i + 1);
}
}
}
// reverse profiles, if necessary
for (Standard_Integer iProf = 1; iProf < nProf; ++iProf) {
if (m_parmsIntersProfiles(iProf, 0) > m_parmsIntersProfiles(iProf, nGuid - 1)) {
reverseProfile(iProf);
}
}
// reverse guide, if necessary
for (Standard_Integer iGuid = 1; iGuid < nGuid; ++iGuid) {
if (m_parmsIntersGuides(0, iGuid) > m_parmsIntersGuides(nProf - 1, iGuid)) {
reverseGuide(iGuid);
}
}
m_hasPerformed = true;
}
size_t CTiglCurveNetworkSorter::NProfiles() const
{
return m_profiles.size();
}
size_t CTiglCurveNetworkSorter::NGuides() const
{
return m_guides.size();
}
const std::vector<std::string> &CTiglCurveNetworkSorter::ProfileIndices() const
{
return m_profIdx;
}
const std::vector<std::string> &CTiglCurveNetworkSorter::GuideIndices() const
{
return m_guidIdx;
}
void CTiglCurveNetworkSorter::reverseProfile(size_t profileIdx)
{
Standard_Integer pIdx = static_cast<Standard_Integer>(profileIdx);
Handle(Geom_Curve) profile = m_profiles[profileIdx];
Standard_Real lastParm = !profile.IsNull() ?
profile->LastParameter() :
m_parmsIntersProfiles(pIdx, static_cast<Standard_Integer>(maxRowIndex(m_parmsIntersProfiles, pIdx)));
Standard_Real firstParm = !profile.IsNull() ?
profile->FirstParameter() :
m_parmsIntersProfiles(pIdx, static_cast<Standard_Integer>(minRowIndex(m_parmsIntersProfiles, pIdx)));
// compute new parameters
for (int icol = 0; icol < NGuides(); ++icol) {
m_parmsIntersProfiles(pIdx, icol) = -m_parmsIntersProfiles(pIdx, icol) + firstParm + lastParm;
}
if (!profile.IsNull()) {
profile->Reverse();
}
m_profIdx[profileIdx] = "-" + m_profIdx[profileIdx];
}
void CTiglCurveNetworkSorter::reverseGuide(size_t guideIdx)
{
Standard_Integer gIdx = static_cast<Standard_Integer>(guideIdx);
Handle(Geom_Curve) guide = m_guides[guideIdx];
Standard_Real lastParm = !guide.IsNull() ?
guide->LastParameter() :
m_parmsIntersGuides(static_cast<Standard_Integer>(maxColIndex(m_parmsIntersGuides, gIdx)), gIdx);
Standard_Real firstParm = !guide.IsNull() ?
guide->FirstParameter() :
m_parmsIntersGuides(static_cast<Standard_Integer>(minColIndex(m_parmsIntersGuides, gIdx)), gIdx);
// compute new parameter
for (int irow = 0; irow < NProfiles(); ++irow) {
m_parmsIntersGuides(irow, gIdx) = -m_parmsIntersGuides(irow, gIdx) + firstParm + lastParm;
}
if (!guide.IsNull()) {
guide->Reverse();
}
m_guidIdx[guideIdx] = "-" + m_guidIdx[guideIdx];
}
} // namespace tigl
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Qt Software Information ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
**
**************************************************************************/
#include "helpfindsupport.h"
#include "helpviewer.h"
#include <utils/qtcassert.h>
using namespace Help::Internal;
HelpFindSupport::HelpFindSupport(CentralWidget *centralWidget)
: m_centralWidget(centralWidget)
{
}
HelpFindSupport::~HelpFindSupport()
{
}
bool HelpFindSupport::isEnabled() const
{
return true;
}
QString HelpFindSupport::currentFindString() const
{
QTC_ASSERT(m_centralWidget, return QString());
HelpViewer *viewer = m_centralWidget->currentHelpViewer();
if (!viewer)
return QString();
#if !defined(QT_NO_WEBKIT)
return viewer->selectedText();
#else
return viewer->textCursor().selectedText();
#endif
}
QString HelpFindSupport::completedFindString() const
{
return QString();
}
bool HelpFindSupport::findIncremental(const QString &txt, QTextDocument::FindFlags findFlags)
{
QTC_ASSERT(m_centralWidget, return false);
findFlags &= ~QTextDocument::FindBackward;
return m_centralWidget->find(txt, findFlags, true);
}
bool HelpFindSupport::findStep(const QString &txt, QTextDocument::FindFlags findFlags)
{
QTC_ASSERT(m_centralWidget, return false);
return m_centralWidget->find(txt, findFlags, false);
}
HelpViewerFindSupport::HelpViewerFindSupport(HelpViewer *viewer)
: m_viewer(viewer)
{
}
QString HelpViewerFindSupport::currentFindString() const
{
QTC_ASSERT(m_viewer, return QString());
return m_viewer->selectedText();
}
bool HelpViewerFindSupport::findIncremental(const QString &txt, QTextDocument::FindFlags findFlags)
{
QTC_ASSERT(m_viewer, return false);
findFlags &= ~QTextDocument::FindBackward;
return find(txt, findFlags, true);
}
bool HelpViewerFindSupport::findStep(const QString &txt, QTextDocument::FindFlags findFlags)
{
QTC_ASSERT(m_viewer, return false);
return find(txt, findFlags, false);
}
bool HelpViewerFindSupport::find(const QString &txt, QTextDocument::FindFlags findFlags, bool incremental)
{
QTC_ASSERT(m_viewer, return false);
#if !defined(QT_NO_WEBKIT)
Q_UNUSED(incremental);
QWebPage::FindFlags options = QWebPage::FindWrapsAroundDocument;
if (findFlags & QTextDocument::FindBackward)
options |= QWebPage::FindBackward;
if (findFlags & QTextDocument::FindCaseSensitively)
options |= QWebPage::FindCaseSensitively;
return m_viewer->findText(txt, options);
#else
QTextCursor cursor = viewer->textCursor();
QTextDocument *doc = viewer->document();
QTextBrowser *browser = qobject_cast<QTextBrowser*>(viewer);
if (!browser || !doc || cursor.isNull())
return false;
if (incremental)
cursor.setPosition(cursor.selectionStart());
QTextCursor found = doc->find(txt, cursor, findFlags);
if (found.isNull()) {
if ((findFlags&QTextDocument::FindBackward) == 0)
cursor.movePosition(QTextCursor::Start);
else
cursor.movePosition(QTextCursor::End);
found = doc->find(txt, cursor, findFlags);
if (found.isNull()) {
return false;
}
}
if (!found.isNull()) {
viewer->setTextCursor(found);
}
return true;
#endif
}
<commit_msg>Fixed: Compile without WebKit RevBy: con<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Qt Software Information ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
**
**************************************************************************/
#include "helpfindsupport.h"
#include "helpviewer.h"
#include <utils/qtcassert.h>
using namespace Help::Internal;
HelpFindSupport::HelpFindSupport(CentralWidget *centralWidget)
: m_centralWidget(centralWidget)
{
}
HelpFindSupport::~HelpFindSupport()
{
}
bool HelpFindSupport::isEnabled() const
{
return true;
}
QString HelpFindSupport::currentFindString() const
{
QTC_ASSERT(m_centralWidget, return QString());
HelpViewer *viewer = m_centralWidget->currentHelpViewer();
if (!viewer)
return QString();
#if !defined(QT_NO_WEBKIT)
return viewer->selectedText();
#else
return viewer->textCursor().selectedText();
#endif
}
QString HelpFindSupport::completedFindString() const
{
return QString();
}
bool HelpFindSupport::findIncremental(const QString &txt, QTextDocument::FindFlags findFlags)
{
QTC_ASSERT(m_centralWidget, return false);
findFlags &= ~QTextDocument::FindBackward;
return m_centralWidget->find(txt, findFlags, true);
}
bool HelpFindSupport::findStep(const QString &txt, QTextDocument::FindFlags findFlags)
{
QTC_ASSERT(m_centralWidget, return false);
return m_centralWidget->find(txt, findFlags, false);
}
HelpViewerFindSupport::HelpViewerFindSupport(HelpViewer *viewer)
: m_viewer(viewer)
{
}
QString HelpViewerFindSupport::currentFindString() const
{
QTC_ASSERT(m_viewer, return QString());
#if !defined(QT_NO_WEBKIT)
return m_viewer->selectedText();
#else
return QString();
#endif
}
bool HelpViewerFindSupport::findIncremental(const QString &txt, QTextDocument::FindFlags findFlags)
{
QTC_ASSERT(m_viewer, return false);
findFlags &= ~QTextDocument::FindBackward;
return find(txt, findFlags, true);
}
bool HelpViewerFindSupport::findStep(const QString &txt, QTextDocument::FindFlags findFlags)
{
QTC_ASSERT(m_viewer, return false);
return find(txt, findFlags, false);
}
bool HelpViewerFindSupport::find(const QString &txt, QTextDocument::FindFlags findFlags, bool incremental)
{
QTC_ASSERT(m_viewer, return false);
#if !defined(QT_NO_WEBKIT)
Q_UNUSED(incremental);
QWebPage::FindFlags options = QWebPage::FindWrapsAroundDocument;
if (findFlags & QTextDocument::FindBackward)
options |= QWebPage::FindBackward;
if (findFlags & QTextDocument::FindCaseSensitively)
options |= QWebPage::FindCaseSensitively;
return m_viewer->findText(txt, options);
#else
QTextCursor cursor = m_viewer->textCursor();
QTextDocument *doc = m_viewer->document();
QTextBrowser *browser = qobject_cast<QTextBrowser*>(m_viewer);
if (!browser || !doc || cursor.isNull())
return false;
if (incremental)
cursor.setPosition(cursor.selectionStart());
QTextCursor found = doc->find(txt, cursor, findFlags);
if (found.isNull()) {
if ((findFlags&QTextDocument::FindBackward) == 0)
cursor.movePosition(QTextCursor::Start);
else
cursor.movePosition(QTextCursor::End);
found = doc->find(txt, cursor, findFlags);
if (found.isNull()) {
return false;
}
}
if (!found.isNull()) {
m_viewer->setTextCursor(found);
}
return true;
#endif
}
<|endoftext|> |
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkTestingMacros.h"
#include <tinyxml.h>
#include <string.h>
#include <itksys/SystemTools.hxx>
static const std::string filename = itksys::SystemTools::GetCurrentWorkingDirectory() + "/TinyXMLTest.txt";
static const std::string elementToStoreAttributeName = "DoubleTest";
static const std::string attributeToStoreName = "CommaValue";
/**
* create a simple xml document which stores the values
* @param valueToWrite value which should be stored
* @return true, if document was successfully created.
*/
static bool Setup(double valueToWrite)
{
// 1. create simple document
TiXmlDocument document;
TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "", "" ); // TODO what to write here? encoding? etc....
document.LinkEndChild( decl );
TiXmlElement* version = new TiXmlElement("Version");
version->SetAttribute("Writer", __FILE__ );
version->SetAttribute("CVSRevision", "$Revision: 17055 $" );
version->SetAttribute("FileVersion", 1 );
document.LinkEndChild(version);
// 2. store one element containing a double value with potentially many after comma digits.
TiXmlElement* vElement = new TiXmlElement( elementToStoreAttributeName );
vElement->SetDoubleAttribute( attributeToStoreName, valueToWrite );
document.LinkEndChild(vElement);
// 3. store in file.
return document.SaveFile( filename );
}
static int readValueFromSetupDocument(double& readOutValue)
{
TiXmlDocument document;
if (!document.LoadFile(filename))
{
MITK_TEST_CONDITION_REQUIRED(false, "Test Setup failed, could not open " << filename);
return TIXML_NO_ATTRIBUTE;
}
else
{
TiXmlElement* doubleTest = document.FirstChildElement(elementToStoreAttributeName);
return doubleTest->QueryDoubleAttribute(attributeToStoreName, &readOutValue);
}
}
static void TearDown()
{
// TODO delete created file, ...
}
static void Test_Setup_works()
{
MITK_TEST_CONDITION_REQUIRED(Setup(1.0), "Test if setup correctly writes data to " << filename);
}
/**
* this first test ensures we can correctly readout values from the
* TinyXMLDocument.
*/
static void Test_ReadOutValue_works()
{
Setup(1.0);
double readValue;
MITK_TEST_CONDITION_REQUIRED(TIXML_SUCCESS == readValueFromSetupDocument(readValue),
"checking if readout mechanism works.");
}
static void Test_DoubleValueWriteOut()
{
const double valueToWrite = -1.123456;
const int validDigitsAfterComma = 6; // indicates the number of valid digits after comma of valueToWrite
const double neededPrecision = 1.0 / ((double) validDigitsAfterComma + 1);
double readValue;
Setup(valueToWrite);
TiXmlBase::SetRequiredDecimalPlaces(validDigitsAfterComma);
readValueFromSetupDocument(readValue);
MITK_TEST_CONDITION_REQUIRED(mitk::Equal(valueToWrite, readValue, neededPrecision),
std::setprecision(validDigitsAfterComma) <<
"Testing if value " << valueToWrite << " equals " << readValue
<< " which was retrieved from TinyXML document");
TearDown();
}
static void Test_DoubleValueWriteOut_manyDecimalPlaces()
{
const double valueToWrite = -1.12345678910111;
const int validDigitsAfterComma = 14; // indicates the number of valid digits after comma of valueToWrite
const double neededPrecision = 1.0 / ((double) validDigitsAfterComma + 1);
double readValue;
Setup(valueToWrite);
TiXmlBase::SetRequiredDecimalPlaces(validDigitsAfterComma);
readValueFromSetupDocument(readValue);
MITK_TEST_CONDITION_REQUIRED(mitk::Equal(valueToWrite, readValue, neededPrecision),
std::setprecision(validDigitsAfterComma) <<
"Testing if value " << valueToWrite << " equals " << readValue
<< " which was retrieved from TinyXML document");
TearDown();
}
static void Test_DoubleValueWriteOut_tooLittlePrecision()
{
const double valueToWrite = -1.12345678910111;
const int validDigitsAfterComma = 14; // indicates the number of valid digits after comma of valueToWrite
const double neededPrecision = 1.0 / ((double) validDigitsAfterComma + 1);
double readValue;
Setup(valueToWrite);
// this should lead the readout value to be different since
// only the first 4 digits are written to xml.
TiXmlBase::SetRequiredDecimalPlaces(4);
readValueFromSetupDocument(readValue);
MITK_TEST_CONDITION_REQUIRED(mitk::Equal(valueToWrite, readValue, neededPrecision),
std::setprecision(validDigitsAfterComma) <<
"Testing if value " << valueToWrite << " equals " << readValue
<< " which was retrieved from TinyXML document");
TearDown();
}
int mitkTinyXMLTest(int /* argc */, char* /*argv*/[])
{
MITK_TEST_BEGIN("TinyXMLTest");
Test_Setup_works();
Test_ReadOutValue_works();
Test_DoubleValueWriteOut();
Test_DoubleValueWriteOut_manyDecimalPlaces();
Test_DoubleValueWriteOut_tooLittlePrecision();
MITK_TEST_END()
}
<commit_msg>changed interface.<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkTestingMacros.h"
#include <tinyxml.h>
#include <string.h>
#include <itksys/SystemTools.hxx>
static const std::string filename = itksys::SystemTools::GetCurrentWorkingDirectory() + "/TinyXMLTest.txt";
static const std::string elementToStoreAttributeName = "DoubleTest";
static const std::string attributeToStoreName = "CommaValue";
/**
* create a simple xml document which stores the values
* @param valueToWrite value which should be stored
* @return true, if document was successfully created.
*/
static bool Setup(double valueToWrite, const unsigned int requiredDecimalPlaces)
{
// 1. create simple document
TiXmlDocument document;
TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "", "" ); // TODO what to write here? encoding? etc....
document.LinkEndChild( decl );
TiXmlElement* version = new TiXmlElement("Version");
version->SetAttribute("Writer", __FILE__ );
version->SetAttribute("CVSRevision", "$Revision: 17055 $" );
version->SetAttribute("FileVersion", 1 );
document.LinkEndChild(version);
// 2. store one element containing a double value with potentially many after comma digits.
TiXmlElement* vElement = new TiXmlElement( elementToStoreAttributeName );
vElement->SetDoubleAttribute( attributeToStoreName, valueToWrite, requiredDecimalPlaces );
document.LinkEndChild(vElement);
// 3. store in file.
return document.SaveFile( filename );
}
static int readValueFromSetupDocument(double& readOutValue)
{
TiXmlDocument document;
if (!document.LoadFile(filename))
{
MITK_TEST_CONDITION_REQUIRED(false, "Test Setup failed, could not open " << filename);
return TIXML_NO_ATTRIBUTE;
}
else
{
TiXmlElement* doubleTest = document.FirstChildElement(elementToStoreAttributeName);
return doubleTest->QueryDoubleAttribute(attributeToStoreName, &readOutValue);
}
}
/**
*
* @return true if TearDown was successful.
*/
static bool TearDown()
{
return !remove(filename.c_str());
}
static void Test_Setup_works()
{
MITK_TEST_CONDITION_REQUIRED(Setup(1.0, 1) && TearDown(),
"Test if setup and teardown correctly writes data to " << filename << " and deletes the file after the test");
}
/**
* this first test ensures we can correctly readout values from the
* TinyXMLDocument.
*/
static void Test_ReadOutValue_works()
{
Setup(1.0, 1);
double readValue;
MITK_TEST_CONDITION_REQUIRED(TIXML_SUCCESS == readValueFromSetupDocument(readValue),
"checking if readout mechanism works.");
}
static void Test_DoubleValueWriteOut()
{
const double valueToWrite = -1.123456;
const int validDigitsAfterComma = 6; // indicates the number of valid digits after comma of valueToWrite
const double neededPrecision = 1.0 / ((double) validDigitsAfterComma + 1);
double readValue;
Setup(valueToWrite, validDigitsAfterComma);
readValueFromSetupDocument(readValue);
MITK_TEST_CONDITION_REQUIRED(mitk::Equal(valueToWrite, readValue, neededPrecision),
std::setprecision(validDigitsAfterComma) <<
"Testing if value " << valueToWrite << " equals " << readValue
<< " which was retrieved from TinyXML document");
TearDown();
}
static void Test_DoubleValueWriteOut_manyDecimalPlaces()
{
const double valueToWrite = -1.12345678910111;
const int validDigitsAfterComma = 14; // indicates the number of valid digits after comma of valueToWrite
const double neededPrecision = 1.0 / ((double) validDigitsAfterComma + 1);
double readValue;
Setup(valueToWrite, validDigitsAfterComma);
readValueFromSetupDocument(readValue);
MITK_TEST_CONDITION_REQUIRED(mitk::Equal(valueToWrite, readValue, neededPrecision),
std::setprecision(validDigitsAfterComma) <<
"Testing if value " << valueToWrite << " equals " << readValue
<< " which was retrieved from TinyXML document");
TearDown();
}
static void Test_DoubleValueWriteOut_tooLittlePrecision()
{
const double valueToWrite = -1.12345678910111;
const int validDigitsAfterComma = 14; // indicates the number of valid digits after comma of valueToWrite
const double neededPrecision = 1.0 / ((double) validDigitsAfterComma + 1);
double readValue;
Setup(valueToWrite, validDigitsAfterComma);
readValueFromSetupDocument(readValue);
MITK_TEST_CONDITION_REQUIRED(!mitk::Equal(valueToWrite, readValue, neededPrecision),
std::setprecision(validDigitsAfterComma) <<
"Testing if value " << valueToWrite << " doesn't equal " << readValue
<< " which was retrieved from TinyXML document because decimal places are set too low.");
TearDown();
}
int mitkTinyXMLTest(int /* argc */, char* /*argv*/[])
{
MITK_TEST_BEGIN("TinyXMLTest");
Test_Setup_works();
Test_ReadOutValue_works();
Test_DoubleValueWriteOut();
Test_DoubleValueWriteOut_manyDecimalPlaces();
Test_DoubleValueWriteOut_tooLittlePrecision();
MITK_TEST_END()
}
<|endoftext|> |
<commit_before>/*
Copyright 2013-present Barefoot Networks, Inc.
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 <config.h>
#include <errno.h>
#if HAVE_EXECINFO_H
#include <execinfo.h>
#endif
#include <fcntl.h>
#include <limits.h>
#include <signal.h>
#include <string.h>
#include <sys/wait.h>
#if HAVE_UCONTEXT_H
#include <ucontext.h>
#endif
#include <unistd.h>
#include <iostream>
#include "exceptions.h"
#include "hex.h"
#include "log.h"
static const char *signames[] = {
"NONE", "HUP", "INT", "QUIT", "ILL", "TRAP", "ABRT", "BUS", "FPE", "KILL",
"USR1", "SEGV", "USR2", "PIPE", "ALRM", "TERM", "STKFLT", "CHLD", "CONT", "STOP",
"TSTP", "TTIN", "TTOU", "URG", "XCPU", "XFSZ", "VTALRM", "PROF", "WINCH", "POLL",
"PWR", "SYS"
};
char *program_name;
#ifdef MULTITHREAD
#include <pthread.h>
#include <mutex>
std::vector<pthread_t> thread_ids;
__thread int my_id;
void register_thread() {
static std::mutex lock;
std::lock_guard<std::mutex> acquire(lock);
my_id = thread_ids.size();
thread_ids.push_back(pthread_self());
}
#define MTONLY(...) __VA_ARGS__
#else
#define MTONLY(...)
#endif // MULTITHREAD
static MTONLY(__thread) int shutdown_loop = 0; // avoid infinite loop if shutdown crashes
static void sigint_shutdown(int sig, siginfo_t *, void *) {
if (shutdown_loop++) _exit(-1);
LOG1("Exiting with SIG" << signames[sig]);
_exit(sig + 0x80);
}
/*
* call external program addr2line WITHOUT using malloc or stdio or anything
* else that might be problematic if there's memory corruption or exhaustion
*/
const char *addr2line(void *addr, const char *text) {
int pfd[2], len;
pid_t child;
static char buffer[1024];
char *p = buffer;
const char *argv[4] = { "/bin/sh", "-c", buffer, 0 }, *t;
strcpy(p, "addr2line "); p += strlen(p); // NOLINT
uintptr_t a = (uintptr_t)addr;
int shift = (CHAR_BIT * sizeof(uintptr_t) - 1) & ~3;
while (shift > 0 && (a >> shift) == 0) shift -= 4;
while (shift >= 0) {
*p++ = "0123456789abcdef"[(a >> shift) & 0xf];
shift -= 4; }
strcpy(p, " -fsipe "); p += strlen(p); // NOLINT
if (!text || !(t = strchr(text, '('))) {
text = program_name;
t = text + strlen(text); }
if (!memchr(text, '/', t-text)) {
strcpy(p, "$(which "); p += strlen(p); } // NOLINT
strncpy(p, text, t-text);
p += t-text;
if (!memchr(text, '/', t-text)) *p++ = ')';
strcpy(p, " | c++filt"); // NOLINT
p += strlen(p);
#if HAVE_PIPE2
if (pipe2(pfd, O_CLOEXEC) < 0) return 0;
#else
if (pipe(pfd) < 0) return 0;
fcntl(pfd[0], F_SETFD, FD_CLOEXEC | fcntl(pfd[0], F_GETFL));
fcntl(pfd[1], F_SETFD, FD_CLOEXEC | fcntl(pfd[1], F_GETFL));
#endif
while ((child = fork()) == -1 && errno == EAGAIN) {}
if (child == -1) return 0;
if (child == 0) {
dup2(pfd[1], 1);
dup2(pfd[1], 2);
execvp(argv[0], (char*const*)argv);
_exit(-1); }
close(pfd[1]);
p = buffer;
while (p < buffer + sizeof(buffer) - 1 &&
(len = read(pfd[0], p, buffer+sizeof(buffer)-p-1)) > 0 &&
(p += len) && !memchr(p-len, '\n', len)) {}
close(pfd[0]);
waitpid(child, &len, WNOHANG);
*p = 0;
if ((p = strchr(buffer, '\n'))) *p = 0;
if (buffer[0] == 0 || buffer[0] == '?')
return 0;
return buffer;
}
#if HAVE_UCONTEXT_H
static void dumpregs(mcontext_t *mctxt) {
#if defined(REG_EAX)
LOG1(" eax=" << hex(mctxt->gregs[REG_EAX], 8, '0') <<
" ebx=" << hex(mctxt->gregs[REG_EBX], 8, '0') <<
" ecx=" << hex(mctxt->gregs[REG_ECX], 8, '0') <<
" edx=" << hex(mctxt->gregs[REG_EDX], 8, '0'));
LOG1(" edi=" << hex(mctxt->gregs[REG_EDI], 8, '0') <<
" esi=" << hex(mctxt->gregs[REG_ESI], 8, '0') <<
" ebp=" << hex(mctxt->gregs[REG_EBP], 8, '0') <<
" esp=" << hex(mctxt->gregs[REG_ESP], 8, '0'));
#elif defined(REG_RAX)
LOG1(" rax=" << hex(mctxt->gregs[REG_RAX], 16, '0') <<
" rbx=" << hex(mctxt->gregs[REG_RBX], 16, '0') <<
" rcx=" << hex(mctxt->gregs[REG_RCX], 16, '0'));
LOG1(" rdx=" << hex(mctxt->gregs[REG_RDX], 16, '0') <<
" rdi=" << hex(mctxt->gregs[REG_RDI], 16, '0') <<
" rsi=" << hex(mctxt->gregs[REG_RSI], 16, '0'));
LOG1(" rbp=" << hex(mctxt->gregs[REG_RBP], 16, '0') <<
" rsp=" << hex(mctxt->gregs[REG_RSP], 16, '0') <<
" r8=" << hex(mctxt->gregs[REG_R8], 16, '0'));
LOG1(" r9=" << hex(mctxt->gregs[REG_R9], 16, '0') <<
" r10=" << hex(mctxt->gregs[REG_R10], 16, '0') <<
" r11=" << hex(mctxt->gregs[REG_R11], 16, '0'));
LOG1(" r12=" << hex(mctxt->gregs[REG_R12], 16, '0') <<
" r13=" << hex(mctxt->gregs[REG_R13], 16, '0') <<
" r14=" << hex(mctxt->gregs[REG_R14], 16, '0'));
LOG1(" r15=" << hex(mctxt->gregs[REG_R15], 16, '0'));
#elif defined(__i386__)
LOG1(" eax=" << hex(mctxt->mc_eax, 8, '0') <<
" ebx=" << hex(mctxt->mc_ebx, 8, '0') <<
" ecx=" << hex(mctxt->mc_ecx, 8, '0') <<
" edx=" << hex(mctxt->mc_edx, 8, '0'));
LOG1(" edi=" << hex(mctxt->mc_edi, 8, '0') <<
" esi=" << hex(mctxt->mc_esi, 8, '0') <<
" ebp=" << hex(mctxt->mc_ebp, 8, '0') <<
" esp=" << hex(mctxt->mc_esp, 8, '0'));
#elif defined(__amd64__)
LOG1(" rax=" << hex(mctxt->mc_rax, 16, '0') <<
" rbx=" << hex(mctxt->mc_rbx, 16, '0') <<
" rcx=" << hex(mctxt->mc_rcx, 16, '0'));
LOG1(" rdx=" << hex(mctxt->mc_rdx, 16, '0') <<
" rdi=" << hex(mctxt->mc_rdi, 16, '0') <<
" rsi=" << hex(mctxt->mc_rsi, 16, '0'));
LOG1(" rbp=" << hex(mctxt->mc_rbp, 16, '0') <<
" rsp=" << hex(mctxt->mc_rsp, 16, '0') <<
" r8=" << hex(mctxt->mc_r8, 16, '0'));
LOG1(" r9=" << hex(mctxt->mc_r9, 16, '0') <<
" r10=" << hex(mctxt->mc_r10, 16, '0') <<
" r11=" << hex(mctxt->mc_r11, 16, '0'));
LOG1(" r12=" << hex(mctxt->mc_r12, 16, '0') <<
" r13=" << hex(mctxt->mc_r13, 16, '0') <<
" r14=" << hex(mctxt->mc_r14, 16, '0'));
LOG1(" r15=" << hex(mctxt->mc_r15, 16, '0'));
#else
#warning "unknown machine type"
#endif
}
#endif
static void crash_shutdown(int sig, siginfo_t *info, void *uctxt) {
if (shutdown_loop++) _exit(-1);
MTONLY(
static std::recursive_mutex lock;
static int threads_dumped = 0;
static bool killed_all_threads = false;
lock.lock();
if (!killed_all_threads) {
killed_all_threads = true;
for (int i = 0; i < int(thread_ids.size()); i++)
if (i != my_id-1) {
pthread_kill(thread_ids[i], SIGABRT); } } )
LOG1(MTONLY("Thread #" << my_id << " " <<) "exiting with SIG" <<
signames[sig] << ", trace:");
if (sig == SIGILL || sig == SIGFPE || sig == SIGSEGV ||
sig == SIGBUS || sig == SIGTRAP)
LOG1(" address = " << hex(info->si_addr));
#if HAVE_UCONTEXT_H
dumpregs(&(static_cast<ucontext_t *>(uctxt)->uc_mcontext));
#else
(void) uctxt; // Suppress unused parameter warning.
#endif
#if HAVE_EXECINFO_H
if (LOGGING(1)) {
static void *buffer[64];
int size = backtrace(buffer, 64);
char **strings = backtrace_symbols(buffer, size);
for (int i = 1; i < size; i++) {
if (strings)
LOG1(" " << strings[i]);
if (const char *line = addr2line(buffer[i], strings ? strings[i] : 0))
LOG1(" " << line); }
if (size < 1)
LOG1("backtrace failed");
free(strings); }
#endif
MTONLY(
if (++threads_dumped < int(thread_ids.size())) {
lock.unlock();
pthread_exit(0);
} else {
lock.unlock(); } )
if (sig != SIGABRT)
BUG("Exiting with SIG%s", signames[sig]);
_exit(sig + 0x80);
}
void setup_signals() {
struct sigaction sigact;
sigact.sa_sigaction = sigint_shutdown;
sigact.sa_flags = SA_SIGINFO;
sigemptyset(&sigact.sa_mask);
sigaction(SIGHUP, &sigact, 0);
sigaction(SIGINT, &sigact, 0);
sigaction(SIGQUIT, &sigact, 0);
sigaction(SIGTERM, &sigact, 0);
sigact.sa_sigaction = crash_shutdown;
sigaction(SIGILL, &sigact, 0);
sigaction(SIGABRT, &sigact, 0);
sigaction(SIGFPE, &sigact, 0);
sigaction(SIGSEGV, &sigact, 0);
sigaction(SIGBUS, &sigact, 0);
sigaction(SIGTRAP, &sigact, 0);
signal(SIGPIPE, SIG_IGN);
}
<commit_msg>Faster crash dumps (#2380)<commit_after>/*
Copyright 2013-present Barefoot Networks, Inc.
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 <config.h>
#include <errno.h>
#if HAVE_EXECINFO_H
#include <execinfo.h>
#endif
#include <fcntl.h>
#include <limits.h>
#include <signal.h>
#include <string.h>
#include <sys/wait.h>
#if HAVE_UCONTEXT_H
#include <ucontext.h>
#endif
#include <unistd.h>
#include <iostream>
#include "exceptions.h"
#include "hex.h"
#include "log.h"
static const char *signames[] = {
"NONE", "HUP", "INT", "QUIT", "ILL", "TRAP", "ABRT", "BUS", "FPE", "KILL",
"USR1", "SEGV", "USR2", "PIPE", "ALRM", "TERM", "STKFLT", "CHLD", "CONT", "STOP",
"TSTP", "TTIN", "TTOU", "URG", "XCPU", "XFSZ", "VTALRM", "PROF", "WINCH", "POLL",
"PWR", "SYS"
};
char *program_name;
#ifdef MULTITHREAD
#include <pthread.h>
#include <mutex>
std::vector<pthread_t> thread_ids;
__thread int my_id;
void register_thread() {
static std::mutex lock;
std::lock_guard<std::mutex> acquire(lock);
my_id = thread_ids.size();
thread_ids.push_back(pthread_self());
}
#define MTONLY(...) __VA_ARGS__
#else
#define MTONLY(...)
#endif // MULTITHREAD
static MTONLY(__thread) int shutdown_loop = 0; // avoid infinite loop if shutdown crashes
static void sigint_shutdown(int sig, siginfo_t *, void *) {
if (shutdown_loop++) _exit(-1);
LOG1("Exiting with SIG" << signames[sig]);
_exit(sig + 0x80);
}
/*
* call external program addr2line WITHOUT using malloc or stdio or anything
* else that might be problematic if there's memory corruption or exhaustion
*/
const char *addr2line(void *addr, const char *text) {
MTONLY(
static std::mutex lock;
std::lock_guard<std::mutex> acquire(lock); )
static pid_t child = 0;
static int to_child, from_child;
static char buffer[1024];
if (!child) {
int pfd1[2], pfd2[2];
char *p = buffer;
const char *argv[4] = { "/bin/sh", "-c", buffer, 0 }, *t;
strcpy(p, "addr2line "); p += strlen(p); // NOLINT
strcpy(p, " -Cfspe "); p += strlen(p); // NOLINT
if (!text || !(t = strchr(text, '('))) {
text = program_name;
t = text + strlen(text); }
if (!memchr(text, '/', t-text)) {
strcpy(p, "$(which "); p += strlen(p); } // NOLINT
strncpy(p, text, t-text);
p += t-text;
if (!memchr(text, '/', t-text)) *p++ = ')';
child = -1;
#if HAVE_PIPE2
if (pipe2(pfd1, O_CLOEXEC) < 0) return 0;
if (pipe2(pfd2, O_CLOEXEC) < 0) return 0;
#else
if (pipe(pfd1) < 0) return 0;
if (pipe(pfd2) < 0) return 0;
fcntl(pfd1[0], F_SETFD, FD_CLOEXEC | fcntl(pfd1[0], F_GETFL));
fcntl(pfd1[1], F_SETFD, FD_CLOEXEC | fcntl(pfd1[1], F_GETFL));
fcntl(pfd2[0], F_SETFD, FD_CLOEXEC | fcntl(pfd2[0], F_GETFL));
fcntl(pfd2[1], F_SETFD, FD_CLOEXEC | fcntl(pfd2[1], F_GETFL));
#endif
while ((child = fork()) == -1 && errno == EAGAIN) {}
if (child == -1) return 0;
if (child == 0) {
dup2(pfd1[1], 1);
dup2(pfd1[1], 2);
dup2(pfd2[0], 0);
execvp(argv[0], (char*const*)argv);
_exit(-1); }
close(pfd1[1]);
from_child = pfd1[0];
close(pfd2[0]);
to_child = pfd2[1]; }
if (child == -1) return 0;
char *p = buffer;
uintptr_t a = (uintptr_t)addr;
int shift = (CHAR_BIT * sizeof(uintptr_t) - 1) & ~3;
while (shift > 0 && (a >> shift) == 0) shift -= 4;
while (shift >= 0) {
*p++ = "0123456789abcdef"[(a >> shift) & 0xf];
shift -= 4; }
*p++ = '\n';
write(to_child, buffer, p-buffer);
p = buffer;
int len;
while (p < buffer + sizeof(buffer) - 1 &&
(len = read(from_child, p, buffer+sizeof(buffer)-p-1)) > 0 &&
(p += len) && !memchr(p-len, '\n', len)) {}
*p = 0;
if ((p = strchr(buffer, '\n'))) *p = 0;
if (buffer[0] == 0 || buffer[0] == '?')
return 0;
return buffer;
}
#if HAVE_UCONTEXT_H
static void dumpregs(mcontext_t *mctxt) {
#if defined(REG_EAX)
LOG1(" eax=" << hex(mctxt->gregs[REG_EAX], 8, '0') <<
" ebx=" << hex(mctxt->gregs[REG_EBX], 8, '0') <<
" ecx=" << hex(mctxt->gregs[REG_ECX], 8, '0') <<
" edx=" << hex(mctxt->gregs[REG_EDX], 8, '0'));
LOG1(" edi=" << hex(mctxt->gregs[REG_EDI], 8, '0') <<
" esi=" << hex(mctxt->gregs[REG_ESI], 8, '0') <<
" ebp=" << hex(mctxt->gregs[REG_EBP], 8, '0') <<
" esp=" << hex(mctxt->gregs[REG_ESP], 8, '0'));
#elif defined(REG_RAX)
LOG1(" rax=" << hex(mctxt->gregs[REG_RAX], 16, '0') <<
" rbx=" << hex(mctxt->gregs[REG_RBX], 16, '0') <<
" rcx=" << hex(mctxt->gregs[REG_RCX], 16, '0'));
LOG1(" rdx=" << hex(mctxt->gregs[REG_RDX], 16, '0') <<
" rdi=" << hex(mctxt->gregs[REG_RDI], 16, '0') <<
" rsi=" << hex(mctxt->gregs[REG_RSI], 16, '0'));
LOG1(" rbp=" << hex(mctxt->gregs[REG_RBP], 16, '0') <<
" rsp=" << hex(mctxt->gregs[REG_RSP], 16, '0') <<
" r8=" << hex(mctxt->gregs[REG_R8], 16, '0'));
LOG1(" r9=" << hex(mctxt->gregs[REG_R9], 16, '0') <<
" r10=" << hex(mctxt->gregs[REG_R10], 16, '0') <<
" r11=" << hex(mctxt->gregs[REG_R11], 16, '0'));
LOG1(" r12=" << hex(mctxt->gregs[REG_R12], 16, '0') <<
" r13=" << hex(mctxt->gregs[REG_R13], 16, '0') <<
" r14=" << hex(mctxt->gregs[REG_R14], 16, '0'));
LOG1(" r15=" << hex(mctxt->gregs[REG_R15], 16, '0'));
#elif defined(__i386__)
LOG1(" eax=" << hex(mctxt->mc_eax, 8, '0') <<
" ebx=" << hex(mctxt->mc_ebx, 8, '0') <<
" ecx=" << hex(mctxt->mc_ecx, 8, '0') <<
" edx=" << hex(mctxt->mc_edx, 8, '0'));
LOG1(" edi=" << hex(mctxt->mc_edi, 8, '0') <<
" esi=" << hex(mctxt->mc_esi, 8, '0') <<
" ebp=" << hex(mctxt->mc_ebp, 8, '0') <<
" esp=" << hex(mctxt->mc_esp, 8, '0'));
#elif defined(__amd64__)
LOG1(" rax=" << hex(mctxt->mc_rax, 16, '0') <<
" rbx=" << hex(mctxt->mc_rbx, 16, '0') <<
" rcx=" << hex(mctxt->mc_rcx, 16, '0'));
LOG1(" rdx=" << hex(mctxt->mc_rdx, 16, '0') <<
" rdi=" << hex(mctxt->mc_rdi, 16, '0') <<
" rsi=" << hex(mctxt->mc_rsi, 16, '0'));
LOG1(" rbp=" << hex(mctxt->mc_rbp, 16, '0') <<
" rsp=" << hex(mctxt->mc_rsp, 16, '0') <<
" r8=" << hex(mctxt->mc_r8, 16, '0'));
LOG1(" r9=" << hex(mctxt->mc_r9, 16, '0') <<
" r10=" << hex(mctxt->mc_r10, 16, '0') <<
" r11=" << hex(mctxt->mc_r11, 16, '0'));
LOG1(" r12=" << hex(mctxt->mc_r12, 16, '0') <<
" r13=" << hex(mctxt->mc_r13, 16, '0') <<
" r14=" << hex(mctxt->mc_r14, 16, '0'));
LOG1(" r15=" << hex(mctxt->mc_r15, 16, '0'));
#else
#warning "unknown machine type"
#endif
}
#endif
static void crash_shutdown(int sig, siginfo_t *info, void *uctxt) {
if (shutdown_loop++) _exit(-1);
MTONLY(
static std::recursive_mutex lock;
static int threads_dumped = 0;
static bool killed_all_threads = false;
lock.lock();
if (!killed_all_threads) {
killed_all_threads = true;
for (int i = 0; i < int(thread_ids.size()); i++)
if (i != my_id-1) {
pthread_kill(thread_ids[i], SIGABRT); } } )
LOG1(MTONLY("Thread #" << my_id << " " <<) "exiting with SIG" <<
signames[sig] << ", trace:");
if (sig == SIGILL || sig == SIGFPE || sig == SIGSEGV ||
sig == SIGBUS || sig == SIGTRAP)
LOG1(" address = " << hex(info->si_addr));
#if HAVE_UCONTEXT_H
dumpregs(&(static_cast<ucontext_t *>(uctxt)->uc_mcontext));
#else
(void) uctxt; // Suppress unused parameter warning.
#endif
#if HAVE_EXECINFO_H
if (LOGGING(1)) {
static void *buffer[64];
int size = backtrace(buffer, 64);
char **strings = backtrace_symbols(buffer, size);
for (int i = 1; i < size; i++) {
if (strings)
LOG1(" " << strings[i]);
if (const char *line = addr2line(buffer[i], strings ? strings[i] : 0))
LOG1(" " << line); }
if (size < 1)
LOG1("backtrace failed");
free(strings); }
#endif
MTONLY(
if (++threads_dumped < int(thread_ids.size())) {
lock.unlock();
pthread_exit(0);
} else {
lock.unlock(); } )
if (sig != SIGABRT)
BUG("Exiting with SIG%s", signames[sig]);
_exit(sig + 0x80);
}
void setup_signals() {
struct sigaction sigact;
sigact.sa_sigaction = sigint_shutdown;
sigact.sa_flags = SA_SIGINFO;
sigemptyset(&sigact.sa_mask);
sigaction(SIGHUP, &sigact, 0);
sigaction(SIGINT, &sigact, 0);
sigaction(SIGQUIT, &sigact, 0);
sigaction(SIGTERM, &sigact, 0);
sigact.sa_sigaction = crash_shutdown;
sigaction(SIGILL, &sigact, 0);
sigaction(SIGABRT, &sigact, 0);
sigaction(SIGFPE, &sigact, 0);
sigaction(SIGSEGV, &sigact, 0);
sigaction(SIGBUS, &sigact, 0);
sigaction(SIGTRAP, &sigact, 0);
signal(SIGPIPE, SIG_IGN);
}
<|endoftext|> |
<commit_before>#include <iostream>
class matrix_t final
{
private:
unsigned int rows_;
unsigned int columns_;
int** elements_;
public:
matrix_t() noexcept;
auto rows() -> unsigned int;
auto columns() -> unsigned int;
};
<commit_msg>Update matrix.hpp<commit_after>#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
class Matrix
{
private:
int **matr;
int st, cl;
public:
Matrix();
Matrix(int, int);
Matrix(Matrix &matrс);
~Matrix();
Matrix operator+ (const Matrix &mat_2) const;
Matrix operator* (const Matrix &mat_2) const;
Matrix& operator =(Matrix &);
bool operator==(const Matrix&)const;
friend istream& operator >> (istream& ist, const Matrix& cmatr);
friend ostream& operator << (ostream&, const Matrix&);
};
<|endoftext|> |
<commit_before>#include "master.hpp"
namespace factor
{
gc_event::gc_event(gc_op op_, factor_vm *parent) :
op(op_),
cards_scanned(0),
decks_scanned(0),
code_blocks_scanned(0),
start_time(nano_count()),
card_scan_time(0),
code_scan_time(0),
data_sweep_time(0),
code_sweep_time(0),
compaction_time(0)
{
data_heap_before = parent->data_room();
code_heap_before = parent->code_room();
start_time = nano_count();
}
void gc_event::started_card_scan()
{
temp_time = nano_count();
}
void gc_event::ended_card_scan(cell cards_scanned_, cell decks_scanned_)
{
cards_scanned += cards_scanned_;
decks_scanned += decks_scanned_;
card_scan_time = (cell)(nano_count() - temp_time);
}
void gc_event::started_code_scan()
{
temp_time = nano_count();
}
void gc_event::ended_code_scan(cell code_blocks_scanned_)
{
code_blocks_scanned += code_blocks_scanned_;
code_scan_time = (cell)(nano_count() - temp_time);
}
void gc_event::started_data_sweep()
{
temp_time = nano_count();
}
void gc_event::ended_data_sweep()
{
data_sweep_time = (cell)(nano_count() - temp_time);
}
void gc_event::started_code_sweep()
{
temp_time = nano_count();
}
void gc_event::ended_code_sweep()
{
code_sweep_time = (cell)(nano_count() - temp_time);
}
void gc_event::started_compaction()
{
temp_time = nano_count();
}
void gc_event::ended_compaction()
{
compaction_time = (cell)(nano_count() - temp_time);
}
void gc_event::ended_gc(factor_vm *parent)
{
data_heap_after = parent->data_room();
code_heap_after = parent->code_room();
total_time = (cell)(nano_count() - start_time);
}
gc_state::gc_state(gc_op op_, factor_vm *parent) : op(op_)
{
if(parent->gc_events)
{
event = new gc_event(op,parent);
start_time = nano_count();
}
else
event = NULL;
}
gc_state::~gc_state()
{
if(event)
{
delete event;
event = NULL;
}
}
void factor_vm::end_gc()
{
if(gc_events)
{
current_gc->event->ended_gc(this);
gc_events->push_back(*current_gc->event);
}
}
void factor_vm::start_gc_again()
{
end_gc();
switch(current_gc->op)
{
case collect_nursery_op:
current_gc->op = collect_aging_op;
break;
case collect_aging_op:
current_gc->op = collect_to_tenured_op;
break;
case collect_to_tenured_op:
current_gc->op = collect_full_op;
break;
case collect_full_op:
case collect_compact_op:
current_gc->op = collect_growing_heap_op;
break;
default:
critical_error("Bad GC op",current_gc->op);
break;
}
if(gc_events)
current_gc->event = new gc_event(current_gc->op,this);
}
void factor_vm::set_current_gc_op(gc_op op)
{
current_gc->op = op;
if(gc_events) current_gc->event->op = op;
}
void factor_vm::gc(gc_op op, cell requested_bytes, bool trace_contexts_p)
{
/* Save and reset FPU state before, restore it after, so that
nano_count() doesn't bomb on Windows if inexact traps are enabled
(fun huh?) */
cell fpu_state = get_fpu_state();
assert(!gc_off);
assert(!current_gc);
current_gc = new gc_state(op,this);
/* Keep trying to GC higher and higher generations until we don't run out
of space */
for(;;)
{
try
{
if(gc_events) current_gc->event->op = current_gc->op;
switch(current_gc->op)
{
case collect_nursery_op:
collect_nursery();
break;
case collect_aging_op:
collect_aging();
if(data->high_fragmentation_p())
{
set_current_gc_op(collect_full_op);
collect_full(trace_contexts_p);
}
break;
case collect_to_tenured_op:
collect_to_tenured();
if(data->high_fragmentation_p())
{
set_current_gc_op(collect_full_op);
collect_full(trace_contexts_p);
}
break;
case collect_full_op:
collect_full(trace_contexts_p);
break;
case collect_compact_op:
collect_compact(trace_contexts_p);
break;
case collect_growing_heap_op:
collect_growing_heap(requested_bytes,trace_contexts_p);
break;
default:
critical_error("Bad GC op",current_gc->op);
break;
}
break;
}
catch(const must_start_gc_again &)
{
/* We come back here if a generation is full */
start_gc_again();
continue;
}
}
end_gc();
delete current_gc;
current_gc = NULL;
set_fpu_state(fpu_state);
}
/* primitive_minor_gc() is invoked by inline GC checks, and it needs to fill in
uninitialized stack locations before actually calling the GC. See the comment
in compiler.cfg.stacks.uninitialized for details. */
struct call_frame_scrubber {
factor_vm *parent;
context *ctx;
explicit call_frame_scrubber(factor_vm *parent_, context *ctx_) :
parent(parent_), ctx(ctx_) {}
void operator()(stack_frame *frame)
{
cell return_address = parent->frame_offset(frame);
if(return_address == (cell)-1)
return;
code_block *compiled = parent->frame_code(frame);
gc_info *info = compiled->block_gc_info();
assert(return_address < compiled->size());
int index = info->return_address_index(return_address);
if(index != -1)
ctx->scrub_stacks(info,index);
}
};
void factor_vm::scrub_context(context *ctx)
{
call_frame_scrubber scrubber(this,ctx);
iterate_callstack(ctx,scrubber);
}
void factor_vm::scrub_contexts()
{
std::set<context *>::const_iterator begin = active_contexts.begin();
std::set<context *>::const_iterator end = active_contexts.end();
while(begin != end)
{
scrub_context(*begin);
begin++;
}
}
void factor_vm::primitive_minor_gc()
{
scrub_contexts();
gc(collect_nursery_op,
0, /* requested size */
true /* trace contexts? */);
}
void factor_vm::primitive_full_gc()
{
gc(collect_full_op,
0, /* requested size */
true /* trace contexts? */);
}
void factor_vm::primitive_compact_gc()
{
gc(collect_compact_op,
0, /* requested size */
true /* trace contexts? */);
}
/*
* It is up to the caller to fill in the object's fields in a meaningful
* fashion!
*/
object *factor_vm::allot_large_object(cell type, cell size)
{
/* If tenured space does not have enough room, collect and compact */
if(!data->tenured->can_allot_p(size))
{
primitive_compact_gc();
/* If it still won't fit, grow the heap */
if(!data->tenured->can_allot_p(size))
{
gc(collect_growing_heap_op,
size, /* requested size */
true /* trace contexts? */);
}
}
object *obj = data->tenured->allot(size);
/* Allows initialization code to store old->new pointers
without hitting the write barrier in the common case of
a nursery allocation */
write_barrier(obj,size);
obj->initialize(type);
return obj;
}
void factor_vm::primitive_enable_gc_events()
{
gc_events = new std::vector<gc_event>();
}
void factor_vm::primitive_disable_gc_events()
{
if(gc_events)
{
growable_array result(this);
std::vector<gc_event> *gc_events = this->gc_events;
this->gc_events = NULL;
std::vector<gc_event>::const_iterator iter = gc_events->begin();
std::vector<gc_event>::const_iterator end = gc_events->end();
for(; iter != end; iter++)
{
gc_event event = *iter;
byte_array *obj = byte_array_from_value(&event);
result.add(tag<byte_array>(obj));
}
result.trim();
ctx->push(result.elements.value());
delete this->gc_events;
}
else
ctx->push(false_object);
}
}
<commit_msg>vm: don't need to save/restore FPU state when doing GC anymore, since we don't call nano_count() unless GC events are being recorded. If you want to record GC events with FP traps on, you're out of luck<commit_after>#include "master.hpp"
namespace factor
{
gc_event::gc_event(gc_op op_, factor_vm *parent) :
op(op_),
cards_scanned(0),
decks_scanned(0),
code_blocks_scanned(0),
start_time(nano_count()),
card_scan_time(0),
code_scan_time(0),
data_sweep_time(0),
code_sweep_time(0),
compaction_time(0)
{
data_heap_before = parent->data_room();
code_heap_before = parent->code_room();
start_time = nano_count();
}
void gc_event::started_card_scan()
{
temp_time = nano_count();
}
void gc_event::ended_card_scan(cell cards_scanned_, cell decks_scanned_)
{
cards_scanned += cards_scanned_;
decks_scanned += decks_scanned_;
card_scan_time = (cell)(nano_count() - temp_time);
}
void gc_event::started_code_scan()
{
temp_time = nano_count();
}
void gc_event::ended_code_scan(cell code_blocks_scanned_)
{
code_blocks_scanned += code_blocks_scanned_;
code_scan_time = (cell)(nano_count() - temp_time);
}
void gc_event::started_data_sweep()
{
temp_time = nano_count();
}
void gc_event::ended_data_sweep()
{
data_sweep_time = (cell)(nano_count() - temp_time);
}
void gc_event::started_code_sweep()
{
temp_time = nano_count();
}
void gc_event::ended_code_sweep()
{
code_sweep_time = (cell)(nano_count() - temp_time);
}
void gc_event::started_compaction()
{
temp_time = nano_count();
}
void gc_event::ended_compaction()
{
compaction_time = (cell)(nano_count() - temp_time);
}
void gc_event::ended_gc(factor_vm *parent)
{
data_heap_after = parent->data_room();
code_heap_after = parent->code_room();
total_time = (cell)(nano_count() - start_time);
}
gc_state::gc_state(gc_op op_, factor_vm *parent) : op(op_)
{
if(parent->gc_events)
{
event = new gc_event(op,parent);
start_time = nano_count();
}
else
event = NULL;
}
gc_state::~gc_state()
{
if(event)
{
delete event;
event = NULL;
}
}
void factor_vm::end_gc()
{
if(gc_events)
{
current_gc->event->ended_gc(this);
gc_events->push_back(*current_gc->event);
}
}
void factor_vm::start_gc_again()
{
end_gc();
switch(current_gc->op)
{
case collect_nursery_op:
current_gc->op = collect_aging_op;
break;
case collect_aging_op:
current_gc->op = collect_to_tenured_op;
break;
case collect_to_tenured_op:
current_gc->op = collect_full_op;
break;
case collect_full_op:
case collect_compact_op:
current_gc->op = collect_growing_heap_op;
break;
default:
critical_error("Bad GC op",current_gc->op);
break;
}
if(gc_events)
current_gc->event = new gc_event(current_gc->op,this);
}
void factor_vm::set_current_gc_op(gc_op op)
{
current_gc->op = op;
if(gc_events) current_gc->event->op = op;
}
void factor_vm::gc(gc_op op, cell requested_bytes, bool trace_contexts_p)
{
assert(!gc_off);
assert(!current_gc);
current_gc = new gc_state(op,this);
/* Keep trying to GC higher and higher generations until we don't run out
of space */
for(;;)
{
try
{
if(gc_events) current_gc->event->op = current_gc->op;
switch(current_gc->op)
{
case collect_nursery_op:
collect_nursery();
break;
case collect_aging_op:
collect_aging();
if(data->high_fragmentation_p())
{
set_current_gc_op(collect_full_op);
collect_full(trace_contexts_p);
}
break;
case collect_to_tenured_op:
collect_to_tenured();
if(data->high_fragmentation_p())
{
set_current_gc_op(collect_full_op);
collect_full(trace_contexts_p);
}
break;
case collect_full_op:
collect_full(trace_contexts_p);
break;
case collect_compact_op:
collect_compact(trace_contexts_p);
break;
case collect_growing_heap_op:
collect_growing_heap(requested_bytes,trace_contexts_p);
break;
default:
critical_error("Bad GC op",current_gc->op);
break;
}
break;
}
catch(const must_start_gc_again &)
{
/* We come back here if a generation is full */
start_gc_again();
continue;
}
}
end_gc();
delete current_gc;
current_gc = NULL;
}
/* primitive_minor_gc() is invoked by inline GC checks, and it needs to fill in
uninitialized stack locations before actually calling the GC. See the comment
in compiler.cfg.stacks.uninitialized for details. */
struct call_frame_scrubber {
factor_vm *parent;
context *ctx;
explicit call_frame_scrubber(factor_vm *parent_, context *ctx_) :
parent(parent_), ctx(ctx_) {}
void operator()(stack_frame *frame)
{
cell return_address = parent->frame_offset(frame);
if(return_address == (cell)-1)
return;
code_block *compiled = parent->frame_code(frame);
gc_info *info = compiled->block_gc_info();
assert(return_address < compiled->size());
int index = info->return_address_index(return_address);
if(index != -1)
ctx->scrub_stacks(info,index);
}
};
void factor_vm::scrub_context(context *ctx)
{
call_frame_scrubber scrubber(this,ctx);
iterate_callstack(ctx,scrubber);
}
void factor_vm::scrub_contexts()
{
std::set<context *>::const_iterator begin = active_contexts.begin();
std::set<context *>::const_iterator end = active_contexts.end();
while(begin != end)
{
scrub_context(*begin);
begin++;
}
}
void factor_vm::primitive_minor_gc()
{
scrub_contexts();
gc(collect_nursery_op,
0, /* requested size */
true /* trace contexts? */);
}
void factor_vm::primitive_full_gc()
{
gc(collect_full_op,
0, /* requested size */
true /* trace contexts? */);
}
void factor_vm::primitive_compact_gc()
{
gc(collect_compact_op,
0, /* requested size */
true /* trace contexts? */);
}
/*
* It is up to the caller to fill in the object's fields in a meaningful
* fashion!
*/
object *factor_vm::allot_large_object(cell type, cell size)
{
/* If tenured space does not have enough room, collect and compact */
if(!data->tenured->can_allot_p(size))
{
primitive_compact_gc();
/* If it still won't fit, grow the heap */
if(!data->tenured->can_allot_p(size))
{
gc(collect_growing_heap_op,
size, /* requested size */
true /* trace contexts? */);
}
}
object *obj = data->tenured->allot(size);
/* Allows initialization code to store old->new pointers
without hitting the write barrier in the common case of
a nursery allocation */
write_barrier(obj,size);
obj->initialize(type);
return obj;
}
void factor_vm::primitive_enable_gc_events()
{
gc_events = new std::vector<gc_event>();
}
void factor_vm::primitive_disable_gc_events()
{
if(gc_events)
{
growable_array result(this);
std::vector<gc_event> *gc_events = this->gc_events;
this->gc_events = NULL;
std::vector<gc_event>::const_iterator iter = gc_events->begin();
std::vector<gc_event>::const_iterator end = gc_events->end();
for(; iter != end; iter++)
{
gc_event event = *iter;
byte_array *obj = byte_array_from_value(&event);
result.add(tag<byte_array>(obj));
}
result.trim();
ctx->push(result.elements.value());
delete this->gc_events;
}
else
ctx->push(false_object);
}
}
<|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/>.
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <util/RefHashTableOf.hpp>
#include <util/XML88591Transcoder.hpp>
#include <util/XMLASCIITranscoder.hpp>
#include <util/XMLChTranscoder.hpp>
#include <util/XMLEBCDICTranscoder.hpp>
#include <util/XMLIBM1140Transcoder.hpp>
#include <util/XMLUCS4Transcoder.hpp>
#include <util/XMLUTF8Transcoder.hpp>
#include <util/XMLUTF16Transcoder.hpp>
#include <util/XMLWin1252Transcoder.hpp>
#include <util/XMLUni.hpp>
#include <util/TransENameMap.hpp>
// ---------------------------------------------------------------------------
// Local, static data
//
// gMappings
// This is a hash table of ENameMap objects. It is created and filled
// in when the platform init calls our initTransService() method.
//
// gDisallow1
// gDisallowX
// These area small set of encoding names that, for temporary reasons,
// we disallow at this time.
//
// gDisallowList
// gDisallowListSize
// An array of the disallow strings, for easier searching below.
//
// gDisallowPre
// All of the disallowed encodings start with 'IBM', so we have a prefix
// we can check for and quickly decide if we need to search the list.
// ---------------------------------------------------------------------------
static RefHashTableOf<ENameMap>* gMappings = 0;
static XMLCh gDisallow1[] =
{
chLatin_I, chLatin_B, chLatin_M, chDash, chDigit_0, chDigit_3
, chDigit_7, chNull
};
static XMLCh gDisallow2[] =
{
chLatin_I, chLatin_B, chLatin_M, chDash, chDigit_3, chDigit_7, chNull
};
static XMLCh gDisallow3[] =
{
chLatin_I, chLatin_B, chLatin_M, chDash, chDigit_0, chDigit_3
, chDigit_7, chDash, chLatin_S, chDigit_3, chDigit_9, chDigit_0, chNull
};
static XMLCh gDisallow4[] =
{
chLatin_I, chLatin_B, chLatin_M, chDash, chDigit_3, chDigit_7, chDash
, chLatin_S, chDigit_3, chDigit_9, chDigit_0, chNull
};
static XMLCh gDisallow5[] =
{
chLatin_I, chLatin_B, chLatin_M, chDash, chDigit_1, chDigit_1
, chDigit_1, chDigit_4, chDigit_0, chNull
};
static XMLCh gDisallow6[] =
{
chLatin_I, chLatin_B, chLatin_M, chDash, chDigit_1, chDigit_1
, chDigit_1, chDigit_4, chDigit_0, chDash, chLatin_S, chDigit_3
, chDigit_9, chDigit_0, chNull
};
static const unsigned int gDisallowListSize = 6;
static XMLCh* gDisallowList[gDisallowListSize] =
{
gDisallow1, gDisallow2, gDisallow3, gDisallow4, gDisallow5, gDisallow6
};
static XMLCh gDisallowPre[] =
{
chLatin_I, chLatin_B, chLatin_M, chNull
};
// ---------------------------------------------------------------------------
// XLMTransService: Constructors and destructor
// ---------------------------------------------------------------------------
XMLTransService::XMLTransService()
{
}
XMLTransService::~XMLTransService()
{
}
// ---------------------------------------------------------------------------
// XLMTranscoder: Non-virtual API
// ---------------------------------------------------------------------------
XMLTranscoder*
XMLTransService::makeNewTranscoderFor( const XMLCh* const encodingName
, XMLTransService::Codes& resValue
, const unsigned int blockSize)
{
//
// First try to find it in our list of mappings to intrinsically
// supported encodings. We have to upper case the passed encoding
// name because we use a hash table and we stored all our mappings
// in all uppercase.
//
const unsigned int bufSize = 2048;
XMLCh upBuf[bufSize + 1];
if (!XMLString::copyNString(upBuf, encodingName, bufSize))
return 0;
XMLString::upperCase(upBuf);
ENameMap* ourMapping = gMappings->get(upBuf);
// If we found it, then call the factory method for it
if (ourMapping)
return ourMapping->makeNew(blockSize);
//
// For now, we have a little list of encodings that we disallow
// explicitly. So lets check for them up front. They all start with
// IBM, so we can do a quick check to see if we should even do
// anything at all.
//
if (XMLString::startsWith(upBuf, gDisallowPre))
{
for (unsigned int index = 0; index < gDisallowListSize; index++)
{
// If its one of our guys, then pretend we don't understand it
if (!XMLString::compareString(upBuf, gDisallowList[index]))
return 0;
}
}
//
// It wasn't an intrinsic and it wasn't disallowed, so pass it on
// to the trans service to see if he can make anything of it.
//
return makeNewXMLTranscoder(encodingName, resValue, blockSize);
}
// ---------------------------------------------------------------------------
// XLMTranscoder: Public Destructor
// ---------------------------------------------------------------------------
XMLTranscoder::~XMLTranscoder()
{
delete [] fEncodingName;
}
// ---------------------------------------------------------------------------
// XLMTranscoder: Hidden Constructors
// ---------------------------------------------------------------------------
XMLTranscoder::XMLTranscoder(const XMLCh* const encodingName
, const unsigned int blockSize) :
fEncodingName(0)
, fBlockSize(blockSize)
{
fEncodingName = XMLString::replicate(encodingName);
}
// ---------------------------------------------------------------------------
// XLMTranscoder: Protected helpers
// ---------------------------------------------------------------------------
void XMLTranscoder::checkBlockSize(const unsigned int toCheck)
{
if (toCheck > fBlockSize)
{
// <TBD> Throw an exception here
}
}
// ---------------------------------------------------------------------------
// XLMLCPTranscoder: Public Destructor
// ---------------------------------------------------------------------------
XMLLCPTranscoder::XMLLCPTranscoder()
{
}
// ---------------------------------------------------------------------------
// XLMTranscoder: Hidden Constructors
// ---------------------------------------------------------------------------
XMLLCPTranscoder::~XMLLCPTranscoder()
{
}
// ---------------------------------------------------------------------------
// XLMTranscoder: Hidden Init Method
//
// This is called by platform utils during startup.
// ---------------------------------------------------------------------------
void XMLTransService::initTransService()
{
//
// Create our hash table that we will fill with mappings. The default
// is to adopt the elements, which is fine with us.
//
gMappings = new RefHashTableOf<ENameMap>(103);
//
// Add in the magical mapping for the native XMLCh transcoder. This
// is used for internal entities.
//
gMappings->put(new ENameMapFor<XMLChTranscoder>(XMLUni::fgXMLChEncodingString));
//
// Add in our mappings for ASCII.
//
gMappings->put(new ENameMapFor<XMLASCIITranscoder>(XMLUni::fgUSASCIIEncodingString));
gMappings->put(new ENameMapFor<XMLASCIITranscoder>(XMLUni::fgUSASCIIEncodingString2));
gMappings->put(new ENameMapFor<XMLASCIITranscoder>(XMLUni::fgUSASCIIEncodingString3));
gMappings->put(new ENameMapFor<XMLASCIITranscoder>(XMLUni::fgUSASCIIEncodingString4));
//
// Add in our mappings for UTF-8
//
gMappings->put(new ENameMapFor<XMLUTF8Transcoder>(XMLUni::fgUTF8EncodingString));
gMappings->put(new ENameMapFor<XMLUTF8Transcoder>(XMLUni::fgUTF8EncodingString2));
//
// Add in our mappings for Latin1
//
gMappings->put(new ENameMapFor<XML88591Transcoder>(XMLUni::fgISO88591EncodingString));
gMappings->put(new ENameMapFor<XML88591Transcoder>(XMLUni::fgISO88591EncodingString2));
gMappings->put(new ENameMapFor<XML88591Transcoder>(XMLUni::fgISO88591EncodingString3));
gMappings->put(new ENameMapFor<XML88591Transcoder>(XMLUni::fgISO88591EncodingString4));
gMappings->put(new ENameMapFor<XML88591Transcoder>(XMLUni::fgISO88591EncodingString5));
gMappings->put(new ENameMapFor<XML88591Transcoder>(XMLUni::fgISO88591EncodingString6));
gMappings->put(new ENameMapFor<XML88591Transcoder>(XMLUni::fgISO88591EncodingString7));
gMappings->put(new ENameMapFor<XML88591Transcoder>(XMLUni::fgISO88591EncodingString8));
//
// Add in our mappings for UTF-16 and UCS-4, little endian
//
bool swapped = false;
#if defined(ENDIANMODE_BIG)
swapped = true;
#endif
gMappings->put
(
new EEndianNameMapFor<XMLUTF16Transcoder>
(
XMLUni::fgUTF16LEncodingString
, swapped
)
);
gMappings->put
(
new EEndianNameMapFor<XMLUTF16Transcoder>
(
XMLUni::fgUTF16LEncodingString2
, swapped
)
);
gMappings->put
(
new EEndianNameMapFor<XMLUCS4Transcoder>
(
XMLUni::fgUCS4LEncodingString
, swapped
)
);
gMappings->put
(
new EEndianNameMapFor<XMLUCS4Transcoder>
(
XMLUni::fgUCS4LEncodingString2
, swapped
)
);
//
// Add in our mappings for UTF-16 and UCS-4, big endian
//
swapped = false;
#if defined(ENDIANMODE_LITTLE)
swapped = true;
#endif
gMappings->put
(
new EEndianNameMapFor<XMLUTF16Transcoder>
(
XMLUni::fgUTF16BEncodingString
, swapped
)
);
gMappings->put
(
new EEndianNameMapFor<XMLUTF16Transcoder>
(
XMLUni::fgUTF16BEncodingString2
, swapped
)
);
gMappings->put
(
new EEndianNameMapFor<XMLUCS4Transcoder>
(
XMLUni::fgUCS4BEncodingString
, swapped
)
);
gMappings->put
(
new EEndianNameMapFor<XMLUCS4Transcoder>
(
XMLUni::fgUCS4BEncodingString2
, swapped
)
);
//
// Add in our mappings for IBM037, and the one alias we support for
// it, which is EBCDIC-CP-US.
//
gMappings->put(new ENameMapFor<XMLEBCDICTranscoder>(XMLUni::fgIBM037EncodingString));
gMappings->put(new ENameMapFor<XMLEBCDICTranscoder>(XMLUni::fgIBM037EncodingString2));
//
// Add in our mappings for IBM037 with Euro update, i.e. IBM1140. It
// has no aliases
//
gMappings->put(new ENameMapFor<XMLIBM1140Transcoder>(XMLUni::fgIBM1140EncodingString));
//
// Add in our mappings for Windows-1252. We don't have any aliases for
// this one, so there is just one mapping.
//
gMappings->put(new ENameMapFor<XMLWin1252Transcoder>(XMLUni::fgWin1252EncodingString));
}
<commit_msg>Fix wrong encoding name. ibm-11140 becomes ibm-1140<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/>.
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <util/RefHashTableOf.hpp>
#include <util/XML88591Transcoder.hpp>
#include <util/XMLASCIITranscoder.hpp>
#include <util/XMLChTranscoder.hpp>
#include <util/XMLEBCDICTranscoder.hpp>
#include <util/XMLIBM1140Transcoder.hpp>
#include <util/XMLUCS4Transcoder.hpp>
#include <util/XMLUTF8Transcoder.hpp>
#include <util/XMLUTF16Transcoder.hpp>
#include <util/XMLWin1252Transcoder.hpp>
#include <util/XMLUni.hpp>
#include <util/TransENameMap.hpp>
// ---------------------------------------------------------------------------
// Local, static data
//
// gMappings
// This is a hash table of ENameMap objects. It is created and filled
// in when the platform init calls our initTransService() method.
//
// gDisallow1
// gDisallowX
// These area small set of encoding names that, for temporary reasons,
// we disallow at this time.
//
// gDisallowList
// gDisallowListSize
// An array of the disallow strings, for easier searching below.
//
// gDisallowPre
// All of the disallowed encodings start with 'IBM', so we have a prefix
// we can check for and quickly decide if we need to search the list.
// ---------------------------------------------------------------------------
static RefHashTableOf<ENameMap>* gMappings = 0;
static XMLCh gDisallow1[] =
{
chLatin_I, chLatin_B, chLatin_M, chDash, chDigit_0, chDigit_3
, chDigit_7, chNull
};
static XMLCh gDisallow2[] =
{
chLatin_I, chLatin_B, chLatin_M, chDash, chDigit_3, chDigit_7, chNull
};
static XMLCh gDisallow3[] =
{
chLatin_I, chLatin_B, chLatin_M, chDash, chDigit_0, chDigit_3
, chDigit_7, chDash, chLatin_S, chDigit_3, chDigit_9, chDigit_0, chNull
};
static XMLCh gDisallow4[] =
{
chLatin_I, chLatin_B, chLatin_M, chDash, chDigit_3, chDigit_7, chDash
, chLatin_S, chDigit_3, chDigit_9, chDigit_0, chNull
};
static XMLCh gDisallow5[] =
{
chLatin_I, chLatin_B, chLatin_M, chDash, chDigit_1, chDigit_1
, chDigit_4, chDigit_0, chNull
};
static XMLCh gDisallow6[] =
{
chLatin_I, chLatin_B, chLatin_M, chDash, chDigit_1, chDigit_1
, chDigit_4, chDigit_0, chDash, chLatin_S, chDigit_3
, chDigit_9, chDigit_0, chNull
};
static const unsigned int gDisallowListSize = 6;
static XMLCh* gDisallowList[gDisallowListSize] =
{
gDisallow1, gDisallow2, gDisallow3, gDisallow4, gDisallow5, gDisallow6
};
static XMLCh gDisallowPre[] =
{
chLatin_I, chLatin_B, chLatin_M, chNull
};
// ---------------------------------------------------------------------------
// XLMTransService: Constructors and destructor
// ---------------------------------------------------------------------------
XMLTransService::XMLTransService()
{
}
XMLTransService::~XMLTransService()
{
}
// ---------------------------------------------------------------------------
// XLMTranscoder: Non-virtual API
// ---------------------------------------------------------------------------
XMLTranscoder*
XMLTransService::makeNewTranscoderFor( const XMLCh* const encodingName
, XMLTransService::Codes& resValue
, const unsigned int blockSize)
{
//
// First try to find it in our list of mappings to intrinsically
// supported encodings. We have to upper case the passed encoding
// name because we use a hash table and we stored all our mappings
// in all uppercase.
//
const unsigned int bufSize = 2048;
XMLCh upBuf[bufSize + 1];
if (!XMLString::copyNString(upBuf, encodingName, bufSize))
return 0;
XMLString::upperCase(upBuf);
ENameMap* ourMapping = gMappings->get(upBuf);
// If we found it, then call the factory method for it
if (ourMapping)
return ourMapping->makeNew(blockSize);
//
// For now, we have a little list of encodings that we disallow
// explicitly. So lets check for them up front. They all start with
// IBM, so we can do a quick check to see if we should even do
// anything at all.
//
if (XMLString::startsWith(upBuf, gDisallowPre))
{
for (unsigned int index = 0; index < gDisallowListSize; index++)
{
// If its one of our guys, then pretend we don't understand it
if (!XMLString::compareString(upBuf, gDisallowList[index]))
return 0;
}
}
//
// It wasn't an intrinsic and it wasn't disallowed, so pass it on
// to the trans service to see if he can make anything of it.
//
return makeNewXMLTranscoder(encodingName, resValue, blockSize);
}
// ---------------------------------------------------------------------------
// XLMTranscoder: Public Destructor
// ---------------------------------------------------------------------------
XMLTranscoder::~XMLTranscoder()
{
delete [] fEncodingName;
}
// ---------------------------------------------------------------------------
// XLMTranscoder: Hidden Constructors
// ---------------------------------------------------------------------------
XMLTranscoder::XMLTranscoder(const XMLCh* const encodingName
, const unsigned int blockSize) :
fEncodingName(0)
, fBlockSize(blockSize)
{
fEncodingName = XMLString::replicate(encodingName);
}
// ---------------------------------------------------------------------------
// XLMTranscoder: Protected helpers
// ---------------------------------------------------------------------------
void XMLTranscoder::checkBlockSize(const unsigned int toCheck)
{
if (toCheck > fBlockSize)
{
// <TBD> Throw an exception here
}
}
// ---------------------------------------------------------------------------
// XLMLCPTranscoder: Public Destructor
// ---------------------------------------------------------------------------
XMLLCPTranscoder::XMLLCPTranscoder()
{
}
// ---------------------------------------------------------------------------
// XLMTranscoder: Hidden Constructors
// ---------------------------------------------------------------------------
XMLLCPTranscoder::~XMLLCPTranscoder()
{
}
// ---------------------------------------------------------------------------
// XLMTranscoder: Hidden Init Method
//
// This is called by platform utils during startup.
// ---------------------------------------------------------------------------
void XMLTransService::initTransService()
{
//
// Create our hash table that we will fill with mappings. The default
// is to adopt the elements, which is fine with us.
//
gMappings = new RefHashTableOf<ENameMap>(103);
//
// Add in the magical mapping for the native XMLCh transcoder. This
// is used for internal entities.
//
gMappings->put(new ENameMapFor<XMLChTranscoder>(XMLUni::fgXMLChEncodingString));
//
// Add in our mappings for ASCII.
//
gMappings->put(new ENameMapFor<XMLASCIITranscoder>(XMLUni::fgUSASCIIEncodingString));
gMappings->put(new ENameMapFor<XMLASCIITranscoder>(XMLUni::fgUSASCIIEncodingString2));
gMappings->put(new ENameMapFor<XMLASCIITranscoder>(XMLUni::fgUSASCIIEncodingString3));
gMappings->put(new ENameMapFor<XMLASCIITranscoder>(XMLUni::fgUSASCIIEncodingString4));
//
// Add in our mappings for UTF-8
//
gMappings->put(new ENameMapFor<XMLUTF8Transcoder>(XMLUni::fgUTF8EncodingString));
gMappings->put(new ENameMapFor<XMLUTF8Transcoder>(XMLUni::fgUTF8EncodingString2));
//
// Add in our mappings for Latin1
//
gMappings->put(new ENameMapFor<XML88591Transcoder>(XMLUni::fgISO88591EncodingString));
gMappings->put(new ENameMapFor<XML88591Transcoder>(XMLUni::fgISO88591EncodingString2));
gMappings->put(new ENameMapFor<XML88591Transcoder>(XMLUni::fgISO88591EncodingString3));
gMappings->put(new ENameMapFor<XML88591Transcoder>(XMLUni::fgISO88591EncodingString4));
gMappings->put(new ENameMapFor<XML88591Transcoder>(XMLUni::fgISO88591EncodingString5));
gMappings->put(new ENameMapFor<XML88591Transcoder>(XMLUni::fgISO88591EncodingString6));
gMappings->put(new ENameMapFor<XML88591Transcoder>(XMLUni::fgISO88591EncodingString7));
gMappings->put(new ENameMapFor<XML88591Transcoder>(XMLUni::fgISO88591EncodingString8));
//
// Add in our mappings for UTF-16 and UCS-4, little endian
//
bool swapped = false;
#if defined(ENDIANMODE_BIG)
swapped = true;
#endif
gMappings->put
(
new EEndianNameMapFor<XMLUTF16Transcoder>
(
XMLUni::fgUTF16LEncodingString
, swapped
)
);
gMappings->put
(
new EEndianNameMapFor<XMLUTF16Transcoder>
(
XMLUni::fgUTF16LEncodingString2
, swapped
)
);
gMappings->put
(
new EEndianNameMapFor<XMLUCS4Transcoder>
(
XMLUni::fgUCS4LEncodingString
, swapped
)
);
gMappings->put
(
new EEndianNameMapFor<XMLUCS4Transcoder>
(
XMLUni::fgUCS4LEncodingString2
, swapped
)
);
//
// Add in our mappings for UTF-16 and UCS-4, big endian
//
swapped = false;
#if defined(ENDIANMODE_LITTLE)
swapped = true;
#endif
gMappings->put
(
new EEndianNameMapFor<XMLUTF16Transcoder>
(
XMLUni::fgUTF16BEncodingString
, swapped
)
);
gMappings->put
(
new EEndianNameMapFor<XMLUTF16Transcoder>
(
XMLUni::fgUTF16BEncodingString2
, swapped
)
);
gMappings->put
(
new EEndianNameMapFor<XMLUCS4Transcoder>
(
XMLUni::fgUCS4BEncodingString
, swapped
)
);
gMappings->put
(
new EEndianNameMapFor<XMLUCS4Transcoder>
(
XMLUni::fgUCS4BEncodingString2
, swapped
)
);
//
// Add in our mappings for IBM037, and the one alias we support for
// it, which is EBCDIC-CP-US.
//
gMappings->put(new ENameMapFor<XMLEBCDICTranscoder>(XMLUni::fgIBM037EncodingString));
gMappings->put(new ENameMapFor<XMLEBCDICTranscoder>(XMLUni::fgIBM037EncodingString2));
//
// Add in our mappings for IBM037 with Euro update, i.e. IBM1140. It
// has no aliases
//
gMappings->put(new ENameMapFor<XMLIBM1140Transcoder>(XMLUni::fgIBM1140EncodingString));
//
// Add in our mappings for Windows-1252. We don't have any aliases for
// this one, so there is just one mapping.
//
gMappings->put(new ENameMapFor<XMLWin1252Transcoder>(XMLUni::fgWin1252EncodingString));
}
<|endoftext|> |
<commit_before>#include <memory>
#include <algorithm>
#include <stdexcept>
#include <system_error>
#include <random>
#include <realm/util/features.h>
#include <realm/util/assert.hpp>
#include <realm/util/basic_system_errors.hpp>
#include <realm/impl/simulated_failure.hpp>
#if REALM_PLATFORM_APPLE
# define USE_PTHREADS_IMPL 1
#else
# define USE_PTHREADS_IMPL 0
#endif
#if USE_PTHREADS_IMPL
# include <pthread.h>
#endif
using namespace realm;
using namespace realm::_impl;
#ifdef REALM_ENABLE_SIMULATED_FAILURE
namespace {
const int num_failure_types = SimulatedFailure::_num_failure_types;
struct PrimeMode {
virtual bool check_trigger() noexcept = 0;
virtual ~PrimeMode() noexcept {}
};
struct PrimeState {
std::unique_ptr<PrimeMode> slots[num_failure_types];
};
struct OneShotPrimeMode: PrimeMode {
bool triggered = false;
bool check_trigger() noexcept override
{
if (triggered)
return false;
triggered = true;
return true;
}
};
struct RandomPrimeMode: PrimeMode {
std::mt19937_64 random;
std::uniform_int_distribution<int> dist;
int n;
RandomPrimeMode(int n, int m, uint_fast64_t seed):
random(seed),
dist(0, m-1),
n(n)
{
REALM_ASSERT(n >= 0 && m > 0);
}
bool check_trigger() noexcept override
{
int i = dist(random);
return i < n;
}
};
# if !USE_PTHREADS_IMPL
thread_local PrimeState t_prime_state;
PrimeState& get() noexcept
{
return t_prime_state;
}
# else // USE_PTHREADS_IMPL
pthread_key_t key;
pthread_once_t key_once = PTHREAD_ONCE_INIT;
void destroy(void* ptr) noexcept
{
PrimeState* prime_state = static_cast<PrimeState*>(ptr);
delete prime_state;
}
void create() noexcept
{
int ret = pthread_key_create(&key, &destroy);
if (REALM_UNLIKELY(ret != 0)) {
std::error_code ec = util::make_basic_system_error_code(errno);
throw std::system_error(ec); // Termination intended
}
}
PrimeState& get() noexcept
{
pthread_once(&key_once, &create);
void* ptr = pthread_getspecific(key);
PrimeState* prime_state = static_cast<PrimeState*>(ptr);
if (!prime_state) {
prime_state = new PrimeState; // Throws with intended termination
int ret = pthread_setspecific(key, prime_state);
if (REALM_UNLIKELY(ret != 0)) {
std::error_code ec = util::make_basic_system_error_code(errno);
throw std::system_error(ec); // Termination intended
}
}
return *prime_state;
}
# endif // USE_PTHREADS_IMPL
} // unnamed namespace
void SimulatedFailure::do_prime_one_shot(FailureType failure_type)
{
PrimeState& state = get();
if (state.slots[failure_type])
throw std::runtime_error("Already primed");
state.slots[failure_type].reset(new OneShotPrimeMode); // Throws
}
void SimulatedFailure::do_prime_random(FailureType failure_type, int n, int m, uint_fast64_t seed)
{
PrimeState& state = get();
if (state.slots[failure_type])
throw std::runtime_error("Already primed");
state.slots[failure_type].reset(new RandomPrimeMode(n, m, seed)); // Throws
}
void SimulatedFailure::do_unprime(FailureType failure_type) noexcept
{
PrimeState& state = get();
state.slots[failure_type].reset();
}
bool SimulatedFailure::do_check_trigger(FailureType failure_type) noexcept
{
PrimeState& state = get();
if (PrimeMode* p = state.slots[failure_type].get())
return p->check_trigger();
return false;
}
#endif // REALM_ENABLE_SIMULATED_FAILURE
namespace {
class ErrorCategory: public std::error_category {
public:
const char* name() const noexcept override;
std::string message(int) const override;
};
ErrorCategory g_error_category;
const char* ErrorCategory::name() const noexcept
{
return "realm.simulated_failure";
}
std::string ErrorCategory::message(int value) const
{
switch (SimulatedFailure::FailureType(value)) {
case SimulatedFailure::generic:
return "Simulated failure (generic)";
case SimulatedFailure::slab_alloc__reset_free_space_tracking:
return "Simulated failure (slab_alloc__reset_free_space_tracking)";
case SimulatedFailure::slab_alloc__remap:
return "Simulated failure (slab_alloc__remap)";
case SimulatedFailure::shared_group__grow_reader_mapping:
return "Simulated failure (shared_group__grow_reader_mapping)";
case SimulatedFailure::sync_client__read_head:
return "Simulated failure (sync_client__read_head)";
case SimulatedFailure::sync_server__read_head:
return "Simulated failure (sync_server__read_head)";
case SimulatedFailure::_num_failure_types:
break;
}
REALM_ASSERT(false);
return std::string();
}
} // unnamed namespace
namespace realm {
namespace _impl {
std::error_code make_error_code(SimulatedFailure::FailureType failure_type) noexcept
{
return std::error_code(failure_type, g_error_category);
}
} // namespace _impl
} // namespace realm
<commit_msg>Fix for: Various improvements to failure simulation (_impl::SimulatedFailure)<commit_after>#include <memory>
#include <algorithm>
#include <stdexcept>
#include <system_error>
#include <random>
#include <realm/util/features.h>
#include <realm/util/assert.hpp>
#include <realm/util/basic_system_errors.hpp>
#include <realm/impl/simulated_failure.hpp>
#if REALM_PLATFORM_APPLE
# define USE_PTHREADS_IMPL 1
#else
# define USE_PTHREADS_IMPL 0
#endif
#if USE_PTHREADS_IMPL
# include <pthread.h>
#endif
using namespace realm;
using namespace realm::_impl;
#ifdef REALM_ENABLE_SIMULATED_FAILURE
namespace {
const int num_failure_types = SimulatedFailure::_num_failure_types;
struct PrimeMode {
virtual bool check_trigger() noexcept = 0;
virtual ~PrimeMode() noexcept {}
};
struct PrimeState {
std::unique_ptr<PrimeMode> slots[num_failure_types];
};
struct OneShotPrimeMode: PrimeMode {
bool triggered = false;
bool check_trigger() noexcept override
{
if (triggered)
return false;
triggered = true;
return true;
}
};
struct RandomPrimeMode: PrimeMode {
std::mt19937_64 random;
std::uniform_int_distribution<int> dist;
int n;
RandomPrimeMode(int n, int m, uint_fast64_t seed):
random(seed),
dist(0, m-1),
n(n)
{
REALM_ASSERT(n >= 0 && m > 0);
}
bool check_trigger() noexcept override
{
int i = dist(random);
return i < n;
}
};
# if !USE_PTHREADS_IMPL
thread_local PrimeState t_prime_state;
PrimeState& get() noexcept
{
return t_prime_state;
}
# else // USE_PTHREADS_IMPL
pthread_key_t key;
pthread_once_t key_once = PTHREAD_ONCE_INIT;
void destroy(void* ptr) noexcept
{
PrimeState* prime_state = static_cast<PrimeState*>(ptr);
delete prime_state;
}
void create() noexcept
{
int ret = pthread_key_create(&key, &destroy);
if (REALM_UNLIKELY(ret != 0)) {
std::error_code ec = util::make_basic_system_error_code(errno);
throw std::system_error(ec); // Termination intended
}
}
PrimeState& get() noexcept
{
pthread_once(&key_once, &create);
void* ptr = pthread_getspecific(key);
PrimeState* prime_state = static_cast<PrimeState*>(ptr);
if (!prime_state) {
prime_state = new PrimeState; // Throws with intended termination
int ret = pthread_setspecific(key, prime_state);
if (REALM_UNLIKELY(ret != 0)) {
std::error_code ec = util::make_basic_system_error_code(errno);
throw std::system_error(ec); // Termination intended
}
}
return *prime_state;
}
# endif // USE_PTHREADS_IMPL
} // unnamed namespace
void SimulatedFailure::do_prime_one_shot(FailureType failure_type)
{
PrimeState& state = get();
if (state.slots[failure_type])
throw std::runtime_error("Already primed");
state.slots[failure_type].reset(new OneShotPrimeMode); // Throws
}
void SimulatedFailure::do_prime_random(FailureType failure_type, int n, int m, uint_fast64_t seed)
{
PrimeState& state = get();
if (state.slots[failure_type])
throw std::runtime_error("Already primed");
state.slots[failure_type].reset(new RandomPrimeMode(n, m, seed)); // Throws
}
void SimulatedFailure::do_unprime(FailureType failure_type) noexcept
{
PrimeState& state = get();
state.slots[failure_type].reset();
}
bool SimulatedFailure::do_check_trigger(FailureType failure_type) noexcept
{
PrimeState& state = get();
if (PrimeMode* p = state.slots[failure_type].get())
return p->check_trigger();
return false;
}
#endif // REALM_ENABLE_SIMULATED_FAILURE
namespace {
class ErrorCategory: public std::error_category {
public:
const char* name() const noexcept override;
std::string message(int) const override;
};
const ErrorCategory g_error_category;
const char* ErrorCategory::name() const noexcept
{
return "realm.simulated_failure";
}
std::string ErrorCategory::message(int value) const
{
switch (SimulatedFailure::FailureType(value)) {
case SimulatedFailure::generic:
return "Simulated failure (generic)";
case SimulatedFailure::slab_alloc__reset_free_space_tracking:
return "Simulated failure (slab_alloc__reset_free_space_tracking)";
case SimulatedFailure::slab_alloc__remap:
return "Simulated failure (slab_alloc__remap)";
case SimulatedFailure::shared_group__grow_reader_mapping:
return "Simulated failure (shared_group__grow_reader_mapping)";
case SimulatedFailure::sync_client__read_head:
return "Simulated failure (sync_client__read_head)";
case SimulatedFailure::sync_server__read_head:
return "Simulated failure (sync_server__read_head)";
case SimulatedFailure::_num_failure_types:
break;
}
REALM_ASSERT(false);
return std::string();
}
} // unnamed namespace
namespace realm {
namespace _impl {
std::error_code make_error_code(SimulatedFailure::FailureType failure_type) noexcept
{
return std::error_code(failure_type, g_error_category);
}
} // namespace _impl
} // namespace realm
<|endoftext|> |
<commit_before>
/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "WindowContextFactory_android.h"
#include "../VulkanWindowContext.h"
namespace sk_app {
namespace window_context_factory {
WindowContext* NewVulkanForAndroid(ANativeWindow* window, const DisplayParams& params) {
auto createVkSurface = [window] (VkInstance instance) -> VkSurfaceKHR {
static PFN_vkCreateAndroidSurfaceKHR createAndroidSurfaceKHR = nullptr;
if (!createAndroidSurfaceKHR) {
createAndroidSurfaceKHR = (PFN_vkCreateAndroidSurfaceKHR)vkGetInstanceProcAddr(
instance, "vkCreateAndroidSurfaceKHR");
}
if (!window) {
return VK_NULL_HANDLE;
}
VkSurfaceKHR surface;
VkAndroidSurfaceCreateInfoKHR surfaceCreateInfo;
memset(&surfaceCreateInfo, 0, sizeof(VkAndroidSurfaceCreateInfoKHR));
surfaceCreateInfo.sType = VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR;
surfaceCreateInfo.pNext = nullptr;
surfaceCreateInfo.flags = 0;
surfaceCreateInfo.window = window;
VkResult res = createAndroidSurfaceKHR(instance, &surfaceCreateInfo,
nullptr, &surface);
return (VK_SUCCESS == res) ? surface : VK_NULL_HANDLE;
};
auto canPresent = [](VkInstance, VkPhysicalDevice, uint32_t) { return true; };
WindowContext* ctx = new VulkanWindowContext(params, createVkSurface, canPresent);
if (!ctx->isValid()) {
delete ctx;
return nullptr;
}
return ctx;
}
} // namespace window_context_factory
} // namespace sk_app
<commit_msg>Fix crash in viewer on certain android devices<commit_after>
/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "WindowContextFactory_android.h"
#include "../VulkanWindowContext.h"
namespace sk_app {
namespace window_context_factory {
WindowContext* NewVulkanForAndroid(ANativeWindow* window, const DisplayParams& params) {
auto createVkSurface = [window] (VkInstance instance) -> VkSurfaceKHR {
PFN_vkCreateAndroidSurfaceKHR createAndroidSurfaceKHR =
(PFN_vkCreateAndroidSurfaceKHR)vkGetInstanceProcAddr(instance,
"vkCreateAndroidSurfaceKHR");
if (!window) {
return VK_NULL_HANDLE;
}
VkSurfaceKHR surface;
VkAndroidSurfaceCreateInfoKHR surfaceCreateInfo;
memset(&surfaceCreateInfo, 0, sizeof(VkAndroidSurfaceCreateInfoKHR));
surfaceCreateInfo.sType = VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR;
surfaceCreateInfo.pNext = nullptr;
surfaceCreateInfo.flags = 0;
surfaceCreateInfo.window = window;
VkResult res = createAndroidSurfaceKHR(instance, &surfaceCreateInfo,
nullptr, &surface);
return (VK_SUCCESS == res) ? surface : VK_NULL_HANDLE;
};
auto canPresent = [](VkInstance, VkPhysicalDevice, uint32_t) { return true; };
WindowContext* ctx = new VulkanWindowContext(params, createVkSurface, canPresent);
if (!ctx->isValid()) {
delete ctx;
return nullptr;
}
return ctx;
}
} // namespace window_context_factory
} // namespace sk_app
<|endoftext|> |
<commit_before>/**
Plugin to feed core state and commands to and from the Valkyrie ros_control API.
Listens for torque commands, and feeds them to the robot.
Forwards IMU, force/torque, and joint state over LCM in appropriate status messages.
Runs at 500hz in the Valkyrie ros_control main loop as a plugin.
Significant reference to
https://github.com/NASA-JSC-Robotics/valkyrie/wiki/Running-Controllers-on-Valkyrie
[email protected], 201601**
**/
#include <LCM2ROSControl.hpp>
namespace valkyrie_translator
{
LCM2ROSControl::LCM2ROSControl()
{
}
LCM2ROSControl::~LCM2ROSControl()
{}
bool LCM2ROSControl::initRequest(hardware_interface::RobotHW* robot_hw,
ros::NodeHandle& root_nh, ros::NodeHandle& controller_nh,
std::set<std::string>& claimed_resources)
{
// check if construction finished cleanly
if (state_ != CONSTRUCTED){
ROS_ERROR("Cannot initialize this controller because it failed to be constructed");
return false;
}
// setup LCM (todo: move to constructor? how to propagate an error then?)
lcm_ = boost::shared_ptr<lcm::LCM>(new lcm::LCM);
if (!lcm_->good())
{
std::cerr << "ERROR: lcm is not good()" << std::endl;
return false;
}
lcm_->subscribe("NASA_COMMAND", &LCM2ROSControl::jointCommandHandler, this);
// get a pointer to the effort interface
hardware_interface::EffortJointInterface* effort_hw = robot_hw->get<hardware_interface::EffortJointInterface>();
if (!effort_hw)
{
ROS_ERROR("This controller requires a hardware interface of type hardware_interface::EffortJointInterface.");
return false;
}
effort_hw->clearClaims();
const std::vector<std::string>& effortNames = effort_hw->getNames();
// initialize command buffer for each joint we found on the HW
for(unsigned int i=0; i<effortNames.size(); i++)
{
effortJointHandles[effortNames[i]] = effort_hw->getHandle(effortNames[i]);
latest_commands[effortNames[i]] = drc::joint_command_t();
latest_commands[effortNames[i]].joint_name = effortNames[i];
latest_commands[effortNames[i]].position = 0.0;
latest_commands[effortNames[i]].velocity = 0.0;
latest_commands[effortNames[i]].effort = 0.0;
latest_commands[effortNames[i]].k_q_p = 0.0;
latest_commands[effortNames[i]].k_q_i = 0.0;
latest_commands[effortNames[i]].k_qd_p = 0.0;
latest_commands[effortNames[i]].k_f_p = 0.0;
latest_commands[effortNames[i]].ff_qd = 0.0;
latest_commands[effortNames[i]].ff_qd_d = 0.0;
latest_commands[effortNames[i]].ff_f_d = 0.0;
latest_commands[effortNames[i]].ff_const = 0.0;
}
auto effort_hw_claims = effort_hw->getClaims();
claimed_resources.insert(effort_hw_claims.begin(), effort_hw_claims.end());
effort_hw->clearClaims();
// get a pointer to the imu interface
hardware_interface::ImuSensorInterface* imu_hw = robot_hw->get<hardware_interface::ImuSensorInterface>();
if (!imu_hw)
{
ROS_ERROR("This controller requires a hardware interface of type hardware_interface::ImuSensorInterface.");
return false;
}
imu_hw->clearClaims();
const std::vector<std::string>& imuNames = imu_hw->getNames();
for(unsigned int i=0; i<imuNames.size(); i++)
{
imuSensorHandles[imuNames[i]] = imu_hw->getHandle(imuNames[i]);
}
auto imu_hw_claims = imu_hw->getClaims();
claimed_resources.insert(imu_hw_claims.begin(), imu_hw_claims.end());
imu_hw->clearClaims();
hardware_interface::ForceTorqueSensorInterface* forceTorque_hw = robot_hw->get<hardware_interface::ForceTorqueSensorInterface>();
if (!forceTorque_hw)
{
ROS_ERROR("This controller requires a hardware interface of type hardware_interface::EffortJointInterface.");
return false;
}
// get pointer to forcetorque interface
forceTorque_hw->clearClaims();
const std::vector<std::string>& forceTorqueNames = forceTorque_hw->getNames();
for(unsigned int i=0; i<forceTorqueNames.size(); i++)
{
forceTorqueHandles[forceTorqueNames[i]] = forceTorque_hw->getHandle(forceTorqueNames[i]);
}
auto forceTorque_hw_claims = forceTorque_hw->getClaims();
claimed_resources.insert(forceTorque_hw_claims.begin(), forceTorque_hw_claims.end());
forceTorque_hw->clearClaims();
// success
state_ = INITIALIZED;
ROS_INFO("LCM2ROSCONTROL ON\n");
return true;
}
void LCM2ROSControl::starting(const ros::Time& time)
{
last_update = time;
}
void LCM2ROSControl::update(const ros::Time& time, const ros::Duration& period)
{
lcm_->handleTimeout(0);
double dt = (time - last_update).toSec();
last_update = time;
int64_t utime = time.toSec() * 100000.;
// push out the joint states for all joints we see advertised
// and also the commanded torques, for reference
pronto::joint_state_t lcm_pose_msg;
lcm_pose_msg.utime = utime;
lcm_pose_msg.num_joints = effortJointHandles.size();
lcm_pose_msg.joint_name.assign(effortJointHandles.size(), "");
lcm_pose_msg.joint_position.assign(effortJointHandles.size(), 0.);
lcm_pose_msg.joint_velocity.assign(effortJointHandles.size(), 0.);
lcm_pose_msg.joint_effort.assign(effortJointHandles.size(), 0.);
pronto::joint_state_t lcm_commanded_msg;
lcm_commanded_msg.utime = utime;
lcm_commanded_msg.num_joints = effortJointHandles.size();
lcm_commanded_msg.joint_name.assign(effortJointHandles.size(), "");
lcm_commanded_msg.joint_position.assign(effortJointHandles.size(), 0.);
lcm_commanded_msg.joint_velocity.assign(effortJointHandles.size(), 0.);
lcm_commanded_msg.joint_effort.assign(effortJointHandles.size(), 0.);
int i = 0;
for(auto iter = effortJointHandles.begin(); iter != effortJointHandles.end(); iter++)
{
// see drc_joint_command_t.lcm for explanation of gains and
// force calculation.
double q = iter->second.getPosition();
double qd = iter->second.getVelocity();
double f = iter->second.getEffort();
drc::joint_command_t command = latest_commands[iter->first];
double command_effort =
command.k_q_p * ( command.position - q ) +
command.k_q_i * ( command.position - q ) * dt +
command.k_qd_p * ( command.velocity - qd) +
command.k_f_p * ( command.effort - f) +
command.ff_qd * ( qd ) +
command.ff_qd_d * ( command.velocity ) +
command.ff_f_d * ( command.effort ) +
command.ff_const;
if (fabs(command_effort) < 1000.){
iter->second.setCommand(command_effort);
} else{
ROS_INFO("Dangerous latest_commands[%s]: %f\n", iter->first.c_str(), command_effort);
iter->second.setCommand(0.0);
}
lcm_pose_msg.joint_name[i] = iter->first;
lcm_pose_msg.joint_position[i] = q;
lcm_pose_msg.joint_velocity[i] = qd;
lcm_pose_msg.joint_effort[i] = iter->second.getEffort(); // measured!
// republish to guarantee sync
lcm_commanded_msg.joint_name[i] = iter->first;
lcm_commanded_msg.joint_position[i] = command.position;
lcm_commanded_msg.joint_velocity[i] = command.velocity;
lcm_commanded_msg.joint_effort[i] = command.effort;
i++;
}
lcm_->publish("NASA_STATE", &lcm_pose_msg);
lcm_->publish("NASA_COMMANDED_VALUES", &lcm_commanded_msg);
// push out the measurements for all imus we see advertised
for (auto iter = imuSensorHandles.begin(); iter != imuSensorHandles.end(); iter ++){
mav::ins_t lcm_imu_msg;
//lcm_imu_msg.utime = utime;
std::ostringstream imuchannel;
imuchannel << "NASA_INS_" << iter->first;
lcm_imu_msg.utime = utime;
for (i=0; i<3; i++){
lcm_imu_msg.quat[i]= iter->second.getOrientation()[i];
lcm_imu_msg.gyro[i] = iter->second.getAngularVelocity()[i];
lcm_imu_msg.accel[i] = iter->second.getLinearAcceleration()[i];
lcm_imu_msg.mag[i] = 0.0;
}
lcm_imu_msg.quat[3] = iter->second.getOrientation()[3];
lcm_imu_msg.pressure = 0.0;
lcm_imu_msg.rel_alt = 0.0;
lcm_->publish(imuchannel.str(), &lcm_imu_msg);
}
// push out the measurements for all ft's we see advertised
drc::six_axis_force_torque_array_t lcm_ft_array_msg;
lcm_ft_array_msg.utime = utime;
lcm_ft_array_msg.num_sensors = forceTorqueHandles.size();
lcm_ft_array_msg.names.resize(forceTorqueHandles.size());
lcm_ft_array_msg.sensors.resize(forceTorqueHandles.size());
i = 0;
for (auto iter = forceTorqueHandles.begin(); iter != forceTorqueHandles.end(); iter ++){
lcm_ft_array_msg.sensors[i].utime = utime;
lcm_ft_array_msg.sensors[i].force[0] = iter->second.getForce()[0];
lcm_ft_array_msg.sensors[i].force[1] = iter->second.getForce()[1];
lcm_ft_array_msg.sensors[i].force[2] = iter->second.getForce()[2];
lcm_ft_array_msg.sensors[i].moment[0] = iter->second.getTorque()[0];
lcm_ft_array_msg.sensors[i].moment[1] = iter->second.getTorque()[1];
lcm_ft_array_msg.sensors[i].moment[2] = iter->second.getTorque()[2];
lcm_ft_array_msg.names[i] = iter->first;
i++;
}
lcm_->publish("NASA_FORCE_TORQUE", &lcm_ft_array_msg);
}
void LCM2ROSControl::stopping(const ros::Time& time)
{}
void LCM2ROSControl::jointCommandHandler(const lcm::ReceiveBuffer* rbuf, const std::string &channel,
const drc::robot_command_t* msg)
{
//ROS_INFO("Got new setpoints\n");
// TODO: zero non-mentioned joints for safety?
for(unsigned int i = 0; i < msg->num_joints; ++i){
//ROS_INFO("Joint %s ", msg->joint_commands[i].joint_name.c_str());
auto search = latest_commands.find(msg->joint_commands[i].joint_name);
if (search != latest_commands.end()) {
//ROS_INFO("found in keys");
latest_commands[msg->joint_commands[i].joint_name] = msg->joint_commands[i];
} else {
//ROS_INFO("had no match.");
}
}
}
}
PLUGINLIB_EXPORT_CLASS(valkyrie_translator::LCM2ROSControl, controller_interface::ControllerBase)
<commit_msg>Secondary status message. Still seeing memory-corruption-y bug.<commit_after>/**
Plugin to feed core state and commands to and from the Valkyrie ros_control API.
Listens for torque commands, and feeds them to the robot.
Forwards IMU, force/torque, and joint state over LCM in appropriate status messages.
Runs at 500hz in the Valkyrie ros_control main loop as a plugin.
Significant reference to
https://github.com/NASA-JSC-Robotics/valkyrie/wiki/Running-Controllers-on-Valkyrie
[email protected], 201601**
**/
#include <LCM2ROSControl.hpp>
namespace valkyrie_translator
{
LCM2ROSControl::LCM2ROSControl()
{
}
LCM2ROSControl::~LCM2ROSControl()
{}
bool LCM2ROSControl::initRequest(hardware_interface::RobotHW* robot_hw,
ros::NodeHandle& root_nh, ros::NodeHandle& controller_nh,
std::set<std::string>& claimed_resources)
{
// check if construction finished cleanly
if (state_ != CONSTRUCTED){
ROS_ERROR("Cannot initialize this controller because it failed to be constructed");
return false;
}
// setup LCM (todo: move to constructor? how to propagate an error then?)
lcm_ = boost::shared_ptr<lcm::LCM>(new lcm::LCM);
if (!lcm_->good())
{
std::cerr << "ERROR: lcm is not good()" << std::endl;
return false;
}
lcm_->subscribe("NASA_COMMAND", &LCM2ROSControl::jointCommandHandler, this);
// get a pointer to the effort interface
hardware_interface::EffortJointInterface* effort_hw = robot_hw->get<hardware_interface::EffortJointInterface>();
if (!effort_hw)
{
ROS_ERROR("This controller requires a hardware interface of type hardware_interface::EffortJointInterface.");
return false;
}
effort_hw->clearClaims();
const std::vector<std::string>& effortNames = effort_hw->getNames();
// initialize command buffer for each joint we found on the HW
for(unsigned int i=0; i<effortNames.size(); i++)
{
effortJointHandles[effortNames[i]] = effort_hw->getHandle(effortNames[i]);
latest_commands[effortNames[i]] = drc::joint_command_t();
latest_commands[effortNames[i]].joint_name = effortNames[i];
latest_commands[effortNames[i]].position = 0.0;
latest_commands[effortNames[i]].velocity = 0.0;
latest_commands[effortNames[i]].effort = 0.0;
latest_commands[effortNames[i]].k_q_p = 0.0;
latest_commands[effortNames[i]].k_q_i = 0.0;
latest_commands[effortNames[i]].k_qd_p = 0.0;
latest_commands[effortNames[i]].k_f_p = 0.0;
latest_commands[effortNames[i]].ff_qd = 0.0;
latest_commands[effortNames[i]].ff_qd_d = 0.0;
latest_commands[effortNames[i]].ff_f_d = 0.0;
latest_commands[effortNames[i]].ff_const = 0.0;
}
auto effort_hw_claims = effort_hw->getClaims();
claimed_resources.insert(effort_hw_claims.begin(), effort_hw_claims.end());
effort_hw->clearClaims();
// get a pointer to the imu interface
hardware_interface::ImuSensorInterface* imu_hw = robot_hw->get<hardware_interface::ImuSensorInterface>();
if (!imu_hw)
{
ROS_ERROR("This controller requires a hardware interface of type hardware_interface::ImuSensorInterface.");
return false;
}
imu_hw->clearClaims();
const std::vector<std::string>& imuNames = imu_hw->getNames();
for(unsigned int i=0; i<imuNames.size(); i++)
{
imuSensorHandles[imuNames[i]] = imu_hw->getHandle(imuNames[i]);
}
auto imu_hw_claims = imu_hw->getClaims();
claimed_resources.insert(imu_hw_claims.begin(), imu_hw_claims.end());
imu_hw->clearClaims();
hardware_interface::ForceTorqueSensorInterface* forceTorque_hw = robot_hw->get<hardware_interface::ForceTorqueSensorInterface>();
if (!forceTorque_hw)
{
ROS_ERROR("This controller requires a hardware interface of type hardware_interface::EffortJointInterface.");
return false;
}
// get pointer to forcetorque interface
forceTorque_hw->clearClaims();
const std::vector<std::string>& forceTorqueNames = forceTorque_hw->getNames();
for(unsigned int i=0; i<forceTorqueNames.size(); i++)
{
forceTorqueHandles[forceTorqueNames[i]] = forceTorque_hw->getHandle(forceTorqueNames[i]);
}
auto forceTorque_hw_claims = forceTorque_hw->getClaims();
claimed_resources.insert(forceTorque_hw_claims.begin(), forceTorque_hw_claims.end());
forceTorque_hw->clearClaims();
// success
state_ = INITIALIZED;
ROS_INFO("LCM2ROSCONTROL ON\n");
return true;
}
void LCM2ROSControl::starting(const ros::Time& time)
{
last_update = time;
}
void LCM2ROSControl::update(const ros::Time& time, const ros::Duration& period)
{
lcm_->handleTimeout(0);
double dt = (time - last_update).toSec();
last_update = time;
int64_t utime = time.toSec() * 100000.;
// push out the joint states for all joints we see advertised
// and also the commanded torques, for reference
pronto::joint_state_t lcm_pose_msg;
lcm_pose_msg.utime = utime;
lcm_pose_msg.num_joints = effortJointHandles.size();
lcm_pose_msg.joint_name.assign(effortJointHandles.size(), "");
lcm_pose_msg.joint_position.assign(effortJointHandles.size(), 0.);
lcm_pose_msg.joint_velocity.assign(effortJointHandles.size(), 0.);
lcm_pose_msg.joint_effort.assign(effortJointHandles.size(), 0.);
pronto::joint_state_t lcm_commanded_msg;
lcm_commanded_msg.utime = utime;
lcm_commanded_msg.num_joints = effortJointHandles.size();
lcm_commanded_msg.joint_name.assign(effortJointHandles.size(), "");
lcm_commanded_msg.joint_position.assign(effortJointHandles.size(), 0.);
lcm_commanded_msg.joint_velocity.assign(effortJointHandles.size(), 0.);
lcm_commanded_msg.joint_effort.assign(effortJointHandles.size(), 0.);
pronto::joint_angles_t lcm_torque_msg;
lcm_torque_msg.robot_name = "val!";
lcm_torque_msg.utime = utime;
lcm_torque_msg.num_joints = effortJointHandles.size();
lcm_torque_msg.joint_name.assign(effortJointHandles.size(), "");
lcm_torque_msg.joint_position.assign(effortJointHandles.size(), 0.);
int i = 0;
for(auto iter = effortJointHandles.begin(); iter != effortJointHandles.end(); iter++)
{
// see drc_joint_command_t.lcm for explanation of gains and
// force calculation.
double q = iter->second.getPosition();
double qd = iter->second.getVelocity();
double f = iter->second.getEffort();
drc::joint_command_t command = latest_commands[iter->first];
double command_effort =
command.k_q_p * ( command.position - q ) +
command.k_q_i * ( command.position - q ) * dt +
command.k_qd_p * ( command.velocity - qd) +
command.k_f_p * ( command.effort - f) +
command.ff_qd * ( qd ) +
command.ff_qd_d * ( command.velocity ) +
command.ff_f_d * ( command.effort ) +
command.ff_const;
if (fabs(command_effort) < 1000.){
iter->second.setCommand(command_effort);
} else{
ROS_INFO("Dangerous latest_commands[%s]: %f\n", iter->first.c_str(), command_effort);
iter->second.setCommand(0.0);
}
lcm_pose_msg.joint_name[i] = iter->first;
lcm_pose_msg.joint_position[i] = q;
lcm_pose_msg.joint_velocity[i] = qd;
lcm_pose_msg.joint_effort[i] = iter->second.getEffort(); // measured!
// republish to guarantee sync
lcm_commanded_msg.joint_name[i] = iter->first;
lcm_commanded_msg.joint_position[i] = command.position;
lcm_commanded_msg.joint_velocity[i] = command.velocity;
lcm_commanded_msg.joint_effort[i] = command.effort;
lcm_torque_msg.joint_name[i] = iter->first;
lcm_torque_msg.joint_position[i] = command_effort;
i++;
}
ROS_INFO("BEFORE 1");
lcm_->publish("NASA_STATE", &lcm_pose_msg);
ROS_INFO("AFTER 1");
lcm_->publish("NASA_COMMANDED_VALUES", &lcm_commanded_msg);
ROS_INFO("AFTER 2");
lcm_->publish("NASA_COMMANDED_TORQUE", &lcm_torque_msg);
ROS_INFO("AFTER 3");
// push out the measurements for all imus we see advertised
for (auto iter = imuSensorHandles.begin(); iter != imuSensorHandles.end(); iter ++){
mav::ins_t lcm_imu_msg;
//lcm_imu_msg.utime = utime;
std::ostringstream imuchannel;
imuchannel << "NASA_INS_" << iter->first;
lcm_imu_msg.utime = utime;
for (i=0; i<3; i++){
lcm_imu_msg.quat[i]= iter->second.getOrientation()[i];
lcm_imu_msg.gyro[i] = iter->second.getAngularVelocity()[i];
lcm_imu_msg.accel[i] = iter->second.getLinearAcceleration()[i];
lcm_imu_msg.mag[i] = 0.0;
}
lcm_imu_msg.quat[3] = iter->second.getOrientation()[3];
lcm_imu_msg.pressure = 0.0;
lcm_imu_msg.rel_alt = 0.0;
lcm_->publish(imuchannel.str(), &lcm_imu_msg);
}
// push out the measurements for all ft's we see advertised
drc::six_axis_force_torque_array_t lcm_ft_array_msg;
lcm_ft_array_msg.utime = utime;
lcm_ft_array_msg.num_sensors = forceTorqueHandles.size();
lcm_ft_array_msg.names.resize(forceTorqueHandles.size());
lcm_ft_array_msg.sensors.resize(forceTorqueHandles.size());
i = 0;
for (auto iter = forceTorqueHandles.begin(); iter != forceTorqueHandles.end(); iter ++){
lcm_ft_array_msg.sensors[i].utime = utime;
lcm_ft_array_msg.sensors[i].force[0] = iter->second.getForce()[0];
lcm_ft_array_msg.sensors[i].force[1] = iter->second.getForce()[1];
lcm_ft_array_msg.sensors[i].force[2] = iter->second.getForce()[2];
lcm_ft_array_msg.sensors[i].moment[0] = iter->second.getTorque()[0];
lcm_ft_array_msg.sensors[i].moment[1] = iter->second.getTorque()[1];
lcm_ft_array_msg.sensors[i].moment[2] = iter->second.getTorque()[2];
lcm_ft_array_msg.names[i] = iter->first;
i++;
}
lcm_->publish("NASA_FORCE_TORQUE", &lcm_ft_array_msg);
}
void LCM2ROSControl::stopping(const ros::Time& time)
{}
void LCM2ROSControl::jointCommandHandler(const lcm::ReceiveBuffer* rbuf, const std::string &channel,
const drc::robot_command_t* msg)
{
ROS_INFO("Got new setpoints\n");
// TODO: zero non-mentioned joints for safety?
for(unsigned int i = 0; i < msg->num_joints; ++i){
//ROS_INFO("Joint %s ", msg->joint_commands[i].joint_name.c_str());
auto search = latest_commands.find(msg->joint_commands[i].joint_name);
if (search != latest_commands.end()) {
//ROS_INFO("found in keys");
latest_commands[msg->joint_commands[i].joint_name] = msg->joint_commands[i];
} else {
//ROS_INFO("had no match.");
}
}
}
}
PLUGINLIB_EXPORT_CLASS(valkyrie_translator::LCM2ROSControl, controller_interface::ControllerBase)
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/*
* Copyright 2017 IBM International Business Machines Corp.
*
* 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.
*/
/* IBM_PROLOG_END_TAG */
///
/// @file mvpd_access_defs.H
///
/// @brief Defines the Module VPD Records and Keywords
///
#ifndef _FAPI2_MVPDACCESS_DEFS_H_
#define _FAPI2_MVPDACCESS_DEFS_H_
namespace fapi2
{
enum MvpdRecord
{
MVPD_RECORD_CRP0 = 0x00,
MVPD_RECORD_CP00 = 0x01,
MVPD_RECORD_VINI = 0x02,
MVPD_RECORD_LRP0 = 0x03,
MVPD_RECORD_LRP1 = 0x04,
MVPD_RECORD_LRP2 = 0x05,
MVPD_RECORD_LRP3 = 0x06,
MVPD_RECORD_LRP4 = 0x07,
MVPD_RECORD_LRP5 = 0x08,
MVPD_RECORD_LRP6 = 0x09,
MVPD_RECORD_LRP7 = 0x0a,
MVPD_RECORD_LRP8 = 0x0b,
MVPD_RECORD_LRP9 = 0x0c,
MVPD_RECORD_LRPA = 0x0d,
MVPD_RECORD_LRPB = 0x0e,
MVPD_RECORD_LRPC = 0x0f,
MVPD_RECORD_LRPD = 0x10,
MVPD_RECORD_LRPE = 0x11,
MVPD_RECORD_LWP0 = 0x12,
MVPD_RECORD_LWP1 = 0x13,
MVPD_RECORD_LWP2 = 0x14,
MVPD_RECORD_LWP3 = 0x15,
MVPD_RECORD_LWP4 = 0x16,
MVPD_RECORD_LWP5 = 0x17,
MVPD_RECORD_LWP6 = 0x18,
MVPD_RECORD_LWP7 = 0x19,
MVPD_RECORD_LWP8 = 0x1a,
MVPD_RECORD_LWP9 = 0x1b,
MVPD_RECORD_LWPA = 0x1c,
MVPD_RECORD_LWPB = 0x1d,
MVPD_RECORD_LWPC = 0x1e,
MVPD_RECORD_LWPD = 0x1f,
MVPD_RECORD_LWPE = 0x20,
MVPD_RECORD_VWML = 0x21,
MVPD_RECORD_MER0 = 0x22,
MVPD_RECORD_LAST, //useful for testcases
MVPD_RECORD_FIRST = MVPD_RECORD_CRP0, //useful for testcases
};
enum MvpdKeyword
{
MVPD_KEYWORD_VD = 0x00,
MVPD_KEYWORD_ED = 0x01,
MVPD_KEYWORD_TE = 0x02,
MVPD_KEYWORD_DD = 0x03,
MVPD_KEYWORD_PDP = 0x04,
MVPD_KEYWORD_ST = 0x05,
MVPD_KEYWORD_DN = 0x06,
MVPD_KEYWORD_PG = 0x07,
MVPD_KEYWORD_PK = 0x08,
MVPD_KEYWORD_PDR = 0x09,
MVPD_KEYWORD_PDV = 0x0a,
MVPD_KEYWORD_PDH = 0x0b,
MVPD_KEYWORD_SB = 0x0c,
MVPD_KEYWORD_DR = 0x0d,
MVPD_KEYWORD_VZ = 0x0e,
MVPD_KEYWORD_CC = 0x0f,
MVPD_KEYWORD_CE = 0x10,
MVPD_KEYWORD_FN = 0x11,
MVPD_KEYWORD_PN = 0x12,
MVPD_KEYWORD_SN = 0x13,
MVPD_KEYWORD_PR = 0x14,
MVPD_KEYWORD_HE = 0x15,
MVPD_KEYWORD_CT = 0x16,
MVPD_KEYWORD_HW = 0x17,
MVPD_KEYWORD_PDM = 0x18,
MVPD_KEYWORD_IN = 0x19,
MVPD_KEYWORD_PD2 = 0x1a,
MVPD_KEYWORD_PD3 = 0x1b,
MVPD_KEYWORD_OC = 0x1c,
MVPD_KEYWORD_FO = 0x1d,
MVPD_KEYWORD_PDI = 0x1e,
MVPD_KEYWORD_PDG = 0x1f,
MVPD_KEYWORD_MK = 0x20,
MVPD_KEYWORD_PB = 0x21,
MVPD_KEYWORD_CH = 0x22,
MVPD_KEYWORD_IQ = 0x23,
MVPD_KEYWORD_L1 = 0x24,
MVPD_KEYWORD_L2 = 0x25,
MVPD_KEYWORD_L3 = 0x26,
MVPD_KEYWORD_L4 = 0x27,
MVPD_KEYWORD_L5 = 0x28,
MVPD_KEYWORD_L6 = 0x29,
MVPD_KEYWORD_L7 = 0x2a,
MVPD_KEYWORD_L8 = 0x2b,
MVPD_KEYWORD_PDW = 0x2c,
MVPD_KEYWORD_LAST, //useful for testcases
MVPD_KEYWORD_FIRST = MVPD_KEYWORD_VD, //useful for testcases
};
}
#endif
<commit_msg>add enum for AW keyword access<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/*
* Copyright 2017 IBM International Business Machines Corp.
*
* 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.
*/
/* IBM_PROLOG_END_TAG */
///
/// @file mvpd_access_defs.H
///
/// @brief Defines the Module VPD Records and Keywords
///
#ifndef _FAPI2_MVPDACCESS_DEFS_H_
#define _FAPI2_MVPDACCESS_DEFS_H_
namespace fapi2
{
enum MvpdRecord
{
MVPD_RECORD_CRP0 = 0x00,
MVPD_RECORD_CP00 = 0x01,
MVPD_RECORD_VINI = 0x02,
MVPD_RECORD_LRP0 = 0x03,
MVPD_RECORD_LRP1 = 0x04,
MVPD_RECORD_LRP2 = 0x05,
MVPD_RECORD_LRP3 = 0x06,
MVPD_RECORD_LRP4 = 0x07,
MVPD_RECORD_LRP5 = 0x08,
MVPD_RECORD_LRP6 = 0x09,
MVPD_RECORD_LRP7 = 0x0a,
MVPD_RECORD_LRP8 = 0x0b,
MVPD_RECORD_LRP9 = 0x0c,
MVPD_RECORD_LRPA = 0x0d,
MVPD_RECORD_LRPB = 0x0e,
MVPD_RECORD_LRPC = 0x0f,
MVPD_RECORD_LRPD = 0x10,
MVPD_RECORD_LRPE = 0x11,
MVPD_RECORD_LWP0 = 0x12,
MVPD_RECORD_LWP1 = 0x13,
MVPD_RECORD_LWP2 = 0x14,
MVPD_RECORD_LWP3 = 0x15,
MVPD_RECORD_LWP4 = 0x16,
MVPD_RECORD_LWP5 = 0x17,
MVPD_RECORD_LWP6 = 0x18,
MVPD_RECORD_LWP7 = 0x19,
MVPD_RECORD_LWP8 = 0x1a,
MVPD_RECORD_LWP9 = 0x1b,
MVPD_RECORD_LWPA = 0x1c,
MVPD_RECORD_LWPB = 0x1d,
MVPD_RECORD_LWPC = 0x1e,
MVPD_RECORD_LWPD = 0x1f,
MVPD_RECORD_LWPE = 0x20,
MVPD_RECORD_VWML = 0x21,
MVPD_RECORD_MER0 = 0x22,
MVPD_RECORD_LAST, //useful for testcases
MVPD_RECORD_FIRST = MVPD_RECORD_CRP0, //useful for testcases
};
enum MvpdKeyword
{
MVPD_KEYWORD_VD = 0x00,
MVPD_KEYWORD_ED = 0x01,
MVPD_KEYWORD_TE = 0x02,
MVPD_KEYWORD_DD = 0x03,
MVPD_KEYWORD_PDP = 0x04,
MVPD_KEYWORD_ST = 0x05,
MVPD_KEYWORD_DN = 0x06,
MVPD_KEYWORD_PG = 0x07,
MVPD_KEYWORD_PK = 0x08,
MVPD_KEYWORD_PDR = 0x09,
MVPD_KEYWORD_PDV = 0x0a,
MVPD_KEYWORD_PDH = 0x0b,
MVPD_KEYWORD_SB = 0x0c,
MVPD_KEYWORD_DR = 0x0d,
MVPD_KEYWORD_VZ = 0x0e,
MVPD_KEYWORD_CC = 0x0f,
MVPD_KEYWORD_CE = 0x10,
MVPD_KEYWORD_FN = 0x11,
MVPD_KEYWORD_PN = 0x12,
MVPD_KEYWORD_SN = 0x13,
MVPD_KEYWORD_PR = 0x14,
MVPD_KEYWORD_HE = 0x15,
MVPD_KEYWORD_CT = 0x16,
MVPD_KEYWORD_HW = 0x17,
MVPD_KEYWORD_PDM = 0x18,
MVPD_KEYWORD_IN = 0x19,
MVPD_KEYWORD_PD2 = 0x1a,
MVPD_KEYWORD_PD3 = 0x1b,
MVPD_KEYWORD_OC = 0x1c,
MVPD_KEYWORD_FO = 0x1d,
MVPD_KEYWORD_PDI = 0x1e,
MVPD_KEYWORD_PDG = 0x1f,
MVPD_KEYWORD_MK = 0x20,
MVPD_KEYWORD_PB = 0x21,
MVPD_KEYWORD_CH = 0x22,
MVPD_KEYWORD_IQ = 0x23,
MVPD_KEYWORD_L1 = 0x24,
MVPD_KEYWORD_L2 = 0x25,
MVPD_KEYWORD_L3 = 0x26,
MVPD_KEYWORD_L4 = 0x27,
MVPD_KEYWORD_L5 = 0x28,
MVPD_KEYWORD_L6 = 0x29,
MVPD_KEYWORD_L7 = 0x2a,
MVPD_KEYWORD_L8 = 0x2b,
MVPD_KEYWORD_PDW = 0x2c,
MVPD_KEYWORD_AW = 0x2d,
MVPD_KEYWORD_LAST, //useful for testcases
MVPD_KEYWORD_FIRST = MVPD_KEYWORD_VD, //useful for testcases
};
}
#endif
<|endoftext|> |
<commit_before>#include "../../include/ScreenJogo.hpp"
#include "../../include/Config.hpp"
#include "../../include/MusicManager.hpp"
#include "../../include/PaoInferior.hpp"
#include "../../include/PaoSuperior.hpp"
#include "../../include/TextureManager.hpp"
#include "../../include/Utils.hpp"
#define VELOCIDADE_QUEDA 30
#define VELOCIDADE_HORIZONTAL 7
ScreenJogo::ScreenJogo( GameRef& gameRef )
: Screen( gameRef ) {
loadAssets();
caindo = false;
movendoHorizontal = true;
velocidadeHorizontal = VELOCIDADE_HORIZONTAL;
// TODO: Mudar para receber a lista de lanches
meu = new Lanche( 4 );
modelo = new Lanche( 4 );
meu->empilhar( new PaoInferior() );
modelo->empilhar( new PaoInferior() );
while( !modelo->faltaApenasPaoSuperior() ) {
modelo->empilhar( Utils::sortearItemCerto() );
}
modelo->empilhar( new PaoSuperior() );
modelo->setPosition( 0, WINDOW_HEIGHT - 85 );
}
ScreenJogo::~ScreenJogo() {
delete ingrediente;
delete meu;
delete modelo;
}
void ScreenJogo::loadAssets() {
TextureManager::add( "backgroundJogo", "jogo.jpg" );
background.setTexture( TextureManager::get( "backgroundJogo" ) );
TextureManager::add( "barraFila", "fila_barra.png" );
bar.setTexture( TextureManager::get( "barraFila" ) );
bar.setPosition( 640, 30 );
MusicManager::add( "musicJogar", "background.ogg" );
music = &MusicManager::get( "musicJogar" );
ingrediente = Utils::sortearQualquerItem();
ingrediente->setPosition( WINDOW_WIDTH / 2 - ingrediente->getGlobalBounds().width / 2, 0 );
}
void ScreenJogo::draw() {
window->clear();
window->draw( background );
window->draw( bar );
window->draw( *modelo );
window->draw( *ingrediente );
window->display();
}
void ScreenJogo::update() {
if( *isAudioOn && music->getStatus() != sf::SoundSource::Status::Playing ) {
music->play();
}
while( window->pollEvent( *event ) ) {
if( event->type == sf::Event::Closed ) {
music->stop();
window->close();
}
if( inputManager->keyPressed( sf::Keyboard::Space ) ) {
movendoHorizontal = false;
caindo = true;
}
}
if( movendoHorizontal ) {
if( Utils::isForaDaJanelaHorizontalmente( ingrediente ) ) {
velocidadeHorizontal = -1 * velocidadeHorizontal;
}
ingrediente->move( velocidadeHorizontal, 0 );
} else if( caindo ) {
if( Utils::isForaDaJanelaVerticalmente( ingrediente ) ) {
caindo = false;
} else {
ingrediente->move( 0, VELOCIDADE_QUEDA );
}
} else {
delete ingrediente;
ingrediente = Utils::sortearQualquerItem();
ingrediente->setPosition( WINDOW_WIDTH / 2 - ingrediente->getGlobalBounds().width / 2, 0 );
movendoHorizontal = true;
}
draw();
}
<commit_msg>Exibindo meu lanche<commit_after>#include "../../include/ScreenJogo.hpp"
#include "../../include/Config.hpp"
#include "../../include/MusicManager.hpp"
#include "../../include/PaoInferior.hpp"
#include "../../include/PaoSuperior.hpp"
#include "../../include/TextureManager.hpp"
#include "../../include/Utils.hpp"
#define VELOCIDADE_QUEDA 30
#define VELOCIDADE_HORIZONTAL 7
ScreenJogo::ScreenJogo( GameRef& gameRef )
: Screen( gameRef ) {
loadAssets();
caindo = false;
movendoHorizontal = true;
velocidadeHorizontal = VELOCIDADE_HORIZONTAL;
// TODO: Mudar para receber a lista de lanches
meu = new Lanche( 4 );
modelo = new Lanche( 4 );
meu->empilhar( new PaoInferior() );
meu->setPosition( WINDOW_WIDTH / 2 - 50, WINDOW_HEIGHT - 85 );
modelo->empilhar( new PaoInferior() );
while( !modelo->faltaApenasPaoSuperior() ) {
modelo->empilhar( Utils::sortearItemCerto() );
}
modelo->empilhar( new PaoSuperior() );
modelo->setPosition( 0, WINDOW_HEIGHT - 85 );
}
ScreenJogo::~ScreenJogo() {
delete ingrediente;
delete meu;
delete modelo;
}
void ScreenJogo::loadAssets() {
TextureManager::add( "backgroundJogo", "jogo.jpg" );
background.setTexture( TextureManager::get( "backgroundJogo" ) );
TextureManager::add( "barraFila", "fila_barra.png" );
bar.setTexture( TextureManager::get( "barraFila" ) );
bar.setPosition( 640, 30 );
MusicManager::add( "musicJogar", "background.ogg" );
music = &MusicManager::get( "musicJogar" );
ingrediente = Utils::sortearQualquerItem();
ingrediente->setPosition( WINDOW_WIDTH / 2 - ingrediente->getGlobalBounds().width / 2, 0 );
}
void ScreenJogo::draw() {
window->clear();
window->draw( background );
window->draw( bar );
window->draw( *modelo );
window->draw( *meu );
window->draw( *ingrediente );
window->display();
}
void ScreenJogo::update() {
if( *isAudioOn && music->getStatus() != sf::SoundSource::Status::Playing ) {
music->play();
}
while( window->pollEvent( *event ) ) {
if( event->type == sf::Event::Closed ) {
music->stop();
window->close();
}
if( inputManager->keyPressed( sf::Keyboard::Space ) ) {
movendoHorizontal = false;
caindo = true;
}
}
if( movendoHorizontal ) {
if( Utils::isForaDaJanelaHorizontalmente( ingrediente ) ) {
velocidadeHorizontal = -1 * velocidadeHorizontal;
}
ingrediente->move( velocidadeHorizontal, 0 );
} else if( caindo ) {
if( Utils::isForaDaJanelaVerticalmente( ingrediente ) ) {
caindo = false;
} else {
ingrediente->move( 0, VELOCIDADE_QUEDA );
}
} else {
delete ingrediente;
ingrediente = Utils::sortearQualquerItem();
ingrediente->setPosition( WINDOW_WIDTH / 2 - ingrediente->getGlobalBounds().width / 2, 0 );
movendoHorizontal = true;
}
draw();
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/background/background_contents_service.h"
#include "chrome/browser/background/background_contents_service_factory.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/test/base/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"
class AppBackgroundPageApiTest : public ExtensionApiTest {
public:
void SetUpCommandLine(CommandLine* command_line) {
ExtensionApiTest::SetUpCommandLine(command_line);
command_line->AppendSwitch(switches::kDisablePopupBlocking);
command_line->AppendSwitch(switches::kAllowHTTPBackgroundPage);
}
bool CreateApp(const std::string& app_manifest,
FilePath* app_dir) {
if (!app_dir_.CreateUniqueTempDir()) {
LOG(ERROR) << "Unable to create a temporary directory.";
return false;
}
FilePath manifest_path = app_dir_.path().AppendASCII("manifest.json");
int bytes_written = file_util::WriteFile(manifest_path,
app_manifest.data(),
app_manifest.size());
if (bytes_written != static_cast<int>(app_manifest.size())) {
LOG(ERROR) << "Unable to write complete manifest to file. Return code="
<< bytes_written;
return false;
}
*app_dir = app_dir_.path();
return true;
}
private:
ScopedTempDir app_dir_;
};
IN_PROC_BROWSER_TEST_F(AppBackgroundPageApiTest, Basic) {
host_resolver()->AddRule("a.com", "127.0.0.1");
ASSERT_TRUE(StartTestServer());
std::string app_manifest = base::StringPrintf(
"{"
" \"name\": \"App\","
" \"version\": \"0.1\","
" \"app\": {"
" \"urls\": ["
" \"http://a.com/\""
" ],"
" \"launch\": {"
" \"web_url\": \"http://a.com:%d/\""
" }"
" },"
" \"permissions\": [\"background\"]"
"}",
test_server()->host_port_pair().port());
FilePath app_dir;
ASSERT_TRUE(CreateApp(app_manifest, &app_dir));
ASSERT_TRUE(LoadExtension(app_dir));
ASSERT_TRUE(RunExtensionTest("app_background_page/basic")) << message_;
}
// Crashy, http://crbug.com/49215.
IN_PROC_BROWSER_TEST_F(AppBackgroundPageApiTest, DISABLED_LacksPermission) {
host_resolver()->AddRule("a.com", "127.0.0.1");
ASSERT_TRUE(StartTestServer());
std::string app_manifest = base::StringPrintf(
"{"
" \"name\": \"App\","
" \"version\": \"0.1\","
" \"app\": {"
" \"urls\": ["
" \"http://a.com/\""
" ],"
" \"launch\": {"
" \"web_url\": \"http://a.com:%d/\""
" }"
" }"
"}",
test_server()->host_port_pair().port());
FilePath app_dir;
ASSERT_TRUE(CreateApp(app_manifest, &app_dir));
ASSERT_TRUE(LoadExtension(app_dir));
ASSERT_TRUE(RunExtensionTest("app_background_page/lacks_permission"))
<< message_;
}
IN_PROC_BROWSER_TEST_F(AppBackgroundPageApiTest, ManifestBackgroundPage) {
host_resolver()->AddRule("a.com", "127.0.0.1");
ASSERT_TRUE(StartTestServer());
std::string app_manifest = base::StringPrintf(
"{"
" \"name\": \"App\","
" \"version\": \"0.1\","
" \"app\": {"
" \"urls\": ["
" \"http://a.com/\""
" ],"
" \"launch\": {"
" \"web_url\": \"http://a.com:%d/\""
" }"
" },"
" \"permissions\": [\"background\"],"
" \"background_page\": \"http://a.com:%d/test.html\""
"}",
test_server()->host_port_pair().port(),
test_server()->host_port_pair().port());
FilePath app_dir;
ASSERT_TRUE(CreateApp(app_manifest, &app_dir));
ASSERT_TRUE(LoadExtension(app_dir));
const Extension* extension = GetSingleLoadedExtension();
ASSERT_TRUE(
BackgroundContentsServiceFactory::GetForProfile(browser()->profile())->
GetAppBackgroundContents(ASCIIToUTF16(extension->id())));
}
<commit_msg>Disable failed test AppBackgroundPageApiTest.Basic on Mac.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/background/background_contents_service.h"
#include "chrome/browser/background/background_contents_service_factory.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/test/base/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"
class AppBackgroundPageApiTest : public ExtensionApiTest {
public:
void SetUpCommandLine(CommandLine* command_line) {
ExtensionApiTest::SetUpCommandLine(command_line);
command_line->AppendSwitch(switches::kDisablePopupBlocking);
command_line->AppendSwitch(switches::kAllowHTTPBackgroundPage);
}
bool CreateApp(const std::string& app_manifest,
FilePath* app_dir) {
if (!app_dir_.CreateUniqueTempDir()) {
LOG(ERROR) << "Unable to create a temporary directory.";
return false;
}
FilePath manifest_path = app_dir_.path().AppendASCII("manifest.json");
int bytes_written = file_util::WriteFile(manifest_path,
app_manifest.data(),
app_manifest.size());
if (bytes_written != static_cast<int>(app_manifest.size())) {
LOG(ERROR) << "Unable to write complete manifest to file. Return code="
<< bytes_written;
return false;
}
*app_dir = app_dir_.path();
return true;
}
private:
ScopedTempDir app_dir_;
};
// Disable on Mac only. http://crbug.com/95139
#if defined(OS_MACOSX)
#define MAYBE_Basic DISABLED_Basic
#else
#define MAYBE_Basic Basic
#endif
IN_PROC_BROWSER_TEST_F(AppBackgroundPageApiTest, MAYBE_Basic) {
host_resolver()->AddRule("a.com", "127.0.0.1");
ASSERT_TRUE(StartTestServer());
std::string app_manifest = base::StringPrintf(
"{"
" \"name\": \"App\","
" \"version\": \"0.1\","
" \"app\": {"
" \"urls\": ["
" \"http://a.com/\""
" ],"
" \"launch\": {"
" \"web_url\": \"http://a.com:%d/\""
" }"
" },"
" \"permissions\": [\"background\"]"
"}",
test_server()->host_port_pair().port());
FilePath app_dir;
ASSERT_TRUE(CreateApp(app_manifest, &app_dir));
ASSERT_TRUE(LoadExtension(app_dir));
ASSERT_TRUE(RunExtensionTest("app_background_page/basic")) << message_;
}
// Crashy, http://crbug.com/49215.
IN_PROC_BROWSER_TEST_F(AppBackgroundPageApiTest, DISABLED_LacksPermission) {
host_resolver()->AddRule("a.com", "127.0.0.1");
ASSERT_TRUE(StartTestServer());
std::string app_manifest = base::StringPrintf(
"{"
" \"name\": \"App\","
" \"version\": \"0.1\","
" \"app\": {"
" \"urls\": ["
" \"http://a.com/\""
" ],"
" \"launch\": {"
" \"web_url\": \"http://a.com:%d/\""
" }"
" }"
"}",
test_server()->host_port_pair().port());
FilePath app_dir;
ASSERT_TRUE(CreateApp(app_manifest, &app_dir));
ASSERT_TRUE(LoadExtension(app_dir));
ASSERT_TRUE(RunExtensionTest("app_background_page/lacks_permission"))
<< message_;
}
IN_PROC_BROWSER_TEST_F(AppBackgroundPageApiTest, ManifestBackgroundPage) {
host_resolver()->AddRule("a.com", "127.0.0.1");
ASSERT_TRUE(StartTestServer());
std::string app_manifest = base::StringPrintf(
"{"
" \"name\": \"App\","
" \"version\": \"0.1\","
" \"app\": {"
" \"urls\": ["
" \"http://a.com/\""
" ],"
" \"launch\": {"
" \"web_url\": \"http://a.com:%d/\""
" }"
" },"
" \"permissions\": [\"background\"],"
" \"background_page\": \"http://a.com:%d/test.html\""
"}",
test_server()->host_port_pair().port(),
test_server()->host_port_pair().port());
FilePath app_dir;
ASSERT_TRUE(CreateApp(app_manifest, &app_dir));
ASSERT_TRUE(LoadExtension(app_dir));
const Extension* extension = GetSingleLoadedExtension();
ASSERT_TRUE(
BackgroundContentsServiceFactory::GetForProfile(browser()->profile())->
GetAppBackgroundContents(ASCIIToUTF16(extension->id())));
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/browser_action_test_util.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/extensions/user_script_master.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"
IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoNoScript) {
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
// Loads a simple extension which attempts to change the title of every page
// that loads to "modified".
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("incognito").AppendASCII("content_scripts")));
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
Browser* otr_browser = BrowserList::FindBrowserWithType(
browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
false);
TabContents* tab = otr_browser->GetSelectedTabContents();
// Verify the script didn't run.
bool result = false;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
tab->render_view_host(), L"",
L"window.domAutomationController.send(document.title == 'Unmodified')",
&result));
EXPECT_TRUE(result);
}
IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoYesScript) {
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
// Load a dummy extension. This just tests that we don't regress a
// crash fix when multiple incognito- and non-incognito-enabled extensions
// are mixed.
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("content_scripts").AppendASCII("all_frames")));
// Loads a simple extension which attempts to change the title of every page
// that loads to "modified".
ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_.AppendASCII("api_test")
.AppendASCII("incognito").AppendASCII("content_scripts")));
// Dummy extension #2.
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("content_scripts").AppendASCII("isolated_world1")));
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
Browser* otr_browser = BrowserList::FindBrowserWithType(
browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
false);
TabContents* tab = otr_browser->GetSelectedTabContents();
// Verify the script ran.
bool result = false;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
tab->render_view_host(), L"",
L"window.domAutomationController.send(document.title == 'modified')",
&result));
EXPECT_TRUE(result);
}
// Tests that an extension which is enabled for incognito mode doesn't
// accidentially create and incognito profile.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DontCreateIncognitoProfile) {
ASSERT_FALSE(browser()->profile()->HasOffTheRecordProfile());
ASSERT_TRUE(
RunExtensionTestIncognito("incognito/enumerate_tabs")) << message_;
ASSERT_FALSE(browser()->profile()->HasOffTheRecordProfile());
}
// Tests that the APIs in an incognito-enabled extension work properly.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Incognito) {
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
ResultCatcher catcher;
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
.AppendASCII("incognito").AppendASCII("apis")));
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
// Crashes flakily on Linux. http://crbug.com/58270
#if defined(OS_LINUX)
#define MAYBE_IncognitoSplitMode FLAKY_IncognitoSplitMode
#else
#define MAYBE_IncognitoSplitMode IncognitoSplitMode
#endif
// Tests that the APIs in an incognito-enabled split-mode extension work
// properly.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_IncognitoSplitMode) {
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
// We need 2 ResultCatchers because we'll be running the same test in both
// regular and incognito mode.
ResultCatcher catcher;
catcher.RestrictToProfile(browser()->profile());
ResultCatcher catcher_incognito;
catcher_incognito.RestrictToProfile(
browser()->profile()->GetOffTheRecordProfile());
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
.AppendASCII("incognito").AppendASCII("split")));
// Wait for both extensions to be ready before telling them to proceed.
ExtensionTestMessageListener listener("waiting", true);
EXPECT_TRUE(listener.WaitUntilSatisfied());
ExtensionTestMessageListener listener_incognito("waiting", true);
EXPECT_TRUE(listener_incognito.WaitUntilSatisfied());
listener.Reply("go");
listener_incognito.Reply("go");
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
EXPECT_TRUE(catcher_incognito.GetNextResult()) << catcher.message();
}
// Tests that the APIs in an incognito-disabled extension don't see incognito
// events or callbacks.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoDisabled) {
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
ResultCatcher catcher;
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
ASSERT_TRUE(LoadExtension(test_data_dir_
.AppendASCII("incognito").AppendASCII("apis_disabled")));
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
// Test that opening a popup from an incognito browser window works properly.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoPopup) {
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
ResultCatcher catcher;
ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
.AppendASCII("incognito").AppendASCII("popup")));
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
Browser* incognito_browser = BrowserList::FindBrowserWithType(
browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
false);
// Simulate the incognito's browser action being clicked.
BrowserActionTestUtil(incognito_browser).Press(0);
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
<commit_msg>IncognitoSplitMode hanging or failing periodically<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/browser_action_test_util.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/extensions/user_script_master.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"
IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoNoScript) {
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
// Loads a simple extension which attempts to change the title of every page
// that loads to "modified".
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("incognito").AppendASCII("content_scripts")));
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
Browser* otr_browser = BrowserList::FindBrowserWithType(
browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
false);
TabContents* tab = otr_browser->GetSelectedTabContents();
// Verify the script didn't run.
bool result = false;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
tab->render_view_host(), L"",
L"window.domAutomationController.send(document.title == 'Unmodified')",
&result));
EXPECT_TRUE(result);
}
IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoYesScript) {
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
// Load a dummy extension. This just tests that we don't regress a
// crash fix when multiple incognito- and non-incognito-enabled extensions
// are mixed.
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("content_scripts").AppendASCII("all_frames")));
// Loads a simple extension which attempts to change the title of every page
// that loads to "modified".
ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_.AppendASCII("api_test")
.AppendASCII("incognito").AppendASCII("content_scripts")));
// Dummy extension #2.
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("content_scripts").AppendASCII("isolated_world1")));
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
Browser* otr_browser = BrowserList::FindBrowserWithType(
browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
false);
TabContents* tab = otr_browser->GetSelectedTabContents();
// Verify the script ran.
bool result = false;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
tab->render_view_host(), L"",
L"window.domAutomationController.send(document.title == 'modified')",
&result));
EXPECT_TRUE(result);
}
// Tests that an extension which is enabled for incognito mode doesn't
// accidentially create and incognito profile.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DontCreateIncognitoProfile) {
ASSERT_FALSE(browser()->profile()->HasOffTheRecordProfile());
ASSERT_TRUE(
RunExtensionTestIncognito("incognito/enumerate_tabs")) << message_;
ASSERT_FALSE(browser()->profile()->HasOffTheRecordProfile());
}
// Tests that the APIs in an incognito-enabled extension work properly.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Incognito) {
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
ResultCatcher catcher;
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
.AppendASCII("incognito").AppendASCII("apis")));
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
// Crashes flakily on Linux and Mac. http://crbug.com/53991
#if defined(OS_LINUX) || defined(OS_MACOSX)
#define MAYBE_IncognitoSplitMode FLAKY_IncognitoSplitMode
#else
#define MAYBE_IncognitoSplitMode IncognitoSplitMode
#endif
// Tests that the APIs in an incognito-enabled split-mode extension work
// properly.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_IncognitoSplitMode) {
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
// We need 2 ResultCatchers because we'll be running the same test in both
// regular and incognito mode.
ResultCatcher catcher;
catcher.RestrictToProfile(browser()->profile());
ResultCatcher catcher_incognito;
catcher_incognito.RestrictToProfile(
browser()->profile()->GetOffTheRecordProfile());
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
.AppendASCII("incognito").AppendASCII("split")));
// Wait for both extensions to be ready before telling them to proceed.
ExtensionTestMessageListener listener("waiting", true);
EXPECT_TRUE(listener.WaitUntilSatisfied());
ExtensionTestMessageListener listener_incognito("waiting", true);
EXPECT_TRUE(listener_incognito.WaitUntilSatisfied());
listener.Reply("go");
listener_incognito.Reply("go");
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
EXPECT_TRUE(catcher_incognito.GetNextResult()) << catcher.message();
}
// Tests that the APIs in an incognito-disabled extension don't see incognito
// events or callbacks.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoDisabled) {
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
ResultCatcher catcher;
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
ASSERT_TRUE(LoadExtension(test_data_dir_
.AppendASCII("incognito").AppendASCII("apis_disabled")));
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
// Test that opening a popup from an incognito browser window works properly.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoPopup) {
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(test_server()->Start());
ResultCatcher catcher;
ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
.AppendASCII("incognito").AppendASCII("popup")));
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
Browser* incognito_browser = BrowserList::FindBrowserWithType(
browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
false);
// Simulate the incognito's browser action being clicked.
BrowserActionTestUtil(incognito_browser).Press(0);
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/browser_action_test_util.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/extensions/user_script_master.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"
#if defined(OS_MAC)
// http://crbug.com/40002
#define IncognitoPopup \
DISABLE_IncognitoPopup
#endif
IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoNoScript) {
host_resolver()->AddRule("*", "127.0.0.1");
StartHTTPServer();
// Loads a simple extension which attempts to change the title of every page
// that loads to "modified".
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("incognito").AppendASCII("content_scripts")));
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
Browser* otr_browser = BrowserList::FindBrowserWithType(
browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
false);
TabContents* tab = otr_browser->GetSelectedTabContents();
// Verify the script didn't run.
bool result = false;
ui_test_utils::ExecuteJavaScriptAndExtractBool(
tab->render_view_host(), L"",
L"window.domAutomationController.send(document.title == 'Unmodified')",
&result);
EXPECT_TRUE(result);
}
IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoYesScript) {
host_resolver()->AddRule("*", "127.0.0.1");
StartHTTPServer();
// Load a dummy extension. This just tests that we don't regress a
// crash fix when multiple incognito- and non-incognito-enabled extensions
// are mixed.
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("content_scripts").AppendASCII("all_frames")));
// Loads a simple extension which attempts to change the title of every page
// that loads to "modified".
ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_.AppendASCII("api_test")
.AppendASCII("incognito").AppendASCII("content_scripts")));
// Dummy extension #2.
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("content_scripts").AppendASCII("isolated_world1")));
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
Browser* otr_browser = BrowserList::FindBrowserWithType(
browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
false);
TabContents* tab = otr_browser->GetSelectedTabContents();
// Verify the script ran.
bool result = false;
ui_test_utils::ExecuteJavaScriptAndExtractBool(
tab->render_view_host(), L"",
L"window.domAutomationController.send(document.title == 'modified')",
&result);
EXPECT_TRUE(result);
}
// Tests that the APIs in an incognito-enabled extension work properly.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Incognito) {
host_resolver()->AddRule("*", "127.0.0.1");
StartHTTPServer();
ResultCatcher catcher;
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
.AppendASCII("incognito").AppendASCII("apis")));
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
// Tests that the APIs in an incognito-disabled extension don't see incognito
// events or callbacks.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoDisabled) {
host_resolver()->AddRule("*", "127.0.0.1");
StartHTTPServer();
ResultCatcher catcher;
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
ASSERT_TRUE(LoadExtension(test_data_dir_
.AppendASCII("incognito").AppendASCII("apis_disabled")));
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
// Test that opening a popup from an incognito browser window works properly.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoPopup) {
host_resolver()->AddRule("*", "127.0.0.1");
StartHTTPServer();
ResultCatcher catcher;
ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
.AppendASCII("incognito").AppendASCII("popup")));
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
Browser* incognito_browser = BrowserList::FindBrowserWithType(
browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
false);
// Simulate the incognito's browser action being clicked.
BrowserActionTestUtil(incognito_browser).Press(0);
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
<commit_msg>Fix type in test name s/DISABLE/DISABLED/<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/browser_action_test_util.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/extensions/user_script_master.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"
#if defined(OS_MAC)
// http://crbug.com/40002
#define IncognitoPopup \
DISABLED_IncognitoPopup
#endif
IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoNoScript) {
host_resolver()->AddRule("*", "127.0.0.1");
StartHTTPServer();
// Loads a simple extension which attempts to change the title of every page
// that loads to "modified".
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("incognito").AppendASCII("content_scripts")));
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
Browser* otr_browser = BrowserList::FindBrowserWithType(
browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
false);
TabContents* tab = otr_browser->GetSelectedTabContents();
// Verify the script didn't run.
bool result = false;
ui_test_utils::ExecuteJavaScriptAndExtractBool(
tab->render_view_host(), L"",
L"window.domAutomationController.send(document.title == 'Unmodified')",
&result);
EXPECT_TRUE(result);
}
IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoYesScript) {
host_resolver()->AddRule("*", "127.0.0.1");
StartHTTPServer();
// Load a dummy extension. This just tests that we don't regress a
// crash fix when multiple incognito- and non-incognito-enabled extensions
// are mixed.
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("content_scripts").AppendASCII("all_frames")));
// Loads a simple extension which attempts to change the title of every page
// that loads to "modified".
ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_.AppendASCII("api_test")
.AppendASCII("incognito").AppendASCII("content_scripts")));
// Dummy extension #2.
ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
.AppendASCII("content_scripts").AppendASCII("isolated_world1")));
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
Browser* otr_browser = BrowserList::FindBrowserWithType(
browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
false);
TabContents* tab = otr_browser->GetSelectedTabContents();
// Verify the script ran.
bool result = false;
ui_test_utils::ExecuteJavaScriptAndExtractBool(
tab->render_view_host(), L"",
L"window.domAutomationController.send(document.title == 'modified')",
&result);
EXPECT_TRUE(result);
}
// Tests that the APIs in an incognito-enabled extension work properly.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Incognito) {
host_resolver()->AddRule("*", "127.0.0.1");
StartHTTPServer();
ResultCatcher catcher;
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
.AppendASCII("incognito").AppendASCII("apis")));
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
// Tests that the APIs in an incognito-disabled extension don't see incognito
// events or callbacks.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoDisabled) {
host_resolver()->AddRule("*", "127.0.0.1");
StartHTTPServer();
ResultCatcher catcher;
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
ASSERT_TRUE(LoadExtension(test_data_dir_
.AppendASCII("incognito").AppendASCII("apis_disabled")));
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
// Test that opening a popup from an incognito browser window works properly.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoPopup) {
host_resolver()->AddRule("*", "127.0.0.1");
StartHTTPServer();
ResultCatcher catcher;
ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
.AppendASCII("incognito").AppendASCII("popup")));
// Open incognito window and navigate to test page.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL("http://www.example.com:1337/files/extensions/test_file.html"));
Browser* incognito_browser = BrowserList::FindBrowserWithType(
browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
false);
// Simulate the incognito's browser action being clicked.
BrowserActionTestUtil(incognito_browser).Press(0);
EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
<|endoftext|> |
<commit_before><commit_msg>Dummy change to fix "svn: Inconsistent line ending style"<commit_after><|endoftext|> |
<commit_before>//! @file test-getlinkcount.cpp
//! @author George Fleming <[email protected]>
//! @brief Implements test for getLinkCount()
#include <gtest/gtest.h>
#include <pwd.h>
#include <fstream>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <unistd.h>
#include "getlinkcount.h"
class getLinkCountTest : public ::testing::Test
{
protected:
static const int bufSize = 64;
const std::string fileTemplate = "/tmp/createFile.XXXXXX";
char fileTemplateBuf[bufSize];
int32_t count;
char *file;
getLinkCountTest()
{
// since mkstemp modifies the template string, let's give it writable buffer
strcpy(fileTemplateBuf, fileTemplate.c_str());
int fd = mkstemp(fileTemplateBuf);
EXPECT_TRUE(fd != -1);
file = fileTemplateBuf;
}
void createFileForTesting(const std::string &theFile)
{
std::ofstream ofs;
ofs.open(theFile, std::ofstream::out);
ofs << "hi there, ms ostc!";
ofs.close();
}
std::string createHardLink(const std::string &origFile)
{
std::string newFile = origFile + "_link";
int ret = link(origFile.c_str(), newFile.c_str());
EXPECT_EQ(0, ret);
return newFile;
}
void removeFile(const std::string &fileName)
{
int ret = unlink(fileName.c_str());
EXPECT_EQ(0, ret);
}
};
TEST_F(getLinkCountTest, FilePathNameIsNull)
{
int32_t retVal = GetLinkCount(NULL, &count );
ASSERT_FALSE(retVal);
EXPECT_EQ(ERROR_INVALID_PARAMETER, errno);
}
TEST_F(getLinkCountTest, FilePathNameDoesNotExist)
{
std::string invalidFile = "/tmp/createFile";
int32_t retVal = GetLinkCount(invalidFile.c_str(), &count);
ASSERT_FALSE(retVal);
EXPECT_EQ(ERROR_FILE_NOT_FOUND, errno);
}
TEST_F(getLinkCountTest, LinkCountOfSinglyLinkedFile)
{
createFileForTesting(file);
int32_t retVal = GetLinkCount(file, &count);
ASSERT_TRUE(retVal);
EXPECT_EQ(1, count);
removeFile(file);
}
TEST_F(getLinkCountTest, LinkCountOfMultipliLinkedFile)
{
createFileForTesting(file);
std::string newFile = createHardLink(file);
int32_t retVal = GetLinkCount(file, &count);
ASSERT_TRUE(retVal);
EXPECT_EQ(2, count);
removeFile(file);
removeFile(newFile);
}
<commit_msg>spelling: locals in src/libpsl-native/test<commit_after>//! @file test-getlinkcount.cpp
//! @author George Fleming <[email protected]>
//! @brief Implements test for getLinkCount()
#include <gtest/gtest.h>
#include <pwd.h>
#include <fstream>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <unistd.h>
#include "getlinkcount.h"
class getLinkCountTest : public ::testing::Test
{
protected:
static const int bufSize = 64;
const std::string fileTemplate = "/tmp/createFile.XXXXXX";
char fileTemplateBuf[bufSize];
int32_t count;
char *file;
getLinkCountTest()
{
// since mkstemp modifies the template string, let's give it writable buffer
strcpy(fileTemplateBuf, fileTemplate.c_str());
int fd = mkstemp(fileTemplateBuf);
EXPECT_TRUE(fd != -1);
file = fileTemplateBuf;
}
void createFileForTesting(const std::string &theFile)
{
std::ofstream ofs;
ofs.open(theFile, std::ofstream::out);
ofs << "hi there, ms ostc!";
ofs.close();
}
std::string createHardLink(const std::string &origFile)
{
std::string newFile = origFile + "_link";
int ret = link(origFile.c_str(), newFile.c_str());
EXPECT_EQ(0, ret);
return newFile;
}
void removeFile(const std::string &fileName)
{
int ret = unlink(fileName.c_str());
EXPECT_EQ(0, ret);
}
};
TEST_F(getLinkCountTest, FilePathNameIsNull)
{
int32_t retVal = GetLinkCount(NULL, &count );
ASSERT_FALSE(retVal);
EXPECT_EQ(ERROR_INVALID_PARAMETER, errno);
}
TEST_F(getLinkCountTest, FilePathNameDoesNotExist)
{
std::string invalidFile = "/tmp/createFile";
int32_t retVal = GetLinkCount(invalidFile.c_str(), &count);
ASSERT_FALSE(retVal);
EXPECT_EQ(ERROR_FILE_NOT_FOUND, errno);
}
TEST_F(getLinkCountTest, LinkCountOfSinglyLinkedFile)
{
createFileForTesting(file);
int32_t retVal = GetLinkCount(file, &count);
ASSERT_TRUE(retVal);
EXPECT_EQ(1, count);
removeFile(file);
}
TEST_F(getLinkCountTest, LinkCountOfMultiplyLinkedFile)
{
createFileForTesting(file);
std::string newFile = createHardLink(file);
int32_t retVal = GetLinkCount(file, &count);
ASSERT_TRUE(retVal);
EXPECT_EQ(2, count);
removeFile(file);
removeFile(newFile);
}
<|endoftext|> |
<commit_before>/* junctions_annotator.cc -- class methods for `junctions annotate`
Copyright (c) 2015, The Griffith Lab
Author: Avinash Ramu <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE. */
#include <getopt.h>
#include <stdexcept>
#include <string>
#include "common.h"
#include "junctions_annotator.h"
#include "faidx.h"
using namespace std;
//Return stream to write output to
void JunctionsAnnotator::close_ofstream() {
if(ofs_.is_open())
ofs_.close();
}
//Return stream to write output to
//If output file is not empty, attempt to open
//If output file is empty, set to cout
void JunctionsAnnotator::set_ofstream_object(ofstream &out) {
if(output_file_ == "NA") {
copy_stream(cout, out);
return;
}
ofs_.open(output_file_.c_str());
if(!ofs_.is_open())
throw runtime_error("Unable to open " +
output_file_);
copy_stream(ofs_, out);
}
//Open junctions file
void JunctionsAnnotator::open_junctions() {
junctions_.Open();
}
//Open junctions file
void JunctionsAnnotator::close_junctions() {
junctions_.Close();
}
//Adjust the start and end of the junction
void JunctionsAnnotator::adjust_junction_ends(BED & line) {
//Adjust the start and end with block sizes
//The junction start is thick_start + block_size1
//The junction end is thick_end - block_size2 + 1
if(!line.fields.size() || line.fields[10].empty()) {
stringstream position;
position << line.chrom << ":" << line.start;
throw runtime_error("Block sizes not found. Invalid line. " +
position.str());
}
string blocksize_field = line.fields[10];
vector<int> block_sizes;
Tokenize(blocksize_field, block_sizes, ',');
line.start += block_sizes[0];
line.end -= block_sizes[1] - 1;
}
//Get a single line from the junctions file
bool JunctionsAnnotator::get_single_junction(BED & line) {
junctions_._status = BED_INVALID;
if(junctions_.GetNextBed(line) && junctions_._status == BED_VALID) {
adjust_junction_ends(line);
return true;
} else {
return false;
}
}
//Get the splice_site bases
bool JunctionsAnnotator::get_splice_site(AnnotatedJunction & line) {
string position1 = line.chrom + ":" +
num_to_str(line.start + 1) + "-" + num_to_str(line.start + 2);
string position2 = line.chrom + ":" +
num_to_str(line.end - 2) + "-" + num_to_str(line.end - 1);
string seq1, seq2;
try {
seq1 = get_reference_sequence(position1);
seq2 = get_reference_sequence(position2);
} catch (const runtime_error& e) {
throw e;
}
if(line.strand == "-") {
seq1 = rev_comp(seq1);
seq2 = rev_comp(seq2);
line.splice_site = seq2 + "-" + seq1;
} else {
line.splice_site = seq1 + "-" + seq2;
}
return true;
}
//Extract gtf info
bool JunctionsAnnotator::read_gtf() {
try {
gtf_.create_transcript_map();
gtf_.construct_junctions();
gtf_.sort_exons_within_transcripts();
gtf_.annotate_transcript_with_bins();
//gtf_.print_transcripts();
} catch (runtime_error e) {
throw e;
}
return true;
}
//Find overlap between transcript and junction on the negative strand,
//function returns true if either the acceptor or the donor is known
bool JunctionsAnnotator::overlap_ps(const vector<BED>& exons,
AnnotatedJunction & junction) {
//skip single exon genes
if(skip_single_exon_genes_ && exons.size() == 1) return false;
bool junction_start = false;
bool known_junction = false;
//check if transcript overlaps with junction
if(exons[0].start > junction.end &&
exons[exons.size() - 1].end < junction.start)
return false;
for(std::size_t i = 0; i < exons.size(); i++) {
if(exons[i].start > junction.end) {
//No need to look any further
//the rest of the exons are outside the junction
break;
}
//known junction
if(exons[i].end == junction.start &&
exons[i + 1].start == junction.end) {
junction.known_acceptor = true;
junction.known_donor = true;
junction.known_junction = true;
known_junction = true;
}
else {
if(!junction_start) {
if(exons[i].end >= junction.start) {
junction_start = true;
}
}
if(junction_start) {
if(exons[i].start > junction.start &&
exons[i].end < junction.end) {
junction.exons_skipped.insert(exons[i].name);
}
if(exons[i].start > junction.start) {
junction.donors_skipped.insert(exons[i].start);
}
if(exons[i].end < junction.end) {
junction.acceptors_skipped.insert(exons[i].end);
}
if(exons[i].end == junction.start) {
junction.known_donor = true;
}
//TODO - check for last exon
if(exons[i].start == junction.end) {
junction.known_acceptor = true;
}
}
}
}
annotate_anchor(junction);
return (junction.anchor != "N");
}
//Find overlap between transcript and junction on the negative strand,
//function returns true if either the acceptor or the donor is known
bool JunctionsAnnotator::overlap_ns(const vector<BED> & exons,
AnnotatedJunction & junction) {
//skip single exon genes
if(skip_single_exon_genes_ && exons.size() == 1) return false;
bool junction_start = false;
bool known_junction = false;
//check if transcript overlaps with junction
if(exons[0].end < junction.start ||
exons[exons.size() - 1].start > junction.end) {
return known_junction;
}
for(std::size_t i = 0; i < exons.size(); i++) {
if(exons[i].end < junction.start) {
//No need to look any further
//the rest of the exons are outside the junction
break;
}
//Check if this is a known junction
if(exons[i].start == junction.end &&
exons[i + 1].end == junction.start) {
junction.known_acceptor = true;
junction.known_donor = true;
junction.known_junction = true;
known_junction = true;
}
else {
if(!junction_start) {
if(exons[i].start <= junction.end) {
junction_start = true;
}
}
if(junction_start) {
if(exons[i].start > junction.start &&
exons[i].end < junction.end) {
junction.exons_skipped.insert(exons[i].name);
}
if(exons[i].start > junction.start) {
junction.donors_skipped.insert(exons[i].start);
}
if(exons[i].end < junction.end) {
junction.acceptors_skipped.insert(exons[i].end);
}
if(exons[i].start == junction.end) {
junction.known_donor = true;
}
if(exons[i].end == junction.start) {
junction.known_acceptor = true;
}
}
}
}
annotate_anchor(junction);
return (junction.anchor != "N");
}
//Annotate the anchor i.e is this a known/novel donor-acceptor pair
void JunctionsAnnotator::annotate_anchor(AnnotatedJunction & junction) {
junction.anchor = string("N");
if(junction.known_junction) {
junction.anchor = "DA";
} else {
if(junction.known_donor)
if(junction.known_acceptor)
junction.anchor = string("NDA");
else
junction.anchor = string("D");
else if(junction.known_acceptor)
junction.anchor = string("A");
}
}
//Check for overlap between a transcript and junctions
//Check if the junction we saw is a known junction
//Calculate exons_skipped, donors_skipped, acceptors_skipped
void JunctionsAnnotator::check_for_overlap(string transcript_id, AnnotatedJunction & junction) {
const vector<BED> & exons =
gtf_.get_exons_from_transcript(transcript_id);
if(!exons.size()) {
throw runtime_error("Unexpected error. No exons for transcript "
+ transcript_id);
}
string transcript_strand = exons[0].strand;
//Make sure the strands of the junction and transcript match
if(junction.strand != transcript_strand)
return;
//Remember exons are sorted from exon1 to last exon
if(junction.strand == "+") {
if(overlap_ps(exons, junction)) {
junction.transcripts_overlap.insert(transcript_id);
junction.genes_overlap.insert(
gtf_.get_gene_from_transcript(transcript_id));
}
} else if(junction.strand == "-") {
if(overlap_ns(exons, junction)) {
junction.transcripts_overlap.insert(transcript_id);
junction.genes_overlap.insert(
gtf_.get_gene_from_transcript(transcript_id));
}
} else {
throw runtime_error("\nUnknown strand " + junction.strand);
}
cerr << "\n\tDonors skipped " << junction.donors_skipped.size();
cerr << "\n\tExons skipped " << junction.exons_skipped.size();
cerr << "\n\tAcceptors skipped " << junction.acceptors_skipped.size();
cerr << "\n\tSplice site " << junction.anchor;
}
//Annotate with gtf
//Takes a single junction BED and annotates with GTF
void JunctionsAnnotator::annotate_junction_with_gtf(AnnotatedJunction & j1) {
//From BedTools
BIN start_bin, end_bin;
start_bin = (j1.start >> _binFirstShift);
end_bin = ((j1.end-1) >> _binFirstShift);
//We loop through each UCSC BIN level for feature A's chrom.
//For each BIN, we loop through each B feature and add it to
// hits if it meets all of the user's requests.
for (BINLEVEL i = 0; i < _binLevels; ++i) {
BIN offset = _binOffsetsExtended[i];
for (BIN b = (start_bin + offset); b <= (end_bin + offset); ++b) {
vector<string> transcripts = gtf_.transcripts_from_bin(j1.chrom, b);
if(transcripts.size())
for(std::size_t i = 0; i < transcripts.size(); i++)
check_for_overlap(transcripts[i], j1);
}
start_bin >>= _binNextShift;
end_bin >>= _binNextShift;
}
}
//Get the reference sequence at a particular coordinate
string JunctionsAnnotator::get_reference_sequence(string position) {
int len;
faidx_t *fai = fai_load(ref_.c_str());
char *s = fai_fetch(fai, position.c_str(), &len);
if(s == NULL)
throw runtime_error("Unable to extract FASTA sequence "
"for position " + position);
std::string seq(s);
free(s);
fai_destroy(fai);
return seq;
}
//Get the name of the GTF file
string JunctionsAnnotator::gtf_file() {
return gtf_.gtffile();
}
//Parse the options passed to this tool
int JunctionsAnnotator::parse_options(int argc, char *argv[]) {
optind = 1; //Reset before parsing again.
int c;
while((c = getopt(argc, argv, "Eo:")) != -1) {
switch(c) {
case 'E':
skip_single_exon_genes_ = false;
break;
case 'o':
output_file_ = string(optarg);
break;
default:
usage();
throw runtime_error("\nError parsing inputs!");
}
}
if(argc - optind >= 3) {
junctions_.bedFile = string(argv[optind++]);
ref_ = string(argv[optind++]);
gtf_.set_gtffile(string(argv[optind++]));
}
if(optind < argc ||
ref_ == "NA" ||
junctions_.bedFile.empty() ||
gtf_.gtffile().empty()) {
usage();
throw runtime_error("\nError parsing inputs!");
}
cerr << "\nReference: " << ref_;
cerr << "\nGTF: " << gtf_.gtffile();
cerr << "\nJunctions: " << junctions_.bedFile;
if(skip_single_exon_genes_)
cerr << "\nSkip single exon genes.";
if(!output_file_.empty())
cerr << "\nOutput file: " << output_file_;
return 0;
}
//Usage statement for this tool
int JunctionsAnnotator::usage() {
cout << "\nUsage:\t\t" << "regtools junctions annotate [options] junctions.bed ref.fa annotations.gtf";
cout << "\nOptions:\t" << "-E include single exon genes";
cout << "\n\t\t" << "-o Output file";
cout << "\n";
return 0;
}
<commit_msg>Add more detail to exception message<commit_after>/* junctions_annotator.cc -- class methods for `junctions annotate`
Copyright (c) 2015, The Griffith Lab
Author: Avinash Ramu <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE. */
#include <getopt.h>
#include <stdexcept>
#include <string>
#include "common.h"
#include "junctions_annotator.h"
#include "faidx.h"
using namespace std;
//Return stream to write output to
void JunctionsAnnotator::close_ofstream() {
if(ofs_.is_open())
ofs_.close();
}
//Return stream to write output to
//If output file is not empty, attempt to open
//If output file is empty, set to cout
void JunctionsAnnotator::set_ofstream_object(ofstream &out) {
if(output_file_ == "NA") {
copy_stream(cout, out);
return;
}
ofs_.open(output_file_.c_str());
if(!ofs_.is_open())
throw runtime_error("Unable to open " +
output_file_);
copy_stream(ofs_, out);
}
//Open junctions file
void JunctionsAnnotator::open_junctions() {
junctions_.Open();
}
//Open junctions file
void JunctionsAnnotator::close_junctions() {
junctions_.Close();
}
//Adjust the start and end of the junction
void JunctionsAnnotator::adjust_junction_ends(BED & line) {
//Adjust the start and end with block sizes
//The junction start is thick_start + block_size1
//The junction end is thick_end - block_size2 + 1
if(!line.fields.size() || line.fields[10].empty()) {
stringstream position;
position << line.chrom << ":" << line.start;
throw runtime_error("Block sizes not found. Invalid line. " +
position.str());
}
string blocksize_field = line.fields[10];
vector<int> block_sizes;
Tokenize(blocksize_field, block_sizes, ',');
line.start += block_sizes[0];
line.end -= block_sizes[1] - 1;
}
//Get a single line from the junctions file
bool JunctionsAnnotator::get_single_junction(BED & line) {
junctions_._status = BED_INVALID;
if(junctions_.GetNextBed(line) && junctions_._status == BED_VALID) {
adjust_junction_ends(line);
return true;
} else {
return false;
}
}
//Get the splice_site bases
bool JunctionsAnnotator::get_splice_site(AnnotatedJunction & line) {
string position1 = line.chrom + ":" +
num_to_str(line.start + 1) + "-" + num_to_str(line.start + 2);
string position2 = line.chrom + ":" +
num_to_str(line.end - 2) + "-" + num_to_str(line.end - 1);
string seq1, seq2;
try {
seq1 = get_reference_sequence(position1);
seq2 = get_reference_sequence(position2);
} catch (const runtime_error& e) {
throw e;
}
if(line.strand == "-") {
seq1 = rev_comp(seq1);
seq2 = rev_comp(seq2);
line.splice_site = seq2 + "-" + seq1;
} else {
line.splice_site = seq1 + "-" + seq2;
}
return true;
}
//Extract gtf info
bool JunctionsAnnotator::read_gtf() {
try {
gtf_.create_transcript_map();
gtf_.construct_junctions();
gtf_.sort_exons_within_transcripts();
gtf_.annotate_transcript_with_bins();
//gtf_.print_transcripts();
} catch (runtime_error e) {
throw e;
}
return true;
}
//Find overlap between transcript and junction on the negative strand,
//function returns true if either the acceptor or the donor is known
bool JunctionsAnnotator::overlap_ps(const vector<BED>& exons,
AnnotatedJunction & junction) {
//skip single exon genes
if(skip_single_exon_genes_ && exons.size() == 1) return false;
bool junction_start = false;
bool known_junction = false;
//check if transcript overlaps with junction
if(exons[0].start > junction.end &&
exons[exons.size() - 1].end < junction.start)
return false;
for(std::size_t i = 0; i < exons.size(); i++) {
if(exons[i].start > junction.end) {
//No need to look any further
//the rest of the exons are outside the junction
break;
}
//known junction
if(exons[i].end == junction.start &&
exons[i + 1].start == junction.end) {
junction.known_acceptor = true;
junction.known_donor = true;
junction.known_junction = true;
known_junction = true;
}
else {
if(!junction_start) {
if(exons[i].end >= junction.start) {
junction_start = true;
}
}
if(junction_start) {
if(exons[i].start > junction.start &&
exons[i].end < junction.end) {
junction.exons_skipped.insert(exons[i].name);
}
if(exons[i].start > junction.start) {
junction.donors_skipped.insert(exons[i].start);
}
if(exons[i].end < junction.end) {
junction.acceptors_skipped.insert(exons[i].end);
}
if(exons[i].end == junction.start) {
junction.known_donor = true;
}
//TODO - check for last exon
if(exons[i].start == junction.end) {
junction.known_acceptor = true;
}
}
}
}
annotate_anchor(junction);
return (junction.anchor != "N");
}
//Find overlap between transcript and junction on the negative strand,
//function returns true if either the acceptor or the donor is known
bool JunctionsAnnotator::overlap_ns(const vector<BED> & exons,
AnnotatedJunction & junction) {
//skip single exon genes
if(skip_single_exon_genes_ && exons.size() == 1) return false;
bool junction_start = false;
bool known_junction = false;
//check if transcript overlaps with junction
if(exons[0].end < junction.start ||
exons[exons.size() - 1].start > junction.end) {
return known_junction;
}
for(std::size_t i = 0; i < exons.size(); i++) {
if(exons[i].end < junction.start) {
//No need to look any further
//the rest of the exons are outside the junction
break;
}
//Check if this is a known junction
if(exons[i].start == junction.end &&
exons[i + 1].end == junction.start) {
junction.known_acceptor = true;
junction.known_donor = true;
junction.known_junction = true;
known_junction = true;
}
else {
if(!junction_start) {
if(exons[i].start <= junction.end) {
junction_start = true;
}
}
if(junction_start) {
if(exons[i].start > junction.start &&
exons[i].end < junction.end) {
junction.exons_skipped.insert(exons[i].name);
}
if(exons[i].start > junction.start) {
junction.donors_skipped.insert(exons[i].start);
}
if(exons[i].end < junction.end) {
junction.acceptors_skipped.insert(exons[i].end);
}
if(exons[i].start == junction.end) {
junction.known_donor = true;
}
if(exons[i].end == junction.start) {
junction.known_acceptor = true;
}
}
}
}
annotate_anchor(junction);
return (junction.anchor != "N");
}
//Annotate the anchor i.e is this a known/novel donor-acceptor pair
void JunctionsAnnotator::annotate_anchor(AnnotatedJunction & junction) {
junction.anchor = string("N");
if(junction.known_junction) {
junction.anchor = "DA";
} else {
if(junction.known_donor)
if(junction.known_acceptor)
junction.anchor = string("NDA");
else
junction.anchor = string("D");
else if(junction.known_acceptor)
junction.anchor = string("A");
}
}
//Check for overlap between a transcript and junctions
//Check if the junction we saw is a known junction
//Calculate exons_skipped, donors_skipped, acceptors_skipped
void JunctionsAnnotator::check_for_overlap(string transcript_id, AnnotatedJunction & junction) {
const vector<BED> & exons =
gtf_.get_exons_from_transcript(transcript_id);
if(!exons.size()) {
throw runtime_error("Unexpected error. No exons for transcript "
+ transcript_id);
}
string transcript_strand = exons[0].strand;
//Make sure the strands of the junction and transcript match
if(junction.strand != transcript_strand)
return;
//Remember exons are sorted from exon1 to last exon
if(junction.strand == "+") {
if(overlap_ps(exons, junction)) {
junction.transcripts_overlap.insert(transcript_id);
junction.genes_overlap.insert(
gtf_.get_gene_from_transcript(transcript_id));
}
} else if(junction.strand == "-") {
if(overlap_ns(exons, junction)) {
junction.transcripts_overlap.insert(transcript_id);
junction.genes_overlap.insert(
gtf_.get_gene_from_transcript(transcript_id));
}
} else {
throw runtime_error("\nUnknown strand " + junction.strand);
}
cerr << "\n\tDonors skipped " << junction.donors_skipped.size();
cerr << "\n\tExons skipped " << junction.exons_skipped.size();
cerr << "\n\tAcceptors skipped " << junction.acceptors_skipped.size();
cerr << "\n\tSplice site " << junction.anchor;
}
//Annotate with gtf
//Takes a single junction BED and annotates with GTF
void JunctionsAnnotator::annotate_junction_with_gtf(AnnotatedJunction & j1) {
//From BedTools
BIN start_bin, end_bin;
start_bin = (j1.start >> _binFirstShift);
end_bin = ((j1.end-1) >> _binFirstShift);
//We loop through each UCSC BIN level for feature A's chrom.
//For each BIN, we loop through each B feature and add it to
// hits if it meets all of the user's requests.
for (BINLEVEL i = 0; i < _binLevels; ++i) {
BIN offset = _binOffsetsExtended[i];
for (BIN b = (start_bin + offset); b <= (end_bin + offset); ++b) {
vector<string> transcripts = gtf_.transcripts_from_bin(j1.chrom, b);
if(transcripts.size())
for(std::size_t i = 0; i < transcripts.size(); i++)
check_for_overlap(transcripts[i], j1);
}
start_bin >>= _binNextShift;
end_bin >>= _binNextShift;
}
}
//Get the reference sequence at a particular coordinate
string JunctionsAnnotator::get_reference_sequence(string position) {
int len;
faidx_t *fai = fai_load(ref_.c_str());
char *s = fai_fetch(fai, position.c_str(), &len);
if(s == NULL)
throw runtime_error("Unable to extract FASTA sequence "
"for position " + position);
std::string seq(s);
free(s);
fai_destroy(fai);
return seq;
}
//Get the name of the GTF file
string JunctionsAnnotator::gtf_file() {
return gtf_.gtffile();
}
//Parse the options passed to this tool
int JunctionsAnnotator::parse_options(int argc, char *argv[]) {
optind = 1; //Reset before parsing again.
int c;
while((c = getopt(argc, argv, "Eo:")) != -1) {
switch(c) {
case 'E':
skip_single_exon_genes_ = false;
break;
case 'o':
output_file_ = string(optarg);
break;
default:
usage();
throw runtime_error("\nError parsing inputs!(1)");
}
}
if(argc - optind >= 3) {
junctions_.bedFile = string(argv[optind++]);
ref_ = string(argv[optind++]);
gtf_.set_gtffile(string(argv[optind++]));
}
if(optind < argc ||
ref_ == "NA" ||
junctions_.bedFile.empty() ||
gtf_.gtffile().empty()) {
usage();
throw runtime_error("\nError parsing inputs!(2)");
}
cerr << "\nReference: " << ref_;
cerr << "\nGTF: " << gtf_.gtffile();
cerr << "\nJunctions: " << junctions_.bedFile;
if(skip_single_exon_genes_)
cerr << "\nSkip single exon genes.";
if(!output_file_.empty())
cerr << "\nOutput file: " << output_file_;
return 0;
}
//Usage statement for this tool
int JunctionsAnnotator::usage() {
cout << "\nUsage:\t\t" << "regtools junctions annotate [options] junctions.bed ref.fa annotations.gtf";
cout << "\nOptions:\t" << "-E include single exon genes";
cout << "\n\t\t" << "-o Output file";
cout << "\n";
return 0;
}
<|endoftext|> |
<commit_before>#ifndef MANGAPP_MANGA_LIBRARY_HPP
#define MANGAPP_MANGA_LIBRARY_HPP
#include "manga_directory_entry.hpp"
#include "library.hpp"
#include "manga_entry.hpp"
#include "http_helper.hpp"
#include <string>
#include <vector>
namespace json11
{
class Json;
}
static std::vector<std::wstring> const g_archive_extensions = { L".rar", L".cbr",
L".zip", L".cbz",
L".7z", L".cb7" };
template<class Container, class Element>
static inline bool is_in_container(Container const & container, Element const & element)
{
return std::find(container.cbegin(), container.cend(), element) != container.cend();
}
namespace mangapp
{
class manga_library : public base::library<manga_directory>
{
public:
typedef base::library<manga_directory>::key_type key_type;
manga_library(std::vector<std::wstring> const & library_paths);
manga_library(std::vector<std::string> const & library_paths);
manga_library(json11::Json const & library_paths);
virtual ~manga_library();
/**
* Converts the manga entries to a JSON object.
*
* @return a JSON object representing the manga entries
*/
json11::Json const get_list() const;
json11::Json const get_files(size_t key) const;
/**
* Reads the thumbnail of a manga from its folder or from an archive.
* Retrieval from an archive is NOT implemented yet.
*
* @param key the key of the manga
* @param folder indicates whether or not to retrieve from the folder or archive
* @param index index of the archive in the folder
* @return a string containing the thumbnail's contents
*/
std::string get_thumbnail(key_type key, bool folder, uint32_t index = 0) const;
/**
* Gets the details of a manga from mangaupdates.com
*
* @param key the key of the manga
* @param on_event a function object that will be called on success or failure
*/
void get_manga_details(key_type key, std::function<void(json11::Json)> on_event);
/**
* Gets the desired image from an archive.
*
* @param key the key of the manga
* @param key the key of the archive file
* @param index the index of the image
* @return a string containing the image's contents
*/
std::string get_image(key_type key, key_type file_key, size_t index) const;
protected:
/**
* Asynchronously searches mangaupdates for the supplied name of the manga.
* The results are stored in a JSON object and passed to the 'on_event' callback.
*
* @param name the name of the manga
* @param on_event a callback that handles the JSON object
*/
void search_mangaupdates_for(std::string const & name, std::function<void(json11::Json)> on_event);
private:
http_helper m_http_helper;
};
}
#endif<commit_msg>Tab to space<commit_after>#ifndef MANGAPP_MANGA_LIBRARY_HPP
#define MANGAPP_MANGA_LIBRARY_HPP
#include "manga_directory_entry.hpp"
#include "library.hpp"
#include "manga_entry.hpp"
#include "http_helper.hpp"
#include <string>
#include <vector>
namespace json11
{
class Json;
}
static std::vector<std::wstring> const g_archive_extensions = { L".rar", L".cbr",
L".zip", L".cbz",
L".7z", L".cb7" };
template<class Container, class Element>
static inline bool is_in_container(Container const & container, Element const & element)
{
return std::find(container.cbegin(), container.cend(), element) != container.cend();
}
namespace mangapp
{
class manga_library : public base::library<manga_directory>
{
public:
typedef base::library<manga_directory>::key_type key_type;
manga_library(std::vector<std::wstring> const & library_paths);
manga_library(std::vector<std::string> const & library_paths);
manga_library(json11::Json const & library_paths);
virtual ~manga_library();
/**
* Converts the manga entries to a JSON object.
*
* @return a JSON object representing the manga entries
*/
json11::Json const get_list() const;
json11::Json const get_files(size_t key) const;
/**
* Reads the thumbnail of a manga from its folder or from an archive.
* Retrieval from an archive is NOT implemented yet.
*
* @param key the key of the manga
* @param folder indicates whether or not to retrieve from the folder or archive
* @param index index of the archive in the folder
* @return a string containing the thumbnail's contents
*/
std::string get_thumbnail(key_type key, bool folder, uint32_t index = 0) const;
/**
* Gets the details of a manga from mangaupdates.com
*
* @param key the key of the manga
* @param on_event a function object that will be called on success or failure
*/
void get_manga_details(key_type key, std::function<void(json11::Json)> on_event);
/**
* Gets the desired image from an archive.
*
* @param key the key of the manga
* @param key the key of the archive file
* @param index the index of the image
* @return a string containing the image's contents
*/
std::string get_image(key_type key, key_type file_key, size_t index) const;
protected:
/**
* Asynchronously searches mangaupdates for the supplied name of the manga.
* The results are stored in a JSON object and passed to the 'on_event' callback.
*
* @param name the name of the manga
* @param on_event a callback that handles the JSON object
*/
void search_mangaupdates_for(std::string const & name, std::function<void(json11::Json)> on_event);
private:
http_helper m_http_helper;
};
}
#endif<|endoftext|> |
<commit_before>// ========================================================================== //
// This file is part of Sara, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2015-2017 David Ok <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //
#define BOOST_TEST_MODULE "FeatureDescriptors/SIFT Descriptor"
#include <boost/test/unit_test.hpp>
#include <DO/Sara/FeatureDescriptors/SIFT.hpp>
using namespace std;
using namespace DO::Sara;
BOOST_AUTO_TEST_SUITE(TestSIFTDescriptors)
BOOST_AUTO_TEST_CASE(test_computation)
{
constexpr auto N{5};
auto grad_polar_coords = Image<Vector2f>{N, N};
const Point2f c{grad_polar_coords.sizes().cast<float>() / 2.f};
const Vector2f g{Vector2f::Zero()};
const auto theta = atan2(0 - c.y(), 0 - c.x());
// Set all gradients to zero except at coords (gx, gy).
for (int y = 0; y < grad_polar_coords.height(); ++y)
for (int x = 0; x < grad_polar_coords.width(); ++x)
grad_polar_coords(x,y) = Vector2f::Zero();
grad_polar_coords(0, 0) = Vector2f{ 1.f, theta };
auto feature = OERegion{ c, 1.f };
auto sift = ComputeSIFTDescriptor<>{}(feature, grad_polar_coords);
// TODO.
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>MAINT: tentative fix for Travis CI with gcc 4.8.<commit_after>// ========================================================================== //
// This file is part of Sara, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2015-2017 David Ok <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //
#define BOOST_TEST_MODULE "FeatureDescriptors/SIFT Descriptor"
#include <boost/test/unit_test.hpp>
#include <DO/Sara/FeatureDescriptors/SIFT.hpp>
using namespace std;
using namespace DO::Sara;
BOOST_AUTO_TEST_SUITE(TestSIFTDescriptors)
BOOST_AUTO_TEST_CASE(test_computation)
{
constexpr int N{5};
auto grad_polar_coords = Image<Vector2f>{N, N};
const Point2f c{grad_polar_coords.sizes().cast<float>() / 2.f};
const Vector2f g{Vector2f::Zero()};
const auto theta = atan2(0 - c.y(), 0 - c.x());
// Set all gradients to zero except at coords (gx, gy).
for (int y = 0; y < grad_polar_coords.height(); ++y)
for (int x = 0; x < grad_polar_coords.width(); ++x)
grad_polar_coords(x,y) = Vector2f::Zero();
grad_polar_coords(0, 0) = Vector2f{ 1.f, theta };
auto feature = OERegion{ c, 1.f };
auto sift = ComputeSIFTDescriptor<>{}(feature, grad_polar_coords);
// TODO.
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>#ifndef MANIFOLDS_FUNCTION_INTERFACE_HH
#define MANIFOLDS_FUNCTION_INTERFACE_HH
#include <utility>
namespace manifolds {
//Tag
struct Function
{
static const bool stateless = false;
};
//Tag
struct MultiFunction : Function
{
};
template <class T>
struct is_stateless
{
static const bool value = T::stateless;
typedef std::integral_constant<
bool, value> type;
};
template <class Arg, class ... Args>
struct and_ : std::conditional<
Arg::value, and_<Args...>, std::false_type>{};
template <class Arg>
struct and_<Arg> : std::conditional<
Arg::value, std::true_type, std::false_type>{};
}
#endif
<commit_msg>Added abelian metadata tag<commit_after>#ifndef MANIFOLDS_FUNCTION_INTERFACE_HH
#define MANIFOLDS_FUNCTION_INTERFACE_HH
#include <utility>
namespace manifolds {
//Tag
struct Function
{
static const bool stateless = false;
//Means you can change the order of
//Multiplications, ie A*B == B*A
static const bool abelian_arithmetic = true;
};
//Tag
struct MultiFunction : Function
{
};
template <class T>
struct is_stateless
{
static const bool value = T::stateless;
typedef std::integral_constant<
bool, value> type;
};
template <class T>
struct has_abelian_arithmetic
{
static const bool value = T::abelian_arithmetic;
typedef std::integral_constant<
bool, value> type;
};
template <class Arg, class ... Args>
struct and_ : std::conditional<
Arg::value, and_<Args...>, std::false_type>::type{};
template <class Arg>
struct and_<Arg> : std::conditional<
Arg::value, std::true_type, std::false_type>::type{};
template <int N>
using int_ = std::integral_constant<int, N>;
template <bool B>
using bool_ = std::integral_constant<bool, B>;
}
#endif
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "clocks-impl.hh"
#include <seastar/core/lowres_clock.hh>
#include <chrono>
#include <optional>
class gc_clock final {
public:
using base = seastar::lowres_system_clock;
using rep = int64_t;
using period = std::ratio<1, 1>; // seconds
using duration = std::chrono::duration<rep, period>;
using time_point = std::chrono::time_point<gc_clock, duration>;
static constexpr auto is_steady = base::is_steady;
static constexpr std::time_t to_time_t(time_point t) {
return std::chrono::duration_cast<std::chrono::seconds>(t.time_since_epoch()).count();
}
static constexpr time_point from_time_t(std::time_t t) {
return time_point(std::chrono::duration_cast<duration>(std::chrono::seconds(t)));
}
static time_point now() {
return time_point(std::chrono::duration_cast<duration>(base::now().time_since_epoch())) + get_clocks_offset();
}
static int32_t as_int32(duration d) {
auto count = d.count();
int32_t count_32 = static_cast<int32_t>(count);
if (count_32 != count) {
throw std::runtime_error("Duration too big");
}
return count_32;
}
static int32_t as_int32(time_point tp) {
return as_int32(tp.time_since_epoch());
}
};
using expiry_opt = std::optional<gc_clock::time_point>;
using ttl_opt = std::optional<gc_clock::duration>;
// 20 years in seconds
static constexpr gc_clock::duration max_ttl = gc_clock::duration{20 * 365 * 24 * 60 * 60};
std::ostream& operator<<(std::ostream& os, gc_clock::time_point tp);
<commit_msg>gc_clock: Fix hashing to be backwards-compatible<commit_after>/*
* Copyright (C) 2015 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "clocks-impl.hh"
#include "hashing.hh"
#include <seastar/core/lowres_clock.hh>
#include <chrono>
#include <optional>
class gc_clock final {
public:
using base = seastar::lowres_system_clock;
using rep = int64_t;
using period = std::ratio<1, 1>; // seconds
using duration = std::chrono::duration<rep, period>;
using time_point = std::chrono::time_point<gc_clock, duration>;
static constexpr auto is_steady = base::is_steady;
static constexpr std::time_t to_time_t(time_point t) {
return std::chrono::duration_cast<std::chrono::seconds>(t.time_since_epoch()).count();
}
static constexpr time_point from_time_t(std::time_t t) {
return time_point(std::chrono::duration_cast<duration>(std::chrono::seconds(t)));
}
static time_point now() {
return time_point(std::chrono::duration_cast<duration>(base::now().time_since_epoch())) + get_clocks_offset();
}
static int32_t as_int32(duration d) {
auto count = d.count();
int32_t count_32 = static_cast<int32_t>(count);
if (count_32 != count) {
throw std::runtime_error("Duration too big");
}
return count_32;
}
static int32_t as_int32(time_point tp) {
return as_int32(tp.time_since_epoch());
}
};
using expiry_opt = std::optional<gc_clock::time_point>;
using ttl_opt = std::optional<gc_clock::duration>;
// 20 years in seconds
static constexpr gc_clock::duration max_ttl = gc_clock::duration{20 * 365 * 24 * 60 * 60};
std::ostream& operator<<(std::ostream& os, gc_clock::time_point tp);
template<>
struct appending_hash<gc_clock::time_point> {
template<typename Hasher>
void operator()(Hasher& h, gc_clock::time_point t) const {
// Remain backwards-compatible with the 32-bit duration::rep (refs #4460).
uint64_t d64 = t.time_since_epoch().count();
feed_hash(h, uint32_t(d64 & 0xffff'ffff));
uint32_t msb = d64 >> 32;
if (msb) {
feed_hash(h, msb);
}
}
};
<|endoftext|> |
<commit_before>#include <sys/ioctl.h>
#include <fcntl.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/utsname.h>
#include <sys/select.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <netdb.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include "sockio.h"
char const* Socket::unixSocketDir = "/tmp/";
static void setGlobalSocketOptions(int sd)
{
int optval = 1;
setsockopt(sd, IPPROTO_TCP, TCP_NODELAY, (char const*)&optval, sizeof(int));
}
const char* SocketError::what() const throw()
{
char* error = new char[strlen(msg) + 32];
sprintf(error, "%s: %d\n", msg, errno);
return error;
}
bool Socket::isLocalHost(char const* address)
{
struct utsname localHost;
uname(&localHost);
size_t localHostNodeNameLen = strlen(localHost.nodename);
return strncmp(address, "localhost:", 10) == 0
|| (strncmp(address, localHost.nodename, localHostNodeNameLen) == 0 &&
(address[localHostNodeNameLen] == ':' || address[localHostNodeNameLen] == '.'));
}
Socket* Socket::createGlobal(int port, size_t listenQueueSize)
{
struct sockaddr_in sock;
sock.sin_family = AF_INET;
sock.sin_addr.s_addr = htonl(INADDR_ANY);
sock.sin_port = htons(port);
int sd = socket(AF_INET, SOCK_STREAM, 0);
if (sd < 0) {
throw SocketError("Failed to create global socket");
}
int on = 1;
setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof on);
if (bind(sd, (sockaddr*)&sock, sizeof(sock)) < 0) {
throw SocketError("Failed to bind global socket");
}
if (listen(sd, listenQueueSize) < 0) {
throw SocketError("Failed to listen global socket");
}
setGlobalSocketOptions(sd);
return new Socket(sd, false);
}
Socket* Socket::createLocal(int port, size_t listenQueueSize)
{
struct sockaddr sock;
sock.sa_family = AF_UNIX;
size_t len = ((char*)sock.sa_data - (char*)&sock) + sprintf(sock.sa_data, "%sp%u", unixSocketDir, port);
unlink(sock.sa_data); /* remove file if existed */
int sd = socket(AF_UNIX, SOCK_STREAM, 0);
if (sd < 0) {
throw SocketError("Failed to create local socket");
}
if (bind(sd, &sock, len) < 0) {
throw SocketError("Failed to bind local socket");
}
if (listen(sd, listenQueueSize) < 0) {
throw SocketError("Failed to listen local socket");
}
return new Socket(sd, true);
}
static bool getAddrsByName(const char *hostname, unsigned* addrs, size_t* n_addrs)
{
struct sockaddr_in sin;
struct hostent* hp;
size_t i;
sin.sin_addr.s_addr = inet_addr(hostname);
if (sin.sin_addr.s_addr != INADDR_NONE) {
memcpy(&addrs[0], &sin.sin_addr.s_addr, sizeof(sin.sin_addr.s_addr));
*n_addrs = 1;
return true;
}
hp = gethostbyname(hostname);
if (hp == NULL || hp->h_addrtype != AF_INET) {
return false;
}
for (i = 0; hp->h_addr_list[i] != NULL && i < *n_addrs; i++) {
memcpy(&addrs[i], hp->h_addr_list[i], sizeof(addrs[i]));
}
*n_addrs = i;
return true;
}
Socket* Socket::connect(char const* address, size_t maxAttempts)
{
char* sep = (char*)strchr(address, ':');
if (sep == NULL) {
throw SocketError("Port is not specified");
}
int port = atoi(sep+1);
int rc = 0;
int sd;
while (1) {
bool isLocal;
if (isLocalHost(address)) {
struct sockaddr sock;
isLocal = true;
sock.sa_family = AF_UNIX;
sd = socket(AF_UNIX, SOCK_STREAM, 0);
if (sd < 0) {
throw SocketError("Failed to create local socket");
}
size_t len = ((char*)sock.sa_data - (char*)&sock) + sprintf(sock.sa_data, "%sp%u", unixSocketDir, port);
do {
rc = ::connect(sd, &sock, len);
} while (rc < 0 && errno == EINTR);
} else {
struct sockaddr_in sock_inet;
unsigned addrs[128];
size_t n_addrs = sizeof(addrs) / sizeof(addrs[0]);
isLocal = false;
sock_inet.sin_family = AF_INET;
sock_inet.sin_port = htons(port);
size_t hostLen = sep - address;
char* host = new char[hostLen+1];
memcpy(host, address, hostLen);
host[hostLen] = '\0';
if (!getAddrsByName(host, addrs, &n_addrs)) {
throw SocketError("Failed to resolve addresses");
}
delete[] host;
sd = socket(AF_INET, SOCK_STREAM, 0);
if (sd < 0) {
throw SocketError("Failed to create global socket");
}
for (size_t i = 0; i < n_addrs; ++i) {
memcpy(&sock_inet.sin_addr, &addrs[i], sizeof sock_inet.sin_addr);
do {
rc = ::connect(sd, (struct sockaddr*)&sock_inet, sizeof(sock_inet));
} while (rc < 0 && errno == EINTR);
if (rc >= 0 || errno == EINPROGRESS) {
if (rc >= 0) {
setGlobalSocketOptions(sd);
}
break;
}
}
}
if (rc < 0) {
::close(sd);
if (errno == EINPROGRESS) {
throw SocketError("Failed to connect socket");
}
if (errno == ENOENT || errno == ECONNREFUSED) {
if (maxAttempts-- != 0) {
sleep(1);
continue;
}
}
throw SocketError("Connection can not be establish");
} else {
return new Socket(sd, isLocal);
}
}
}
void Socket::read(void* buf, size_t size)
{
size_t offs = 0;
while (offs < size) {
int rc = recv(sd, (char*)buf + offs, size - offs, 0);
if (rc <= 0) {
if (errno == EINTR) {
continue;
}
throw SocketError("Failed to read data from socket");
}
offs += rc;
}
}
void Socket::write(void const* buf, size_t size)
{
size_t offs = 0;
while (offs < size) {
int rc = send(sd, (char const*)buf + offs, size - offs, 0);
if (rc <= 0) {
if (errno == EINTR) {
continue;
}
throw SocketError("Failed to write data to socket");
}
offs += rc;
}
}
Socket* Socket::accept()
{
int ns = ::accept(sd, NULL, NULL);
if (ns < 0) {
throw SocketError("Failed to accept socket");
}
setGlobalSocketOptions(ns);
return new Socket(ns, localSocket);
}
Socket* Socket::select(size_t nSockets, Socket** sockets)
{
static size_t rr = 0;
while (true) {
fd_set events;
FD_ZERO(&events);
int max_sd = 0;
for (size_t i = 0; i < nSockets; i++) {
if (sockets[i] != NULL) {
int sd = sockets[i]->sd;
if (sd > max_sd) {
max_sd = sd;
}
FD_SET(sd, &events);
}
}
int rc = ::select(max_sd+1, &events, NULL, NULL, NULL);
if (rc < 0) {
if (rc != EINTR) {
throw SocketError("Failed to select socket");
}
} else {
for (size_t i = 0, j = rr; i < nSockets; i++) {
j = (j + 1) % nSockets; // round robin
if (sockets[j] && FD_ISSET(sockets[j]->sd, &events)) {
rr = j;
return sockets[j];
}
}
}
}
}
Socket::~Socket()
{
::close(sd);
}
<commit_msg>Use epoll instead of select<commit_after>#include <sys/ioctl.h>
#include <fcntl.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/utsname.h>
#include <sys/select.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <netdb.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include "sockio.h"
#ifndef USE_EPOLL
#define USE_EPOLL 1
#endif
#if USE_EPOLL
#include <sys/epoll.h>
#endif
char const* Socket::unixSocketDir = "/tmp/";
static void setGlobalSocketOptions(int sd)
{
int optval = 1;
setsockopt(sd, IPPROTO_TCP, TCP_NODELAY, (char const*)&optval, sizeof(int));
}
const char* SocketError::what() const throw()
{
char* error = new char[strlen(msg) + 32];
sprintf(error, "%s: %d\n", msg, errno);
return error;
}
bool Socket::isLocalHost(char const* address)
{
struct utsname localHost;
uname(&localHost);
size_t localHostNodeNameLen = strlen(localHost.nodename);
return strncmp(address, "localhost:", 10) == 0
|| (strncmp(address, localHost.nodename, localHostNodeNameLen) == 0 &&
(address[localHostNodeNameLen] == ':' || address[localHostNodeNameLen] == '.'));
}
Socket* Socket::createGlobal(int port, size_t listenQueueSize)
{
struct sockaddr_in sock;
sock.sin_family = AF_INET;
sock.sin_addr.s_addr = htonl(INADDR_ANY);
sock.sin_port = htons(port);
int sd = socket(AF_INET, SOCK_STREAM, 0);
if (sd < 0) {
throw SocketError("Failed to create global socket");
}
int on = 1;
setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof on);
if (bind(sd, (sockaddr*)&sock, sizeof(sock)) < 0) {
throw SocketError("Failed to bind global socket");
}
if (listen(sd, listenQueueSize) < 0) {
throw SocketError("Failed to listen global socket");
}
setGlobalSocketOptions(sd);
return new Socket(sd, false);
}
Socket* Socket::createLocal(int port, size_t listenQueueSize)
{
struct sockaddr sock;
sock.sa_family = AF_UNIX;
size_t len = ((char*)sock.sa_data - (char*)&sock) + sprintf(sock.sa_data, "%sp%u", unixSocketDir, port);
unlink(sock.sa_data); /* remove file if existed */
int sd = socket(AF_UNIX, SOCK_STREAM, 0);
if (sd < 0) {
throw SocketError("Failed to create local socket");
}
if (bind(sd, &sock, len) < 0) {
throw SocketError("Failed to bind local socket");
}
if (listen(sd, listenQueueSize) < 0) {
throw SocketError("Failed to listen local socket");
}
return new Socket(sd, true);
}
static bool getAddrsByName(const char *hostname, unsigned* addrs, size_t* n_addrs)
{
struct sockaddr_in sin;
struct hostent* hp;
size_t i;
sin.sin_addr.s_addr = inet_addr(hostname);
if (sin.sin_addr.s_addr != INADDR_NONE) {
memcpy(&addrs[0], &sin.sin_addr.s_addr, sizeof(sin.sin_addr.s_addr));
*n_addrs = 1;
return true;
}
hp = gethostbyname(hostname);
if (hp == NULL || hp->h_addrtype != AF_INET) {
return false;
}
for (i = 0; hp->h_addr_list[i] != NULL && i < *n_addrs; i++) {
memcpy(&addrs[i], hp->h_addr_list[i], sizeof(addrs[i]));
}
*n_addrs = i;
return true;
}
Socket* Socket::connect(char const* address, size_t maxAttempts)
{
char* sep = (char*)strchr(address, ':');
if (sep == NULL) {
throw SocketError("Port is not specified");
}
int port = atoi(sep+1);
int rc = 0;
int sd;
while (1) {
bool isLocal;
if (isLocalHost(address)) {
struct sockaddr sock;
isLocal = true;
sock.sa_family = AF_UNIX;
sd = socket(AF_UNIX, SOCK_STREAM, 0);
if (sd < 0) {
throw SocketError("Failed to create local socket");
}
size_t len = ((char*)sock.sa_data - (char*)&sock) + sprintf(sock.sa_data, "%sp%u", unixSocketDir, port);
do {
rc = ::connect(sd, &sock, len);
} while (rc < 0 && errno == EINTR);
} else {
struct sockaddr_in sock_inet;
unsigned addrs[128];
size_t n_addrs = sizeof(addrs) / sizeof(addrs[0]);
isLocal = false;
sock_inet.sin_family = AF_INET;
sock_inet.sin_port = htons(port);
size_t hostLen = sep - address;
char* host = new char[hostLen+1];
memcpy(host, address, hostLen);
host[hostLen] = '\0';
if (!getAddrsByName(host, addrs, &n_addrs)) {
throw SocketError("Failed to resolve addresses");
}
delete[] host;
sd = socket(AF_INET, SOCK_STREAM, 0);
if (sd < 0) {
throw SocketError("Failed to create global socket");
}
for (size_t i = 0; i < n_addrs; ++i) {
memcpy(&sock_inet.sin_addr, &addrs[i], sizeof sock_inet.sin_addr);
do {
rc = ::connect(sd, (struct sockaddr*)&sock_inet, sizeof(sock_inet));
} while (rc < 0 && errno == EINTR);
if (rc >= 0 || errno == EINPROGRESS) {
if (rc >= 0) {
setGlobalSocketOptions(sd);
}
break;
}
}
}
if (rc < 0) {
::close(sd);
if (errno == EINPROGRESS) {
throw SocketError("Failed to connect socket");
}
if (errno == ENOENT || errno == ECONNREFUSED) {
if (maxAttempts-- != 0) {
sleep(1);
continue;
}
}
throw SocketError("Connection can not be establish");
} else {
return new Socket(sd, isLocal);
}
}
}
void Socket::read(void* buf, size_t size)
{
size_t offs = 0;
while (offs < size) {
int rc = recv(sd, (char*)buf + offs, size - offs, 0);
if (rc <= 0) {
if (errno == EINTR) {
continue;
}
throw SocketError("Failed to read data from socket");
}
offs += rc;
}
}
void Socket::write(void const* buf, size_t size)
{
size_t offs = 0;
while (offs < size) {
int rc = send(sd, (char const*)buf + offs, size - offs, 0);
if (rc <= 0) {
if (errno == EINTR) {
continue;
}
throw SocketError("Failed to write data to socket");
}
offs += rc;
}
}
Socket* Socket::accept()
{
int ns = ::accept(sd, NULL, NULL);
if (ns < 0) {
throw SocketError("Failed to accept socket");
}
setGlobalSocketOptions(ns);
return new Socket(ns, localSocket);
}
Socket* Socket::select(size_t nSockets, Socket** sockets)
{
static size_t rr = 0;
int rc;
while (true) {
#if USE_EPOLL
struct epoll_event event;
event.events = EPOLLIN;
int epollfd = epoll_create(1);
assert(epollfd >= 0);
for (size_t i = 0; i < nSockets; i++) {
if (sockets[i] != NULL) {
event.data.ptr = (void*)sockets[i];
rc = epoll_ctl(epollfd, EPOLL_CTL_ADD, sockets[i]->sd, &event);
assert(rc == 0);
}
}
rc = epoll_wait(epollfd, &event, 1, -1);
close(epollfd);
if (rc < 0) {
throw SocketError("Failed to select socket");
} else if (rc != 0) {
return (Socket*)event.data.ptr;
}
#else
fd_set events;
FD_ZERO(&events);
int max_sd = 0;
for (size_t i = 0; i < nSockets; i++) {
if (sockets[i] != NULL) {
int sd = sockets[i]->sd;
if (sd > max_sd) {
max_sd = sd;
}
FD_SET(sd, &events);
}
}
int rc = ::select(max_sd+1, &events, NULL, NULL, NULL);
if (rc < 0) {
if (errno != EINTR) {
throw SocketError("Failed to select socket");
}
} else {
for (size_t i = 0, j = rr; i < nSockets; i++) {
j = (j + 1) % nSockets; // round robin
if (sockets[j] && FD_ISSET(sockets[j]->sd, &events)) {
rr = j;
return sockets[j];
}
}
}
#endif
}
}
Socket::~Socket()
{
::close(sd);
}
<|endoftext|> |
<commit_before>/** \file
*
* Copyright (c) 2014 by Travis Gockel. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify it under the terms of the Apache License
* as published by the Apache Software Foundation, either version 2 of the License, or (at your option) any later
* version.
*
* \author Travis Gockel ([email protected])
**/
#include <jsonv/detail/token_patterns.hpp>
#include <algorithm>
#include <cassert>
#include <iterator>
#include JSONV_REGEX_INCLUDE
namespace jsonv
{
namespace detail
{
namespace regex_ns = JSONV_REGEX_NAMESPACE;
class re_values
{
public:
static const regex_ns::regex& number()
{
return instance().re_number;
}
/** Like \c number, but will successfully match an EOF-ed value. **/
static const regex_ns::regex& number_trunc()
{
return instance().re_number_trunc;
}
static const regex_ns::regex& comment()
{
return instance().re_comment;
}
static const regex_ns::regex& simplestring()
{
return instance().re_simplestring;
}
private:
static const re_values& instance()
{
static re_values x;
return x;
}
re_values() :
syntax_options(regex_ns::regex_constants::ECMAScript | regex_ns::regex_constants::optimize),
re_number( R"(^-?[0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+(\.[0-9]+)?)?)", syntax_options),
re_number_trunc(R"(^-?[0-9]*(\.[0-9]*)?([eE][+-]?[0-9]*(\.[0-9]*)?)?)", syntax_options),
re_comment( R"(^/\*([^\*]*|\*[^/])*\*/)", syntax_options),
re_simplestring(R"(^[a-zA-Z_$][a-zA-Z0-9_$]*)", syntax_options)
{ }
private:
const regex_ns::regex_constants::syntax_option_type syntax_options;
const regex_ns::regex re_number;
const regex_ns::regex re_number_trunc;
const regex_ns::regex re_comment;
const regex_ns::regex re_simplestring;
};
template <std::ptrdiff_t N>
static match_result match_literal(const char* begin, const char* end, const char (& literal)[N], std::size_t& length)
{
for (length = 0; length < (N-1); ++length)
{
if (begin + length == end)
return match_result::incomplete_eof;
else if (begin[length] != literal[length])
return match_result::unmatched;
}
return match_result::complete;
}
static match_result match_true(const char* begin, const char* end, token_kind& kind, std::size_t& length)
{
kind = token_kind::boolean;
return match_literal(begin, end, "true", length);
}
static match_result match_false(const char* begin, const char* end, token_kind& kind, std::size_t& length)
{
kind = token_kind::boolean;
return match_literal(begin, end, "false", length);
}
static match_result match_null(const char* begin, const char* end, token_kind& kind, std::size_t& length)
{
kind = token_kind::null;
return match_literal(begin, end, "null", length);
}
static match_result match_pattern(const char* begin,
const char* end,
const regex_ns::regex& pattern,
std::size_t& length
)
{
regex_ns::cmatch match;
if (regex_ns::regex_search(begin, end, match, pattern))
{
length = match.length(0);
return begin + length == end ? match_result::complete_eof : match_result::complete;
}
else
{
length = 1;
return match_result::unmatched;
}
}
static match_result match_number(const char* begin, const char* end, token_kind& kind, std::size_t& length)
{
kind = token_kind::number;
regex_ns::cmatch match;
if (regex_ns::regex_search(begin, end, match, re_values::number()))
{
length = match.length(0);
if (begin + length == end)
return match_result::complete_eof;
else switch (begin[length])
{
case '.':
case '-':
case '+':
case 'e':
case 'E':
return match_result::incomplete_eof;
default:
return match_result::complete;
}
}
else
{
length = 1;
return regex_ns::regex_search(begin, end, match, re_values::number_trunc())
? match_result::incomplete_eof
: match_result::unmatched;
}
}
static match_result match_string(const char* begin, const char* end, token_kind& kind, std::size_t& length)
{
assert(*begin == '\"');
kind = token_kind::string;
length = 1;
while (true)
{
if (begin + length == end)
return match_result::complete_eof;
if (begin[length] == '\"')
{
++length;
return match_result::complete;
}
else if (begin[length] == '\\')
{
if (begin + length + 1 == end)
return match_result::complete_eof;
else
length += 2;
}
else
{
++length;
}
}
}
static match_result match_whitespace(const char* begin, const char* end, token_kind& kind, std::size_t& length)
{
kind = token_kind::whitespace;
for (length = 0; begin != end; ++length, ++begin)
switch (*begin)
{
case ' ':
case '\t':
case '\r':
case '\n':
continue;
default:
return match_result::complete;
}
return match_result::complete_eof;
}
static match_result match_comment(const char* begin, const char* end, token_kind& kind, std::size_t& length)
{
kind = token_kind::comment;
return match_pattern(begin, end, re_values::comment(), length);
}
match_result attempt_match(const char* begin, const char* end, token_kind& kind, std::size_t& length)
{
auto result = [&] (match_result r, token_kind kind_, std::size_t length_)
{
kind = kind_;
length = length_;
return r;
};
if (begin == end)
{
return result(match_result::incomplete_eof, token_kind::unknown, 0);
}
switch (*begin)
{
case '[': return result(match_result::complete, token_kind::array_begin, 1);
case ']': return result(match_result::complete, token_kind::array_end, 1);
case '{': return result(match_result::complete, token_kind::object_begin, 1);
case '}': return result(match_result::complete, token_kind::object_end, 1);
case ':': return result(match_result::complete, token_kind::object_key_delimiter, 1);
case ',': return result(match_result::complete, token_kind::separator, 1);
case 't': return match_true( begin, end, kind, length);
case 'f': return match_false(begin, end, kind, length);
case 'n': return match_null( begin, end, kind, length);
case '-':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return match_number(begin, end, kind, length);
case '\"':
return match_string(begin, end, kind, length);
case ' ':
case '\t':
case '\n':
case '\r':
return match_whitespace(begin, end, kind, length);
case '/':
return match_comment(begin, end, kind, length);
default:
return result(match_result::unmatched, token_kind::unknown, 1);
}
}
path_match_result path_match(string_view input, string_view& match_contents)
{
if (input.length() < 2)
return path_match_result::invalid;
match_result result;
token_kind kind;
std::size_t length;
switch (input.at(0))
{
case '.':
result = match_pattern(input.data() + 1, input.data() + input.size(), re_values::simplestring(), length);
if (result == match_result::complete || result == match_result::complete_eof)
{
match_contents = input.substr(0, length + 1);
return path_match_result::simple_object;
}
else
{
return path_match_result::invalid;
}
case '[':
result = attempt_match(input.data() + 1, input.data() + input.length(), kind, length);
if (result == match_result::complete || result == match_result::complete_eof)
{
if (input.length() == length + 1 || input.at(1 + length) != ']')
return path_match_result::invalid;
if (kind != token_kind::string && kind != token_kind::number)
return path_match_result::invalid;
match_contents = input.substr(0, length + 2);
return path_match_result::brace;
}
else
{
return path_match_result::invalid;
}
default:
return path_match_result::invalid;
}
}
}
}
<commit_msg>Don't consider unterminated strings as complete<commit_after>/** \file
*
* Copyright (c) 2014 by Travis Gockel. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify it under the terms of the Apache License
* as published by the Apache Software Foundation, either version 2 of the License, or (at your option) any later
* version.
*
* \author Travis Gockel ([email protected])
**/
#include <jsonv/detail/token_patterns.hpp>
#include <algorithm>
#include <cassert>
#include <iterator>
#include JSONV_REGEX_INCLUDE
namespace jsonv
{
namespace detail
{
namespace regex_ns = JSONV_REGEX_NAMESPACE;
class re_values
{
public:
static const regex_ns::regex& number()
{
return instance().re_number;
}
/** Like \c number, but will successfully match an EOF-ed value. **/
static const regex_ns::regex& number_trunc()
{
return instance().re_number_trunc;
}
static const regex_ns::regex& comment()
{
return instance().re_comment;
}
static const regex_ns::regex& simplestring()
{
return instance().re_simplestring;
}
private:
static const re_values& instance()
{
static re_values x;
return x;
}
re_values() :
syntax_options(regex_ns::regex_constants::ECMAScript | regex_ns::regex_constants::optimize),
re_number( R"(^-?[0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+(\.[0-9]+)?)?)", syntax_options),
re_number_trunc(R"(^-?[0-9]*(\.[0-9]*)?([eE][+-]?[0-9]*(\.[0-9]*)?)?)", syntax_options),
re_comment( R"(^/\*([^\*]*|\*[^/])*\*/)", syntax_options),
re_simplestring(R"(^[a-zA-Z_$][a-zA-Z0-9_$]*)", syntax_options)
{ }
private:
const regex_ns::regex_constants::syntax_option_type syntax_options;
const regex_ns::regex re_number;
const regex_ns::regex re_number_trunc;
const regex_ns::regex re_comment;
const regex_ns::regex re_simplestring;
};
template <std::ptrdiff_t N>
static match_result match_literal(const char* begin, const char* end, const char (& literal)[N], std::size_t& length)
{
for (length = 0; length < (N-1); ++length)
{
if (begin + length == end)
return match_result::incomplete_eof;
else if (begin[length] != literal[length])
return match_result::unmatched;
}
return match_result::complete;
}
static match_result match_true(const char* begin, const char* end, token_kind& kind, std::size_t& length)
{
kind = token_kind::boolean;
return match_literal(begin, end, "true", length);
}
static match_result match_false(const char* begin, const char* end, token_kind& kind, std::size_t& length)
{
kind = token_kind::boolean;
return match_literal(begin, end, "false", length);
}
static match_result match_null(const char* begin, const char* end, token_kind& kind, std::size_t& length)
{
kind = token_kind::null;
return match_literal(begin, end, "null", length);
}
static match_result match_pattern(const char* begin,
const char* end,
const regex_ns::regex& pattern,
std::size_t& length
)
{
regex_ns::cmatch match;
if (regex_ns::regex_search(begin, end, match, pattern))
{
length = match.length(0);
return begin + length == end ? match_result::complete_eof : match_result::complete;
}
else
{
length = 1;
return match_result::unmatched;
}
}
static match_result match_number(const char* begin, const char* end, token_kind& kind, std::size_t& length)
{
kind = token_kind::number;
regex_ns::cmatch match;
if (regex_ns::regex_search(begin, end, match, re_values::number()))
{
length = match.length(0);
if (begin + length == end)
return match_result::complete_eof;
else switch (begin[length])
{
case '.':
case '-':
case '+':
case 'e':
case 'E':
return match_result::incomplete_eof;
default:
return match_result::complete;
}
}
else
{
length = 1;
return regex_ns::regex_search(begin, end, match, re_values::number_trunc())
? match_result::incomplete_eof
: match_result::unmatched;
}
}
static match_result match_string(const char* begin, const char* end, token_kind& kind, std::size_t& length)
{
assert(*begin == '\"');
kind = token_kind::string;
length = 1;
while (true)
{
if (begin + length == end)
return match_result::incomplete_eof;
if (begin[length] == '\"')
{
++length;
return match_result::complete;
}
else if (begin[length] == '\\')
{
if (begin + length + 1 == end)
return match_result::incomplete_eof;
else
length += 2;
}
else
{
++length;
}
}
}
static match_result match_whitespace(const char* begin, const char* end, token_kind& kind, std::size_t& length)
{
kind = token_kind::whitespace;
for (length = 0; begin != end; ++length, ++begin)
switch (*begin)
{
case ' ':
case '\t':
case '\r':
case '\n':
continue;
default:
return match_result::complete;
}
return match_result::complete_eof;
}
static match_result match_comment(const char* begin, const char* end, token_kind& kind, std::size_t& length)
{
kind = token_kind::comment;
return match_pattern(begin, end, re_values::comment(), length);
}
match_result attempt_match(const char* begin, const char* end, token_kind& kind, std::size_t& length)
{
auto result = [&] (match_result r, token_kind kind_, std::size_t length_)
{
kind = kind_;
length = length_;
return r;
};
if (begin == end)
{
return result(match_result::incomplete_eof, token_kind::unknown, 0);
}
switch (*begin)
{
case '[': return result(match_result::complete, token_kind::array_begin, 1);
case ']': return result(match_result::complete, token_kind::array_end, 1);
case '{': return result(match_result::complete, token_kind::object_begin, 1);
case '}': return result(match_result::complete, token_kind::object_end, 1);
case ':': return result(match_result::complete, token_kind::object_key_delimiter, 1);
case ',': return result(match_result::complete, token_kind::separator, 1);
case 't': return match_true( begin, end, kind, length);
case 'f': return match_false(begin, end, kind, length);
case 'n': return match_null( begin, end, kind, length);
case '-':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return match_number(begin, end, kind, length);
case '\"':
return match_string(begin, end, kind, length);
case ' ':
case '\t':
case '\n':
case '\r':
return match_whitespace(begin, end, kind, length);
case '/':
return match_comment(begin, end, kind, length);
default:
return result(match_result::unmatched, token_kind::unknown, 1);
}
}
path_match_result path_match(string_view input, string_view& match_contents)
{
if (input.length() < 2)
return path_match_result::invalid;
match_result result;
token_kind kind;
std::size_t length;
switch (input.at(0))
{
case '.':
result = match_pattern(input.data() + 1, input.data() + input.size(), re_values::simplestring(), length);
if (result == match_result::complete || result == match_result::complete_eof)
{
match_contents = input.substr(0, length + 1);
return path_match_result::simple_object;
}
else
{
return path_match_result::invalid;
}
case '[':
result = attempt_match(input.data() + 1, input.data() + input.length(), kind, length);
if (result == match_result::complete || result == match_result::complete_eof)
{
if (input.length() == length + 1 || input.at(1 + length) != ']')
return path_match_result::invalid;
if (kind != token_kind::string && kind != token_kind::number)
return path_match_result::invalid;
match_contents = input.substr(0, length + 2);
return path_match_result::brace;
}
else
{
return path_match_result::invalid;
}
default:
return path_match_result::invalid;
}
}
}
}
<|endoftext|> |
<commit_before>#include <algorithm>
#include <iterator>
#include <iostream>
#include <memory>
#include <string>
#include <set>
#include <vector>
#include <stack>
#include "mcrl2/lps/nextstate.h"
#include "mcrl2/lps/specification.h"
#include "mcrl2/lps/mcrl22lps.h"
#include "mcrl2/atermpp/set.h"
#include "mcrl2/core/print.h"
#include "mcrl2/lps/data_elimination.h"
class group_information {
private:
mcrl2::lps::specification const& m_model;
std::vector< std::vector< size_t > > m_group_indices;
private:
void gather(mcrl2::lps::specification const& l);
public:
/**
* \brief constructor from an mCRL2 lps
**/
group_information(mcrl2::lps::specification const& l) : m_model(l) {
gather(l);
}
/**
* \brief The number of groups (summands in the LPS)
* \return lps::specification(l).summands().size()
**/
inline size_t number_of_groups() const {
return m_group_indices.size();
}
inline size_t number_of_parameters() const {
return m_model.process().process_parameters().size();
}
/**
* \brief Indices of process parameters that influence event or next state of a summand
* \param[in] index the selected summand
* \returns reference to a vector of indices of parameters
**/
inline std::vector< size_t > const& get_group(size_t index) const {
return m_group_indices[index];
}
};
void group_information::gather(mcrl2::lps::specification const& l) {
using namespace mcrl2;
using data::find_all_data_variables;
using data::data_variable;
struct local {
static void add_used_variables(std::set< data_variable >& r, std::set< data_variable > const& c) {
r.insert(c.begin(), c.end());
}
};
lps::linear_process specification(l.process());
// the set with process parameters
std::set< data_variable > parameters = find_all_data_variables(specification.process_parameters());
// the list of summands
std::vector< lps::summand > summands(specification.summands().begin(), specification.summands().end());
m_group_indices.resize(summands.size());
for (std::vector< lps::summand >::const_iterator i = summands.begin(); i != summands.end(); ++i) {
std::set< data_variable > used_variables;
local::add_used_variables(used_variables, find_all_data_variables(i->condition()));
local::add_used_variables(used_variables, find_all_data_variables(i->actions()));
if (i->has_time()) {
local::add_used_variables(used_variables, find_all_data_variables(i->time()));
}
data::data_assignment_list assignments(i->assignments());
for (data::data_assignment_list::const_iterator j = assignments.begin(); j != assignments.end(); ++j) {
if(j->lhs() != j->rhs()) {
local::add_used_variables(used_variables, find_all_data_variables(j->lhs()));
local::add_used_variables(used_variables, find_all_data_variables(j->rhs()));
}
}
// process parameters used in condition or action of summand
std::set< data_variable > used_parameters;
std::set_intersection(used_variables.begin(), used_variables.end(),
parameters.begin(), parameters.end(), std::inserter(used_parameters, used_parameters.begin()));
std::vector< data_variable > parameters_list(specification.process_parameters().begin(), specification.process_parameters().end());
for (std::vector< data_variable >::const_iterator j = parameters_list.begin(); j != parameters_list.end(); ++j) {
if (used_parameters.find(*j) != used_parameters.end()) {
m_group_indices[i - summands.begin()].push_back(j - parameters_list.begin());
}
}
}
}
mcrl2::lps::specification convert(mcrl2::lps::specification const& l) {
mcrl2::lps::linear_process lp(l.process());
mcrl2::lps::summand_list summands;
for (mcrl2::lps::non_delta_summand_list::iterator i = lp.non_delta_summands().begin(); i != lp.non_delta_summands().end(); ++i) {
summands = push_front(summands, *i);
}
summands = reverse(summands);
return mcrl2::lps::specification(l.data(), l.action_labels(),
mcrl2::lps::linear_process(lp.free_variables(), lp.process_parameters(), summands),
l.initial_process());
}
extern "C" {
#include "mcrl2-greybox.h"
/// We have to define CONFIG_H_ due to a problem with double defines.
#define CONFIG_H_
#include "runtime.h"
#include "at-map.h"
static void WarningHandler(const char *format, va_list args) {
FILE* f=log_get_stream(info);
if (f) {
fprintf(f,"MCRL2 grey box: ");
ATvfprintf(f, format, args);
fprintf(f,"\n");
}
}
static void ErrorHandler(const char *format, va_list args) {
FILE* f=log_get_stream(error);
if (f) {
fprintf(f,"MCRL2 grey box: ");
ATvfprintf(f, format, args);
fprintf(f,"\n");
}
Fatal(1,error,"ATerror");
exit(1);
}
void MCRL2initGreybox(int argc,char *argv[],void* stack_bottom){
ATinit(argc, argv, (ATerm*) stack_bottom);
ATsetWarningHandler(WarningHandler);
ATsetErrorHandler(ErrorHandler);
}
typedef struct grey_box_context {
int atPars;
int atGrps;
NextState* explorer;
AFun StateFun;
group_information *info;
ATerm s0;
at_map_t termmap;
at_map_t actionmap;
ATermTable action_memo;
} *mcrl2_model_t;
static struct state_info s_info={0,NULL,NULL};
static inline int resolve_label(mcrl2_model_t model,ATerm act){
ATerm res=ATtableGet(model->action_memo,act);
if (res==NULL){
char str[1024];
sprintf(str,"%s",mcrl2::core::pp(act).c_str());
res=(ATerm)ATmakeInt(ATfindIndex(model->actionmap,ATreadFromString(str)));
ATtablePut(model->action_memo,act,res);
}
return ATgetInt((ATermInt)res);
}
static int MCRL2getTransitionsLong(model_t m,int group,int*src,TransitionCB cb,void*context){
struct grey_box_context *model=(struct grey_box_context*)GBgetContext(m);
ATerm src_term[model->atPars];
for(int i=0;i<model->atPars;i++) {
src_term[i]=ATfindTerm(model->termmap,src[i]);
}
ATerm src_state=(ATerm)ATmakeApplArray(model->StateFun,src_term);
src_state=(ATerm)model->explorer->parseStateVector((ATermAppl)src_state);
std::auto_ptr< NextStateGenerator > generator(model->explorer->getNextStates(src_state, group));
ATerm state;
ATermAppl transition;
int dst[model->atPars];
int pp_lbl[1];
int count=0;
while(generator->next(&transition, &state)){
state=(ATerm)model->explorer->makeStateVector(state);
for(int i=0;i<model->atPars;i++) {
dst[i]=ATfindIndex(model->termmap,ATgetArgument(state,i));
}
pp_lbl[0]=resolve_label(model,(ATerm)transition);
cb(context,pp_lbl,dst);
count++;
}
return count;
}
static int MCRL2getTransitionsAll(model_t m,int*src,TransitionCB cb,void*context){
struct grey_box_context *model=(struct grey_box_context*)GBgetContext(m);
ATerm src_term[model->atPars];
for(int i=0;i<model->atPars;i++) {
src_term[i]=ATfindTerm(model->termmap,src[i]);
}
ATerm src_state=(ATerm)ATmakeApplArray(model->StateFun,src_term);
src_state=(ATerm)model->explorer->parseStateVector((ATermAppl)src_state);
std::auto_ptr< NextStateGenerator > generator(model->explorer->getNextStates(src_state));
ATerm state;
ATermAppl transition;
int dst[model->atPars];
int pp_lbl[1];
int count=0;
while(generator->next(&transition, &state)){
state=(ATerm)model->explorer->makeStateVector(state);
for(int i=0;i<model->atPars;i++) {
dst[i]=ATfindIndex(model->termmap,ATgetArgument(state,i));
}
pp_lbl[0]=resolve_label(model,(ATerm)transition);
cb(context,pp_lbl,dst);
count++;
}
return count;
}
static char const_action[7]="action";
static char* edge_name[1]={const_action};
static int edge_type[1]={1};
static char const_leaf[5]="leaf";
static char* MCRL_types[2]={const_leaf,const_action};
void MCRL2loadGreyboxModel(model_t m,char*model_name){
struct grey_box_context *ctx=(struct grey_box_context*)RTmalloc(sizeof(struct grey_box_context));
GBsetContext(m,ctx);
using namespace mcrl2;
using namespace mcrl2::lps;
ATermAppl Spec=(ATermAppl)ATreadFromNamedFile(model_name);
Warning(info,"removing unused parts of the data specification.");
Spec = removeUnusedData(Spec);
lps::specification model(Spec);
// model.load(model_name);
model = convert(model);
lts_struct_t ltstype=(lts_struct_t)RTmalloc(sizeof(struct lts_structure_s));
ltstype->state_length=model.process().process_parameters().size();
ltstype->visible_count=0;
ltstype->visible_indices=NULL;
ltstype->visible_name=NULL;
ltstype->visible_type=NULL;
ltstype->state_labels=0;
ltstype->state_label_name=NULL;
ltstype->state_label_type=NULL;
ltstype->edge_labels=1;
ltstype->edge_label_name=edge_name;
ltstype->edge_label_type=edge_type;
ltstype->type_count=2;
ltstype->type_names=MCRL_types;
GBsetLTStype(m,ltstype);
// Note the second argument that specifies that don't care variables are not treated specially
ctx->explorer = createNextState(model, false, GS_STATE_VECTOR,GS_REWR_JITTYC);
ctx->info=new group_information(model);
ctx->termmap=ATmapCreate(m,0,NULL,NULL);
ctx->actionmap=ATmapCreate(m,1,NULL,NULL);
ctx->atPars=model.process().process_parameters().size();
ctx->atGrps=model.process().summands().size();
ATerm s0=ctx->explorer->getInitialState();
s0=(ATerm)ctx->explorer->makeStateVector(s0);
ctx->StateFun=ATgetAFun(s0);
ctx->action_memo=ATtableCreate(1024,75);
int temp[ltstype->state_length];
for(int i=0;i<ltstype->state_length;i++) {
temp[i]=ATfindIndex(ctx->termmap,ATgetArgument(s0,i));
}
GBsetInitialState(m,temp);
edge_info_t e_info=(edge_info_t)RTmalloc(sizeof(struct edge_info));
e_info->groups=ctx->atGrps;
e_info->length=(int*)RTmalloc(e_info->groups*sizeof(int));
e_info->indices=(int**)RTmalloc(e_info->groups*sizeof(int*));
for(int i=0;i<e_info->groups;i++){
std::vector< size_t > const & vec = ctx->info->get_group(i);
e_info->length[i]=vec.size();
e_info->indices[i]=(int*)&(vec[0]);
}
GBsetEdgeInfo(m,e_info);
GBsetStateInfo(m,&s_info);
GBsetNextStateLong(m,MCRL2getTransitionsLong);
GBsetNextStateAll(m,MCRL2getTransitionsAll);
}
}// end extern "C".
<commit_msg>mcrl2 fix<commit_after>#include <algorithm>
#include <iterator>
#include <iostream>
#include <memory>
#include <string>
#include <set>
#include <vector>
#include <stack>
#include "mcrl2/lps/nextstate.h"
#include "mcrl2/lps/specification.h"
#include "mcrl2/lps/mcrl22lps.h"
#include "mcrl2/atermpp/set.h"
#include "mcrl2/core/print.h"
#include "mcrl2/lps/data_elimination.h"
class group_information {
private:
mcrl2::lps::specification const& m_model;
std::vector< std::vector< size_t > > m_group_indices;
private:
void gather(mcrl2::lps::specification const& l);
public:
/**
* \brief constructor from an mCRL2 lps
**/
group_information(mcrl2::lps::specification const& l) : m_model(l) {
gather(l);
}
/**
* \brief The number of groups (summands in the LPS)
* \return lps::specification(l).summands().size()
**/
inline size_t number_of_groups() const {
return m_group_indices.size();
}
inline size_t number_of_parameters() const {
return m_model.process().process_parameters().size();
}
/**
* \brief Indices of process parameters that influence event or next state of a summand
* \param[in] index the selected summand
* \returns reference to a vector of indices of parameters
**/
inline std::vector< size_t > const& get_group(size_t index) const {
return m_group_indices[index];
}
};
void group_information::gather(mcrl2::lps::specification const& l) {
using namespace mcrl2;
using data::find_all_data_variables;
using data::data_variable;
struct local {
static void add_used_variables(std::set< data_variable >& r, std::set< data_variable > const& c) {
r.insert(c.begin(), c.end());
}
};
lps::linear_process specification(l.process());
// the set with process parameters
std::set< data_variable > parameters = find_all_data_variables(specification.process_parameters());
// the list of summands
std::vector< lps::summand > summands(specification.summands().begin(), specification.summands().end());
m_group_indices.resize(summands.size());
for (std::vector< lps::summand >::const_iterator i = summands.begin(); i != summands.end(); ++i) {
std::set< data_variable > used_variables;
local::add_used_variables(used_variables, find_all_data_variables(i->condition()));
local::add_used_variables(used_variables, find_all_data_variables(i->actions()));
if (i->has_time()) {
local::add_used_variables(used_variables, find_all_data_variables(i->time()));
}
data::data_assignment_list assignments(i->assignments());
for (data::data_assignment_list::const_iterator j = assignments.begin(); j != assignments.end(); ++j) {
if(j->lhs() != j->rhs()) {
local::add_used_variables(used_variables, find_all_data_variables(j->lhs()));
local::add_used_variables(used_variables, find_all_data_variables(j->rhs()));
}
}
// process parameters used in condition or action of summand
std::set< data_variable > used_parameters;
std::set_intersection(used_variables.begin(), used_variables.end(),
parameters.begin(), parameters.end(), std::inserter(used_parameters, used_parameters.begin()));
std::vector< data_variable > parameters_list(specification.process_parameters().begin(), specification.process_parameters().end());
for (std::vector< data_variable >::const_iterator j = parameters_list.begin(); j != parameters_list.end(); ++j) {
if (used_parameters.find(*j) != used_parameters.end()) {
m_group_indices[i - summands.begin()].push_back(j - parameters_list.begin());
}
}
}
}
mcrl2::lps::specification convert(mcrl2::lps::specification const& l) {
mcrl2::lps::linear_process lp(l.process());
mcrl2::lps::summand_list summands;
for (mcrl2::lps::non_delta_summand_list::iterator i = lp.non_delta_summands().begin(); i != lp.non_delta_summands().end(); ++i) {
summands = push_front(summands, *i);
}
summands = reverse(summands);
return mcrl2::lps::specification(l.data(), l.action_labels(),
mcrl2::lps::linear_process(lp.free_variables(), lp.process_parameters(), summands),
l.initial_process());
}
extern "C" {
#include "mcrl2-greybox.h"
/// We have to define CONFIG_H_ due to a problem with double defines.
#define CONFIG_H_
#include "runtime.h"
#include "at-map.h"
static void WarningHandler(const char *format, va_list args) {
FILE* f=log_get_stream(info);
if (f) {
fprintf(f,"MCRL2 grey box: ");
ATvfprintf(f, format, args);
fprintf(f,"\n");
}
}
static void ErrorHandler(const char *format, va_list args) {
FILE* f=log_get_stream(error);
if (f) {
fprintf(f,"MCRL2 grey box: ");
ATvfprintf(f, format, args);
fprintf(f,"\n");
}
Fatal(1,error,"ATerror");
exit(1);
}
void MCRL2initGreybox(int argc,char *argv[],void* stack_bottom){
ATinit(argc, argv, (ATerm*) stack_bottom);
ATsetWarningHandler(WarningHandler);
ATsetErrorHandler(ErrorHandler);
}
typedef struct grey_box_context {
int atPars;
int atGrps;
NextState* explorer;
AFun StateFun;
group_information *info;
ATerm s0;
at_map_t termmap;
at_map_t actionmap;
ATermTable action_memo;
} *mcrl2_model_t;
static struct state_info s_info={0,NULL,NULL};
static inline int resolve_label(mcrl2_model_t model,ATerm act){
ATerm res=ATtableGet(model->action_memo,act);
if (res==NULL){
char str[1024];
sprintf(str,"%s",mcrl2::core::pp(act).c_str());
res=(ATerm)ATmakeInt(ATfindIndex(model->actionmap,ATreadFromString(str)));
ATtablePut(model->action_memo,act,res);
}
return ATgetInt((ATermInt)res);
}
static int MCRL2getTransitionsLong(model_t m,int group,int*src,TransitionCB cb,void*context){
struct grey_box_context *model=(struct grey_box_context*)GBgetContext(m);
ATerm src_term[model->atPars];
for(int i=0;i<model->atPars;i++) {
src_term[i]=ATfindTerm(model->termmap,src[i]);
}
ATerm src_state=(ATerm)ATmakeApplArray(model->StateFun,src_term);
src_state=(ATerm)model->explorer->parseStateVector((ATermAppl)src_state);
std::auto_ptr< NextStateGenerator > generator(model->explorer->getNextStates(src_state, group));
ATerm state;
ATermAppl transition;
int dst[model->atPars];
int pp_lbl[1];
int count=0;
while(generator->next(&transition, &state)){
state=(ATerm)model->explorer->makeStateVector(state);
for(int i=0;i<model->atPars;i++) {
dst[i]=ATfindIndex(model->termmap,ATgetArgument(state,i));
}
pp_lbl[0]=resolve_label(model,(ATerm)transition);
cb(context,pp_lbl,dst);
count++;
}
return count;
}
static int MCRL2getTransitionsAll(model_t m,int*src,TransitionCB cb,void*context){
struct grey_box_context *model=(struct grey_box_context*)GBgetContext(m);
ATerm src_term[model->atPars];
for(int i=0;i<model->atPars;i++) {
src_term[i]=ATfindTerm(model->termmap,src[i]);
}
ATerm src_state=(ATerm)ATmakeApplArray(model->StateFun,src_term);
src_state=(ATerm)model->explorer->parseStateVector((ATermAppl)src_state);
std::auto_ptr< NextStateGenerator > generator(model->explorer->getNextStates(src_state));
ATerm state;
ATermAppl transition;
int dst[model->atPars];
int pp_lbl[1];
int count=0;
while(generator->next(&transition, &state)){
state=(ATerm)model->explorer->makeStateVector(state);
for(int i=0;i<model->atPars;i++) {
dst[i]=ATfindIndex(model->termmap,ATgetArgument(state,i));
}
pp_lbl[0]=resolve_label(model,(ATerm)transition);
cb(context,pp_lbl,dst);
count++;
}
return count;
}
static char const_action[7]="action";
static char* edge_name[1]={const_action};
static int edge_type[1]={1};
static char const_leaf[5]="leaf";
static char* MCRL_types[2]={const_leaf,const_action};
void MCRL2loadGreyboxModel(model_t m,char*model_name){
struct grey_box_context *ctx=(struct grey_box_context*)RTmalloc(sizeof(struct grey_box_context));
GBsetContext(m,ctx);
using namespace mcrl2;
using namespace mcrl2::lps;
ATermAppl Spec=(ATermAppl)ATreadFromNamedFile(model_name);
Warning(info,"removing unused parts of the data specification.");
Spec = removeUnusedData(Spec);
lps::specification model(Spec);
// model.load(model_name);
model = convert(model);
lts_struct_t ltstype=(lts_struct_t)RTmalloc(sizeof(struct lts_structure_s));
ltstype->state_length=model.process().process_parameters().size();
ltstype->visible_count=0;
ltstype->visible_indices=NULL;
ltstype->visible_name=NULL;
ltstype->visible_type=NULL;
ltstype->state_labels=0;
ltstype->state_label_name=NULL;
ltstype->state_label_type=NULL;
ltstype->edge_labels=1;
ltstype->edge_label_name=edge_name;
ltstype->edge_label_type=edge_type;
ltstype->type_count=2;
ltstype->type_names=MCRL_types;
GBsetLTStype(m,ltstype);
// Note the second argument that specifies that don't care variables are not treated specially
ctx->explorer = createNextState(model, false, GS_STATE_VECTOR,GS_REWR_JITTYC);
ctx->info=new group_information(model);
ctx->termmap=ATmapCreate(m,0,NULL,NULL);
ctx->actionmap=ATmapCreate(m,1,NULL,NULL);
ctx->atPars=model.process().process_parameters().size();
ctx->atGrps=model.process().summands().size();
ATerm s0=ctx->explorer->getInitialState();
s0=(ATerm)ctx->explorer->makeStateVector(s0);
ctx->StateFun=ATgetAFun(s0);
ctx->action_memo=ATtableCreate(1024,75);
int temp[ltstype->state_length];
for(int i=0;i<ltstype->state_length;i++) {
temp[i]=ATfindIndex(ctx->termmap,ATgetArgument(s0,i));
}
GBsetInitialState(m,temp);
edge_info_t e_info=(edge_info_t)RTmalloc(sizeof(struct edge_info));
e_info->groups=ctx->atGrps;
e_info->length=(int*)RTmalloc(e_info->groups*sizeof(int));
e_info->indices=(int**)RTmalloc(e_info->groups*sizeof(int*));
for(int i=0;i<e_info->groups;i++){
std::vector< size_t > const & vec = ctx->info->get_group(i);
e_info->length[i]=vec.size();
e_info->indices[i]=(int*)RTmalloc(vec.size()*sizeof(int));
for(int j=0;j<vec.size();j++) e_info->indices[i][j]=vec[j];
}
GBsetEdgeInfo(m,e_info);
GBsetStateInfo(m,&s_info);
GBsetNextStateLong(m,MCRL2getTransitionsLong);
GBsetNextStateAll(m,MCRL2getTransitionsAll);
}
}// end extern "C".
<|endoftext|> |
<commit_before>/*
* TLS Handshaking
* (C) 2004-2006,2011,2012,2015,2016 Jack Lloyd
* 2017 Harry Reimann, Rohde & Schwarz Cybersecurity
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/internal/tls_handshake_state.h>
#include <botan/internal/tls_record.h>
#include <botan/tls_messages.h>
#include <botan/kdf.h>
#include <sstream>
namespace Botan {
namespace TLS {
std::string Handshake_Message::type_string() const
{
return handshake_type_to_string(type());
}
const char* handshake_type_to_string(Handshake_Type type)
{
switch(type)
{
case HELLO_VERIFY_REQUEST:
return "hello_verify_request";
case HELLO_REQUEST:
return "hello_request";
case CLIENT_HELLO:
return "client_hello";
case SERVER_HELLO:
return "server_hello";
case CERTIFICATE:
return "certificate";
case CERTIFICATE_URL:
return "certificate_url";
case CERTIFICATE_STATUS:
return "certificate_status";
case SERVER_KEX:
return "server_key_exchange";
case CERTIFICATE_REQUEST:
return "certificate_request";
case SERVER_HELLO_DONE:
return "server_hello_done";
case CERTIFICATE_VERIFY:
return "certificate_verify";
case CLIENT_KEX:
return "client_key_exchange";
case NEW_SESSION_TICKET:
return "new_session_ticket";
case HANDSHAKE_CCS:
return "change_cipher_spec";
case FINISHED:
return "finished";
case HANDSHAKE_NONE:
return "invalid";
}
throw TLS_Exception(Alert::UNEXPECTED_MESSAGE,
"Unknown TLS handshake message type " + std::to_string(type));
}
namespace {
uint32_t bitmask_for_handshake_type(Handshake_Type type)
{
switch(type)
{
case HELLO_VERIFY_REQUEST:
return (1 << 0);
case HELLO_REQUEST:
return (1 << 1);
case CLIENT_HELLO:
return (1 << 2);
case SERVER_HELLO:
return (1 << 3);
case CERTIFICATE:
return (1 << 4);
case CERTIFICATE_URL:
return (1 << 5);
case CERTIFICATE_STATUS:
return (1 << 6);
case SERVER_KEX:
return (1 << 7);
case CERTIFICATE_REQUEST:
return (1 << 8);
case SERVER_HELLO_DONE:
return (1 << 9);
case CERTIFICATE_VERIFY:
return (1 << 10);
case CLIENT_KEX:
return (1 << 11);
case NEW_SESSION_TICKET:
return (1 << 12);
case HANDSHAKE_CCS:
return (1 << 13);
case FINISHED:
return (1 << 14);
// allow explicitly disabling new handshakes
case HANDSHAKE_NONE:
return 0;
}
throw TLS_Exception(Alert::UNEXPECTED_MESSAGE,
"Unknown TLS handshake message type " + std::to_string(type));
}
std::string handshake_mask_to_string(uint32_t mask, char combiner)
{
const Handshake_Type types[] = {
HELLO_VERIFY_REQUEST,
HELLO_REQUEST,
CLIENT_HELLO,
SERVER_HELLO,
CERTIFICATE,
CERTIFICATE_URL,
CERTIFICATE_STATUS,
SERVER_KEX,
CERTIFICATE_REQUEST,
SERVER_HELLO_DONE,
CERTIFICATE_VERIFY,
CLIENT_KEX,
NEW_SESSION_TICKET,
HANDSHAKE_CCS,
FINISHED
};
std::ostringstream o;
bool empty = true;
for(auto&& t : types)
{
if(mask & bitmask_for_handshake_type(t))
{
if(!empty)
o << combiner;
o << handshake_type_to_string(t);
empty = false;
}
}
return o.str();
}
}
/*
* Initialize the SSL/TLS Handshake State
*/
Handshake_State::Handshake_State(std::unique_ptr<Handshake_IO> io, Callbacks& cb) :
m_callbacks(cb),
m_handshake_io(std::move(io)),
m_version(m_handshake_io->initial_record_version())
{
}
void Handshake_State::note_message(const Handshake_Message& msg)
{
m_callbacks.tls_inspect_handshake_msg(msg);
}
void Handshake_State::hello_verify_request(const Hello_Verify_Request& hello_verify)
{
note_message(hello_verify);
m_client_hello->update_hello_cookie(hello_verify);
hash().reset();
hash().update(handshake_io().send(*m_client_hello));
note_message(*m_client_hello);
}
void Handshake_State::client_hello(Client_Hello* client_hello)
{
if(client_hello == nullptr)
{
m_client_hello.reset();
hash().reset();
}
else
{
m_client_hello.reset(client_hello);
note_message(*m_client_hello);
}
}
void Handshake_State::server_hello(Server_Hello* server_hello)
{
m_server_hello.reset(server_hello);
m_ciphersuite = Ciphersuite::by_id(m_server_hello->ciphersuite());
note_message(*m_server_hello);
}
void Handshake_State::server_certs(Certificate* server_certs)
{
m_server_certs.reset(server_certs);
note_message(*m_server_certs);
}
void Handshake_State::server_cert_status(Certificate_Status* server_cert_status)
{
m_server_cert_status.reset(server_cert_status);
note_message(*m_server_cert_status);
}
void Handshake_State::server_kex(Server_Key_Exchange* server_kex)
{
m_server_kex.reset(server_kex);
note_message(*m_server_kex);
}
void Handshake_State::cert_req(Certificate_Req* cert_req)
{
m_cert_req.reset(cert_req);
note_message(*m_cert_req);
}
void Handshake_State::server_hello_done(Server_Hello_Done* server_hello_done)
{
m_server_hello_done.reset(server_hello_done);
note_message(*m_server_hello_done);
}
void Handshake_State::client_certs(Certificate* client_certs)
{
m_client_certs.reset(client_certs);
note_message(*m_client_certs);
}
void Handshake_State::client_kex(Client_Key_Exchange* client_kex)
{
m_client_kex.reset(client_kex);
note_message(*m_client_kex);
}
void Handshake_State::client_verify(Certificate_Verify* client_verify)
{
m_client_verify.reset(client_verify);
note_message(*m_client_verify);
}
void Handshake_State::new_session_ticket(New_Session_Ticket* new_session_ticket)
{
m_new_session_ticket.reset(new_session_ticket);
note_message(*m_new_session_ticket);
}
void Handshake_State::server_finished(Finished* server_finished)
{
m_server_finished.reset(server_finished);
note_message(*m_server_finished);
}
void Handshake_State::client_finished(Finished* client_finished)
{
m_client_finished.reset(client_finished);
note_message(*m_client_finished);
}
const Ciphersuite& Handshake_State::ciphersuite() const
{
if (!m_ciphersuite.has_value())
{
throw Decoding_Error("Cipher suite is not set");
}
return m_ciphersuite.value();
}
void Handshake_State::set_version(const Protocol_Version& version)
{
m_version = version;
}
void Handshake_State::compute_session_keys()
{
m_session_keys = Session_Keys(this, client_kex()->pre_master_secret(), false);
}
void Handshake_State::compute_session_keys(const secure_vector<uint8_t>& resume_master_secret)
{
m_session_keys = Session_Keys(this, resume_master_secret, true);
}
void Handshake_State::confirm_transition_to(Handshake_Type handshake_msg)
{
const uint32_t mask = bitmask_for_handshake_type(handshake_msg);
m_hand_received_mask |= mask;
const bool ok = (m_hand_expecting_mask & mask) != 0; // overlap?
if(!ok)
{
const uint32_t seen_so_far = m_hand_received_mask & ~mask;
std::ostringstream msg;
msg << "Unexpected state transition in handshake got a " << handshake_type_to_string(handshake_msg);
if(m_hand_expecting_mask == 0)
msg << " not expecting messages";
else
msg << " expected " << handshake_mask_to_string(m_hand_expecting_mask, '|');
if(seen_so_far != 0)
msg << " seen " << handshake_mask_to_string(seen_so_far, '+');
throw Unexpected_Message(msg.str());
}
/* We don't know what to expect next, so force a call to
set_expected_next; if it doesn't happen, the next transition
check will always fail which is what we want.
*/
m_hand_expecting_mask = 0;
}
void Handshake_State::set_expected_next(Handshake_Type handshake_msg)
{
m_hand_expecting_mask |= bitmask_for_handshake_type(handshake_msg);
}
bool Handshake_State::received_handshake_msg(Handshake_Type handshake_msg) const
{
const uint32_t mask = bitmask_for_handshake_type(handshake_msg);
return (m_hand_received_mask & mask) != 0;
}
std::pair<Handshake_Type, std::vector<uint8_t>>
Handshake_State::get_next_handshake_msg()
{
const bool expecting_ccs =
(bitmask_for_handshake_type(HANDSHAKE_CCS) & m_hand_expecting_mask) != 0;
return m_handshake_io->get_next_record(expecting_ccs);
}
std::vector<uint8_t> Handshake_State::session_ticket() const
{
if(new_session_ticket() && !new_session_ticket()->ticket().empty())
return new_session_ticket()->ticket();
return client_hello()->session_ticket();
}
std::unique_ptr<KDF> Handshake_State::protocol_specific_prf() const
{
const std::string prf_algo = ciphersuite().prf_algo();
if(prf_algo == "MD5" || prf_algo == "SHA-1")
return KDF::create_or_throw("TLS-12-PRF(SHA-256)");
return KDF::create_or_throw("TLS-12-PRF(" + prf_algo + ")");
}
std::pair<std::string, Signature_Format>
Handshake_State::choose_sig_format(const Private_Key& key,
Signature_Scheme& chosen_scheme,
bool for_client_auth,
const Policy& policy) const
{
const std::string sig_algo = key.algo_name();
const std::vector<Signature_Scheme> allowed = policy.allowed_signature_schemes();
std::vector<Signature_Scheme> requested =
(for_client_auth) ? cert_req()->signature_schemes() : client_hello()->signature_schemes();
for(Signature_Scheme scheme : allowed)
{
if(signature_scheme_is_known(scheme) == false)
{
continue;
}
if(signature_algorithm_of_scheme(scheme) == sig_algo)
{
if(std::find(requested.begin(), requested.end(), scheme) != requested.end())
{
chosen_scheme = scheme;
break;
}
}
}
const std::string hash = hash_function_of_scheme(chosen_scheme);
if(!policy.allowed_signature_hash(hash))
{
throw TLS_Exception(Alert::HANDSHAKE_FAILURE,
"Policy refuses to accept signing with any hash supported by peer");
}
if(sig_algo == "RSA")
{
return std::make_pair(padding_string_for_scheme(chosen_scheme), IEEE_1363);
}
else if(sig_algo == "DSA" || sig_algo == "ECDSA")
{
return std::make_pair(padding_string_for_scheme(chosen_scheme), DER_SEQUENCE);
}
throw Invalid_Argument(sig_algo + " is invalid/unknown for TLS signatures");
}
namespace {
bool supported_algos_include(
const std::vector<Signature_Scheme>& schemes,
const std::string& key_type,
const std::string& hash_type)
{
for(Signature_Scheme scheme : schemes)
{
if(signature_scheme_is_known(scheme) &&
hash_function_of_scheme(scheme) == hash_type &&
signature_algorithm_of_scheme(scheme) == key_type)
{
return true;
}
}
return false;
}
}
std::pair<std::string, Signature_Format>
Handshake_State::parse_sig_format(const Public_Key& key,
Signature_Scheme scheme,
bool for_client_auth,
const Policy& policy) const
{
const std::string key_type = key.algo_name();
if(!policy.allowed_signature_method(key_type))
{
throw TLS_Exception(Alert::HANDSHAKE_FAILURE,
"Rejecting " + key_type + " signature");
}
if(scheme == Signature_Scheme::NONE)
throw Decoding_Error("Counterparty did not send hash/sig IDS");
if(key_type != signature_algorithm_of_scheme(scheme))
throw Decoding_Error("Counterparty sent inconsistent key and sig types");
if(for_client_auth && !cert_req())
{
throw TLS_Exception(Alert::HANDSHAKE_FAILURE,
"No certificate verify set");
}
/*
Confirm the signature type we just received against the
supported_algos list that we sent; it better be there.
*/
const std::vector<Signature_Scheme> supported_algos =
for_client_auth ? cert_req()->signature_schemes() :
client_hello()->signature_schemes();
if(!signature_scheme_is_known(scheme))
throw TLS_Exception(Alert::HANDSHAKE_FAILURE,
"Peer sent unknown signature scheme");
const std::string hash_algo = hash_function_of_scheme(scheme);
if(!supported_algos_include(supported_algos, key_type, hash_algo))
{
throw TLS_Exception(Alert::ILLEGAL_PARAMETER,
"TLS signature extension did not allow for " +
key_type + "/" + hash_algo + " signature");
}
if(key_type == "RSA")
{
return std::make_pair(padding_string_for_scheme(scheme), IEEE_1363);
}
else if(key_type == "DSA" || key_type == "ECDSA")
{
return std::make_pair(padding_string_for_scheme(scheme), DER_SEQUENCE);
}
throw Invalid_Argument(key_type + " is invalid/unknown for TLS signatures");
}
}
}
<commit_msg>FIX: review comment<commit_after>/*
* TLS Handshaking
* (C) 2004-2006,2011,2012,2015,2016 Jack Lloyd
* 2017 Harry Reimann, Rohde & Schwarz Cybersecurity
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/internal/tls_handshake_state.h>
#include <botan/internal/tls_record.h>
#include <botan/tls_messages.h>
#include <botan/kdf.h>
#include <sstream>
namespace Botan {
namespace TLS {
std::string Handshake_Message::type_string() const
{
return handshake_type_to_string(type());
}
const char* handshake_type_to_string(Handshake_Type type)
{
switch(type)
{
case HELLO_VERIFY_REQUEST:
return "hello_verify_request";
case HELLO_REQUEST:
return "hello_request";
case CLIENT_HELLO:
return "client_hello";
case SERVER_HELLO:
return "server_hello";
case CERTIFICATE:
return "certificate";
case CERTIFICATE_URL:
return "certificate_url";
case CERTIFICATE_STATUS:
return "certificate_status";
case SERVER_KEX:
return "server_key_exchange";
case CERTIFICATE_REQUEST:
return "certificate_request";
case SERVER_HELLO_DONE:
return "server_hello_done";
case CERTIFICATE_VERIFY:
return "certificate_verify";
case CLIENT_KEX:
return "client_key_exchange";
case NEW_SESSION_TICKET:
return "new_session_ticket";
case HANDSHAKE_CCS:
return "change_cipher_spec";
case FINISHED:
return "finished";
case HANDSHAKE_NONE:
return "invalid";
}
throw TLS_Exception(Alert::UNEXPECTED_MESSAGE,
"Unknown TLS handshake message type " + std::to_string(type));
}
namespace {
uint32_t bitmask_for_handshake_type(Handshake_Type type)
{
switch(type)
{
case HELLO_VERIFY_REQUEST:
return (1 << 0);
case HELLO_REQUEST:
return (1 << 1);
case CLIENT_HELLO:
return (1 << 2);
case SERVER_HELLO:
return (1 << 3);
case CERTIFICATE:
return (1 << 4);
case CERTIFICATE_URL:
return (1 << 5);
case CERTIFICATE_STATUS:
return (1 << 6);
case SERVER_KEX:
return (1 << 7);
case CERTIFICATE_REQUEST:
return (1 << 8);
case SERVER_HELLO_DONE:
return (1 << 9);
case CERTIFICATE_VERIFY:
return (1 << 10);
case CLIENT_KEX:
return (1 << 11);
case NEW_SESSION_TICKET:
return (1 << 12);
case HANDSHAKE_CCS:
return (1 << 13);
case FINISHED:
return (1 << 14);
// allow explicitly disabling new handshakes
case HANDSHAKE_NONE:
return 0;
}
throw TLS_Exception(Alert::UNEXPECTED_MESSAGE,
"Unknown TLS handshake message type " + std::to_string(type));
}
std::string handshake_mask_to_string(uint32_t mask, char combiner)
{
const Handshake_Type types[] = {
HELLO_VERIFY_REQUEST,
HELLO_REQUEST,
CLIENT_HELLO,
SERVER_HELLO,
CERTIFICATE,
CERTIFICATE_URL,
CERTIFICATE_STATUS,
SERVER_KEX,
CERTIFICATE_REQUEST,
SERVER_HELLO_DONE,
CERTIFICATE_VERIFY,
CLIENT_KEX,
NEW_SESSION_TICKET,
HANDSHAKE_CCS,
FINISHED
};
std::ostringstream o;
bool empty = true;
for(auto&& t : types)
{
if(mask & bitmask_for_handshake_type(t))
{
if(!empty)
o << combiner;
o << handshake_type_to_string(t);
empty = false;
}
}
return o.str();
}
}
/*
* Initialize the SSL/TLS Handshake State
*/
Handshake_State::Handshake_State(std::unique_ptr<Handshake_IO> io, Callbacks& cb) :
m_callbacks(cb),
m_handshake_io(std::move(io)),
m_version(m_handshake_io->initial_record_version())
{
}
void Handshake_State::note_message(const Handshake_Message& msg)
{
m_callbacks.tls_inspect_handshake_msg(msg);
}
void Handshake_State::hello_verify_request(const Hello_Verify_Request& hello_verify)
{
note_message(hello_verify);
m_client_hello->update_hello_cookie(hello_verify);
hash().reset();
hash().update(handshake_io().send(*m_client_hello));
note_message(*m_client_hello);
}
void Handshake_State::client_hello(Client_Hello* client_hello)
{
if(client_hello == nullptr)
{
m_client_hello.reset();
hash().reset();
}
else
{
m_client_hello.reset(client_hello);
note_message(*m_client_hello);
}
}
void Handshake_State::server_hello(Server_Hello* server_hello)
{
m_server_hello.reset(server_hello);
m_ciphersuite = Ciphersuite::by_id(m_server_hello->ciphersuite());
note_message(*m_server_hello);
}
void Handshake_State::server_certs(Certificate* server_certs)
{
m_server_certs.reset(server_certs);
note_message(*m_server_certs);
}
void Handshake_State::server_cert_status(Certificate_Status* server_cert_status)
{
m_server_cert_status.reset(server_cert_status);
note_message(*m_server_cert_status);
}
void Handshake_State::server_kex(Server_Key_Exchange* server_kex)
{
m_server_kex.reset(server_kex);
note_message(*m_server_kex);
}
void Handshake_State::cert_req(Certificate_Req* cert_req)
{
m_cert_req.reset(cert_req);
note_message(*m_cert_req);
}
void Handshake_State::server_hello_done(Server_Hello_Done* server_hello_done)
{
m_server_hello_done.reset(server_hello_done);
note_message(*m_server_hello_done);
}
void Handshake_State::client_certs(Certificate* client_certs)
{
m_client_certs.reset(client_certs);
note_message(*m_client_certs);
}
void Handshake_State::client_kex(Client_Key_Exchange* client_kex)
{
m_client_kex.reset(client_kex);
note_message(*m_client_kex);
}
void Handshake_State::client_verify(Certificate_Verify* client_verify)
{
m_client_verify.reset(client_verify);
note_message(*m_client_verify);
}
void Handshake_State::new_session_ticket(New_Session_Ticket* new_session_ticket)
{
m_new_session_ticket.reset(new_session_ticket);
note_message(*m_new_session_ticket);
}
void Handshake_State::server_finished(Finished* server_finished)
{
m_server_finished.reset(server_finished);
note_message(*m_server_finished);
}
void Handshake_State::client_finished(Finished* client_finished)
{
m_client_finished.reset(client_finished);
note_message(*m_client_finished);
}
const Ciphersuite& Handshake_State::ciphersuite() const
{
if (!m_ciphersuite.has_value())
{
throw Invalid_State("Cipher suite is not set");
}
return m_ciphersuite.value();
}
void Handshake_State::set_version(const Protocol_Version& version)
{
m_version = version;
}
void Handshake_State::compute_session_keys()
{
m_session_keys = Session_Keys(this, client_kex()->pre_master_secret(), false);
}
void Handshake_State::compute_session_keys(const secure_vector<uint8_t>& resume_master_secret)
{
m_session_keys = Session_Keys(this, resume_master_secret, true);
}
void Handshake_State::confirm_transition_to(Handshake_Type handshake_msg)
{
const uint32_t mask = bitmask_for_handshake_type(handshake_msg);
m_hand_received_mask |= mask;
const bool ok = (m_hand_expecting_mask & mask) != 0; // overlap?
if(!ok)
{
const uint32_t seen_so_far = m_hand_received_mask & ~mask;
std::ostringstream msg;
msg << "Unexpected state transition in handshake got a " << handshake_type_to_string(handshake_msg);
if(m_hand_expecting_mask == 0)
msg << " not expecting messages";
else
msg << " expected " << handshake_mask_to_string(m_hand_expecting_mask, '|');
if(seen_so_far != 0)
msg << " seen " << handshake_mask_to_string(seen_so_far, '+');
throw Unexpected_Message(msg.str());
}
/* We don't know what to expect next, so force a call to
set_expected_next; if it doesn't happen, the next transition
check will always fail which is what we want.
*/
m_hand_expecting_mask = 0;
}
void Handshake_State::set_expected_next(Handshake_Type handshake_msg)
{
m_hand_expecting_mask |= bitmask_for_handshake_type(handshake_msg);
}
bool Handshake_State::received_handshake_msg(Handshake_Type handshake_msg) const
{
const uint32_t mask = bitmask_for_handshake_type(handshake_msg);
return (m_hand_received_mask & mask) != 0;
}
std::pair<Handshake_Type, std::vector<uint8_t>>
Handshake_State::get_next_handshake_msg()
{
const bool expecting_ccs =
(bitmask_for_handshake_type(HANDSHAKE_CCS) & m_hand_expecting_mask) != 0;
return m_handshake_io->get_next_record(expecting_ccs);
}
std::vector<uint8_t> Handshake_State::session_ticket() const
{
if(new_session_ticket() && !new_session_ticket()->ticket().empty())
return new_session_ticket()->ticket();
return client_hello()->session_ticket();
}
std::unique_ptr<KDF> Handshake_State::protocol_specific_prf() const
{
const std::string prf_algo = ciphersuite().prf_algo();
if(prf_algo == "MD5" || prf_algo == "SHA-1")
return KDF::create_or_throw("TLS-12-PRF(SHA-256)");
return KDF::create_or_throw("TLS-12-PRF(" + prf_algo + ")");
}
std::pair<std::string, Signature_Format>
Handshake_State::choose_sig_format(const Private_Key& key,
Signature_Scheme& chosen_scheme,
bool for_client_auth,
const Policy& policy) const
{
const std::string sig_algo = key.algo_name();
const std::vector<Signature_Scheme> allowed = policy.allowed_signature_schemes();
std::vector<Signature_Scheme> requested =
(for_client_auth) ? cert_req()->signature_schemes() : client_hello()->signature_schemes();
for(Signature_Scheme scheme : allowed)
{
if(signature_scheme_is_known(scheme) == false)
{
continue;
}
if(signature_algorithm_of_scheme(scheme) == sig_algo)
{
if(std::find(requested.begin(), requested.end(), scheme) != requested.end())
{
chosen_scheme = scheme;
break;
}
}
}
const std::string hash = hash_function_of_scheme(chosen_scheme);
if(!policy.allowed_signature_hash(hash))
{
throw TLS_Exception(Alert::HANDSHAKE_FAILURE,
"Policy refuses to accept signing with any hash supported by peer");
}
if(sig_algo == "RSA")
{
return std::make_pair(padding_string_for_scheme(chosen_scheme), IEEE_1363);
}
else if(sig_algo == "DSA" || sig_algo == "ECDSA")
{
return std::make_pair(padding_string_for_scheme(chosen_scheme), DER_SEQUENCE);
}
throw Invalid_Argument(sig_algo + " is invalid/unknown for TLS signatures");
}
namespace {
bool supported_algos_include(
const std::vector<Signature_Scheme>& schemes,
const std::string& key_type,
const std::string& hash_type)
{
for(Signature_Scheme scheme : schemes)
{
if(signature_scheme_is_known(scheme) &&
hash_function_of_scheme(scheme) == hash_type &&
signature_algorithm_of_scheme(scheme) == key_type)
{
return true;
}
}
return false;
}
}
std::pair<std::string, Signature_Format>
Handshake_State::parse_sig_format(const Public_Key& key,
Signature_Scheme scheme,
bool for_client_auth,
const Policy& policy) const
{
const std::string key_type = key.algo_name();
if(!policy.allowed_signature_method(key_type))
{
throw TLS_Exception(Alert::HANDSHAKE_FAILURE,
"Rejecting " + key_type + " signature");
}
if(scheme == Signature_Scheme::NONE)
throw Decoding_Error("Counterparty did not send hash/sig IDS");
if(key_type != signature_algorithm_of_scheme(scheme))
throw Decoding_Error("Counterparty sent inconsistent key and sig types");
if(for_client_auth && !cert_req())
{
throw TLS_Exception(Alert::HANDSHAKE_FAILURE,
"No certificate verify set");
}
/*
Confirm the signature type we just received against the
supported_algos list that we sent; it better be there.
*/
const std::vector<Signature_Scheme> supported_algos =
for_client_auth ? cert_req()->signature_schemes() :
client_hello()->signature_schemes();
if(!signature_scheme_is_known(scheme))
throw TLS_Exception(Alert::HANDSHAKE_FAILURE,
"Peer sent unknown signature scheme");
const std::string hash_algo = hash_function_of_scheme(scheme);
if(!supported_algos_include(supported_algos, key_type, hash_algo))
{
throw TLS_Exception(Alert::ILLEGAL_PARAMETER,
"TLS signature extension did not allow for " +
key_type + "/" + hash_algo + " signature");
}
if(key_type == "RSA")
{
return std::make_pair(padding_string_for_scheme(scheme), IEEE_1363);
}
else if(key_type == "DSA" || key_type == "ECDSA")
{
return std::make_pair(padding_string_for_scheme(scheme), DER_SEQUENCE);
}
throw Invalid_Argument(key_type + " is invalid/unknown for TLS signatures");
}
}
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Denis Shienkov <[email protected]>
** Copyright (C) 2012 Laszlo Papp <[email protected]>
** Copyright (C) 2012 Andre Hartmann <[email protected]>
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtSerialPort module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qserialport_win_p.h"
#include <QtCore/qelapsedtimer.h>
#include <QtCore/qthread.h>
#include <QtCore/qtimer.h>
QT_BEGIN_NAMESPACE
class QSerialPortPrivate;
class CommEventNotifier : public QThread
{
Q_OBJECT
signals:
void eventMask(quint32 mask);
public:
CommEventNotifier(DWORD mask, QSerialPortPrivate *d, QObject *parent)
: QThread(parent), dptr(d), running(true) {
connect(this, SIGNAL(eventMask(quint32)), this, SLOT(processNotification(quint32)));
::SetCommMask(dptr->descriptor, mask);
}
virtual ~CommEventNotifier() {
running = false;
::SetCommMask(dptr->descriptor, 0);
wait();
}
protected:
void run() Q_DECL_OVERRIDE {
DWORD mask = 0;
while (running) {
if (::WaitCommEvent(dptr->descriptor, &mask, FALSE)) {
// Wait until complete the operation changes the port settings,
// see updateDcb().
dptr->settingsChangeMutex.lock();
dptr->settingsChangeMutex.unlock();
emit eventMask(quint32(mask));
}
}
}
private slots:
void processNotification(quint32 eventMask) {
bool error = false;
// Check for unexpected event. This event triggered when pulled previously
// opened device from the system, when opened as for not to read and not to
// write options and so forth.
if ((eventMask == 0)
|| ((eventMask & (EV_ERR | EV_RXCHAR | EV_TXEMPTY)) == 0)) {
error = true;
}
if (error || (EV_ERR & eventMask))
dptr->processIoErrors(error);
if (EV_RXCHAR & eventMask)
dptr->notifyRead();
if (EV_TXEMPTY & eventMask)
dptr->notifyWrite(QSerialPortPrivateData::WriteChunkSize);
}
private:
QSerialPortPrivate *dptr;
mutable bool running;
};
class WaitCommEventBreaker : public QThread
{
Q_OBJECT
public:
WaitCommEventBreaker(HANDLE descriptor, int timeout, QObject *parent = 0)
: QThread(parent), descriptor(descriptor), timeout(timeout), worked(false) {
start();
}
virtual ~WaitCommEventBreaker() {
stop();
wait();
}
void stop() {
exit(0);
}
bool isWorked() const {
return worked;
}
protected:
void run() {
QTimer timer;
QObject::connect(&timer, SIGNAL(timeout()), this, SLOT(processTimeout()), Qt::DirectConnection);
timer.start(timeout);
exec();
worked = true;
}
private slots:
void processTimeout() {
::SetCommMask(descriptor, 0);
stop();
}
private:
HANDLE descriptor;
int timeout;
mutable bool worked;
};
#include "qserialport_wince.moc"
QSerialPortPrivate::QSerialPortPrivate(QSerialPort *q)
: QSerialPortPrivateData(q)
, descriptor(INVALID_HANDLE_VALUE)
, parityErrorOccurred(false)
, eventNotifier(0)
{
}
bool QSerialPortPrivate::open(QIODevice::OpenMode mode)
{
Q_Q(QSerialPort);
DWORD desiredAccess = 0;
DWORD eventMask = EV_ERR;
if (mode & QIODevice::ReadOnly) {
desiredAccess |= GENERIC_READ;
eventMask |= EV_RXCHAR;
}
if (mode & QIODevice::WriteOnly) {
desiredAccess |= GENERIC_WRITE;
eventMask |= EV_TXEMPTY;
}
descriptor = ::CreateFile(reinterpret_cast<const wchar_t*>(systemLocation.utf16()),
desiredAccess, 0, NULL, OPEN_EXISTING, 0, NULL);
if (descriptor == INVALID_HANDLE_VALUE) {
q->setError(decodeSystemError());
return false;
}
if (!::GetCommState(descriptor, &restoredDcb)) {
q->setError(decodeSystemError());
return false;
}
currentDcb = restoredDcb;
currentDcb.fBinary = true;
currentDcb.fInX = false;
currentDcb.fOutX = false;
currentDcb.fAbortOnError = false;
currentDcb.fNull = false;
currentDcb.fErrorChar = false;
if (!updateDcb())
return false;
if (!::GetCommTimeouts(descriptor, &restoredCommTimeouts)) {
q->setError(decodeSystemError());
return false;
}
::memset(¤tCommTimeouts, 0, sizeof(currentCommTimeouts));
currentCommTimeouts.ReadIntervalTimeout = MAXDWORD;
if (!updateCommTimeouts())
return false;
eventNotifier = new CommEventNotifier(eventMask, this, q);
eventNotifier->start();
detectDefaultSettings();
return true;
}
void QSerialPortPrivate::close()
{
if (eventNotifier) {
eventNotifier->deleteLater();
eventNotifier = 0;
}
if (settingsRestoredOnClose) {
::SetCommState(descriptor, &restoredDcb);
::SetCommTimeouts(descriptor, &restoredCommTimeouts);
}
::CloseHandle(descriptor);
descriptor = INVALID_HANDLE_VALUE;
}
bool QSerialPortPrivate::flush()
{
return notifyWrite() && ::FlushFileBuffers(descriptor);
}
bool QSerialPortPrivate::clear(QSerialPort::Directions directions)
{
DWORD flags = 0;
if (directions & QSerialPort::Input)
flags |= PURGE_RXABORT | PURGE_RXCLEAR;
if (directions & QSerialPort::Output)
flags |= PURGE_TXABORT | PURGE_TXCLEAR;
return ::PurgeComm(descriptor, flags);
}
qint64 QSerialPortPrivate::bytesAvailable() const
{
return readBuffer.size();
}
qint64 QSerialPortPrivate::readFromBuffer(char *data, qint64 maxSize)
{
if (readBuffer.isEmpty())
return 0;
if (maxSize == 1) {
*data = readBuffer.getChar();
return 1;
}
const qint64 bytesToRead = qMin(qint64(readBuffer.size()), maxSize);
qint64 readSoFar = 0;
while (readSoFar < bytesToRead) {
const char *ptr = readBuffer.readPointer();
const int bytesToReadFromThisBlock = qMin(int(bytesToRead - readSoFar),
readBuffer.nextDataBlockSize());
::memcpy(data + readSoFar, ptr, bytesToReadFromThisBlock);
readSoFar += bytesToReadFromThisBlock;
readBuffer.free(bytesToReadFromThisBlock);
}
return readSoFar;
}
qint64 QSerialPortPrivate::writeToBuffer(const char *data, qint64 maxSize)
{
char *ptr = writeBuffer.reserve(maxSize);
if (maxSize == 1)
*ptr = *data;
else
::memcpy(ptr, data, maxSize);
// trigger write sequence
notifyWrite(QSerialPortPrivateData::WriteChunkSize);
return maxSize;
}
bool QSerialPortPrivate::waitForReadyRead(int msec)
{
if (!readBuffer.isEmpty())
return true;
QElapsedTimer stopWatch;
stopWatch.start();
forever {
bool readyToRead = false;
bool readyToWrite = false;
bool timedOut = false;
if (!waitForReadOrWrite(&readyToRead, &readyToWrite,
true, !writeBuffer.isEmpty(),
timeoutValue(msec, stopWatch.elapsed()),
&timedOut)) {
return false;
}
if (readyToRead) {
if (notifyRead())
return true;
}
if (readyToWrite)
notifyWrite(WriteChunkSize);
}
return false;
}
bool QSerialPortPrivate::waitForBytesWritten(int msec)
{
if (writeBuffer.isEmpty())
return false;
QElapsedTimer stopWatch;
stopWatch.start();
forever {
bool readyToRead = false;
bool readyToWrite = false;
bool timedOut = false;
if (!waitForReadOrWrite(&readyToRead, &readyToWrite,
true, !writeBuffer.isEmpty(),
timeoutValue(msec, stopWatch.elapsed()),
&timedOut)) {
return false;
}
if (readyToRead) {
if (!notifyRead())
return false;
}
if (readyToWrite) {
if (notifyWrite(WriteChunkSize))
return true;
}
}
return false;
}
bool QSerialPortPrivate::notifyRead()
{
Q_Q(QSerialPort);
DWORD bytesToRead = (policy == QSerialPort::IgnorePolicy) ? ReadChunkSize : 1;
if (readBufferMaxSize && bytesToRead > (readBufferMaxSize - readBuffer.size())) {
bytesToRead = readBufferMaxSize - readBuffer.size();
if (bytesToRead == 0) {
// Buffer is full. User must read data from the buffer
// before we can read more from the port.
return false;
}
}
char *ptr = readBuffer.reserve(bytesToRead);
DWORD readBytes = 0;
BOOL sucessResult = ::ReadFile(descriptor, ptr, bytesToRead, &readBytes, NULL);
if (!sucessResult) {
readBuffer.truncate(bytesToRead);
q->setError(QSerialPort::ReadError);
return false;
}
readBuffer.truncate(readBytes);
// Process emulate policy.
if ((policy != QSerialPort::IgnorePolicy) && parityErrorOccurred) {
parityErrorOccurred = false;
switch (policy) {
case QSerialPort::SkipPolicy:
readBuffer.getChar();
return true;
case QSerialPort::PassZeroPolicy:
readBuffer.getChar();
readBuffer.putChar('\0');
break;
case QSerialPort::StopReceivingPolicy:
// FIXME: Maybe need disable read notifier?
break;
default:
break;
}
}
if (readBytes > 0)
emit q->readyRead();
return true;
}
bool QSerialPortPrivate::notifyWrite(int maxSize)
{
Q_Q(QSerialPort);
int nextSize = qMin(writeBuffer.nextDataBlockSize(), maxSize);
const char *ptr = writeBuffer.readPointer();
DWORD bytesWritten = 0;
if (!::WriteFile(descriptor, ptr, nextSize, &bytesWritten, NULL)) {
q->setError(QSerialPort::WriteError);
return false;
}
writeBuffer.free(bytesWritten);
if (bytesWritten > 0)
emit q->bytesWritten(bytesWritten);
return true;
}
bool QSerialPortPrivate::waitForReadOrWrite(bool *selectForRead, bool *selectForWrite,
bool checkRead, bool checkWrite,
int msecs, bool *timedOut)
{
Q_Q(QSerialPort);
DWORD eventMask = 0;
// FIXME: Here the situation is not properly handled with zero timeout:
// breaker can work out before you call a method WaitCommEvent()
// and so it will loop forever!
WaitCommEventBreaker breaker(descriptor, qMax(msecs, 0));
::WaitCommEvent(descriptor, &eventMask, NULL);
breaker.stop();
if (breaker.isWorked()) {
*timedOut = true;
q->setError(QSerialPort::TimeoutError);
}
if (!breaker.isWorked()) {
if (checkRead) {
Q_ASSERT(selectForRead);
*selectForRead = eventMask & EV_RXCHAR;
}
if (checkWrite) {
Q_ASSERT(selectForWrite);
*selectForWrite = eventMask & EV_TXEMPTY;
}
return true;
}
return false;
}
bool QSerialPortPrivate::updateDcb()
{
Q_Q(QSerialPort);
QMutexLocker locker(&settingsChangeMutex);
DWORD eventMask = 0;
// Save the event mask
if (!::GetCommMask(descriptor, &eventMask))
return false;
// Break event notifier from WaitCommEvent
::SetCommMask(descriptor, 0);
// Change parameters
bool ret = ::SetCommState(descriptor, ¤tDcb);
if (!ret)
q->setError(decodeSystemError());
// Restore the event mask
::SetCommMask(descriptor, eventMask);
return ret;
}
bool QSerialPortPrivate::updateCommTimeouts()
{
Q_Q(QSerialPort);
if (!::SetCommTimeouts(descriptor, ¤tCommTimeouts)) {
q->setError(decodeSystemError());
return false;
}
return true;
}
static const QLatin1String defaultPathPostfix(":");
QString QSerialPortPrivate::portNameToSystemLocation(const QString &port)
{
QString ret = port;
if (!ret.contains(defaultPathPostfix))
ret.append(defaultPathPostfix);
return ret;
}
QString QSerialPortPrivate::portNameFromSystemLocation(const QString &location)
{
QString ret = location;
if (ret.contains(defaultPathPostfix))
ret.remove(defaultPathPostfix);
return ret;
}
QT_END_NAMESPACE
<commit_msg>Use local QLatin1Char as opposed to a static QLatin1String<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Denis Shienkov <[email protected]>
** Copyright (C) 2012 Laszlo Papp <[email protected]>
** Copyright (C) 2012 Andre Hartmann <[email protected]>
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtSerialPort module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qserialport_win_p.h"
#include <QtCore/qelapsedtimer.h>
#include <QtCore/qthread.h>
#include <QtCore/qtimer.h>
QT_BEGIN_NAMESPACE
class QSerialPortPrivate;
class CommEventNotifier : public QThread
{
Q_OBJECT
signals:
void eventMask(quint32 mask);
public:
CommEventNotifier(DWORD mask, QSerialPortPrivate *d, QObject *parent)
: QThread(parent), dptr(d), running(true) {
connect(this, SIGNAL(eventMask(quint32)), this, SLOT(processNotification(quint32)));
::SetCommMask(dptr->descriptor, mask);
}
virtual ~CommEventNotifier() {
running = false;
::SetCommMask(dptr->descriptor, 0);
wait();
}
protected:
void run() Q_DECL_OVERRIDE {
DWORD mask = 0;
while (running) {
if (::WaitCommEvent(dptr->descriptor, &mask, FALSE)) {
// Wait until complete the operation changes the port settings,
// see updateDcb().
dptr->settingsChangeMutex.lock();
dptr->settingsChangeMutex.unlock();
emit eventMask(quint32(mask));
}
}
}
private slots:
void processNotification(quint32 eventMask) {
bool error = false;
// Check for unexpected event. This event triggered when pulled previously
// opened device from the system, when opened as for not to read and not to
// write options and so forth.
if ((eventMask == 0)
|| ((eventMask & (EV_ERR | EV_RXCHAR | EV_TXEMPTY)) == 0)) {
error = true;
}
if (error || (EV_ERR & eventMask))
dptr->processIoErrors(error);
if (EV_RXCHAR & eventMask)
dptr->notifyRead();
if (EV_TXEMPTY & eventMask)
dptr->notifyWrite(QSerialPortPrivateData::WriteChunkSize);
}
private:
QSerialPortPrivate *dptr;
mutable bool running;
};
class WaitCommEventBreaker : public QThread
{
Q_OBJECT
public:
WaitCommEventBreaker(HANDLE descriptor, int timeout, QObject *parent = 0)
: QThread(parent), descriptor(descriptor), timeout(timeout), worked(false) {
start();
}
virtual ~WaitCommEventBreaker() {
stop();
wait();
}
void stop() {
exit(0);
}
bool isWorked() const {
return worked;
}
protected:
void run() {
QTimer timer;
QObject::connect(&timer, SIGNAL(timeout()), this, SLOT(processTimeout()), Qt::DirectConnection);
timer.start(timeout);
exec();
worked = true;
}
private slots:
void processTimeout() {
::SetCommMask(descriptor, 0);
stop();
}
private:
HANDLE descriptor;
int timeout;
mutable bool worked;
};
#include "qserialport_wince.moc"
QSerialPortPrivate::QSerialPortPrivate(QSerialPort *q)
: QSerialPortPrivateData(q)
, descriptor(INVALID_HANDLE_VALUE)
, parityErrorOccurred(false)
, eventNotifier(0)
{
}
bool QSerialPortPrivate::open(QIODevice::OpenMode mode)
{
Q_Q(QSerialPort);
DWORD desiredAccess = 0;
DWORD eventMask = EV_ERR;
if (mode & QIODevice::ReadOnly) {
desiredAccess |= GENERIC_READ;
eventMask |= EV_RXCHAR;
}
if (mode & QIODevice::WriteOnly) {
desiredAccess |= GENERIC_WRITE;
eventMask |= EV_TXEMPTY;
}
descriptor = ::CreateFile(reinterpret_cast<const wchar_t*>(systemLocation.utf16()),
desiredAccess, 0, NULL, OPEN_EXISTING, 0, NULL);
if (descriptor == INVALID_HANDLE_VALUE) {
q->setError(decodeSystemError());
return false;
}
if (!::GetCommState(descriptor, &restoredDcb)) {
q->setError(decodeSystemError());
return false;
}
currentDcb = restoredDcb;
currentDcb.fBinary = true;
currentDcb.fInX = false;
currentDcb.fOutX = false;
currentDcb.fAbortOnError = false;
currentDcb.fNull = false;
currentDcb.fErrorChar = false;
if (!updateDcb())
return false;
if (!::GetCommTimeouts(descriptor, &restoredCommTimeouts)) {
q->setError(decodeSystemError());
return false;
}
::memset(¤tCommTimeouts, 0, sizeof(currentCommTimeouts));
currentCommTimeouts.ReadIntervalTimeout = MAXDWORD;
if (!updateCommTimeouts())
return false;
eventNotifier = new CommEventNotifier(eventMask, this, q);
eventNotifier->start();
detectDefaultSettings();
return true;
}
void QSerialPortPrivate::close()
{
if (eventNotifier) {
eventNotifier->deleteLater();
eventNotifier = 0;
}
if (settingsRestoredOnClose) {
::SetCommState(descriptor, &restoredDcb);
::SetCommTimeouts(descriptor, &restoredCommTimeouts);
}
::CloseHandle(descriptor);
descriptor = INVALID_HANDLE_VALUE;
}
bool QSerialPortPrivate::flush()
{
return notifyWrite() && ::FlushFileBuffers(descriptor);
}
bool QSerialPortPrivate::clear(QSerialPort::Directions directions)
{
DWORD flags = 0;
if (directions & QSerialPort::Input)
flags |= PURGE_RXABORT | PURGE_RXCLEAR;
if (directions & QSerialPort::Output)
flags |= PURGE_TXABORT | PURGE_TXCLEAR;
return ::PurgeComm(descriptor, flags);
}
qint64 QSerialPortPrivate::bytesAvailable() const
{
return readBuffer.size();
}
qint64 QSerialPortPrivate::readFromBuffer(char *data, qint64 maxSize)
{
if (readBuffer.isEmpty())
return 0;
if (maxSize == 1) {
*data = readBuffer.getChar();
return 1;
}
const qint64 bytesToRead = qMin(qint64(readBuffer.size()), maxSize);
qint64 readSoFar = 0;
while (readSoFar < bytesToRead) {
const char *ptr = readBuffer.readPointer();
const int bytesToReadFromThisBlock = qMin(int(bytesToRead - readSoFar),
readBuffer.nextDataBlockSize());
::memcpy(data + readSoFar, ptr, bytesToReadFromThisBlock);
readSoFar += bytesToReadFromThisBlock;
readBuffer.free(bytesToReadFromThisBlock);
}
return readSoFar;
}
qint64 QSerialPortPrivate::writeToBuffer(const char *data, qint64 maxSize)
{
char *ptr = writeBuffer.reserve(maxSize);
if (maxSize == 1)
*ptr = *data;
else
::memcpy(ptr, data, maxSize);
// trigger write sequence
notifyWrite(QSerialPortPrivateData::WriteChunkSize);
return maxSize;
}
bool QSerialPortPrivate::waitForReadyRead(int msec)
{
if (!readBuffer.isEmpty())
return true;
QElapsedTimer stopWatch;
stopWatch.start();
forever {
bool readyToRead = false;
bool readyToWrite = false;
bool timedOut = false;
if (!waitForReadOrWrite(&readyToRead, &readyToWrite,
true, !writeBuffer.isEmpty(),
timeoutValue(msec, stopWatch.elapsed()),
&timedOut)) {
return false;
}
if (readyToRead) {
if (notifyRead())
return true;
}
if (readyToWrite)
notifyWrite(WriteChunkSize);
}
return false;
}
bool QSerialPortPrivate::waitForBytesWritten(int msec)
{
if (writeBuffer.isEmpty())
return false;
QElapsedTimer stopWatch;
stopWatch.start();
forever {
bool readyToRead = false;
bool readyToWrite = false;
bool timedOut = false;
if (!waitForReadOrWrite(&readyToRead, &readyToWrite,
true, !writeBuffer.isEmpty(),
timeoutValue(msec, stopWatch.elapsed()),
&timedOut)) {
return false;
}
if (readyToRead) {
if (!notifyRead())
return false;
}
if (readyToWrite) {
if (notifyWrite(WriteChunkSize))
return true;
}
}
return false;
}
bool QSerialPortPrivate::notifyRead()
{
Q_Q(QSerialPort);
DWORD bytesToRead = (policy == QSerialPort::IgnorePolicy) ? ReadChunkSize : 1;
if (readBufferMaxSize && bytesToRead > (readBufferMaxSize - readBuffer.size())) {
bytesToRead = readBufferMaxSize - readBuffer.size();
if (bytesToRead == 0) {
// Buffer is full. User must read data from the buffer
// before we can read more from the port.
return false;
}
}
char *ptr = readBuffer.reserve(bytesToRead);
DWORD readBytes = 0;
BOOL sucessResult = ::ReadFile(descriptor, ptr, bytesToRead, &readBytes, NULL);
if (!sucessResult) {
readBuffer.truncate(bytesToRead);
q->setError(QSerialPort::ReadError);
return false;
}
readBuffer.truncate(readBytes);
// Process emulate policy.
if ((policy != QSerialPort::IgnorePolicy) && parityErrorOccurred) {
parityErrorOccurred = false;
switch (policy) {
case QSerialPort::SkipPolicy:
readBuffer.getChar();
return true;
case QSerialPort::PassZeroPolicy:
readBuffer.getChar();
readBuffer.putChar('\0');
break;
case QSerialPort::StopReceivingPolicy:
// FIXME: Maybe need disable read notifier?
break;
default:
break;
}
}
if (readBytes > 0)
emit q->readyRead();
return true;
}
bool QSerialPortPrivate::notifyWrite(int maxSize)
{
Q_Q(QSerialPort);
int nextSize = qMin(writeBuffer.nextDataBlockSize(), maxSize);
const char *ptr = writeBuffer.readPointer();
DWORD bytesWritten = 0;
if (!::WriteFile(descriptor, ptr, nextSize, &bytesWritten, NULL)) {
q->setError(QSerialPort::WriteError);
return false;
}
writeBuffer.free(bytesWritten);
if (bytesWritten > 0)
emit q->bytesWritten(bytesWritten);
return true;
}
bool QSerialPortPrivate::waitForReadOrWrite(bool *selectForRead, bool *selectForWrite,
bool checkRead, bool checkWrite,
int msecs, bool *timedOut)
{
Q_Q(QSerialPort);
DWORD eventMask = 0;
// FIXME: Here the situation is not properly handled with zero timeout:
// breaker can work out before you call a method WaitCommEvent()
// and so it will loop forever!
WaitCommEventBreaker breaker(descriptor, qMax(msecs, 0));
::WaitCommEvent(descriptor, &eventMask, NULL);
breaker.stop();
if (breaker.isWorked()) {
*timedOut = true;
q->setError(QSerialPort::TimeoutError);
}
if (!breaker.isWorked()) {
if (checkRead) {
Q_ASSERT(selectForRead);
*selectForRead = eventMask & EV_RXCHAR;
}
if (checkWrite) {
Q_ASSERT(selectForWrite);
*selectForWrite = eventMask & EV_TXEMPTY;
}
return true;
}
return false;
}
bool QSerialPortPrivate::updateDcb()
{
Q_Q(QSerialPort);
QMutexLocker locker(&settingsChangeMutex);
DWORD eventMask = 0;
// Save the event mask
if (!::GetCommMask(descriptor, &eventMask))
return false;
// Break event notifier from WaitCommEvent
::SetCommMask(descriptor, 0);
// Change parameters
bool ret = ::SetCommState(descriptor, ¤tDcb);
if (!ret)
q->setError(decodeSystemError());
// Restore the event mask
::SetCommMask(descriptor, eventMask);
return ret;
}
bool QSerialPortPrivate::updateCommTimeouts()
{
Q_Q(QSerialPort);
if (!::SetCommTimeouts(descriptor, ¤tCommTimeouts)) {
q->setError(decodeSystemError());
return false;
}
return true;
}
QString QSerialPortPrivate::portNameToSystemLocation(const QString &port)
{
QString ret = port;
if (!ret.contains(QLatin1Char(':')))
ret.append(QLatin1Char(':'));
return ret;
}
QString QSerialPortPrivate::portNameFromSystemLocation(const QString &location)
{
QString ret = location;
if (ret.contains(QLatin1Char(':')))
ret.remove(QLatin1Char(':'));
return ret;
}
QT_END_NAMESPACE
<|endoftext|> |
<commit_before>// Copyright Joshua Boyce 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// This file is part of HadesMem.
// <http://www.raptorfactor.com/> <[email protected]>
#include "hadesmem/module_list.hpp"
#include "hadesmem/detail/warning_disable_prefix.hpp"
#include <boost/assert.hpp>
#include "hadesmem/detail/warning_disable_suffix.hpp"
#include "hadesmem/error.hpp"
#include "hadesmem/module.hpp"
#include "hadesmem/process.hpp"
#include "hadesmem/detail/module_iterator_impl.hpp"
#include <windows.h>
#include <tlhelp32.h>
#include "hadesmem/error.hpp"
#include "hadesmem/module.hpp"
#include "hadesmem/process.hpp"
#include "hadesmem/detail/module_iterator_impl.hpp"
namespace hadesmem
{
ModuleIterator::ModuleIterator() BOOST_NOEXCEPT
: impl_()
{ }
ModuleIterator::ModuleIterator(Process const* process)
: impl_(new detail::ModuleIteratorImpl)
{
BOOST_ASSERT(impl_.get());
BOOST_ASSERT(process != nullptr);
impl_->process_ = process;
impl_->snap_ = ::CreateToolhelp32Snapshot(
TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32,
impl_->process_->GetId());
if (impl_->snap_ == INVALID_HANDLE_VALUE)
{
if (GetLastError() == ERROR_BAD_LENGTH)
{
impl_->snap_ = ::CreateToolhelp32Snapshot(
TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32,
impl_->process_->GetId());
if (impl_->snap_ == INVALID_HANDLE_VALUE)
{
DWORD const last_error = ::GetLastError();
BOOST_THROW_EXCEPTION(HadesMemError() <<
ErrorString("CreateToolhelp32Snapshot failed.") <<
ErrorCodeWinLast(last_error));
}
}
else
{
DWORD const last_error = ::GetLastError();
BOOST_THROW_EXCEPTION(HadesMemError() <<
ErrorString("CreateToolhelp32Snapshot failed.") <<
ErrorCodeWinLast(last_error));
}
}
MODULEENTRY32 entry;
::ZeroMemory(&entry, sizeof(entry));
entry.dwSize = sizeof(entry);
if (!::Module32First(impl_->snap_, &entry))
{
DWORD const last_error = ::GetLastError();
if (last_error == ERROR_NO_MORE_FILES)
{
impl_.reset();
return;
}
BOOST_THROW_EXCEPTION(HadesMemError() <<
ErrorString("Module32First failed.") <<
ErrorCodeWinLast(last_error));
}
impl_->module_ = Module(impl_->process_, entry);
}
ModuleIterator::ModuleIterator(ModuleIterator const& other) BOOST_NOEXCEPT
: impl_(other.impl_)
{ }
ModuleIterator& ModuleIterator::operator=(ModuleIterator const& other)
BOOST_NOEXCEPT
{
impl_ = other.impl_;
return *this;
}
ModuleIterator::ModuleIterator(ModuleIterator&& other) BOOST_NOEXCEPT
: impl_(std::move(other.impl_))
{ }
ModuleIterator& ModuleIterator::operator=(ModuleIterator&& other)
BOOST_NOEXCEPT
{
impl_ = std::move(other.impl_);
return *this;
}
ModuleIterator::~ModuleIterator()
{ }
ModuleIterator::reference ModuleIterator::operator*() const BOOST_NOEXCEPT
{
BOOST_ASSERT(impl_.get());
return *impl_->module_;
}
ModuleIterator::pointer ModuleIterator::operator->() const BOOST_NOEXCEPT
{
BOOST_ASSERT(impl_.get());
return &*impl_->module_;
}
ModuleIterator& ModuleIterator::operator++()
{
BOOST_ASSERT(impl_.get());
MODULEENTRY32 entry;
::ZeroMemory(&entry, sizeof(entry));
entry.dwSize = sizeof(entry);
if (!::Module32Next(impl_->snap_, &entry))
{
DWORD const last_error = ::GetLastError();
if (last_error == ERROR_NO_MORE_FILES)
{
impl_.reset();
return *this;
}
BOOST_THROW_EXCEPTION(HadesMemError() <<
ErrorString("Module32Next failed.") <<
ErrorCodeWinLast(last_error));
}
impl_->module_ = Module(impl_->process_, entry);
return *this;
}
ModuleIterator ModuleIterator::operator++(int)
{
ModuleIterator iter(*this);
++*this;
return iter;
}
bool ModuleIterator::operator==(ModuleIterator const& other) const
BOOST_NOEXCEPT
{
return impl_ == other.impl_;
}
bool ModuleIterator::operator!=(ModuleIterator const& other) const
BOOST_NOEXCEPT
{
return !(*this == other);
}
ModuleList::ModuleList(Process const* process) BOOST_NOEXCEPT
: process_(process)
{
BOOST_ASSERT(process != nullptr);
}
ModuleList::ModuleList(ModuleList const& other) BOOST_NOEXCEPT
: process_(other.process_)
{ }
ModuleList& ModuleList::operator=(ModuleList const& other) BOOST_NOEXCEPT
{
process_ = other.process_;
return *this;
}
ModuleList::ModuleList(ModuleList&& other) BOOST_NOEXCEPT
: process_(other.process_)
{
other.process_ = nullptr;
}
ModuleList& ModuleList::operator=(ModuleList&& other) BOOST_NOEXCEPT
{
process_ = other.process_;
other.process_ = nullptr;
return *this;
}
ModuleList::~ModuleList()
{ }
ModuleList::iterator ModuleList::begin()
{
return ModuleList::iterator(process_);
}
ModuleList::const_iterator ModuleList::begin() const
{
return ModuleList::iterator(process_);
}
ModuleList::iterator ModuleList::end() BOOST_NOEXCEPT
{
return ModuleList::iterator();
}
ModuleList::const_iterator ModuleList::end() const BOOST_NOEXCEPT
{
return ModuleList::iterator();
}
}
<commit_msg>* Remove accidental include.<commit_after>// Copyright Joshua Boyce 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// This file is part of HadesMem.
// <http://www.raptorfactor.com/> <[email protected]>
#include "hadesmem/module_list.hpp"
#include "hadesmem/detail/warning_disable_prefix.hpp"
#include <boost/assert.hpp>
#include "hadesmem/detail/warning_disable_suffix.hpp"
#include <windows.h>
#include <tlhelp32.h>
#include "hadesmem/error.hpp"
#include "hadesmem/module.hpp"
#include "hadesmem/process.hpp"
#include "hadesmem/detail/module_iterator_impl.hpp"
namespace hadesmem
{
ModuleIterator::ModuleIterator() BOOST_NOEXCEPT
: impl_()
{ }
ModuleIterator::ModuleIterator(Process const* process)
: impl_(new detail::ModuleIteratorImpl)
{
BOOST_ASSERT(impl_.get());
BOOST_ASSERT(process != nullptr);
impl_->process_ = process;
impl_->snap_ = ::CreateToolhelp32Snapshot(
TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32,
impl_->process_->GetId());
if (impl_->snap_ == INVALID_HANDLE_VALUE)
{
if (GetLastError() == ERROR_BAD_LENGTH)
{
impl_->snap_ = ::CreateToolhelp32Snapshot(
TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32,
impl_->process_->GetId());
if (impl_->snap_ == INVALID_HANDLE_VALUE)
{
DWORD const last_error = ::GetLastError();
BOOST_THROW_EXCEPTION(HadesMemError() <<
ErrorString("CreateToolhelp32Snapshot failed.") <<
ErrorCodeWinLast(last_error));
}
}
else
{
DWORD const last_error = ::GetLastError();
BOOST_THROW_EXCEPTION(HadesMemError() <<
ErrorString("CreateToolhelp32Snapshot failed.") <<
ErrorCodeWinLast(last_error));
}
}
MODULEENTRY32 entry;
::ZeroMemory(&entry, sizeof(entry));
entry.dwSize = sizeof(entry);
if (!::Module32First(impl_->snap_, &entry))
{
DWORD const last_error = ::GetLastError();
if (last_error == ERROR_NO_MORE_FILES)
{
impl_.reset();
return;
}
BOOST_THROW_EXCEPTION(HadesMemError() <<
ErrorString("Module32First failed.") <<
ErrorCodeWinLast(last_error));
}
impl_->module_ = Module(impl_->process_, entry);
}
ModuleIterator::ModuleIterator(ModuleIterator const& other) BOOST_NOEXCEPT
: impl_(other.impl_)
{ }
ModuleIterator& ModuleIterator::operator=(ModuleIterator const& other)
BOOST_NOEXCEPT
{
impl_ = other.impl_;
return *this;
}
ModuleIterator::ModuleIterator(ModuleIterator&& other) BOOST_NOEXCEPT
: impl_(std::move(other.impl_))
{ }
ModuleIterator& ModuleIterator::operator=(ModuleIterator&& other)
BOOST_NOEXCEPT
{
impl_ = std::move(other.impl_);
return *this;
}
ModuleIterator::~ModuleIterator()
{ }
ModuleIterator::reference ModuleIterator::operator*() const BOOST_NOEXCEPT
{
BOOST_ASSERT(impl_.get());
return *impl_->module_;
}
ModuleIterator::pointer ModuleIterator::operator->() const BOOST_NOEXCEPT
{
BOOST_ASSERT(impl_.get());
return &*impl_->module_;
}
ModuleIterator& ModuleIterator::operator++()
{
BOOST_ASSERT(impl_.get());
MODULEENTRY32 entry;
::ZeroMemory(&entry, sizeof(entry));
entry.dwSize = sizeof(entry);
if (!::Module32Next(impl_->snap_, &entry))
{
DWORD const last_error = ::GetLastError();
if (last_error == ERROR_NO_MORE_FILES)
{
impl_.reset();
return *this;
}
BOOST_THROW_EXCEPTION(HadesMemError() <<
ErrorString("Module32Next failed.") <<
ErrorCodeWinLast(last_error));
}
impl_->module_ = Module(impl_->process_, entry);
return *this;
}
ModuleIterator ModuleIterator::operator++(int)
{
ModuleIterator iter(*this);
++*this;
return iter;
}
bool ModuleIterator::operator==(ModuleIterator const& other) const
BOOST_NOEXCEPT
{
return impl_ == other.impl_;
}
bool ModuleIterator::operator!=(ModuleIterator const& other) const
BOOST_NOEXCEPT
{
return !(*this == other);
}
ModuleList::ModuleList(Process const* process) BOOST_NOEXCEPT
: process_(process)
{
BOOST_ASSERT(process != nullptr);
}
ModuleList::ModuleList(ModuleList const& other) BOOST_NOEXCEPT
: process_(other.process_)
{ }
ModuleList& ModuleList::operator=(ModuleList const& other) BOOST_NOEXCEPT
{
process_ = other.process_;
return *this;
}
ModuleList::ModuleList(ModuleList&& other) BOOST_NOEXCEPT
: process_(other.process_)
{
other.process_ = nullptr;
}
ModuleList& ModuleList::operator=(ModuleList&& other) BOOST_NOEXCEPT
{
process_ = other.process_;
other.process_ = nullptr;
return *this;
}
ModuleList::~ModuleList()
{ }
ModuleList::iterator ModuleList::begin()
{
return ModuleList::iterator(process_);
}
ModuleList::const_iterator ModuleList::begin() const
{
return ModuleList::iterator(process_);
}
ModuleList::iterator ModuleList::end() BOOST_NOEXCEPT
{
return ModuleList::iterator();
}
ModuleList::const_iterator ModuleList::end() const BOOST_NOEXCEPT
{
return ModuleList::iterator();
}
}
<|endoftext|> |
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/eval/eval/operation.h>
#include <vespa/eval/eval/simple_tensor.h>
#include <vespa/eval/eval/simple_tensor_engine.h>
#include <vespa/eval/eval/tensor_function.h>
#include <vespa/eval/eval/value_type.h>
#include <vespa/vespalib/util/stash.h>
#include <map>
using namespace vespalib;
using namespace vespalib::eval;
using namespace vespalib::eval::tensor_function;
struct EvalCtx {
const TensorEngine &engine;
Stash stash;
ErrorValue error;
std::vector<Value::UP> tensors;
std::vector<Value::CREF> params;
EvalCtx(const TensorEngine &engine_in)
: engine(engine_in), stash(), error(), tensors() {}
~EvalCtx() {}
size_t add_tensor(Value::UP tensor) {
size_t id = params.size();
params.emplace_back(*tensor);
tensors.push_back(std::move(tensor));
return id;
}
const Value &eval(const TensorFunction &fun) {
return fun.eval(params, stash);
}
const TensorFunction &compile(const tensor_function::Node &expr) {
return engine.compile(expr, stash);
}
Value::UP make_tensor_inject() {
return engine.from_spec(
TensorSpec("tensor(x[2],y[2])")
.add({{"x", 0}, {"y", 0}}, 1.0)
.add({{"x", 0}, {"y", 1}}, 2.0)
.add({{"x", 1}, {"y", 0}}, 3.0)
.add({{"x", 1}, {"y", 1}}, 4.0));
}
Value::UP make_tensor_reduce_input() {
return engine.from_spec(
TensorSpec("tensor(x[3],y[2])")
.add({{"x",0},{"y",0}}, 1)
.add({{"x",1},{"y",0}}, 2)
.add({{"x",2},{"y",0}}, 3)
.add({{"x",0},{"y",1}}, 4)
.add({{"x",1},{"y",1}}, 5)
.add({{"x",2},{"y",1}}, 6));
}
Value::UP make_tensor_reduce_y_output() {
return engine.from_spec(
TensorSpec("tensor(x[3])")
.add({{"x",0}}, 5)
.add({{"x",1}}, 7)
.add({{"x",2}}, 9));
}
Value::UP make_tensor_map_input() {
return engine.from_spec(
TensorSpec("tensor(x{},y{})")
.add({{"x","1"},{"y","1"}}, 1)
.add({{"x","2"},{"y","1"}}, -3)
.add({{"x","1"},{"y","2"}}, 5));
}
Value::UP make_tensor_map_output() {
return engine.from_spec(
TensorSpec("tensor(x{},y{})")
.add({{"x","1"},{"y","1"}}, -1)
.add({{"x","2"},{"y","1"}}, 3)
.add({{"x","1"},{"y","2"}}, -5));
}
Value::UP make_tensor_apply_lhs() {
return engine.from_spec(
TensorSpec("tensor(x{},y{})")
.add({{"x","1"},{"y","1"}}, 1)
.add({{"x","2"},{"y","1"}}, 3)
.add({{"x","1"},{"y","2"}}, 5));
}
Value::UP make_tensor_apply_rhs() {
return engine.from_spec(
TensorSpec("tensor(y{},z{})")
.add({{"y","1"},{"z","1"}}, 7)
.add({{"y","2"},{"z","1"}}, 11)
.add({{"y","1"},{"z","2"}}, 13));
}
Value::UP make_tensor_apply_output() {
return engine.from_spec(
TensorSpec("tensor(x{},y{},z{})")
.add({{"x","1"},{"y","1"},{"z","1"}}, 7)
.add({{"x","1"},{"y","1"},{"z","2"}}, 13)
.add({{"x","2"},{"y","1"},{"z","1"}}, 21)
.add({{"x","2"},{"y","1"},{"z","2"}}, 39)
.add({{"x","1"},{"y","2"},{"z","1"}}, 55));
}
};
void verify_equal(const Value &expect, const Value &value) {
const Tensor *tensor = value.as_tensor();
ASSERT_TRUE(tensor != nullptr);
const Tensor *expect_tensor = expect.as_tensor();
ASSERT_TRUE(expect_tensor != nullptr);
ASSERT_EQUAL(&expect_tensor->engine(), &tensor->engine());
auto expect_spec = expect_tensor->engine().to_spec(expect);
auto value_spec = tensor->engine().to_spec(value);
EXPECT_EQUAL(expect_spec, value_spec);
}
TEST("require that tensor injection works") {
EvalCtx ctx(SimpleTensorEngine::ref());
size_t a_id = ctx.add_tensor(ctx.make_tensor_inject());
Value::UP expect = ctx.make_tensor_inject();
const auto &fun = inject(ValueType::from_spec("tensor(x[2],y[2])"), a_id, ctx.stash);
EXPECT_EQUAL(expect->type(), fun.result_type);
const auto &prog = ctx.compile(fun);
TEST_DO(verify_equal(*expect, ctx.eval(prog)));
}
TEST("require that partial tensor reduction works") {
EvalCtx ctx(SimpleTensorEngine::ref());
size_t a_id = ctx.add_tensor(ctx.make_tensor_reduce_input());
Value::UP expect = ctx.make_tensor_reduce_y_output();
const auto &fun = reduce(inject(ValueType::from_spec("tensor(x[3],y[2])"), a_id, ctx.stash), Aggr::SUM, {"y"}, ctx.stash);
EXPECT_EQUAL(expect->type(), fun.result_type);
const auto &prog = ctx.compile(fun);
TEST_DO(verify_equal(*expect, ctx.eval(prog)));
}
TEST("require that full tensor reduction works") {
EvalCtx ctx(SimpleTensorEngine::ref());
size_t a_id = ctx.add_tensor(ctx.make_tensor_reduce_input());
const auto &fun = reduce(inject(ValueType::from_spec("tensor(x[3],y[2])"), a_id, ctx.stash), Aggr::SUM, {}, ctx.stash);
EXPECT_EQUAL(ValueType::from_spec("double"), fun.result_type);
const auto &prog = ctx.compile(fun);
const Value &result = ctx.eval(prog);
EXPECT_TRUE(result.is_double());
EXPECT_EQUAL(21.0, result.as_double());
}
TEST("require that tensor map works") {
EvalCtx ctx(SimpleTensorEngine::ref());
size_t a_id = ctx.add_tensor(ctx.make_tensor_map_input());
Value::UP expect = ctx.make_tensor_map_output();
const auto &fun = map(inject(ValueType::from_spec("tensor(x{},y{})"), a_id, ctx.stash), operation::Neg::f, ctx.stash);
EXPECT_EQUAL(expect->type(), fun.result_type);
const auto &prog = ctx.compile(fun);
TEST_DO(verify_equal(*expect, ctx.eval(prog)));
}
TEST("require that tensor join works") {
EvalCtx ctx(SimpleTensorEngine::ref());
size_t a_id = ctx.add_tensor(ctx.make_tensor_apply_lhs());
size_t b_id = ctx.add_tensor(ctx.make_tensor_apply_rhs());
Value::UP expect = ctx.make_tensor_apply_output();
const auto &fun = join(inject(ValueType::from_spec("tensor(x{},y{})"), a_id, ctx.stash),
inject(ValueType::from_spec("tensor(y{},z{})"), b_id, ctx.stash),
operation::Mul::f, ctx.stash);
EXPECT_EQUAL(expect->type(), fun.result_type);
const auto &prog = ctx.compile(fun);
TEST_DO(verify_equal(*expect, ctx.eval(prog)));
}
TEST_MAIN() { TEST_RUN_ALL(); }
<commit_msg>added test for push_children (tensor IR nodes)<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/eval/eval/operation.h>
#include <vespa/eval/eval/simple_tensor.h>
#include <vespa/eval/eval/simple_tensor_engine.h>
#include <vespa/eval/eval/tensor_function.h>
#include <vespa/eval/eval/value_type.h>
#include <vespa/vespalib/util/stash.h>
#include <map>
using namespace vespalib;
using namespace vespalib::eval;
using namespace vespalib::eval::tensor_function;
struct EvalCtx {
const TensorEngine &engine;
Stash stash;
ErrorValue error;
std::vector<Value::UP> tensors;
std::vector<Value::CREF> params;
EvalCtx(const TensorEngine &engine_in)
: engine(engine_in), stash(), error(), tensors() {}
~EvalCtx() {}
size_t add_tensor(Value::UP tensor) {
size_t id = params.size();
params.emplace_back(*tensor);
tensors.push_back(std::move(tensor));
return id;
}
const Value &eval(const TensorFunction &fun) {
return fun.eval(params, stash);
}
const TensorFunction &compile(const tensor_function::Node &expr) {
return engine.compile(expr, stash);
}
Value::UP make_tensor_inject() {
return engine.from_spec(
TensorSpec("tensor(x[2],y[2])")
.add({{"x", 0}, {"y", 0}}, 1.0)
.add({{"x", 0}, {"y", 1}}, 2.0)
.add({{"x", 1}, {"y", 0}}, 3.0)
.add({{"x", 1}, {"y", 1}}, 4.0));
}
Value::UP make_tensor_reduce_input() {
return engine.from_spec(
TensorSpec("tensor(x[3],y[2])")
.add({{"x",0},{"y",0}}, 1)
.add({{"x",1},{"y",0}}, 2)
.add({{"x",2},{"y",0}}, 3)
.add({{"x",0},{"y",1}}, 4)
.add({{"x",1},{"y",1}}, 5)
.add({{"x",2},{"y",1}}, 6));
}
Value::UP make_tensor_reduce_y_output() {
return engine.from_spec(
TensorSpec("tensor(x[3])")
.add({{"x",0}}, 5)
.add({{"x",1}}, 7)
.add({{"x",2}}, 9));
}
Value::UP make_tensor_map_input() {
return engine.from_spec(
TensorSpec("tensor(x{},y{})")
.add({{"x","1"},{"y","1"}}, 1)
.add({{"x","2"},{"y","1"}}, -3)
.add({{"x","1"},{"y","2"}}, 5));
}
Value::UP make_tensor_map_output() {
return engine.from_spec(
TensorSpec("tensor(x{},y{})")
.add({{"x","1"},{"y","1"}}, -1)
.add({{"x","2"},{"y","1"}}, 3)
.add({{"x","1"},{"y","2"}}, -5));
}
Value::UP make_tensor_apply_lhs() {
return engine.from_spec(
TensorSpec("tensor(x{},y{})")
.add({{"x","1"},{"y","1"}}, 1)
.add({{"x","2"},{"y","1"}}, 3)
.add({{"x","1"},{"y","2"}}, 5));
}
Value::UP make_tensor_apply_rhs() {
return engine.from_spec(
TensorSpec("tensor(y{},z{})")
.add({{"y","1"},{"z","1"}}, 7)
.add({{"y","2"},{"z","1"}}, 11)
.add({{"y","1"},{"z","2"}}, 13));
}
Value::UP make_tensor_apply_output() {
return engine.from_spec(
TensorSpec("tensor(x{},y{},z{})")
.add({{"x","1"},{"y","1"},{"z","1"}}, 7)
.add({{"x","1"},{"y","1"},{"z","2"}}, 13)
.add({{"x","2"},{"y","1"},{"z","1"}}, 21)
.add({{"x","2"},{"y","1"},{"z","2"}}, 39)
.add({{"x","1"},{"y","2"},{"z","1"}}, 55));
}
};
void verify_equal(const Value &expect, const Value &value) {
const Tensor *tensor = value.as_tensor();
ASSERT_TRUE(tensor != nullptr);
const Tensor *expect_tensor = expect.as_tensor();
ASSERT_TRUE(expect_tensor != nullptr);
ASSERT_EQUAL(&expect_tensor->engine(), &tensor->engine());
auto expect_spec = expect_tensor->engine().to_spec(expect);
auto value_spec = tensor->engine().to_spec(value);
EXPECT_EQUAL(expect_spec, value_spec);
}
TEST("require that tensor injection works") {
EvalCtx ctx(SimpleTensorEngine::ref());
size_t a_id = ctx.add_tensor(ctx.make_tensor_inject());
Value::UP expect = ctx.make_tensor_inject();
const auto &fun = inject(ValueType::from_spec("tensor(x[2],y[2])"), a_id, ctx.stash);
EXPECT_EQUAL(expect->type(), fun.result_type);
const auto &prog = ctx.compile(fun);
TEST_DO(verify_equal(*expect, ctx.eval(prog)));
}
TEST("require that partial tensor reduction works") {
EvalCtx ctx(SimpleTensorEngine::ref());
size_t a_id = ctx.add_tensor(ctx.make_tensor_reduce_input());
Value::UP expect = ctx.make_tensor_reduce_y_output();
const auto &fun = reduce(inject(ValueType::from_spec("tensor(x[3],y[2])"), a_id, ctx.stash), Aggr::SUM, {"y"}, ctx.stash);
EXPECT_EQUAL(expect->type(), fun.result_type);
const auto &prog = ctx.compile(fun);
TEST_DO(verify_equal(*expect, ctx.eval(prog)));
}
TEST("require that full tensor reduction works") {
EvalCtx ctx(SimpleTensorEngine::ref());
size_t a_id = ctx.add_tensor(ctx.make_tensor_reduce_input());
const auto &fun = reduce(inject(ValueType::from_spec("tensor(x[3],y[2])"), a_id, ctx.stash), Aggr::SUM, {}, ctx.stash);
EXPECT_EQUAL(ValueType::from_spec("double"), fun.result_type);
const auto &prog = ctx.compile(fun);
const Value &result = ctx.eval(prog);
EXPECT_TRUE(result.is_double());
EXPECT_EQUAL(21.0, result.as_double());
}
TEST("require that tensor map works") {
EvalCtx ctx(SimpleTensorEngine::ref());
size_t a_id = ctx.add_tensor(ctx.make_tensor_map_input());
Value::UP expect = ctx.make_tensor_map_output();
const auto &fun = map(inject(ValueType::from_spec("tensor(x{},y{})"), a_id, ctx.stash), operation::Neg::f, ctx.stash);
EXPECT_EQUAL(expect->type(), fun.result_type);
const auto &prog = ctx.compile(fun);
TEST_DO(verify_equal(*expect, ctx.eval(prog)));
}
TEST("require that tensor join works") {
EvalCtx ctx(SimpleTensorEngine::ref());
size_t a_id = ctx.add_tensor(ctx.make_tensor_apply_lhs());
size_t b_id = ctx.add_tensor(ctx.make_tensor_apply_rhs());
Value::UP expect = ctx.make_tensor_apply_output();
const auto &fun = join(inject(ValueType::from_spec("tensor(x{},y{})"), a_id, ctx.stash),
inject(ValueType::from_spec("tensor(y{},z{})"), b_id, ctx.stash),
operation::Mul::f, ctx.stash);
EXPECT_EQUAL(expect->type(), fun.result_type);
const auto &prog = ctx.compile(fun);
TEST_DO(verify_equal(*expect, ctx.eval(prog)));
}
TEST("require that push_children works") {
Stash stash;
std::vector<Node::Child::CREF> refs;
const Node &a = inject(ValueType::double_type(), 0, stash);
const Node &b = inject(ValueType::double_type(), 1, stash);
a.push_children(refs);
b.push_children(refs);
ASSERT_EQUAL(refs.size(), 0u);
//-------------------------------------------------------------------------
reduce(a, Aggr::SUM, {}, stash).push_children(refs);
ASSERT_EQUAL(refs.size(), 1u);
EXPECT_EQUAL(&refs[0].get().get(), &a);
//-------------------------------------------------------------------------
map(b, operation::Neg::f, stash).push_children(refs);
ASSERT_EQUAL(refs.size(), 2u);
EXPECT_EQUAL(&refs[1].get().get(), &b);
//-------------------------------------------------------------------------
join(a, b, operation::Add::f, stash).push_children(refs);
ASSERT_EQUAL(refs.size(), 4u);
EXPECT_EQUAL(&refs[2].get().get(), &a);
EXPECT_EQUAL(&refs[3].get().get(), &b);
//-------------------------------------------------------------------------
}
TEST_MAIN() { TEST_RUN_ALL(); }
<|endoftext|> |
<commit_before>/*
* Copyright 2013 Gustaf Räntilä
*
* 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 <q/queue.hpp>
#include <q/mutex.hpp>
#include <q/memory.hpp>
#include <q/exception.hpp>
#include <queue>
namespace q {
// TODO: Consider using a semaphore instead, and then preferably a non-locking
// queue altogether. The only thing necessary is that two push-calls from the
// same thread must follow order.
struct queue::pimpl
{
pimpl( priority_t priority )
: priority_( priority )
, mutex_( Q_HERE, "queue mutex" )
, parallelism_( 1 )
{ }
const priority_t priority_;
mutex mutex_;
queue::notify_type notify_;
std::size_t parallelism_;
std::queue< task > queue_;
std::queue< timer_task > timer_task_queue_;
};
queue_ptr queue::construct( priority_t priority )
{
return make_shared_using_constructor< queue >( priority );
}
queue::queue( priority_t priority )
: pimpl_( new pimpl( priority ) )
{
}
queue::~queue( )
{
}
void queue::push( task&& task )
{
notify_type notifyer;
{
Q_AUTO_UNIQUE_LOCK( pimpl_->mutex_, Q_HERE, "queue::push" );
pimpl_->queue_.push( std::move( task ) );
notifyer = pimpl_->notify_;
}
if ( notifyer )
notifyer( );
}
void queue::push( task&& task, timer::point_type wait_until )
{
notify_type notifyer;
{
Q_AUTO_UNIQUE_LOCK( pimpl_->mutex_, Q_HERE, "queue::push(2)" );
timer_task tt( std::move( task ), std::move( wait_until ) );
pimpl_->timer_task_queue_.push( std::move( tt ) );
notifyer = pimpl_->notify_;
}
if ( notifyer )
notifyer( );
}
priority_t queue::priority( ) const
{
return pimpl_->priority_;
}
void queue::set_consumer( queue::notify_type fn, std::size_t parallelism )
{
Q_AUTO_UNIQUE_LOCK( pimpl_->mutex_, Q_HERE, "queue::set_consumer" );
pimpl_->notify_ = fn;
pimpl_->parallelism_ = parallelism;
}
bool queue::empty( )
{
return pimpl_->queue_.empty( ) && pimpl_->timer_task_queue_.empty( );
}
timer_task queue::pop( )
{
Q_AUTO_UNIQUE_LOCK( pimpl_->mutex_, Q_HERE, "queue::pop" );
if ( !pimpl_->timer_task_queue_.empty( ) )
{
timer_task task = std::move( pimpl_->timer_task_queue_.front( ) );
pimpl_->timer_task_queue_.pop( );
return task;
}
if ( pimpl_->queue_.empty( ) )
return timer_task( );
timer_task task = std::move( pimpl_->queue_.front( ) );
pimpl_->queue_.pop( );
return task;
}
std::size_t queue::parallelism( ) const
{
return pimpl_->parallelism_;
}
} // namespace q
<commit_msg>queue::empty() now thread-safe<commit_after>/*
* Copyright 2013 Gustaf Räntilä
*
* 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 <q/queue.hpp>
#include <q/mutex.hpp>
#include <q/memory.hpp>
#include <q/exception.hpp>
#include <queue>
namespace q {
// TODO: Consider using a semaphore instead, and then preferably a non-locking
// queue altogether. The only thing necessary is that two push-calls from the
// same thread must follow order.
struct queue::pimpl
{
pimpl( priority_t priority )
: priority_( priority )
, mutex_( Q_HERE, "queue mutex" )
, parallelism_( 1 )
{ }
const priority_t priority_;
mutex mutex_;
queue::notify_type notify_;
std::size_t parallelism_;
std::queue< task > queue_;
std::queue< timer_task > timer_task_queue_;
};
queue_ptr queue::construct( priority_t priority )
{
return make_shared_using_constructor< queue >( priority );
}
queue::queue( priority_t priority )
: pimpl_( new pimpl( priority ) )
{
}
queue::~queue( )
{
}
void queue::push( task&& task )
{
notify_type notifyer;
{
Q_AUTO_UNIQUE_LOCK( pimpl_->mutex_, Q_HERE, "queue::push" );
pimpl_->queue_.push( std::move( task ) );
notifyer = pimpl_->notify_;
}
if ( notifyer )
notifyer( );
}
void queue::push( task&& task, timer::point_type wait_until )
{
notify_type notifyer;
{
Q_AUTO_UNIQUE_LOCK( pimpl_->mutex_, Q_HERE, "queue::push(2)" );
timer_task tt( std::move( task ), std::move( wait_until ) );
pimpl_->timer_task_queue_.push( std::move( tt ) );
notifyer = pimpl_->notify_;
}
if ( notifyer )
notifyer( );
}
priority_t queue::priority( ) const
{
return pimpl_->priority_;
}
void queue::set_consumer( queue::notify_type fn, std::size_t parallelism )
{
Q_AUTO_UNIQUE_LOCK( pimpl_->mutex_, Q_HERE, "queue::set_consumer" );
pimpl_->notify_ = fn;
pimpl_->parallelism_ = parallelism;
}
bool queue::empty( )
{
Q_AUTO_UNIQUE_LOCK( pimpl_->mutex_, Q_HERE, "queue::empty" );
return pimpl_->queue_.empty( ) && pimpl_->timer_task_queue_.empty( );
}
timer_task queue::pop( )
{
Q_AUTO_UNIQUE_LOCK( pimpl_->mutex_, Q_HERE, "queue::pop" );
if ( !pimpl_->timer_task_queue_.empty( ) )
{
timer_task task = std::move( pimpl_->timer_task_queue_.front( ) );
pimpl_->timer_task_queue_.pop( );
return task;
}
if ( pimpl_->queue_.empty( ) )
return timer_task( );
timer_task task = std::move( pimpl_->queue_.front( ) );
pimpl_->queue_.pop( );
return task;
}
std::size_t queue::parallelism( ) const
{
return pimpl_->parallelism_;
}
} // namespace q
<|endoftext|> |
<commit_before>/*
* Advection/diffusion sweeper.
*/
#ifndef _ADVECTION_DIFFUSION_SWEEPER_HPP_
#define _ADVECTION_DIFFUSION_SWEEPER_HPP_
#include <complex>
#include <vector>
#include <cassert>
#include <pfasst/encap/imex_sweeper.hpp>
#include "fft.hpp"
#define PI 3.1415926535897932385
#define TWO_PI 6.2831853071795864769
using namespace std;
template<typename time = pfasst::time_precision>
class AdvectionDiffusionSweeper : public pfasst::encap::IMEXSweeper<time>
{
typedef pfasst::encap::Encapsulation<time> Encapsulation;
typedef pfasst::encap::VectorEncapsulation<double> DVectorT;
FFT fft;
vector<complex<double>> ddx, lap;
double v = 1.0;
time t0 = 1.0;
double nu = 0.02;
size_t nf1evals = 0;
public:
AdvectionDiffusionSweeper(size_t nvars)
{
ddx.resize(nvars);
lap.resize(nvars);
for (size_t i = 0; i < nvars; i++) {
double kx = TWO_PI * ((i <= nvars / 2) ? int(i) : int(i) - int(nvars));
ddx[i] = complex<double>(0.0, 1.0) * kx;
lap[i] = (kx * kx < 1e-13) ? 0.0 : -kx * kx;
}
}
~AdvectionDiffusionSweeper()
{
cout << "number of f1 evals: " << nf1evals << endl;
}
void exact(Encapsulation* q, time t)
{
DVectorT* q_cast = dynamic_cast<DVectorT*>(q);
assert(q_cast != nullptr);
this->exact(*q_cast, t);
}
void exact(DVectorT& q, time t)
{
size_t n = q.size();
double a = 1.0 / sqrt(4 * PI * nu * (t + t0));
for (size_t i = 0; i < n; i++) {
q[i] = 0.0;
}
for (int ii = -2; ii < 3; ii++) {
for (size_t i = 0; i < n; i++) {
double x = double(i) / n - 0.5 + ii - t * v;
q[i] += a * exp(-x * x / (4 * nu * (t + t0)));
}
}
}
void echo_error(time t, bool predict = false)
{
auto& qend = *dynamic_cast<DVectorT*>(this->get_state(this->get_nodes().size() - 1));
auto qex = DVectorT(qend.size());
exact(qex, t);
double max = 0.0;
for (size_t i = 0; i < qend.size(); i++) {
double d = abs(qend[i] - qex[i]);
if (d > max) { max = d; }
}
cout << "err: " << scientific << max << " (" << qend.size() << ", " << predict << ")" << endl;
}
void predict(time t, time dt, bool initial)
{
pfasst::encap::IMEXSweeper<time>::predict(t, dt, initial);
echo_error(t + dt, true);
}
void sweep(time t, time dt)
{
pfasst::encap::IMEXSweeper<time>::sweep(t, dt);
echo_error(t + dt);
}
void f1eval(Encapsulation* f, Encapsulation* q, time t)
{
DVectorT* f_cast = dynamic_cast<DVectorT*>(f);
assert(f_cast != nullptr);
DVectorT* q_cast = dynamic_cast<DVectorT*>(q);
assert(q_cast != nullptr);
this->f1eval(f_cast, q_cast, t);
}
void f1eval(DVectorT* f, DVectorT* q, time t)
{
double c = -v / double(q->size());
auto* z = fft.forward(*q);
for (size_t i = 0; i < q->size(); i++) {
z[i] *= c * ddx[i];
}
fft.backward(*f);
nf1evals++;
}
void f2eval(Encapsulation* f, Encapsulation* q, time t)
{
DVectorT* f_cast = dynamic_cast<DVectorT*>(f);
assert(f_cast != nullptr);
DVectorT* q_cast = dynamic_cast<DVectorT*>(q);
assert(q_cast != nullptr);
this->f2eval(f_cast, q_cast, t);
}
void f2eval(DVectorT* f, DVectorT* q, time t)
{
double c = nu / double(q->size());
auto* z = fft.forward(*q);
for (size_t i = 0; i < q->size(); i++) {
z[i] *= c * lap[i];
}
fft.backward(*f);
}
void f2comp(Encapsulation* f, Encapsulation* q, time t, time dt, Encapsulation* rhs)
{
DVectorT* f_cast = dynamic_cast<DVectorT*>(f);
assert(f_cast != nullptr);
DVectorT* q_cast = dynamic_cast<DVectorT*>(q);
assert(q_cast != nullptr);
DVectorT* rhs_cast = dynamic_cast<DVectorT*>(rhs);
assert(rhs_cast != nullptr);
this->f2comp(f_cast, q_cast, t, dt, rhs_cast);
}
void f2comp(DVectorT* f, DVectorT* q, time t, time dt, DVectorT* rhs)
{
auto* z = fft.forward(*rhs);
for (size_t i = 0; i < q->size(); i++) {
z[i] /= (1.0 - nu * double(dt) * lap[i]) * double(q->size());
}
fft.backward(*q);
for (size_t i = 0; i < q->size(); i++) {
f->at(i) = (q->at(i) - rhs->at(i)) / double(dt);
}
}
};
#endif
<commit_msg>adding some assertions after dynamic_cast<commit_after>/*
* Advection/diffusion sweeper.
*/
#ifndef _ADVECTION_DIFFUSION_SWEEPER_HPP_
#define _ADVECTION_DIFFUSION_SWEEPER_HPP_
#include <complex>
#include <vector>
#include <cassert>
#include <pfasst/encap/imex_sweeper.hpp>
#include "fft.hpp"
#define PI 3.1415926535897932385
#define TWO_PI 6.2831853071795864769
using namespace std;
template<typename time = pfasst::time_precision>
class AdvectionDiffusionSweeper : public pfasst::encap::IMEXSweeper<time>
{
typedef pfasst::encap::Encapsulation<time> Encapsulation;
typedef pfasst::encap::VectorEncapsulation<double> DVectorT;
FFT fft;
vector<complex<double>> ddx, lap;
double v = 1.0;
time t0 = 1.0;
double nu = 0.02;
size_t nf1evals = 0;
public:
AdvectionDiffusionSweeper(size_t nvars)
{
ddx.resize(nvars);
lap.resize(nvars);
for (size_t i = 0; i < nvars; i++) {
double kx = TWO_PI * ((i <= nvars / 2) ? int(i) : int(i) - int(nvars));
ddx[i] = complex<double>(0.0, 1.0) * kx;
lap[i] = (kx * kx < 1e-13) ? 0.0 : -kx * kx;
}
}
~AdvectionDiffusionSweeper()
{
cout << "number of f1 evals: " << nf1evals << endl;
}
void exact(Encapsulation* q, time t)
{
DVectorT* q_cast = dynamic_cast<DVectorT*>(q);
assert(q_cast != nullptr);
this->exact(*q_cast, t);
}
void exact(DVectorT& q, time t)
{
size_t n = q.size();
double a = 1.0 / sqrt(4 * PI * nu * (t + t0));
for (size_t i = 0; i < n; i++) {
q[i] = 0.0;
}
for (int ii = -2; ii < 3; ii++) {
for (size_t i = 0; i < n; i++) {
double x = double(i) / n - 0.5 + ii - t * v;
q[i] += a * exp(-x * x / (4 * nu * (t + t0)));
}
}
}
void echo_error(time t, bool predict = false)
{
DVectorT* qend = dynamic_cast<DVectorT*>(this->get_state(this->get_nodes().size() - 1));
assert(qend != nullptr);
DVectorT qex = DVectorT(qend->size());
exact(qex, t);
double max = 0.0;
for (size_t i = 0; i < qend->size(); i++) {
double d = abs(qend->at(i) - qex[i]);
if (d > max) { max = d; }
}
cout << "err: " << scientific << max << " (" << qend->size() << ", " << predict << ")" << endl;
}
void predict(time t, time dt, bool initial)
{
pfasst::encap::IMEXSweeper<time>::predict(t, dt, initial);
echo_error(t + dt, true);
}
void sweep(time t, time dt)
{
pfasst::encap::IMEXSweeper<time>::sweep(t, dt);
echo_error(t + dt);
}
void f1eval(Encapsulation* f, Encapsulation* q, time t)
{
DVectorT* f_cast = dynamic_cast<DVectorT*>(f);
assert(f_cast != nullptr);
DVectorT* q_cast = dynamic_cast<DVectorT*>(q);
assert(q_cast != nullptr);
this->f1eval(f_cast, q_cast, t);
}
void f1eval(DVectorT* f, DVectorT* q, time t)
{
double c = -v / double(q->size());
auto* z = fft.forward(*q);
for (size_t i = 0; i < q->size(); i++) {
z[i] *= c * ddx[i];
}
fft.backward(*f);
nf1evals++;
}
void f2eval(Encapsulation* f, Encapsulation* q, time t)
{
DVectorT* f_cast = dynamic_cast<DVectorT*>(f);
assert(f_cast != nullptr);
DVectorT* q_cast = dynamic_cast<DVectorT*>(q);
assert(q_cast != nullptr);
this->f2eval(f_cast, q_cast, t);
}
void f2eval(DVectorT* f, DVectorT* q, time t)
{
double c = nu / double(q->size());
auto* z = fft.forward(*q);
for (size_t i = 0; i < q->size(); i++) {
z[i] *= c * lap[i];
}
fft.backward(*f);
}
void f2comp(Encapsulation* f, Encapsulation* q, time t, time dt, Encapsulation* rhs)
{
DVectorT* f_cast = dynamic_cast<DVectorT*>(f);
assert(f_cast != nullptr);
DVectorT* q_cast = dynamic_cast<DVectorT*>(q);
assert(q_cast != nullptr);
DVectorT* rhs_cast = dynamic_cast<DVectorT*>(rhs);
assert(rhs_cast != nullptr);
this->f2comp(f_cast, q_cast, t, dt, rhs_cast);
}
void f2comp(DVectorT* f, DVectorT* q, time t, time dt, DVectorT* rhs)
{
auto* z = fft.forward(*rhs);
for (size_t i = 0; i < q->size(); i++) {
z[i] /= (1.0 - nu * double(dt) * lap[i]) * double(q->size());
}
fft.backward(*q);
for (size_t i = 0; i < q->size(); i++) {
f->at(i) = (q->at(i) - rhs->at(i)) / double(dt);
}
}
};
#endif
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2016 Nagisa Sekiguchi
*
* 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.
*/
#ifndef YDSH_MISC_RESOURCE_HPP
#define YDSH_MISC_RESOURCE_HPP
#include <type_traits>
#include "noncopyable.h"
namespace ydsh {
namespace misc {
template <typename T>
class IntrusivePtr final {
private:
T *ptr;
public:
IntrusivePtr() noexcept : ptr(nullptr) { }
IntrusivePtr(std::nullptr_t) noexcept : ptr(nullptr) { }
IntrusivePtr(T *ptr) noexcept : ptr(ptr) { intrusivePtr_addRef(this->ptr); }
IntrusivePtr(const IntrusivePtr &v) noexcept : IntrusivePtr(v.ptr) { }
IntrusivePtr(IntrusivePtr &&v) noexcept : ptr(v.ptr) { v.ptr = nullptr; }
~IntrusivePtr() { intrusivePtr_release(this->ptr); }
IntrusivePtr &operator=(const IntrusivePtr &v) noexcept {
IntrusivePtr tmp(v);
std::swap(this->ptr, tmp.ptr);
return *this;
}
IntrusivePtr &operator=(IntrusivePtr &&v) noexcept {
IntrusivePtr tmp(std::move(v));
std::swap(this->ptr, tmp.ptr);
return *this;
}
void reset() noexcept {
IntrusivePtr tmp;
std::swap(this->ptr, tmp.ptr);
}
T *get() const noexcept {
return this->ptr;
}
T &operator*() const noexcept {
return *this->ptr;
}
T *operator->() const noexcept {
return this->ptr;
}
explicit operator bool() const noexcept {
return this->ptr != nullptr;
}
};
template <typename T, typename ... A>
inline IntrusivePtr<T> makeIntrusive(A ... arg) {
return IntrusivePtr<T>(new T(std::forward<A>(arg)...));
}
template <typename R, typename D>
class ScopedResource {
private:
R resource;
D deleter;
bool deleteResource;
public:
NON_COPYABLE(ScopedResource);
ScopedResource(R &&resource, D &&deleter) noexcept :
resource(std::move(resource)), deleter(std::move(deleter)), deleteResource(true) { }
ScopedResource(ScopedResource &&o) noexcept :
resource(std::move(o.resource)), deleter(std::move(o.deleter)), deleteResource(true) {
o.release();
}
~ScopedResource() noexcept(this->reset()) {
this->reset();
}
ScopedResource &operator=(ScopedResource &&o) noexcept(this->reset()) {
this->reset();
this->resource = std::move(o.resource);
this->deleter = std::move(o.deleter);
this->deleteResource = true;
o.release();
return *this;
}
R const &get() const noexcept {
return this->resource;
}
D const &getDeleter() const noexcept {
return this->deleter;
}
void reset() noexcept(this->deleter(this->resource)) {
if(this->deleteResource) {
this->deleteResource = false;
this->deleter(this->resource);
}
}
void reset(R &&r) noexcept(this->reset()) {
this->reset();
this->resource = std::move(r);
this->deleteResource = true;
}
R const &release() noexcept {
this->deleteResource = false;
return this->get();
}
};
template <typename R, typename D>
ScopedResource<R, typename std::remove_reference<D>::type> makeScopedResource(R &&r, D &&d) {
using ActualD = typename std::remove_reference<D>::type;
return ScopedResource<R, ActualD>(std::move(r), std::forward<ActualD>(d));
};
} // namespace misc
} // namespace ydsh
#endif //YDSH_MISC_RESOURCE_HPP
<commit_msg>fix noexcept operator due to prevent compile error in gcc<commit_after>/*
* Copyright (C) 2016 Nagisa Sekiguchi
*
* 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.
*/
#ifndef YDSH_MISC_RESOURCE_HPP
#define YDSH_MISC_RESOURCE_HPP
#include <type_traits>
#include "noncopyable.h"
namespace ydsh {
namespace misc {
template <typename T>
class IntrusivePtr final {
private:
T *ptr;
public:
IntrusivePtr() noexcept : ptr(nullptr) { }
IntrusivePtr(std::nullptr_t) noexcept : ptr(nullptr) { }
IntrusivePtr(T *ptr) noexcept : ptr(ptr) { intrusivePtr_addRef(this->ptr); }
IntrusivePtr(const IntrusivePtr &v) noexcept : IntrusivePtr(v.ptr) { }
IntrusivePtr(IntrusivePtr &&v) noexcept : ptr(v.ptr) { v.ptr = nullptr; }
~IntrusivePtr() { intrusivePtr_release(this->ptr); }
IntrusivePtr &operator=(const IntrusivePtr &v) noexcept {
IntrusivePtr tmp(v);
std::swap(this->ptr, tmp.ptr);
return *this;
}
IntrusivePtr &operator=(IntrusivePtr &&v) noexcept {
IntrusivePtr tmp(std::move(v));
std::swap(this->ptr, tmp.ptr);
return *this;
}
void reset() noexcept {
IntrusivePtr tmp;
std::swap(this->ptr, tmp.ptr);
}
T *get() const noexcept {
return this->ptr;
}
T &operator*() const noexcept {
return *this->ptr;
}
T *operator->() const noexcept {
return this->ptr;
}
explicit operator bool() const noexcept {
return this->ptr != nullptr;
}
};
template <typename T, typename ... A>
inline IntrusivePtr<T> makeIntrusive(A ... arg) {
return IntrusivePtr<T>(new T(std::forward<A>(arg)...));
}
template <typename R, typename D>
class ScopedResource {
private:
R resource;
D deleter;
bool deleteResource;
public:
NON_COPYABLE(ScopedResource);
ScopedResource(R &&resource, D &&deleter) noexcept :
resource(std::move(resource)), deleter(std::move(deleter)), deleteResource(true) { }
ScopedResource(ScopedResource &&o) noexcept :
resource(std::move(o.resource)), deleter(std::move(o.deleter)), deleteResource(true) {
o.release();
}
~ScopedResource() noexcept {
this->reset();
}
ScopedResource &operator=(ScopedResource &&o) noexcept {
this->reset();
this->resource = std::move(o.resource);
this->deleter = std::move(o.deleter);
this->deleteResource = true;
o.release();
return *this;
}
R const &get() const noexcept {
return this->resource;
}
D const &getDeleter() const noexcept {
return this->deleter;
}
void reset() noexcept {
if(this->deleteResource) {
this->deleteResource = false;
this->deleter(this->resource);
}
}
void reset(R &&r) noexcept {
this->reset();
this->resource = std::move(r);
this->deleteResource = true;
}
R const &release() noexcept {
this->deleteResource = false;
return this->get();
}
};
template <typename R, typename D>
ScopedResource<R, typename std::remove_reference<D>::type> makeScopedResource(R &&r, D &&d) {
using ActualD = typename std::remove_reference<D>::type;
return ScopedResource<R, ActualD>(std::move(r), std::forward<ActualD>(d));
};
} // namespace misc
} // namespace ydsh
#endif //YDSH_MISC_RESOURCE_HPP
<|endoftext|> |
<commit_before>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2009 Alexander Binder
* Copyright (C) 2009 Fraunhofer Institute FIRST and Max-Planck-Society
*/
#include <iostream>
#include <shogun/lib/io.h>
#include <shogun/lib/ShogunException.h>
#include <shogun/kernel/CustomKernel.h>
#include <shogun/kernel/CombinedKernel.h>
#include <shogun/classifier/mkl/MKLMultiClass.h>
using namespace shogun;
void print_message(FILE* target, const char* str)
{
fprintf(target, "%s", str);
}
void print_warning(FILE* target, const char* str)
{
fprintf(target, "%s", str);
}
void print_error(FILE* target, const char* str)
{
fprintf(target, "%s", str);
}
void getgauss(float64_t & y1, float64_t & y2)
{
float x1, x2, w;
do {
x1 = 2.0 * rand()/(float64_t)RAND_MAX - 1.0;
x2 = 2.0 * rand()/(float64_t)RAND_MAX - 1.0;
w = x1 * x1 + x2 * x2;
} while ( (w >= 1.0)|| (w<1e-9) );
w = sqrt( (-2.0 * log( w ) ) / w );
y1 = x1 * w;
y2 = x2 * w;
}
void gendata(std::vector<float64_t> & x,std::vector<float64_t> & y,
CLabels*& lab)
{
int32_t totalsize=240;
int32_t class1size=80;
int32_t class2size=70;
//generating three class data set
x.resize(totalsize);
y.resize(totalsize);
for(size_t i=0; i< x.size();++i)
getgauss(x[i], y[i]);
for(size_t i=0; i< x.size();++i)
{
if((int32_t)i < class1size)
{
x[i]+=0;
y[i]+=0;
}
else if( (int32_t)i< class1size+class2size)
{
x[i]+=+1;
y[i]+=-1;
}
else
{
x[i]+=-1;
y[i]+=+1;
}
}
//set labels
lab=new CLabels(x.size());
for(size_t i=0; i< x.size();++i)
{
if((int32_t)i < class1size)
lab->set_int_label(i,0);
else if( (int32_t)i< class1size+class2size)
lab->set_int_label(i,1);
else
lab->set_int_label(i,2);
}
}
void gentrainkernel(float64_t * & ker1 ,float64_t * & ker2 ,float64_t &
autosigma,float64_t & n1,float64_t & n2,
const std::vector<float64_t> & x,
const std::vector<float64_t> & y)
{
autosigma=0;
for(size_t l=0; l< x.size();++l)
{
for(size_t r=0; r<= l;++r)
{
float64_t dist=((x[l]-x[r])*(x[l]-x[r]) + (y[l]-y[r])*(y[l]-y[r]));
autosigma+=dist*2.0/(float64_t)x.size()/((float64_t)x.size()+1);
}
}
float64_t fm1=0, mean1=0,fm2=0, mean2=0;
ker1=new float64_t[ x.size()*x.size()];
ker2=new float64_t[ x.size()*x.size()];
for(size_t l=0; l< x.size();++l)
{
for(size_t r=0; r< x.size();++r)
{
float64_t dist=((x[l]-x[r])*(x[l]-x[r]) + (y[l]-y[r])*(y[l]-y[r]));
ker1[l +r*x.size()]= exp( -dist/autosigma/autosigma) ;
//ker2[l +r*x.size()]= exp( -dist/sigma2/sigma2) ;
ker2[l +r*x.size()]= x[l]*x[r] + y[l]*y[r];
fm1+=ker1[l +r*x.size()]/(float64_t)x.size()/((float64_t)x.size());
fm2+=ker2[l +r*x.size()]/(float64_t)x.size()/((float64_t)x.size());
if(l==r)
{
mean1+=ker1[l +r*x.size()]/(float64_t)x.size();
mean2+=ker2[l +r*x.size()]/(float64_t)x.size();
}
}
}
n1=(mean1-fm1);
n2=(mean2-fm2);
for(size_t l=0; l< x.size();++l)
{
for(size_t r=0; r< x.size();++r)
{
ker1[l +r*x.size()]=ker1[l +r*x.size()]/n1;
ker2[l +r*x.size()]=ker2[l +r*x.size()]/n2;
}
}
}
void gentestkernel(float64_t * & ker1 ,float64_t * & ker2,
const float64_t autosigma,const float64_t n1,const float64_t n2,
const std::vector<float64_t> & x,const std::vector<float64_t> & y,
const std::vector<float64_t> & tx,const std::vector<float64_t> & ty)
{
ker1=new float64_t[ x.size()*tx.size()];
ker2=new float64_t[ x.size()*tx.size()];
for(size_t l=0; l< x.size();++l)
{
for(size_t r=0; r< tx.size();++r)
{
float64_t dist=((x[l]-tx[r])*(x[l]-tx[r]) + (y[l]-ty[r])*(y[l]-ty[r]));
ker1[l +r*x.size()]= exp( -dist/autosigma/autosigma) ;
ker2[l +r*x.size()]= x[l]*tx[r] + y[l]*ty[r];
}
}
for(size_t l=0; l< x.size();++l)
{
for(size_t r=0; r< tx.size();++r)
{
ker1[l +r*x.size()]=ker1[l +r*x.size()]/n1;
ker2[l +r*x.size()]=ker2[l +r*x.size()]/n2;
}
}
}
void tester()
{
CLabels* lab=NULL;
std::vector<float64_t> x,y;
gendata(x,y, lab);
SG_REF(lab);
float64_t* ker1=NULL;
float64_t* ker2=NULL;
float64_t autosigma=1;
float64_t n1=0;
float64_t n2=0;
int32_t numdata=0;
gentrainkernel( ker1 , ker2 , autosigma, n1, n2,x,y);
numdata=x.size();
CCombinedKernel* ker=new CCombinedKernel();
CCustomKernel* kernel1=new CCustomKernel();
CCustomKernel* kernel2=new CCustomKernel();
kernel1->set_full_kernel_matrix_from_full(ker1, numdata,numdata);
kernel2->set_full_kernel_matrix_from_full(ker2, numdata,numdata);
ker->append_kernel(kernel1);
ker->append_kernel(kernel2);
//here comes the core stuff
float64_t regconst=1.0;
CMKLMultiClass* tsvm =new CMKLMultiClass(regconst, ker, lab);
tsvm->set_epsilon(0.0001); // SVM epsilon
// MKL parameters
tsvm->set_mkl_epsilon(0.01); // subkernel weight L2 norm termination criterion
tsvm->set_max_num_mkliters(120); // well it will be just three iterations
//starting svm training
tsvm->train();
SG_SPRINT("finished svm training\n");
//starting svm testing on training data
CLabels* res=tsvm->classify();
ASSERT(res);
float64_t err=0;
for(int32_t i=0; i<numdata;++i)
{
ASSERT(i< res->get_num_labels());
if (lab->get_int_label(i)!=res->get_int_label(i))
err+=1;
}
err/=(float64_t)res->get_num_labels();
SG_SPRINT("prediction error on training data (3 classes): %f ",err);
SG_SPRINT("random guess error would be: %f \n",2/3.0);
delete[] ker1;
delete[] ker2;
//generate test data
CLabels* tlab=NULL;
std::vector<float64_t> tx,ty;
gendata( tx,ty,tlab);
SG_REF(tlab);
float64_t* tker1=NULL;
float64_t* tker2=NULL;
gentestkernel(tker1,tker2, autosigma, n1,n2, x,y, tx,ty);
int32_t numdatatest=tx.size();
CCombinedKernel* tker=new CCombinedKernel();
SG_REF(tker);
CCustomKernel* tkernel1=new CCustomKernel();
CCustomKernel* tkernel2=new CCustomKernel();
tkernel1->set_full_kernel_matrix_from_full(tker1,numdata, numdatatest);
tkernel2->set_full_kernel_matrix_from_full(tker2,numdata, numdatatest);
tker->append_kernel(tkernel1);
tker->append_kernel(tkernel2);
int32_t numweights;
float64_t* weights=tsvm->getsubkernelweights(numweights);
SG_SPRINT("test kernel weights\n");
for(int32_t i=0; i< numweights;++i)
SG_SPRINT("%f ", weights[i]);
SG_SPRINT("\n");
//set kernel
tker->set_subkernel_weights(weights, numweights);
tsvm->set_kernel(tker);
//compute classif error, check mem
CLabels* tres=tsvm->classify();
float64_t terr=0;
for(int32_t i=0; i<numdatatest;++i)
{
ASSERT(i< tres->get_num_labels());
if(tlab->get_int_label(i)!=tres->get_int_label(i))
terr+=1;
}
terr/=(float64_t) tres->get_num_labels();
SG_SPRINT("prediction error on test data (3 classes): %f ",terr);
SG_SPRINT("random guess error would be: %f \n",2/3.0);
delete[] tker1;
delete[] tker2;
SG_UNREF(tsvm);
SG_UNREF(res);
SG_UNREF(tres);
SG_UNREF(lab);
SG_UNREF(tlab);
SG_UNREF(tker);
delete[] weights;
weights=NULL;
SG_SPRINT( "finished \n");
}
namespace shogun
{
extern CVersion* sg_version;
extern CIO* sg_io;
}
int main()
{
init_shogun(&print_message, &print_warning,
&print_error);
try
{
sg_version->print_version();
sg_io->set_loglevel(MSG_INFO);
tester();
}
catch(ShogunException & sh)
{
printf("%s",sh.get_exception_string());
}
exit_shogun();
}
<commit_msg>added one kernel more and mkl norm<commit_after>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2009 Alexander Binder
* Copyright (C) 2009 Fraunhofer Institute FIRST and Max-Planck-Society
*/
#include <iostream>
#include <shogun/lib/io.h>
#include <shogun/lib/ShogunException.h>
#include <shogun/kernel/CustomKernel.h>
#include <shogun/kernel/CombinedKernel.h>
#include <shogun/classifier/mkl/MKLMultiClass.h>
// g++ -Wall -O3 classifier_mklmulticlass.cpp -I /home/theseus/private/alx/shoguntrunk/compiledtmp/include -L/home/theseus/private/alx/shoguntrunk/compiledtmp/lib -lshogun
using namespace shogun;
void print_message(FILE* target, const char* str)
{
fprintf(target, "%s", str);
}
void print_warning(FILE* target, const char* str)
{
fprintf(target, "%s", str);
}
void print_error(FILE* target, const char* str)
{
fprintf(target, "%s", str);
}
void getgauss(float64_t & y1, float64_t & y2)
{
float x1, x2, w;
do {
x1 = 2.0 * rand()/(float64_t)RAND_MAX - 1.0;
x2 = 2.0 * rand()/(float64_t)RAND_MAX - 1.0;
w = x1 * x1 + x2 * x2;
} while ( (w >= 1.0)|| (w<1e-9) );
w = sqrt( (-2.0 * log( w ) ) / w );
y1 = x1 * w;
y2 = x2 * w;
}
void gendata(std::vector<float64_t> & x,std::vector<float64_t> & y,
CLabels*& lab)
{
int32_t totalsize=240;
int32_t class1size=80;
int32_t class2size=70;
//generating three class data set
x.resize(totalsize);
y.resize(totalsize);
for(size_t i=0; i< x.size();++i)
getgauss(x[i], y[i]);
for(size_t i=0; i< x.size();++i)
{
if((int32_t)i < class1size)
{
x[i]+=0;
y[i]+=0;
}
else if( (int32_t)i< class1size+class2size)
{
x[i]+=+1;
y[i]+=-1;
}
else
{
x[i]+=-1;
y[i]+=+1;
}
}
//set labels
lab=new CLabels(x.size());
for(size_t i=0; i< x.size();++i)
{
if((int32_t)i < class1size)
lab->set_int_label(i,0);
else if( (int32_t)i< class1size+class2size)
lab->set_int_label(i,1);
else
lab->set_int_label(i,2);
}
}
void gentrainkernel(float64_t * & ker1 ,float64_t * & ker2, float64_t * & ker3 ,float64_t &
autosigma,float64_t & n1,float64_t & n2, float64_t & n3,
const std::vector<float64_t> & x,
const std::vector<float64_t> & y)
{
autosigma=0;
for(size_t l=0; l< x.size();++l)
{
for(size_t r=0; r<= l;++r)
{
float64_t dist=((x[l]-x[r])*(x[l]-x[r]) + (y[l]-y[r])*(y[l]-y[r]));
autosigma+=dist*2.0/(float64_t)x.size()/((float64_t)x.size()+1);
}
}
float64_t fm1=0, mean1=0,fm2=0, mean2=0,fm3=0, mean3=0;
ker1=new float64_t[ x.size()*x.size()];
ker2=new float64_t[ x.size()*x.size()];
ker3=new float64_t[ x.size()*x.size()];
for(size_t l=0; l< x.size();++l)
{
for(size_t r=0; r< x.size();++r)
{
float64_t dist=((x[l]-x[r])*(x[l]-x[r]) + (y[l]-y[r])*(y[l]-y[r]));
ker1[l +r*x.size()]= exp( -dist/autosigma/autosigma) ;
//ker2[l +r*x.size()]= exp( -dist/sigma2/sigma2) ;
ker2[l +r*x.size()]= x[l]*x[r] + y[l]*y[r];
ker3[l +r*x.size()]= (x[l]*x[r] + y[l]*y[r]+1)*(x[l]*x[r] + y[l]*y[r]+1);
fm1+=ker1[l +r*x.size()]/(float64_t)x.size()/((float64_t)x.size());
fm2+=ker2[l +r*x.size()]/(float64_t)x.size()/((float64_t)x.size());
fm3+=ker3[l +r*x.size()]/(float64_t)x.size()/((float64_t)x.size());
if(l==r)
{
mean1+=ker1[l +r*x.size()]/(float64_t)x.size();
mean2+=ker2[l +r*x.size()]/(float64_t)x.size();
mean3+=ker3[l +r*x.size()]/(float64_t)x.size();
}
}
}
n1=(mean1-fm1);
n2=(mean2-fm2);
n3=(mean3-fm3);
for(size_t l=0; l< x.size();++l)
{
for(size_t r=0; r< x.size();++r)
{
ker1[l +r*x.size()]=ker1[l +r*x.size()]/n1;
ker2[l +r*x.size()]=ker2[l +r*x.size()]/n2;
ker3[l +r*x.size()]=ker3[l +r*x.size()]/n3;
}
}
}
void gentestkernel(float64_t * & ker1 ,float64_t * & ker2,float64_t * & ker3,
const float64_t autosigma,const float64_t n1,const float64_t n2, const float64_t n3,
const std::vector<float64_t> & x,const std::vector<float64_t> & y,
const std::vector<float64_t> & tx,const std::vector<float64_t> & ty)
{
ker1=new float64_t[ x.size()*tx.size()];
ker2=new float64_t[ x.size()*tx.size()];
ker3=new float64_t[ x.size()*tx.size()];
for(size_t l=0; l< x.size();++l)
{
for(size_t r=0; r< tx.size();++r)
{
float64_t dist=((x[l]-tx[r])*(x[l]-tx[r]) + (y[l]-ty[r])*(y[l]-ty[r]));
ker1[l +r*x.size()]= exp( -dist/autosigma/autosigma) ;
ker2[l +r*x.size()]= x[l]*tx[r] + y[l]*ty[r];
ker3[l +r*x.size()]= (x[l]*tx[r] + y[l]*ty[r]+1)*(x[l]*tx[r] + y[l]*ty[r]+1);
}
}
for(size_t l=0; l< x.size();++l)
{
for(size_t r=0; r< tx.size();++r)
{
ker1[l +r*x.size()]=ker1[l +r*x.size()]/n1;
ker2[l +r*x.size()]=ker2[l +r*x.size()]/n2;
ker3[l +r*x.size()]=ker3[l +r*x.size()]/n2;
}
}
}
void tester()
{
CLabels* lab=NULL;
std::vector<float64_t> x,y;
gendata(x,y, lab);
SG_REF(lab);
float64_t* ker1=NULL;
float64_t* ker2=NULL;
float64_t* ker3=NULL;
float64_t autosigma=1;
float64_t n1=0;
float64_t n2=0;
float64_t n3=0;
int32_t numdata=0;
gentrainkernel( ker1 , ker2, ker3 , autosigma, n1, n2, n3,x,y);
numdata=x.size();
CCombinedKernel* ker=new CCombinedKernel();
CCustomKernel* kernel1=new CCustomKernel();
CCustomKernel* kernel2=new CCustomKernel();
CCustomKernel* kernel3=new CCustomKernel();
kernel1->set_full_kernel_matrix_from_full(ker1, numdata,numdata);
kernel2->set_full_kernel_matrix_from_full(ker2, numdata,numdata);
kernel3->set_full_kernel_matrix_from_full(ker3, numdata,numdata);
ker->append_kernel(kernel1);
ker->append_kernel(kernel2);
ker->append_kernel(kernel3);
//here comes the core stuff
float64_t regconst=1.0;
CMKLMultiClass* tsvm =new CMKLMultiClass(regconst, ker, lab);
tsvm->set_epsilon(0.0001); // SVM epsilon
// MKL parameters
tsvm->set_mkl_epsilon(0.01); // subkernel weight L2 norm termination criterion
tsvm->set_max_num_mkliters(120); // well it will be just three iterations
tsvm->set_mkl_norm(1.5); // mkl norm
//starting svm training
tsvm->train();
SG_SPRINT("finished svm training\n");
//starting svm testing on training data
CLabels* res=tsvm->classify();
ASSERT(res);
float64_t err=0;
for(int32_t i=0; i<numdata;++i)
{
ASSERT(i< res->get_num_labels());
if (lab->get_int_label(i)!=res->get_int_label(i))
err+=1;
}
err/=(float64_t)res->get_num_labels();
SG_SPRINT("prediction error on training data (3 classes): %f ",err);
SG_SPRINT("random guess error would be: %f \n",2/3.0);
delete[] ker1;
delete[] ker2;
delete[] ker3;
//generate test data
CLabels* tlab=NULL;
std::vector<float64_t> tx,ty;
gendata( tx,ty,tlab);
SG_REF(tlab);
float64_t* tker1=NULL;
float64_t* tker2=NULL;
float64_t* tker3=NULL;
gentestkernel(tker1,tker2,tker3, autosigma, n1,n2,n3, x,y, tx,ty);
int32_t numdatatest=tx.size();
CCombinedKernel* tker=new CCombinedKernel();
SG_REF(tker);
CCustomKernel* tkernel1=new CCustomKernel();
CCustomKernel* tkernel2=new CCustomKernel();
CCustomKernel* tkernel3=new CCustomKernel();
tkernel1->set_full_kernel_matrix_from_full(tker1,numdata, numdatatest);
tkernel2->set_full_kernel_matrix_from_full(tker2,numdata, numdatatest);
tkernel3->set_full_kernel_matrix_from_full(tker2,numdata, numdatatest);
tker->append_kernel(tkernel1);
tker->append_kernel(tkernel2);
tker->append_kernel(tkernel3);
int32_t numweights;
float64_t* weights=tsvm->getsubkernelweights(numweights);
SG_SPRINT("test kernel weights\n");
for(int32_t i=0; i< numweights;++i)
SG_SPRINT("%f ", weights[i]);
SG_SPRINT("\n");
//set kernel
tker->set_subkernel_weights(weights, numweights);
tsvm->set_kernel(tker);
//compute classif error, check mem
CLabels* tres=tsvm->classify();
float64_t terr=0;
for(int32_t i=0; i<numdatatest;++i)
{
ASSERT(i< tres->get_num_labels());
if(tlab->get_int_label(i)!=tres->get_int_label(i))
terr+=1;
}
terr/=(float64_t) tres->get_num_labels();
SG_SPRINT("prediction error on test data (3 classes): %f ",terr);
SG_SPRINT("random guess error would be: %f \n",2/3.0);
delete[] tker1;
delete[] tker2;
delete[] tker3;
SG_UNREF(tsvm);
SG_UNREF(res);
SG_UNREF(tres);
SG_UNREF(lab);
SG_UNREF(tlab);
SG_UNREF(tker);
delete[] weights;
weights=NULL;
SG_SPRINT( "finished \n");
}
namespace shogun
{
extern CVersion* sg_version;
extern CIO* sg_io;
}
int main()
{
init_shogun(&print_message, &print_warning,
&print_error);
try
{
sg_version->print_version();
sg_io->set_loglevel(MSG_INFO);
tester();
}
catch(ShogunException & sh)
{
printf("%s",sh.get_exception_string());
}
exit_shogun();
}
<|endoftext|> |
<commit_before>/**
* @file em_fit.hpp
* @author Ryan Curtin
*
* Utility class to fit a GMM using the EM algorithm. Used by
* GMM::Estimate<>().
*/
#ifndef __MLPACK_METHODS_GMM_EM_FIT_HPP
#define __MLPACK_METHODS_GMM_EM_FIT_HPP
#include <mlpack/core.hpp>
// Default clustering mechanism.
#include <mlpack/methods/kmeans/kmeans.hpp>
// Default covariance matrix constraint.
#include "positive_definite_constraint.hpp"
namespace mlpack {
namespace gmm {
/**
* This class contains methods which can fit a GMM to observations using the EM
* algorithm. It requires an initial clustering mechanism, which is by default
* the KMeans algorithm. The clustering mechanism must implement the following
* method:
*
* - void Cluster(const arma::mat& observations,
* const size_t clusters,
* arma::Col<size_t>& assignments);
*
* This method should create 'clusters' clusters, and return the assignment of
* each point to a cluster.
*/
template<typename InitialClusteringType = kmeans::KMeans<>,
typename CovarianceConstraintPolicy = PositiveDefiniteConstraint>
class EMFit
{
public:
/**
* Construct the EMFit object, optionally passing an InitialClusteringType
* object (just in case it needs to store state). Setting the maximum number
* of iterations to 0 means that the EM algorithm will iterate until
* convergence (with the given tolerance).
*
* The parameter forcePositive controls whether or not the covariance matrices
* are checked for positive definiteness at each iteration. This could be a
* time-consuming task, so, if you know your data is well-behaved, you can set
* it to false and save some runtime.
*
* @param maxIterations Maximum number of iterations for EM.
* @param tolerance Log-likelihood tolerance required for convergence.
* @param forcePositive Check for positive-definiteness of each covariance
* matrix at each iteration.
* @param clusterer Object which will perform the initial clustering.
*/
EMFit(const size_t maxIterations = 300,
const double tolerance = 1e-10,
InitialClusteringType clusterer = InitialClusteringType(),
CovarianceConstraintPolicy constraint = CovarianceConstraintPolicy());
/**
* Fit the observations to a Gaussian mixture model (GMM) using the EM
* algorithm. The size of the vectors (indicating the number of components)
* must already be set. Optionally, if useInitialModel is set to true, then
* the model given in the means, covariances, and weights parameters is used
* as the initial model, instead of using the InitialClusteringType::Cluster()
* option.
*
* @param observations List of observations to train on.
* @param means Vector to store trained means in.
* @param covariances Vector to store trained covariances in.
* @param weights Vector to store a priori weights in.
* @param useInitialModel If true, the given model is used for the initial
* clustering.
*/
void Estimate(const arma::mat& observations,
std::vector<arma::vec>& means,
std::vector<arma::mat>& covariances,
arma::vec& weights,
const bool useInitialModel = false);
/**
* Fit the observations to a Gaussian mixture model (GMM) using the EM
* algorithm, taking into account the probabilities of each point being from
* this mixture. The size of the vectors (indicating the number of
* components) must already be set. Optionally, if useInitialModel is set to
* true, then the model given in the means, covariances, and weights
* parameters is used as the initial model, instead of using the
* InitialClusteringType::Cluster() option.
*
* @param observations List of observations to train on.
* @param probabilities Probability of each point being from this model.
* @param means Vector to store trained means in.
* @param covariances Vector to store trained covariances in.
* @param weights Vector to store a priori weights in.
* @param useInitialModel If true, the given model is used for the initial
* clustering.
*/
void Estimate(const arma::mat& observations,
const arma::vec& probabilities,
std::vector<arma::vec>& means,
std::vector<arma::mat>& covariances,
arma::vec& weights,
const bool useInitialModel = false);
//! Get the clusterer.
const InitialClusteringType& Clusterer() const { return clusterer; }
//! Modify the clusterer.
InitialClusteringType& Clusterer() { return clusterer; }
//! Get the covariance constraint policy class.
const CovarianceConstraintPolicy& Constraint() const { return constraint; }
//! Modify the covariance constraint policy class.
CovarianceConstraintPolicy& Constraint() { return constraint; }
//! Get the maximum number of iterations of the EM algorithm.
size_t MaxIterations() const { return maxIterations; }
//! Modify the maximum number of iterations of the EM algorithm.
size_t& MaxIterations() { return maxIterations; }
//! Get the tolerance for the convergence of the EM algorithm.
double Tolerance() const { return tolerance; }
//! Modify the tolerance for the convergence of the EM algorithm.
double& Tolerance() { return tolerance; }
private:
/**
* Run the clusterer, and then turn the cluster assignments into Gaussians.
* This is a helper function for both overloads of Estimate(). The vectors
* must be already set to the number of clusters.
*
* @param observations List of observations.
* @param means Vector to store means in.
* @param covariances Vector to store covariances in.
* @param weights Vector to store a priori weights in.
*/
void InitialClustering(const arma::mat& observations,
std::vector<arma::vec>& means,
std::vector<arma::mat>& covariances,
arma::vec& weights);
/**
* Calculate the log-likelihood of a model. Yes, this is reimplemented in the
* GMM code. Intuition suggests that the log-likelihood is not the best way
* to determine if the EM algorithm has converged.
*
* @param data Data matrix.
* @param means Vector of means.
* @param covariances Vector of covariance matrices.
* @param weights Vector of a priori weights.
*/
double LogLikelihood(const arma::mat& data,
const std::vector<arma::vec>& means,
const std::vector<arma::mat>& covariances,
const arma::vec& weights) const;
//! Maximum iterations of EM algorithm.
size_t maxIterations;
//! Tolerance for convergence of EM.
double tolerance;
//! Object which will perform the clustering.
InitialClusteringType clusterer;
//! Object which applies constraints to the covariance matrix.
CovarianceConstraintPolicy constraint;
};
}; // namespace gmm
}; // namespace mlpack
// Include implementation.
#include "em_fit_impl.hpp"
#endif
<commit_msg>Changes to work with new, hierarchical GMMs<commit_after>/**
* @file em_fit.hpp
* @author Ryan Curtin
* @author Michael Fox
*
* Utility class to fit a GMM using the EM algorithm. Used by
* GMM::Estimate<>().
*/
#ifndef __MLPACK_METHODS_GMM_EM_FIT_HPP
#define __MLPACK_METHODS_GMM_EM_FIT_HPP
#include <mlpack/core.hpp>
// Default clustering mechanism.
#include <mlpack/methods/kmeans/kmeans.hpp>
// Default covariance matrix constraint.
#include "positive_definite_constraint.hpp"
namespace mlpack {
namespace gmm {
/**
* This class contains methods which can fit a GMM to observations using the EM
* algorithm. It requires an initial clustering mechanism, which is by default
* the KMeans algorithm. The clustering mechanism must implement the following
* method:
*
* - void Cluster(const arma::mat& observations,
* const size_t clusters,
* arma::Col<size_t>& assignments);
*
* This method should create 'clusters' clusters, and return the assignment of
* each point to a cluster.
*/
template<typename InitialClusteringType = kmeans::KMeans<>,
typename CovarianceConstraintPolicy = PositiveDefiniteConstraint>
class EMFit
{
public:
/**
* Construct the EMFit object, optionally passing an InitialClusteringType
* object (just in case it needs to store state). Setting the maximum number
* of iterations to 0 means that the EM algorithm will iterate until
* convergence (with the given tolerance).
*
* The parameter forcePositive controls whether or not the covariance matrices
* are checked for positive definiteness at each iteration. This could be a
* time-consuming task, so, if you know your data is well-behaved, you can set
* it to false and save some runtime.
*
* @param maxIterations Maximum number of iterations for EM.
* @param tolerance Log-likelihood tolerance required for convergence.
* @param forcePositive Check for positive-definiteness of each covariance
* matrix at each iteration.
* @param clusterer Object which will perform the initial clustering.
*/
EMFit(const size_t maxIterations = 300,
const double tolerance = 1e-10,
InitialClusteringType clusterer = InitialClusteringType(),
CovarianceConstraintPolicy constraint = CovarianceConstraintPolicy());
/**
* Fit the observations to a Gaussian mixture model (GMM) using the EM
* algorithm. The size of the vectors (indicating the number of components)
* must already be set. Optionally, if useInitialModel is set to true, then
* the model given in the means, covariances, and weights parameters is used
* as the initial model, instead of using the InitialClusteringType::Cluster()
* option.
*
* @param observations List of observations to train on.
* @param means Vector to store trained means in.
* @param covariances Vector to store trained covariances in.
* @param weights Vector to store a priori weights in.
* @param useInitialModel If true, the given model is used for the initial
* clustering.
*/
void Estimate(const arma::mat& observations,
std::vector<distribution::GaussianDistribution>& dists,
arma::vec& weights,
const bool useInitialModel = false);
/**
* Fit the observations to a Gaussian mixture model (GMM) using the EM
* algorithm, taking into account the probabilities of each point being from
* this mixture. The size of the vectors (indicating the number of
* components) must already be set. Optionally, if useInitialModel is set to
* true, then the model given in the means, covariances, and weights
* parameters is used as the initial model, instead of using the
* InitialClusteringType::Cluster() option.
*
* @param observations List of observations to train on.
* @param probabilities Probability of each point being from this model.
* @param means Vector to store trained means in.
* @param covariances Vector to store trained covariances in.
* @param weights Vector to store a priori weights in.
* @param useInitialModel If true, the given model is used for the initial
* clustering.
*/
void Estimate(const arma::mat& observations,
const arma::vec& probabilities,
std::vector<distribution::GaussianDistribution>& dists,
arma::vec& weights,
const bool useInitialModel = false);
//! Get the clusterer.
const InitialClusteringType& Clusterer() const { return clusterer; }
//! Modify the clusterer.
InitialClusteringType& Clusterer() { return clusterer; }
//! Get the covariance constraint policy class.
const CovarianceConstraintPolicy& Constraint() const { return constraint; }
//! Modify the covariance constraint policy class.
CovarianceConstraintPolicy& Constraint() { return constraint; }
//! Get the maximum number of iterations of the EM algorithm.
size_t MaxIterations() const { return maxIterations; }
//! Modify the maximum number of iterations of the EM algorithm.
size_t& MaxIterations() { return maxIterations; }
//! Get the tolerance for the convergence of the EM algorithm.
double Tolerance() const { return tolerance; }
//! Modify the tolerance for the convergence of the EM algorithm.
double& Tolerance() { return tolerance; }
private:
/**
* Run the clusterer, and then turn the cluster assignments into Gaussians.
* This is a helper function for both overloads of Estimate(). The vectors
* must be already set to the number of clusters.
*
* @param observations List of observations.
* @param means Vector to store means in.
* @param covariances Vector to store covariances in.
* @param weights Vector to store a priori weights in.
*/
void InitialClustering(const arma::mat& observations,
std::vector<distribution::GaussianDistribution>& dists,
arma::vec& weights);
/**
* Calculate the log-likelihood of a model. Yes, this is reimplemented in the
* GMM code. Intuition suggests that the log-likelihood is not the best way
* to determine if the EM algorithm has converged.
*
* @param data Data matrix.
* @param means Vector of means.
* @param covariances Vector of covariance matrices.
* @param weights Vector of a priori weights.
*/
double LogLikelihood(const arma::mat& data,
const std::vector<distribution::GaussianDistribution>&
dists,
const arma::vec& weights) const;
//! Maximum iterations of EM algorithm.
size_t maxIterations;
//! Tolerance for convergence of EM.
double tolerance;
//! Object which will perform the clustering.
InitialClusteringType clusterer;
//! Object which applies constraints to the covariance matrix.
CovarianceConstraintPolicy constraint;
};
}; // namespace gmm
}; // namespace mlpack
// Include implementation.
#include "em_fit_impl.hpp"
#endif
<|endoftext|> |
<commit_before>/** Copyright 2008, 2009, 2010, 2011, 2012 Roland Olbricht
*
* This file is part of Overpass_API.
*
* Overpass_API is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Overpass_API 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 General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Overpass_API. If not, see <http://www.gnu.org/licenses/>.
*/
#include "dispatcher_stub.h"
#include "../frontend/user_interface.h"
#include "../statements/statement_dump.h"
#include <errno.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
string de_escape(string input)
{
string result;
string::size_type pos = 0;
while (pos < input.length())
{
if (input[pos] != '\\')
result += input[pos];
else
{
++pos;
if (pos >= input.length())
break;
if (input[pos] == 'n')
result += '\n';
else if (input[pos] == 't')
result += '\t';
else
result += input[pos];
}
++pos;
}
return result;
}
Dispatcher_Stub::Dispatcher_Stub
(string db_dir_, Error_Output* error_output_, string xml_raw, bool uses_meta, int area_level,
uint32 max_allowed_time, uint64 max_allowed_space)
: db_dir(db_dir_), error_output(error_output_),
dispatcher_client(0), area_dispatcher_client(0),
transaction(0), area_transaction(0), rman(0), meta(uses_meta)
{
if (db_dir == "")
{
uint32 client_token = probe_client_token();
dispatcher_client = new Dispatcher_Client(osm_base_settings().shared_name);
Logger logger(dispatcher_client->get_db_dir());
try
{
logger.annotated_log("request_read_and_idx() start");
dispatcher_client->request_read_and_idx(max_allowed_time, max_allowed_space, client_token);
logger.annotated_log("request_read_and_idx() end");
}
catch (const File_Error& e)
{
ostringstream out;
out<<e.origin<<' '<<e.filename<<' '<<e.error_number<<' '<<strerror(e.error_number);
if (e.origin == "Dispatcher_Client::request_read_and_idx::rate_limited"
|| e.origin == "Dispatcher_Client::request_read_and_idx::timeout")
out<<' '<<probe_client_identifier();
logger.annotated_log(out.str());
throw;
}
transaction = new Nonsynced_Transaction
(false, false, dispatcher_client->get_db_dir(), "");
transaction->data_index(osm_base_settings().NODES);
transaction->random_index(osm_base_settings().NODES);
transaction->data_index(osm_base_settings().NODE_TAGS_LOCAL);
transaction->data_index(osm_base_settings().NODE_TAGS_GLOBAL);
transaction->data_index(osm_base_settings().WAYS);
transaction->random_index(osm_base_settings().WAYS);
transaction->data_index(osm_base_settings().WAY_TAGS_LOCAL);
transaction->data_index(osm_base_settings().WAY_TAGS_GLOBAL);
transaction->data_index(osm_base_settings().RELATIONS);
transaction->random_index(osm_base_settings().RELATIONS);
transaction->data_index(osm_base_settings().RELATION_ROLES);
transaction->data_index(osm_base_settings().RELATION_TAGS_LOCAL);
transaction->data_index(osm_base_settings().RELATION_TAGS_GLOBAL);
if (meta)
{
transaction->data_index(meta_settings().NODES_META);
transaction->data_index(meta_settings().WAYS_META);
transaction->data_index(meta_settings().RELATIONS_META);
transaction->data_index(meta_settings().USER_DATA);
transaction->data_index(meta_settings().USER_INDICES);
}
{
ifstream version((dispatcher_client->get_db_dir() + "osm_base_version").c_str());
getline(version, timestamp);
timestamp = de_escape(timestamp);
}
try
{
logger.annotated_log("read_idx_finished() start");
dispatcher_client->read_idx_finished();
logger.annotated_log("read_idx_finished() end");
logger.annotated_log('\n' + xml_raw);
}
catch (const File_Error& e)
{
ostringstream out;
out<<e.origin<<' '<<e.filename<<' '<<e.error_number<<' '<<strerror(e.error_number);
logger.annotated_log(out.str());
throw;
}
if (area_level > 0)
{
area_dispatcher_client = new Dispatcher_Client(area_settings().shared_name);
Logger logger(area_dispatcher_client->get_db_dir());
if (area_level == 1)
{
try
{
logger.annotated_log("request_read_and_idx() area start");
area_dispatcher_client->request_read_and_idx(max_allowed_time, max_allowed_space, client_token);
logger.annotated_log("request_read_and_idx() area end");
}
catch (const File_Error& e)
{
ostringstream out;
out<<e.origin<<' '<<e.filename<<' '<<e.error_number<<' '<<strerror(e.error_number);
logger.annotated_log(out.str());
throw;
}
area_transaction = new Nonsynced_Transaction
(false, false, area_dispatcher_client->get_db_dir(), "");
{
ifstream version((area_dispatcher_client->get_db_dir() +
"area_version").c_str());
getline(version, area_timestamp);
area_timestamp = de_escape(area_timestamp);
}
}
else if (area_level == 2)
{
try
{
logger.annotated_log("write_start() area start");
area_dispatcher_client->write_start();
logger.annotated_log("write_start() area end");
}
catch (const File_Error& e)
{
ostringstream out;
out<<e.origin<<' '<<e.filename<<' '<<e.error_number<<' '<<strerror(e.error_number);
logger.annotated_log(out.str());
throw;
}
area_transaction = new Nonsynced_Transaction
(true, true, area_dispatcher_client->get_db_dir(), "");
{
ofstream area_version((area_dispatcher_client->get_db_dir()
+ "area_version.shadow").c_str());
area_version<<timestamp<<'\n';
area_timestamp = de_escape(timestamp);
}
}
area_transaction->data_index(area_settings().AREAS);
area_transaction->data_index(area_settings().AREA_BLOCKS);
area_transaction->data_index(area_settings().AREA_TAGS_LOCAL);
area_transaction->data_index(area_settings().AREA_TAGS_GLOBAL);
if (area_level == 1)
{
try
{
logger.annotated_log("read_idx_finished() area start");
area_dispatcher_client->read_idx_finished();
logger.annotated_log("read_idx_finished() area end");
}
catch (const File_Error& e)
{
ostringstream out;
out<<e.origin<<' '<<e.filename<<' '<<e.error_number<<' '<<strerror(e.error_number);
logger.annotated_log(out.str());
throw;
}
}
rman = new Resource_Manager(*transaction, area_level == 2 ? error_output : 0,
*area_transaction, this, area_level == 2 ? new Area_Updater(*area_transaction) : 0);
}
else
rman = new Resource_Manager(*transaction, this, error_output);
}
else
{
transaction = new Nonsynced_Transaction(false, false, db_dir, "");
if (area_level > 0)
{
area_transaction = new Nonsynced_Transaction(area_level == 2, false, db_dir, "");
rman = new Resource_Manager(*transaction, area_level == 2 ? error_output : 0,
*area_transaction, this, area_level == 2 ? new Area_Updater(*area_transaction) : 0);
}
else
rman = new Resource_Manager(*transaction, this);
{
ifstream version((db_dir + "osm_base_version").c_str());
getline(version, timestamp);
timestamp = de_escape(timestamp);
}
if (area_level == 1)
{
ifstream version((db_dir + "area_version").c_str());
getline(version, area_timestamp);
area_timestamp = de_escape(timestamp);
}
else if (area_level == 2)
{
ofstream area_version((db_dir + "area_version").c_str());
area_version<<timestamp<<'\n';
area_timestamp = de_escape(timestamp);
}
}
}
void Dispatcher_Stub::ping() const
{
if (dispatcher_client)
dispatcher_client->ping();
if (area_dispatcher_client)
area_dispatcher_client->ping();
}
Dispatcher_Stub::~Dispatcher_Stub()
{
bool areas_written = (rman->area_updater() != 0);
delete rman;
if (transaction)
delete transaction;
if (area_transaction)
delete area_transaction;
if (dispatcher_client)
{
Logger logger(dispatcher_client->get_db_dir());
try
{
logger.annotated_log("read_finished() start");
dispatcher_client->read_finished();
logger.annotated_log("read_finished() end");
}
catch (const File_Error& e)
{
ostringstream out;
out<<e.origin<<' '<<e.filename<<' '<<e.error_number<<' '<<strerror(e.error_number);
logger.annotated_log(out.str());
}
delete dispatcher_client;
}
if (area_dispatcher_client)
{
if (areas_written)
{
Logger logger(area_dispatcher_client->get_db_dir());
try
{
logger.annotated_log("write_commit() area start");
area_dispatcher_client->write_commit();
rename((area_dispatcher_client->get_db_dir() + "area_version.shadow").c_str(),
(area_dispatcher_client->get_db_dir() + "area_version").c_str());
logger.annotated_log("write_commit() area end");
}
catch (const File_Error& e)
{
ostringstream out;
out<<e.origin<<' '<<e.filename<<' '<<e.error_number<<' '<<strerror(e.error_number);
logger.annotated_log(out.str());
}
}
else
{
Logger logger(area_dispatcher_client->get_db_dir());
try
{
logger.annotated_log("read_finished() area start");
area_dispatcher_client->read_finished();
logger.annotated_log("read_finished() area end");
}
catch (const File_Error& e)
{
ostringstream out;
out<<e.origin<<' '<<e.filename<<' '<<e.error_number<<' '<<strerror(e.error_number);
logger.annotated_log(out.str());
}
}
delete area_dispatcher_client;
}
}
<commit_msg>Fixed a bug: Dispatcher_Stub didn't propagate the error log in some cases.<commit_after>/** Copyright 2008, 2009, 2010, 2011, 2012 Roland Olbricht
*
* This file is part of Overpass_API.
*
* Overpass_API is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Overpass_API 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 General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Overpass_API. If not, see <http://www.gnu.org/licenses/>.
*/
#include "dispatcher_stub.h"
#include "../frontend/user_interface.h"
#include "../statements/statement_dump.h"
#include <errno.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
string de_escape(string input)
{
string result;
string::size_type pos = 0;
while (pos < input.length())
{
if (input[pos] != '\\')
result += input[pos];
else
{
++pos;
if (pos >= input.length())
break;
if (input[pos] == 'n')
result += '\n';
else if (input[pos] == 't')
result += '\t';
else
result += input[pos];
}
++pos;
}
return result;
}
Dispatcher_Stub::Dispatcher_Stub
(string db_dir_, Error_Output* error_output_, string xml_raw, bool uses_meta, int area_level,
uint32 max_allowed_time, uint64 max_allowed_space)
: db_dir(db_dir_), error_output(error_output_),
dispatcher_client(0), area_dispatcher_client(0),
transaction(0), area_transaction(0), rman(0), meta(uses_meta)
{
if (db_dir == "")
{
uint32 client_token = probe_client_token();
dispatcher_client = new Dispatcher_Client(osm_base_settings().shared_name);
Logger logger(dispatcher_client->get_db_dir());
try
{
logger.annotated_log("request_read_and_idx() start");
dispatcher_client->request_read_and_idx(max_allowed_time, max_allowed_space, client_token);
logger.annotated_log("request_read_and_idx() end");
}
catch (const File_Error& e)
{
ostringstream out;
out<<e.origin<<' '<<e.filename<<' '<<e.error_number<<' '<<strerror(e.error_number);
if (e.origin == "Dispatcher_Client::request_read_and_idx::rate_limited"
|| e.origin == "Dispatcher_Client::request_read_and_idx::timeout")
out<<' '<<probe_client_identifier();
logger.annotated_log(out.str());
throw;
}
transaction = new Nonsynced_Transaction
(false, false, dispatcher_client->get_db_dir(), "");
transaction->data_index(osm_base_settings().NODES);
transaction->random_index(osm_base_settings().NODES);
transaction->data_index(osm_base_settings().NODE_TAGS_LOCAL);
transaction->data_index(osm_base_settings().NODE_TAGS_GLOBAL);
transaction->data_index(osm_base_settings().WAYS);
transaction->random_index(osm_base_settings().WAYS);
transaction->data_index(osm_base_settings().WAY_TAGS_LOCAL);
transaction->data_index(osm_base_settings().WAY_TAGS_GLOBAL);
transaction->data_index(osm_base_settings().RELATIONS);
transaction->random_index(osm_base_settings().RELATIONS);
transaction->data_index(osm_base_settings().RELATION_ROLES);
transaction->data_index(osm_base_settings().RELATION_TAGS_LOCAL);
transaction->data_index(osm_base_settings().RELATION_TAGS_GLOBAL);
if (meta)
{
transaction->data_index(meta_settings().NODES_META);
transaction->data_index(meta_settings().WAYS_META);
transaction->data_index(meta_settings().RELATIONS_META);
transaction->data_index(meta_settings().USER_DATA);
transaction->data_index(meta_settings().USER_INDICES);
}
{
ifstream version((dispatcher_client->get_db_dir() + "osm_base_version").c_str());
getline(version, timestamp);
timestamp = de_escape(timestamp);
}
try
{
logger.annotated_log("read_idx_finished() start");
dispatcher_client->read_idx_finished();
logger.annotated_log("read_idx_finished() end");
logger.annotated_log('\n' + xml_raw);
}
catch (const File_Error& e)
{
ostringstream out;
out<<e.origin<<' '<<e.filename<<' '<<e.error_number<<' '<<strerror(e.error_number);
logger.annotated_log(out.str());
throw;
}
if (area_level > 0)
{
area_dispatcher_client = new Dispatcher_Client(area_settings().shared_name);
Logger logger(area_dispatcher_client->get_db_dir());
if (area_level == 1)
{
try
{
logger.annotated_log("request_read_and_idx() area start");
area_dispatcher_client->request_read_and_idx(max_allowed_time, max_allowed_space, client_token);
logger.annotated_log("request_read_and_idx() area end");
}
catch (const File_Error& e)
{
ostringstream out;
out<<e.origin<<' '<<e.filename<<' '<<e.error_number<<' '<<strerror(e.error_number);
logger.annotated_log(out.str());
throw;
}
area_transaction = new Nonsynced_Transaction
(false, false, area_dispatcher_client->get_db_dir(), "");
{
ifstream version((area_dispatcher_client->get_db_dir() +
"area_version").c_str());
getline(version, area_timestamp);
area_timestamp = de_escape(area_timestamp);
}
}
else if (area_level == 2)
{
try
{
logger.annotated_log("write_start() area start");
area_dispatcher_client->write_start();
logger.annotated_log("write_start() area end");
}
catch (const File_Error& e)
{
ostringstream out;
out<<e.origin<<' '<<e.filename<<' '<<e.error_number<<' '<<strerror(e.error_number);
logger.annotated_log(out.str());
throw;
}
area_transaction = new Nonsynced_Transaction
(true, true, area_dispatcher_client->get_db_dir(), "");
{
ofstream area_version((area_dispatcher_client->get_db_dir()
+ "area_version.shadow").c_str());
area_version<<timestamp<<'\n';
area_timestamp = de_escape(timestamp);
}
}
area_transaction->data_index(area_settings().AREAS);
area_transaction->data_index(area_settings().AREA_BLOCKS);
area_transaction->data_index(area_settings().AREA_TAGS_LOCAL);
area_transaction->data_index(area_settings().AREA_TAGS_GLOBAL);
if (area_level == 1)
{
try
{
logger.annotated_log("read_idx_finished() area start");
area_dispatcher_client->read_idx_finished();
logger.annotated_log("read_idx_finished() area end");
}
catch (const File_Error& e)
{
ostringstream out;
out<<e.origin<<' '<<e.filename<<' '<<e.error_number<<' '<<strerror(e.error_number);
logger.annotated_log(out.str());
throw;
}
}
rman = new Resource_Manager(*transaction, area_level == 2 ? error_output : 0,
*area_transaction, this, area_level == 2 ? new Area_Updater(*area_transaction) : 0);
}
else
rman = new Resource_Manager(*transaction, this, error_output);
}
else
{
transaction = new Nonsynced_Transaction(false, false, db_dir, "");
if (area_level > 0)
{
area_transaction = new Nonsynced_Transaction(area_level == 2, false, db_dir, "");
rman = new Resource_Manager(*transaction, area_level == 2 ? error_output : 0,
*area_transaction, this, area_level == 2 ? new Area_Updater(*area_transaction) : 0);
}
else
rman = new Resource_Manager(*transaction, this, error_output);
{
ifstream version((db_dir + "osm_base_version").c_str());
getline(version, timestamp);
timestamp = de_escape(timestamp);
}
if (area_level == 1)
{
ifstream version((db_dir + "area_version").c_str());
getline(version, area_timestamp);
area_timestamp = de_escape(timestamp);
}
else if (area_level == 2)
{
ofstream area_version((db_dir + "area_version").c_str());
area_version<<timestamp<<'\n';
area_timestamp = de_escape(timestamp);
}
}
}
void Dispatcher_Stub::ping() const
{
if (dispatcher_client)
dispatcher_client->ping();
if (area_dispatcher_client)
area_dispatcher_client->ping();
}
Dispatcher_Stub::~Dispatcher_Stub()
{
bool areas_written = (rman->area_updater() != 0);
delete rman;
if (transaction)
delete transaction;
if (area_transaction)
delete area_transaction;
if (dispatcher_client)
{
Logger logger(dispatcher_client->get_db_dir());
try
{
logger.annotated_log("read_finished() start");
dispatcher_client->read_finished();
logger.annotated_log("read_finished() end");
}
catch (const File_Error& e)
{
ostringstream out;
out<<e.origin<<' '<<e.filename<<' '<<e.error_number<<' '<<strerror(e.error_number);
logger.annotated_log(out.str());
}
delete dispatcher_client;
}
if (area_dispatcher_client)
{
if (areas_written)
{
Logger logger(area_dispatcher_client->get_db_dir());
try
{
logger.annotated_log("write_commit() area start");
area_dispatcher_client->write_commit();
rename((area_dispatcher_client->get_db_dir() + "area_version.shadow").c_str(),
(area_dispatcher_client->get_db_dir() + "area_version").c_str());
logger.annotated_log("write_commit() area end");
}
catch (const File_Error& e)
{
ostringstream out;
out<<e.origin<<' '<<e.filename<<' '<<e.error_number<<' '<<strerror(e.error_number);
logger.annotated_log(out.str());
}
}
else
{
Logger logger(area_dispatcher_client->get_db_dir());
try
{
logger.annotated_log("read_finished() area start");
area_dispatcher_client->read_finished();
logger.annotated_log("read_finished() area end");
}
catch (const File_Error& e)
{
ostringstream out;
out<<e.origin<<' '<<e.filename<<' '<<e.error_number<<' '<<strerror(e.error_number);
logger.annotated_log(out.str());
}
}
delete area_dispatcher_client;
}
}
<|endoftext|> |
<commit_before>#pragma once
#include <functional>
#include <set>
#include "simple_graph/graph.hpp"
namespace simple_graph {
vertex_index_t min_idx(const std::set<vertex_index_t> &opened, const std::vector<float> &f_score)
{
vertex_index_t min_idx = 0;
float min = std::numeric_limits<float>::max();
bool inited = false;
for (auto idx : opened) {
if ((f_score[idx] < min) || !inited) {
min_idx = idx;
min = f_score[idx];
inited = true;
}
}
return min_idx;
}
template<bool Dir, typename V, typename E, typename W>
bool astar(const Graph<Dir, V, E, W> &g, vertex_index_t start_idx, vertex_index_t goal_idx,
const std::function<float(simple_graph::vertex_index_t, simple_graph::vertex_index_t)> &heuristic,
std::vector<vertex_index_t> *path)
{
vertex_index_t vnum = g.vertex_num();
if ((start_idx > vnum) || (goal_idx > vnum)) {
return false;
}
std::set<vertex_index_t> closed;
std::set<vertex_index_t> opened;
std::vector<vertex_index_t> came_from(vnum, 0);
std::vector<float> g_score(vnum, std::numeric_limits<float>::max());
std::vector<float> f_score(vnum, std::numeric_limits<float>::max());
g_score[start_idx] = 0;
f_score[start_idx] = heuristic(start_idx, goal_idx);
opened.insert(start_idx);
bool vertex_found = false;
while (!vertex_found && !opened.empty()) {
vertex_index_t current = min_idx(opened, f_score);
if (current == goal_idx) {
vertex_found = true;
break;
}
opened.erase(current);
closed.insert(current);
const std::set<vertex_index_t> &neighbours = g.outbounds(current, 0);
for (const auto &neighbour : neighbours) {
if (closed.count(neighbour) > 0) {
continue;
}
float tentative_score = g_score[current] + g.edge(current, neighbour).weight();
if (opened.count(neighbour) == 0) {
opened.insert(neighbour);
}
else if (tentative_score >= g_score[neighbour]) {
continue;
}
came_from[neighbour] = current;
g_score[neighbour] = tentative_score;
f_score[neighbour] = g_score[neighbour] + heuristic(neighbour, goal_idx);
}
}
if (vertex_found) {
vertex_index_t idx = goal_idx;
do {
path->push_back(idx);
idx = came_from[idx];
} while (idx != start_idx);
path->push_back(idx);
std::reverse(path->begin(), path->end());
}
return vertex_found;
}
} // namespace simple_graph
<commit_msg>Use unordered_set in astar<commit_after>#pragma once
#include <functional>
#include <set>
#include <unordered_set>
#include "simple_graph/graph.hpp"
namespace simple_graph {
vertex_index_t min_idx(const std::unordered_set<vertex_index_t> &opened, const std::vector<float> &f_score)
{
vertex_index_t min_idx = 0;
float min = std::numeric_limits<float>::max();
bool inited = false;
for (auto idx : opened) {
if ((f_score[idx] < min) || !inited) {
min_idx = idx;
min = f_score[idx];
inited = true;
}
}
return min_idx;
}
template<bool Dir, typename V, typename E, typename W>
bool astar(const Graph<Dir, V, E, W> &g, vertex_index_t start_idx, vertex_index_t goal_idx,
const std::function<float(simple_graph::vertex_index_t, simple_graph::vertex_index_t)> &heuristic,
std::vector<vertex_index_t> *path)
{
vertex_index_t vnum = g.vertex_num();
if ((start_idx > vnum) || (goal_idx > vnum)) {
return false;
}
std::unordered_set<vertex_index_t> closed;
std::unordered_set<vertex_index_t> opened;
std::vector<vertex_index_t> came_from(vnum, 0);
std::vector<float> g_score(vnum, std::numeric_limits<float>::max());
std::vector<float> f_score(vnum, std::numeric_limits<float>::max());
g_score[start_idx] = 0;
f_score[start_idx] = heuristic(start_idx, goal_idx);
opened.insert(start_idx);
bool vertex_found = false;
while (!vertex_found && !opened.empty()) {
vertex_index_t current = min_idx(opened, f_score);
if (current == goal_idx) {
vertex_found = true;
break;
}
opened.erase(current);
closed.insert(current);
const std::set<vertex_index_t> &neighbours = g.outbounds(current, 0);
for (const auto &neighbour : neighbours) {
if (closed.count(neighbour) > 0) {
continue;
}
float tentative_score = g_score[current] + g.edge(current, neighbour).weight();
if (opened.count(neighbour) == 0) {
opened.insert(neighbour);
}
else if (tentative_score >= g_score[neighbour]) {
continue;
}
came_from[neighbour] = current;
g_score[neighbour] = tentative_score;
f_score[neighbour] = g_score[neighbour] + heuristic(neighbour, goal_idx);
}
}
if (vertex_found) {
vertex_index_t idx = goal_idx;
do {
path->push_back(idx);
idx = came_from[idx];
} while (idx != start_idx);
path->push_back(idx);
std::reverse(path->begin(), path->end());
}
return vertex_found;
}
} // namespace simple_graph
<|endoftext|> |
<commit_before>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2010 Belledonne Communications SARL.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "agent.hh"
#include "etchosts.hh"
class ForwardModule : public Module, ModuleToolbox {
public:
ForwardModule(Agent *ag);
virtual void onDeclare(ConfigStruct * module_config);
virtual void onLoad(Agent *agent, const ConfigStruct *root);
virtual void onRequest(SipEvent *ev);
virtual void onResponse(SipEvent *ev);
~ForwardModule();
private:
url_t* overrideDest(SipEvent *ev, url_t* dest);
void checkRecordRoutes(SipEvent *ev, url_t *dest);
su_home_t mHome;
sip_route_t *mOutRoute;
bool mRewriteReqUri;
static ModuleInfo<ForwardModule> sInfo;
};
ModuleInfo<ForwardModule> ForwardModule::sInfo("Forward",
"This module executes the basic routing task of SIP requests and pass them to the transport layer. "
"It must always be enabled.");
ForwardModule::ForwardModule(Agent *ag) : Module(ag){
su_home_init(&mHome);
mOutRoute=NULL;
}
ForwardModule::~ForwardModule(){
su_home_deinit(&mHome);
}
void ForwardModule::onDeclare(ConfigStruct * module_config){
ConfigItemDescriptor items[]={
{ String , "route" , "A sip uri where to send all requests", "" },
{ Boolean , "rewrite-req-uri" , "Rewrite request-uri's host and port according to above route", "false" },
config_item_end
};
module_config->addChildrenValues(items);
}
void ForwardModule::onLoad(Agent *agent, const ConfigStruct *module_config){
std::string route=module_config->get<ConfigString>("route")->read();
mRewriteReqUri=module_config->get<ConfigBoolean>("rewrite-req-uri")->read();
if (route.size()>0){
mOutRoute=sip_route_create(&mHome,(url_t*)route.c_str(),NULL);
if (mOutRoute==NULL){
LOGF("Bad route parameter '%s' in configuration of Forward module",route.c_str());
}
}
}
url_t* ForwardModule::overrideDest(SipEvent *ev, url_t *dest){
if (mOutRoute){
dest=mOutRoute->r_url;
if (mRewriteReqUri){
ev->mSip->sip_request->rq_url->url_host=mOutRoute->r_url->url_host;
ev->mSip->sip_request->rq_url->url_port=mOutRoute->r_url->url_port;
}
}
return dest;
}
/* the goal of this method is to check whether we added ourself to the record route, and handle a possible
transport change by adding a new record-route with transport updated.
Typically, if we transfer an INVITE from TCP to UDP, we should find two consecutive record-route, first one with UDP, and second one with TCP
so that further request from both sides are sent to the appropriate transport of flexisip, and also we don't ask to a UDP only equipment to route to TCP.
*/
void ForwardModule::checkRecordRoutes(SipEvent *ev, url_t *dest){
sip_record_route_t *rr=ev->mSip->sip_record_route;
char last_transport[16]={0};
char next_transport[16]={0};
if (rr){
if (getAgent()->isUs(rr->r_url,false)){
if (!url_param(rr->r_url->url_params,"transport",last_transport,sizeof(last_transport))){
strncpy(last_transport,"UDP",sizeof(last_transport));
}
if (!url_param(dest->url_params,"transport",next_transport,sizeof(next_transport))){
strncpy(next_transport,"UDP",sizeof(next_transport));
}
if (strcasecmp(next_transport,last_transport)!=0){
addRecordRoute(ev->getHome(),getAgent(),ev->mMsg,ev->mSip,next_transport);
}
}
}
}
void ForwardModule::onRequest(SipEvent *ev){
size_t msg_size;
char *buf;
url_t* dest=NULL;
sip_t *sip=ev->mSip;
msg_t *msg=ev->mMsg;
switch(sip->sip_request->rq_method){
case sip_method_invite:
LOGD("This is an invite");
break;
case sip_method_register:
LOGD("This is a register");
case sip_method_ack:
default:
break;
}
dest=sip->sip_request->rq_url;
// removes top route headers if they maches us
if (sip->sip_route!=NULL && getAgent()->isUs(sip->sip_route->r_url) ){
sip_route_remove(msg,sip);
}
if (sip->sip_route!=NULL){
/*forward to this route*/
dest=sip->sip_route->r_url;
}
/* workaround bad sip uris with two @ that results in host part being "something@somewhere" */
if (strchr(dest->url_host,'@')!=0){
nta_msg_treply (getSofiaAgent(),msg,400,"Bad request",SIPTAG_SERVER_STR(getAgent()->getServerString()),TAG_END());
return;
}
dest=overrideDest(ev,dest);
std::string ip;
if (EtcHostsResolver::get()->resolve(dest->url_host,&ip)){
LOGD("Found %s in /etc/hosts",dest->url_host);
/* duplication dest because we don't want to modify the message with our name resolution result*/
dest=url_hdup(ev->getHome(),dest);
dest->url_host=ip.c_str();
}
if (!getAgent()->isUs(dest)) {
checkRecordRoutes(ev,dest);
buf=msg_as_string(ev->getHome(), msg, NULL, 0,&msg_size);
LOGD("About to forward request to %s:\n%s",url_as_string(ev->getHome(),dest),buf);
nta_msg_tsend (getSofiaAgent(),msg,(url_string_t*)dest,TAG_END());
}else{
LOGD("This message has final destination this proxy, discarded...");
nta_msg_discard(getSofiaAgent(),msg);
}
}
void ForwardModule::onResponse(SipEvent *ev){
char *buf;
size_t msg_size;
buf=msg_as_string(ev->getHome(), ev->mMsg, NULL, 0,&msg_size);
LOGD("About to forward response:\n%s",buf);
nta_msg_tsend(getSofiaAgent(),ev->mMsg,(url_string_t*)NULL,TAG_END());
}
<commit_msg>fix popping of routes...<commit_after>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2010 Belledonne Communications SARL.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "agent.hh"
#include "etchosts.hh"
class ForwardModule : public Module, ModuleToolbox {
public:
ForwardModule(Agent *ag);
virtual void onDeclare(ConfigStruct * module_config);
virtual void onLoad(Agent *agent, const ConfigStruct *root);
virtual void onRequest(SipEvent *ev);
virtual void onResponse(SipEvent *ev);
~ForwardModule();
private:
url_t* overrideDest(SipEvent *ev, url_t* dest);
void checkRecordRoutes(SipEvent *ev, url_t *dest);
su_home_t mHome;
sip_route_t *mOutRoute;
bool mRewriteReqUri;
static ModuleInfo<ForwardModule> sInfo;
};
ModuleInfo<ForwardModule> ForwardModule::sInfo("Forward",
"This module executes the basic routing task of SIP requests and pass them to the transport layer. "
"It must always be enabled.");
ForwardModule::ForwardModule(Agent *ag) : Module(ag){
su_home_init(&mHome);
mOutRoute=NULL;
}
ForwardModule::~ForwardModule(){
su_home_deinit(&mHome);
}
void ForwardModule::onDeclare(ConfigStruct * module_config){
ConfigItemDescriptor items[]={
{ String , "route" , "A sip uri where to send all requests", "" },
{ Boolean , "rewrite-req-uri" , "Rewrite request-uri's host and port according to above route", "false" },
config_item_end
};
module_config->addChildrenValues(items);
}
void ForwardModule::onLoad(Agent *agent, const ConfigStruct *module_config){
std::string route=module_config->get<ConfigString>("route")->read();
mRewriteReqUri=module_config->get<ConfigBoolean>("rewrite-req-uri")->read();
if (route.size()>0){
mOutRoute=sip_route_create(&mHome,(url_t*)route.c_str(),NULL);
if (mOutRoute==NULL){
LOGF("Bad route parameter '%s' in configuration of Forward module",route.c_str());
}
}
}
url_t* ForwardModule::overrideDest(SipEvent *ev, url_t *dest){
if (mOutRoute){
dest=mOutRoute->r_url;
if (mRewriteReqUri){
ev->mSip->sip_request->rq_url->url_host=mOutRoute->r_url->url_host;
ev->mSip->sip_request->rq_url->url_port=mOutRoute->r_url->url_port;
}
}
return dest;
}
/* the goal of this method is to check whether we added ourself to the record route, and handle a possible
transport change by adding a new record-route with transport updated.
Typically, if we transfer an INVITE from TCP to UDP, we should find two consecutive record-route, first one with UDP, and second one with TCP
so that further request from both sides are sent to the appropriate transport of flexisip, and also we don't ask to a UDP only equipment to route to TCP.
*/
void ForwardModule::checkRecordRoutes(SipEvent *ev, url_t *dest){
sip_record_route_t *rr=ev->mSip->sip_record_route;
char last_transport[16]={0};
char next_transport[16]={0};
if (rr){
if (getAgent()->isUs(rr->r_url,false)){
if (!url_param(rr->r_url->url_params,"transport",last_transport,sizeof(last_transport))){
strncpy(last_transport,"UDP",sizeof(last_transport));
}
if (!url_param(dest->url_params,"transport",next_transport,sizeof(next_transport))){
strncpy(next_transport,"UDP",sizeof(next_transport));
}
if (strcasecmp(next_transport,last_transport)!=0){
addRecordRoute(ev->getHome(),getAgent(),ev->mMsg,ev->mSip,next_transport);
}
}
}
}
void ForwardModule::onRequest(SipEvent *ev){
size_t msg_size;
char *buf;
url_t* dest=NULL;
sip_t *sip=ev->mSip;
msg_t *msg=ev->mMsg;
switch(sip->sip_request->rq_method){
case sip_method_invite:
LOGD("This is an invite");
break;
case sip_method_register:
LOGD("This is a register");
case sip_method_ack:
default:
break;
}
dest=sip->sip_request->rq_url;
// removes top route headers if they maches us
while (sip->sip_route!=NULL && getAgent()->isUs(sip->sip_route->r_url) ){
sip_route_remove(msg,sip);
}
if (sip->sip_route!=NULL){
/*forward to this route*/
dest=sip->sip_route->r_url;
}
/* workaround bad sip uris with two @ that results in host part being "something@somewhere" */
if (strchr(dest->url_host,'@')!=0){
nta_msg_treply (getSofiaAgent(),msg,400,"Bad request",SIPTAG_SERVER_STR(getAgent()->getServerString()),TAG_END());
return;
}
dest=overrideDest(ev,dest);
std::string ip;
if (EtcHostsResolver::get()->resolve(dest->url_host,&ip)){
LOGD("Found %s in /etc/hosts",dest->url_host);
/* duplication dest because we don't want to modify the message with our name resolution result*/
dest=url_hdup(ev->getHome(),dest);
dest->url_host=ip.c_str();
}
if (!getAgent()->isUs(dest)) {
checkRecordRoutes(ev,dest);
buf=msg_as_string(ev->getHome(), msg, NULL, 0,&msg_size);
LOGD("About to forward request to %s:\n%s",url_as_string(ev->getHome(),dest),buf);
nta_msg_tsend (getSofiaAgent(),msg,(url_string_t*)dest,TAG_END());
}else{
LOGD("This message has final destination this proxy, discarded...");
nta_msg_discard(getSofiaAgent(),msg);
}
}
void ForwardModule::onResponse(SipEvent *ev){
char *buf;
size_t msg_size;
buf=msg_as_string(ev->getHome(), ev->mMsg, NULL, 0,&msg_size);
LOGD("About to forward response:\n%s",buf);
nta_msg_tsend(getSofiaAgent(),ev->mMsg,(url_string_t*)NULL,TAG_END());
}
<|endoftext|> |
<commit_before>#include <vector>
using namespace std;
class RRR {
// superblokovi su 0-indeksirani
// blokovi su 0-indeksirani
private:
int b; // velicina bloka
int f; // broj blokova u superbloku
int sumsb[n/(b*f)]; // suma jedinica do i-tog superbloka, ukljucivo
int c[n/b]; // klasa za svaki blok
int o[n/b]; // offset za svaki blok
int cum[c,o][pos]; // kumulativna suma bloka indeksiranog s c, o; 0-indeksirano
int nb = (n-1)/b+1; // broj blokova
int nsb = (n-1)/(b*f)+1; // broj superblokova
// vraca zadnji superblok u kojem se nalazi i-ta jedinica
int sb_search(int i) {
int lo = 0;
int hi = nsb;
while(lo < hi) {
int mid = (lo+hi)/2;
if (sumsb[mid] < i) {
lo = mid+1;
} else {
hi = mid;
}
}
return lo;
}
public:
RRR(vector<bool> bits, int _b, int _f): b(_b), f(_f) {
}
// broj nula do pozicije i (0-indeksiran), ukljucivo
int rank0(int i) {
return i+1-rank1(i);
}
// broj jedinica do pozicije i (0-indeksiran), ukljucivo
int rank1(int i) {
int ib = i/b; // indeks bloka te pozicije
int is = ib/f; // indeks superbloka te pozicije
int result = (is > 0) ? sumsb[is-1] : 0; // suma jedinica do is-tog superbloka
// prodji po svim blokovima od pocetka ovog superbloka do trenutnog bloka
for (int i = is*f; i < ib; ++i) {
result += c[i]; // dodaj broj jedinica u tom bloku
}
result += cum[c[ib], o[ib]][i-ib*b] // dodaj broj jedinica u zadnjem bloku
return result;
}
// vraca poziciju i-te jedinice, 0-indeksirano
int select(int i) {
int is = sb_search(i); // superblok u kojem se nalazi i-ta jedinica
int cnt = (is > 0) ? sumsb[is-1] : 0; // broj jedinica do trenutnog superbloka
int ib = is*f; // trenutni blok
// hodaj po blokovima dok ne dostignes sumu
while (cnt < i) {
cnt += c[ib];
++ib;
}
// vrati se na prethodni blok
--ib;
cnt -= c[ib];
// binary search unutar bloka
int lo = 0;
int hi = b;
while(lo < hi) {
int mid = (lo+hi)/2;
if (cum[c[ib], o[ib]][mid]+cnt < i) {
lo = mid+1;
} else {
hi = mid;
}
}
return ib*b + lo;
}
// vraca bit na i-toj poziciji
int access(int i) {
return (i > 0) ? rank1(i)-rank1(i-1) : rank1(i);
}
};
int main(void) {
return 0;
}
<commit_msg>Converted pseudocode to real code. Translated to english.<commit_after>#include <vector>
using namespace std;
class RRR {
private:
// NB: b should be less than 32 with current implementation
// NB: superblock and block positions are 0-indexed
int b; // block size
int f; // number of blocks in superblock
int numBlocks; // number of blocks
int numSuperblocks; // number of superblocks
vector<int> superblockCumSum; // cumulative sum of ones to i-th superblock, inclusive, size ~ (n/(b*f))
vector<int> blockClass; // block class, ie. number of ones in block, size ~ (n/b)
vector<int> blockOffset; // block offset in class, size ~ (n/b)
// cumulative sum of ones to i-th position in block indexed with (class,offset), 0-indexed
// size ~ (b*2^b)
vector<vector<vector<int>>> cumSumInBlock;
// finds index of superblock containing i-th one
int findSuperblockByOne(int i) {
int lo = 0;
int hi = numSuperblocks;
while(lo < hi) {
int mid = (lo+hi)/2;
if (superblockCumSum[mid] < i) {
lo = mid+1;
} else {
hi = mid;
}
}
return lo;
}
int getIndBlock(int ind) {
return ind/b;
}
int getIndSuperblock(int ind) {
return indBlock/(b*f);
}
int getCumSumToSuperblock(int indSuperblock) {
return (indSuperblock < 0) ? 0 : superblockCumSum[indSuperblock];
}
bool isBlockStart(int ind) {
return getIndBlock(ind) != getIndBlock(ind-1);
}
// TODO: check this
int nChoosek(int n, int k) {
if (k > n) return 0;
if (k*2 > n) k = n-k;
if (k == 0) return 1;
int res = n;
for (int i = 2; i <= k; ++i) {
res *= (n-i+1);
res /= i;
}
return res;
}
public:
// time-complexity - O(b*2^b) for preprocessing
RRR(vector<bool> bits, int _b, int _f): b(_b), f(_f) {
// preprocessing - O(b*2^b) time and memory
vector<int> blockValToOffset;
blockValToOffset.resize(1<<b);
vector<int> indInClass; // index in class
indInClass.resize(b+1, 0); // b+1 different classes in total (0 ones, .., b ones)
cumSumInBlock.resize(b);
for (int i = 0; i < (1<<b); ++i) {
int classType = __builtin_popcount(i);
blockValToOffset[i] = indInClass[classType];
++indInClass[classType];
// calculate cumSumInBlock
cumSumInBlock[classType].resize(nChoosek(b, classType)); // TODO: check what multiple resizing does
cumSumInBlock[classType][blockValToOffset[i]].resize(b);
int cumsum = 0;
for (int j = 0; j < b; ++j) {
cumsum += !!(i&(1<<j));
cumSumInBlock[classType][blockValToOffset[i]][j] = cumsum;
}
}
// preprocessing finished
int n = bits.size();
numBlocks = (n-1)/b+1;
numSuperblocks = (n-1)/(b*f)+1;
blockClass.resize(numBlocks, 0);
blockOffset.resize(numBlocks);
superblockCumSum.resize(numSuperblocks);
int cumsum = 0;
int blockVal = 0;
for (int i = 0; i < n; ++i) {
if (isBlockStart(i)) {
blockVal = 0; // when new block starts reset block value to zero
}
// update block class and offset
indBlock = getIndBlock(i);
blockVal = (blockVal*2) + bits[i]; // NB: currently limits b to 32
blockOffset[indBlock] = blockValToOffset[blockVal];
blockClass[indBlock] += bits[i];
// update superblockCumSum
cumsum += bits[i];
superblockCumSum[getIndSuperBlock(i)] = cumsum;
}
}
// number of zeros to position i, inclusive
// time-complexity - same as rank1()
int rank0(int i) {
// calculate using number of ones
return i+1-rank1(i);
}
// number of ones to position i, inclusive
// time-complexity - O(f)
// TODO: convert to O(1), hint: remove looping through each block in superblock and
// use cumulative sum of blocks in superblock instead
int rank1(int ind) {
int indBlock = getIndBlock(ind); // block index
int indSuperblock = getIndSuperblock(ind); // superblock index
// cumulative sum of ones up to previous superblock
int counter = getCumSumToSuperblock(indSuperblock-1);
// add sum of ones in all blocks of current superblock up to previous block
for (int i = indSuperblock*f; i < indBlock; ++i) {
counter += blockClass[i];
}
// add number of ones in current block up to i-th position
counter += cumSumInBlock[blockClass[indBlock]][blockOffset[indBlock]][i-indBlock*b]
return counter;
}
// index of the i-th one (0-indexed)
// time-complexity - O(log(n/(b*f))+f+log(b))
// TODO: be consistent with binary search, both implemented in separate methods or both
// in this method
// TODO: implement select0()
int select(int i) {
int indSuperblock = findSuperblockByOne(i); // index of superblock containing i-th one
// cumulative sum of ones up to previous superblock
int counter = getCumSumToSuperblock(indSuperblock-1);
int indBlock = indSuperblock*f; // current block index
// loop through blocks until the sum of i is reached
while (counter < i) {
counter += blockClass[indBlock];
++indBlock;
}
// return to previous block
--indBlock;
counter -= blockClass[indBlock];
// binary search in block
int lo = 0;
int hi = b;
while (lo < hi) {
int mid = (lo+hi)/2;
if (cumSumInBlock[blockClass[indBlock]][blockOffset[indBlock]][mid]+counter < i) {
lo = mid+1;
} else {
hi = mid;
}
}
return indBlock*b + lo;
}
// bit on given index
// time-complexity - same as rank1()
int access(int ind) {
return (ind > 0) ? rank1(ind)-rank1(ind-1) : rank1(ind);
}
};
int main(void) {
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012-2014 Eric M. Heien, Michael K. Sachs, John B. Rundle
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#include "UpdateBlockStress.h"
#include "SimError.h"
/*!
Initialize the stress calculation by setting initial block slip and stresses
then calculating the stress in the whole system.
*/
void UpdateBlockStress::init(SimFramework *_sim) {
BlockList::iterator it;
BlockID bid;
sim = static_cast<VCSimulation *>(_sim);
tmpBuffer = new double[sim->numGlobalBlocks()];
for (it=sim->begin(); it!=sim->end(); ++it) {
bid = it->getBlockID();
// Set stresses to their specified initial values
sim->setShearStress(bid, it->getInitShearStress());
sim->setNormalStress(bid, it->getInitNormalStress());
// noise in the range [1-a, 1+a)
it->state.slipDeficit = 0;
if (sim->isLocalBlockID(bid)) {
sim->decompressNormalRow(bid);
//sim->setGreenNormal(bid, bid, 0.0); // Erase diagonal for normal Greens matrix
sim->compressNormalRow(bid, 0.7);
}
}
// Compute initial stress on all blocks
stressRecompute();
}
/*!
Calculate the stress on all blocks and determine which block will be
the next to fail and when it will fail. Use this to determine the
slipDeficit on all blocks at the time of failure. Finally, use the
new slipDeficit to recalculate the stress on all blocks at the time of failure.
*/
SimRequest UpdateBlockStress::run(SimFramework *_sim) {
// Put a stress load on all blocks and determine which block will fail first
int lid;
BlockVal fail_time;
quakelib::Conversion convert;
// Calculate the current rates of stress change on all blocks
stressRecompute();
// Given the rates of change, determine which block will fail next
fail_time.block_id = UNDEFINED_BLOCK_ID;
nextTimeStep(fail_time);
// Increment the simulation year to the next failure time and
// update the slip on all other blocks
sim->incrementYear(fail_time.val);
for (lid=0; lid<sim->numLocalBlocks(); ++lid) {
Block &local_block = sim->getBlock(sim->getGlobalBID(lid));
local_block.state.slipDeficit -= local_block.slip_rate()*convert.year2sec(fail_time.val)*(1.0-local_block.aseismic());
}
// Recalculate the stress on all blocks with the new slip deficits
stressRecompute();
if (sim->getYear() > sim->getSimDuration()) return SIM_STOP_REQUIRED;
else return SIM_CONTINUE;
}
/*!
Determine the next time step in the simulation when a failure occurs.
Return the block ID of the block responsible for the failure and the timestep until the failure.
*/
void UpdateBlockStress::nextTimeStep(BlockVal &fail_time) {
BlockList::iterator it;
BlockVal temp_block_fail;
double ts;
VCEvent new_event;
BlockID gid;
int lid;
quakelib::Conversion convert;
// Set up the temporary buffer and update field
for (it=sim->begin(); it!=sim->end(); ++it) {
tmpBuffer[it->getBlockID()] = 0.0;
// Set the update field to be the slip rate of each block
sim->setUpdateField(it->getBlockID(), it->slip_rate());
}
// update the temporary buffer with the Greens function applied to the block slip rates
sim->matrixVectorMultiplyAccum(tmpBuffer,
sim->greenShear(),
sim->getUpdateFieldPtr(),
true);
if (sim->doNormalStress()) {
for (it=sim->begin(); it!=sim->end(); ++it) {
sim->setUpdateField(it->getBlockID(), -it->friction()*it->slip_rate());
}
sim->matrixVectorMultiplyAccum(tmpBuffer,
sim->greenNormal(),
sim->getUpdateFieldPtr(),
true);
}
// Go through the blocks and find which one will fail first
temp_block_fail.val = DBL_MAX;
temp_block_fail.block_id = UNDEFINED_BLOCK_ID;
for (lid=0; lid<sim->numLocalBlocks(); ++lid) {
gid = sim->getGlobalBID(lid);
Block &block = sim->getBlock(gid);
// Calculate the time until this block will fail
// If the block has aseismic slip, the calculation is the exact solution of the
// differential equation d(cff)/dt = rate_of_stress_change + cff*aseismic_frac*self_shear/recurrence
if (block.aseismic() > 0) {
double A, B, K;
A = -tmpBuffer[gid];
B = -block.aseismic()*block.getSelfStresses()/block.getRecurrence();
K = -log(A+B*block.getCFF())/B;
ts = K + log(A)/B;
} else {
ts = convert.sec2year(block.getCFF()/tmpBuffer[gid]);
}
// Blocks with negative timesteps are skipped. These effectively mean the block
// should have failed already but didn't. This can happen in the starting phase
// of a simulation due to initial stresses. These blocks will fail anyway in the
// event propagation section, so we can safely ignore them here. However, negative
// timesteps should not happen after the simulation has progressed for a while.
if (ts <= 0) continue;
// If the time to slip is less than the current shortest time, record the block
if (ts < temp_block_fail.val) {
temp_block_fail.block_id = gid;
temp_block_fail.val = ts;
}
}
// Each node now has the time before the first failure among its blocks
// Determine the time to first failure over all nodes
sim->allReduceBlockVal(temp_block_fail, fail_time, BLOCK_VAL_MIN);
// If we didn't find any blocks that slipped, abort the simulation
assertThrow(fail_time.val < DBL_MAX, "System stuck, no blocks to move.");
// Setup the current event to have the trigger block ID and time
new_event.setEventTriggerOnThisNode(fail_time.block_id==temp_block_fail.block_id);
new_event.setEventTrigger(fail_time.block_id);
new_event.setEventYear(sim->getYear()+fail_time.val);
new_event.setEventNumber(sim->getEventCount());
sim->addEvent(new_event);
}
/*!
Recompute the stress on each block based on the slip deficits of all the other blocks.
*/
void UpdateBlockStress::stressRecompute(void) {
BlockList::iterator it;
// Reset the shear and normal stress, and set the update field to be the slip deficit
for (it=sim->begin(); it!=sim->end(); ++it) {
sim->setShearStress(it->getBlockID(), 0.0);
sim->setNormalStress(it->getBlockID(), it->getRhogd());
sim->setUpdateField(it->getBlockID(), it->state.slipDeficit);
}
// Distribute the new update field over all nodes
sim->distributeUpdateField();
// Multiply the Greens shear function by the slipDeficit vector
// to get shear on local blocks
sim->matrixVectorMultiplyAccum(sim->getShearStressPtr(),
sim->greenShear(),
sim->getUpdateFieldPtr(),
true);
if (sim->doNormalStress()) {
sim->matrixVectorMultiplyAccum(sim->getNormalStressPtr(),
sim->greenNormal(),
sim->getUpdateFieldPtr(),
true);
}
// Recompute the CFF on blocks based on the new shear/normal stresses
sim->computeCFFs();
}
void UpdateBlockStress::finish(SimFramework *_sim) {
delete tmpBuffer;
}
<commit_msg>Fix stress drop, now passes all but one test<commit_after>// Copyright (c) 2012-2014 Eric M. Heien, Michael K. Sachs, John B. Rundle
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#include "UpdateBlockStress.h"
#include "SimError.h"
/*!
Initialize the stress calculation by setting initial block slip and stresses
then calculating the stress in the whole system.
*/
void UpdateBlockStress::init(SimFramework *_sim) {
BlockList::iterator it, nt;
BlockID bid;
double stress_drop, norm_velocity;
sim = static_cast<VCSimulation *>(_sim);
tmpBuffer = new double[sim->numGlobalBlocks()];
for (it=sim->begin(); it!=sim->end(); ++it) {
bid = it->getBlockID();
// Set stresses to their specified initial values
sim->setShearStress(bid, it->getInitShearStress());
sim->setNormalStress(bid, it->getInitNormalStress());
// Set the stress drop based on the Greens function calculations
stress_drop = 0;
norm_velocity = it->slip_rate();
for (nt=sim->begin(); nt!=sim->end(); ++nt) {
stress_drop += (nt->slip_rate()/norm_velocity)*sim->getGreenShear(it->getBlockID(), nt->getBlockID());
}
it->setStressDrop(it->getMaxSlip()*stress_drop);
// noise in the range [1-a, 1+a)
it->state.slipDeficit = 0;
if (sim->isLocalBlockID(bid)) {
sim->decompressNormalRow(bid);
//sim->setGreenNormal(bid, bid, 0.0); // Erase diagonal for normal Greens matrix
sim->compressNormalRow(bid, 0.7);
}
}
// Compute initial stress on all blocks
stressRecompute();
}
/*!
Calculate the stress on all blocks and determine which block will be
the next to fail and when it will fail. Use this to determine the
slipDeficit on all blocks at the time of failure. Finally, use the
new slipDeficit to recalculate the stress on all blocks at the time of failure.
*/
SimRequest UpdateBlockStress::run(SimFramework *_sim) {
// Put a stress load on all blocks and determine which block will fail first
int lid;
BlockVal fail_time;
quakelib::Conversion convert;
// Calculate the current rates of stress change on all blocks
stressRecompute();
// Given the rates of change, determine which block will fail next
fail_time.block_id = UNDEFINED_BLOCK_ID;
nextTimeStep(fail_time);
// Increment the simulation year to the next failure time and
// update the slip on all other blocks
sim->incrementYear(fail_time.val);
for (lid=0; lid<sim->numLocalBlocks(); ++lid) {
Block &local_block = sim->getBlock(sim->getGlobalBID(lid));
local_block.state.slipDeficit -= local_block.slip_rate()*convert.year2sec(fail_time.val)*(1.0-local_block.aseismic());
}
// Recalculate the stress on all blocks with the new slip deficits
stressRecompute();
if (sim->getYear() > sim->getSimDuration()) return SIM_STOP_REQUIRED;
else return SIM_CONTINUE;
}
/*!
Determine the next time step in the simulation when a failure occurs.
Return the block ID of the block responsible for the failure and the timestep until the failure.
*/
void UpdateBlockStress::nextTimeStep(BlockVal &fail_time) {
BlockList::iterator it;
BlockVal temp_block_fail;
double ts;
VCEvent new_event;
BlockID gid;
int lid;
quakelib::Conversion convert;
// Set up the temporary buffer and update field
for (it=sim->begin(); it!=sim->end(); ++it) {
tmpBuffer[it->getBlockID()] = 0.0;
// Set the update field to be the slip rate of each block
sim->setUpdateField(it->getBlockID(), it->slip_rate());
}
// update the temporary buffer with the Greens function applied to the block slip rates
sim->matrixVectorMultiplyAccum(tmpBuffer,
sim->greenShear(),
sim->getUpdateFieldPtr(),
true);
if (sim->doNormalStress()) {
for (it=sim->begin(); it!=sim->end(); ++it) {
sim->setUpdateField(it->getBlockID(), -it->friction()*it->slip_rate());
}
sim->matrixVectorMultiplyAccum(tmpBuffer,
sim->greenNormal(),
sim->getUpdateFieldPtr(),
true);
}
// Go through the blocks and find which one will fail first
temp_block_fail.val = DBL_MAX;
temp_block_fail.block_id = UNDEFINED_BLOCK_ID;
for (lid=0; lid<sim->numLocalBlocks(); ++lid) {
gid = sim->getGlobalBID(lid);
Block &block = sim->getBlock(gid);
// Calculate the time until this block will fail
// If the block has aseismic slip, the calculation is the exact solution of the
// differential equation d(cff)/dt = rate_of_stress_change + cff*aseismic_frac*self_shear/recurrence
if (block.aseismic() > 0) {
double A, B, K;
A = -tmpBuffer[gid];
B = -block.aseismic()*block.getSelfStresses()/block.getRecurrence();
K = -log(A+B*block.getCFF())/B;
ts = K + log(A)/B;
} else {
ts = convert.sec2year(block.getCFF()/tmpBuffer[gid]);
}
// Blocks with negative timesteps are skipped. These effectively mean the block
// should have failed already but didn't. This can happen in the starting phase
// of a simulation due to initial stresses. These blocks will fail anyway in the
// event propagation section, so we can safely ignore them here. However, negative
// timesteps should not happen after the simulation has progressed for a while.
if (ts <= 0) continue;
// If the time to slip is less than the current shortest time, record the block
if (ts < temp_block_fail.val) {
temp_block_fail.block_id = gid;
temp_block_fail.val = ts;
}
}
// Each node now has the time before the first failure among its blocks
// Determine the time to first failure over all nodes
sim->allReduceBlockVal(temp_block_fail, fail_time, BLOCK_VAL_MIN);
// If we didn't find any blocks that slipped, abort the simulation
assertThrow(fail_time.val < DBL_MAX, "System stuck, no blocks to move.");
// Setup the current event to have the trigger block ID and time
new_event.setEventTriggerOnThisNode(fail_time.block_id==temp_block_fail.block_id);
new_event.setEventTrigger(fail_time.block_id);
new_event.setEventYear(sim->getYear()+fail_time.val);
new_event.setEventNumber(sim->getEventCount());
sim->addEvent(new_event);
}
/*!
Recompute the stress on each block based on the slip deficits of all the other blocks.
*/
void UpdateBlockStress::stressRecompute(void) {
BlockList::iterator it;
// Reset the shear and normal stress, and set the update field to be the slip deficit
for (it=sim->begin(); it!=sim->end(); ++it) {
sim->setShearStress(it->getBlockID(), 0.0);
sim->setNormalStress(it->getBlockID(), it->getRhogd());
sim->setUpdateField(it->getBlockID(), it->state.slipDeficit);
}
// Distribute the new update field over all nodes
sim->distributeUpdateField();
// Multiply the Greens shear function by the slipDeficit vector
// to get shear on local blocks
sim->matrixVectorMultiplyAccum(sim->getShearStressPtr(),
sim->greenShear(),
sim->getUpdateFieldPtr(),
true);
if (sim->doNormalStress()) {
sim->matrixVectorMultiplyAccum(sim->getNormalStressPtr(),
sim->greenNormal(),
sim->getUpdateFieldPtr(),
true);
}
// Recompute the CFF on blocks based on the new shear/normal stresses
sim->computeCFFs();
}
void UpdateBlockStress::finish(SimFramework *_sim) {
delete tmpBuffer;
}
<|endoftext|> |
<commit_before>#include <Arduino.h>
#include <Wire.h>
#include <SPI.h>
#include <TimerOne.h>
#include <LiquidCrystal_I2C.h>
#include <ClickEncoder.h>
#include "ad5541.h"
#include "adc.h"
// Hardware Configuration
#define LCD_IIC_ADDRESS 0x20
#define LCD_IIC_COLS 16
#define LCD_IIC_ROWS 2
#define ENCODER_PIN_1 A0
#define ENCODER_PIN_2 A1
#define ENCODER_SW_PIN 2
#define ENCODER_UPDATE_RATE 4
#define ADC_CS_PIN 8
#define DAC_CS_PIN 9
#define BUTTON_1_PIN 3
#define BUTTON_2_PIN 4
#define BUTTON_3_PIN 6
#define BUTTON_4_PIN 5
#define FAN_SW_PIN 7
#define LM35_PIN A3
#define DEBOUND_DELAY 330
#define MAX_GAINS 2
#define MAX_BUTTON 4
#define ADC_CURRENT_CHN AD7190_CH_AIN2P_AINCOM
#define ADC_VOLTAGE_CHN AD7190_CH_AIN1P_AINCOM
// Constants
const double VREF_VOLTAGE = 5000.0; // mV
// DAC
AD5541 ad5541(DAC_CS_PIN);
// ADC
ADConverter adc(ADC_CS_PIN,
ADC_VOLTAGE_CHN,
ADC_CURRENT_CHN,
VREF_VOLTAGE);
// LCD
LiquidCrystal_I2C lcd(LCD_IIC_ADDRESS,
LCD_IIC_COLS,
LCD_IIC_ROWS);
// encoder
ClickEncoder encoder(ENCODER_PIN_1,
ENCODER_PIN_2,
ENCODER_SW_PIN,
ENCODER_UPDATE_RATE);
enum OPTERATION_STATE
{
STATE_IDLE = 1,
STATE_RUNNING = 2,
STATE_CALIBRATION = 10,
STATE_UNDEF = 99,
};
// Global Data
struct {
// button status
struct {
uint8_t active;
uint32_t time;
} buttons[MAX_BUTTON];
// encoder value
int16_t encoder_val;
ClickEncoder::Button encoder_btn;
// ADC value
double current;
uint8_t current_gain;
double voltage;
uint8_t voltage_gain;
struct {
double offset;
double scale;
} calib[MAX_GAINS];
// DAC
int32_t dac_set_point;
// FAN
uint8_t fan_is_on;
// temperature
double temperature;
// status
OPTERATION_STATE state;
uint32_t state_time;
} g_cb = {0};
// timer service
void timer_one_isr()
{
encoder.service();
}
void UpdateButtons()
{
uint32_t now = millis();
#define UPDATE_BUTTON(index) \
{ \
if (!g_cb.buttons[index - 1].active && !digitalRead(BUTTON_##index##_PIN)) { \
if (g_cb.buttons[index - 1].time + DEBOUND_DELAY < now) { \
g_cb.buttons[index - 1].active = 1; \
g_cb.buttons[index - 1].time = now; \
} \
} else if (g_cb.buttons[index - 1].active && digitalRead(BUTTON_##index##_PIN)) { \
if (g_cb.buttons[index - 1].time + DEBOUND_DELAY < now) { \
g_cb.buttons[index - 1].active = 0; \
g_cb.buttons[index - 1].time = now; \
} \
} \
}
UPDATE_BUTTON(1);
UPDATE_BUTTON(2);
UPDATE_BUTTON(3);
UPDATE_BUTTON(4);
#undef UPDATE_BUTTON
}
void UpdateEncoder()
{
g_cb.encoder_btn = encoder.getButton();
g_cb.encoder_val = encoder.getValue();
}
void UpdateCurrentVoltage()
{
// update current data, no need for idle
if (g_cb.state != STATE_IDLE) {
adc.updateCurrent();
}
// update voltage
adc.updateVoltage();
}
void UpdateTemperature()
{
int reg = analogRead(LM35_PIN);
g_cb.temperature = (double)reg * VREF_VOLTAGE / 1024.0 / 10.0;
}
void UpdateSensors()
{
// update inputs
UpdateButtons();
UpdateEncoder();
// sensors
UpdateCurrentVoltage();
UpdateTemperature();
}
/// Display a double with Fixed length
void DisplayFixedDouble(double value, int width, int prec)
{
char line[20];
dtostrf(value, width, prec, line);
int len = strlen(line);
if (len > width) {
// if we have longger value, truncate it
line[width] = '\0';
} else {
// if the first one is space then we have leading spaces
if (line[0] == ' ') {
for (char* p = strchr(line, ' '); p; p = strchr(line, ' ')) {
*p = '0';
}
}
}
lcd.print(line);
}
void UpdateDisplay()
{
// Display
// Line 1 - Current Set Point, temperature:
// aa.aaaA ttt.ttC X
lcd.setCursor(0, 0);
DisplayFixedDouble((double)g_cb.dac_set_point * VREF_VOLTAGE / (double)AD5541_CODES / 1000.0, 6, 4);
lcd.print("V ");
DisplayFixedDouble(g_cb.temperature, 5, 2);
lcd.print("C ");
// FIXME: print out status
switch (g_cb.state) {
case STATE_IDLE:
lcd.print(" ");
break;
case STATE_RUNNING:
lcd.print("R");
default:
lcd.print("?");
}
// Line 2 - Current Sensing, Voltage Sensing:
// ss.ssssA vvv.vvvV
lcd.setCursor(0, 1);
DisplayFixedDouble(adc.readCurrent(), 6, 3);
lcd.print("A ");
DisplayFixedDouble(adc.readVoltage(), 6, 3);
lcd.print("V ");
}
void ProcessControl()
{
uint32_t now = millis();
// temperature control
if (g_cb.temperature > 40.0 && !g_cb.fan_is_on) {
g_cb.fan_is_on = true;
digitalWrite(FAN_SW_PIN, HIGH);
} else if (g_cb.temperature < 35.0 && g_cb.fan_is_on) {
g_cb.fan_is_on = false;
digitalWrite(FAN_SW_PIN, LOW);
}
if (g_cb.buttons[2].active && g_cb.buttons[3].active && (g_cb.buttons[2].time + 3000.0 < now)) {
g_cb.state = STATE_CALIBRATION;
}
else
{
int32_t set_point = g_cb.dac_set_point;
// set point change
if (g_cb.buttons[0].active) {
set_point += 0x100;
} else if (g_cb.buttons[1].active) {
set_point -= 0x100;
} else if (g_cb.buttons[2].active) {
set_point += 0x10;
} else if (g_cb.buttons[3].active) {
set_point -= 0x10;
}
set_point += g_cb.encoder_val;
set_point = constrain(set_point, AD5541_CODE_LOW, AD5541_CODE_HIGH);
// State change event
if (g_cb.state == STATE_IDLE &&
g_cb.encoder_btn == ClickEncoder::Held &&
g_cb.state_time + 3000.0 < now)
{
// IDLE -> RUNNING
g_cb.state = STATE_RUNNING;
g_cb.state_time = now;
ad5541.setValue(set_point);
}
else if (g_cb.state == STATE_RUNNING)
{
if (g_cb.encoder_btn == ClickEncoder::Clicked)
{
g_cb.state = STATE_IDLE;
ad5541.setValue(0);
}
else if (g_cb.dac_set_point != set_point)
{
ad5541.setValue(set_point);
}
}
g_cb.dac_set_point = set_point;
}
}
void setup()
{
// initialize state to idle
g_cb.state = STATE_IDLE;
// LCD
lcd.init();
lcd.home();
lcd.print("@DC Active Load@");
lcd.setCursor(0, 1);
lcd.print(" R20170923");
// SPI
SPI.begin();
// Timer
Timer1.initialize(1000);
Timer1.attachInterrupt(timer_one_isr);
// VREF
analogReference(EXTERNAL);
// ADC
adc.begin();
while (!adc.detectDevice()) {
lcd.clear();
lcd.print("ADC ERROR");
delay(300);
}
adc.init();
// FIXME: Calibration data should be gotten from EEPROM
adc.setCalibData(AD7190_CONF_GAIN_1, 0.99955, 2.5);
adc.setCalibData(AD7190_CONF_GAIN_8, 1.0, 0);
// Buttons
pinMode(BUTTON_1_PIN, INPUT);
pinMode(BUTTON_2_PIN, INPUT);
pinMode(BUTTON_3_PIN, INPUT);
pinMode(BUTTON_4_PIN, INPUT);
// FAN
pinMode(FAN_SW_PIN, OUTPUT);
digitalWrite(FAN_SW_PIN, g_cb.fan_is_on);
// DAC
ad5541.begin();
ad5541.setValue(g_cb.dac_set_point);
// get lcd ready for using information
delay(3000);
lcd.clear();
}
void loop()
{
// Read Information
UpdateSensors();
// TODO: Controller logic
ProcessControl();
// Output:
UpdateDisplay();
}
<commit_msg>Clean up code<commit_after>#include <Arduino.h>
#include <Wire.h>
#include <SPI.h>
#include <TimerOne.h>
#include <LiquidCrystal_I2C.h>
#include <ClickEncoder.h>
#include "ad5541.h"
#include "adc.h"
// Hardware Configuration
#define LCD_IIC_ADDRESS 0x20
#define LCD_IIC_COLS 16
#define LCD_IIC_ROWS 2
#define ENCODER_PIN_1 A0
#define ENCODER_PIN_2 A1
#define ENCODER_SW_PIN 2
#define ENCODER_UPDATE_RATE 4
#define ADC_CS_PIN 8
#define DAC_CS_PIN 9
#define BUTTON_1_PIN 3
#define BUTTON_2_PIN 4
#define BUTTON_3_PIN 6
#define BUTTON_4_PIN 5
#define FAN_SW_PIN 7
#define LM35_PIN A3
#define DEBOUND_DELAY 330
#define MAX_GAINS 2
#define MAX_BUTTON 4
#define ADC_CURRENT_CHN AD7190_CH_AIN2P_AINCOM
#define ADC_VOLTAGE_CHN AD7190_CH_AIN1P_AINCOM
// Constants
const double VREF_VOLTAGE = 5000.0; // mV
// DAC
AD5541 ad5541(DAC_CS_PIN);
// ADC
ADConverter adc(ADC_CS_PIN,
ADC_VOLTAGE_CHN,
ADC_CURRENT_CHN,
VREF_VOLTAGE);
// LCD
LiquidCrystal_I2C lcd(LCD_IIC_ADDRESS,
LCD_IIC_COLS,
LCD_IIC_ROWS);
// encoder
ClickEncoder encoder(ENCODER_PIN_1,
ENCODER_PIN_2,
ENCODER_SW_PIN,
ENCODER_UPDATE_RATE);
enum OPTERATION_STATE
{
STATE_IDLE = 1,
STATE_RUNNING = 2,
STATE_CALIBRATION = 10,
STATE_UNDEF = 99,
};
// Global Data
struct {
// button status
struct {
uint8_t active;
uint32_t time;
} buttons[MAX_BUTTON];
// encoder value
int16_t encoder_val;
ClickEncoder::Button encoder_btn;
// DAC
int32_t dac_set_point;
// FAN
uint8_t fan_is_on;
// temperature
double temperature;
// status
OPTERATION_STATE state;
uint32_t state_time;
} g_cb = {0};
// timer service
void timer_one_isr()
{
encoder.service();
}
void UpdateButtons()
{
uint32_t now = millis();
#define UPDATE_BUTTON(index) \
{ \
if (!g_cb.buttons[index - 1].active && !digitalRead(BUTTON_##index##_PIN)) { \
if (g_cb.buttons[index - 1].time + DEBOUND_DELAY < now) { \
g_cb.buttons[index - 1].active = 1; \
g_cb.buttons[index - 1].time = now; \
} \
} else if (g_cb.buttons[index - 1].active && digitalRead(BUTTON_##index##_PIN)) { \
if (g_cb.buttons[index - 1].time + DEBOUND_DELAY < now) { \
g_cb.buttons[index - 1].active = 0; \
g_cb.buttons[index - 1].time = now; \
} \
} \
}
UPDATE_BUTTON(1);
UPDATE_BUTTON(2);
UPDATE_BUTTON(3);
UPDATE_BUTTON(4);
#undef UPDATE_BUTTON
}
void UpdateEncoder()
{
g_cb.encoder_btn = encoder.getButton();
g_cb.encoder_val = encoder.getValue();
}
void UpdateCurrentVoltage()
{
// update current data, no need for idle
if (g_cb.state != STATE_IDLE) {
adc.updateCurrent();
}
// update voltage
adc.updateVoltage();
}
void UpdateTemperature()
{
int reg = analogRead(LM35_PIN);
g_cb.temperature = (double)reg * VREF_VOLTAGE / 1024.0 / 10.0;
}
void UpdateSensors()
{
// update inputs
UpdateButtons();
UpdateEncoder();
// sensors
UpdateCurrentVoltage();
UpdateTemperature();
}
/// Display a double with Fixed length
void DisplayFixedDouble(double value, int width, int prec)
{
char line[20];
dtostrf(value, width, prec, line);
int len = strlen(line);
if (len > width) {
// if we have longger value, truncate it
line[width] = '\0';
} else {
// if the first one is space then we have leading spaces
if (line[0] == ' ') {
for (char* p = strchr(line, ' '); p; p = strchr(line, ' ')) {
*p = '0';
}
}
}
lcd.print(line);
}
void UpdateDisplay()
{
// Display
// Line 1 - Current Set Point, temperature:
// aa.aaaA ttt.ttC X
lcd.setCursor(0, 0);
DisplayFixedDouble((double)g_cb.dac_set_point * VREF_VOLTAGE / (double)AD5541_CODES / 1000.0, 6, 4);
lcd.print("V ");
DisplayFixedDouble(g_cb.temperature, 5, 2);
lcd.print("C ");
// FIXME: print out status
switch (g_cb.state) {
case STATE_IDLE:
lcd.print(" ");
break;
case STATE_RUNNING:
lcd.print("R");
default:
lcd.print("?");
}
// Line 2 - Current Sensing, Voltage Sensing:
// ss.ssssA vvv.vvvV
lcd.setCursor(0, 1);
DisplayFixedDouble(adc.readCurrent(), 6, 3);
lcd.print("A ");
DisplayFixedDouble(adc.readVoltage(), 6, 3);
lcd.print("V ");
}
void ProcessControl()
{
uint32_t now = millis();
// temperature control
if (g_cb.temperature > 40.0 && !g_cb.fan_is_on) {
g_cb.fan_is_on = true;
digitalWrite(FAN_SW_PIN, HIGH);
} else if (g_cb.temperature < 35.0 && g_cb.fan_is_on) {
g_cb.fan_is_on = false;
digitalWrite(FAN_SW_PIN, LOW);
}
if (g_cb.buttons[2].active && g_cb.buttons[3].active && (g_cb.buttons[2].time + 3000.0 < now)) {
g_cb.state = STATE_CALIBRATION;
}
else
{
int32_t set_point = g_cb.dac_set_point;
// set point change
if (g_cb.buttons[0].active) {
set_point += 0x100;
} else if (g_cb.buttons[1].active) {
set_point -= 0x100;
} else if (g_cb.buttons[2].active) {
set_point += 0x10;
} else if (g_cb.buttons[3].active) {
set_point -= 0x10;
}
set_point += g_cb.encoder_val;
set_point = constrain(set_point, AD5541_CODE_LOW, AD5541_CODE_HIGH);
// State change event
if (g_cb.state == STATE_IDLE &&
g_cb.encoder_btn == ClickEncoder::Held &&
g_cb.state_time + 3000.0 < now)
{
// IDLE -> RUNNING
g_cb.state = STATE_RUNNING;
g_cb.state_time = now;
ad5541.setValue(set_point);
}
else if (g_cb.state == STATE_RUNNING)
{
if (g_cb.encoder_btn == ClickEncoder::Clicked)
{
g_cb.state = STATE_IDLE;
ad5541.setValue(0);
}
else if (g_cb.dac_set_point != set_point)
{
ad5541.setValue(set_point);
}
}
g_cb.dac_set_point = set_point;
}
}
void setup()
{
// initialize state to idle
g_cb.state = STATE_IDLE;
// LCD
lcd.init();
lcd.home();
lcd.print("@DC Active Load@");
lcd.setCursor(0, 1);
lcd.print(" R20170923");
// SPI
SPI.begin();
// Timer
Timer1.initialize(1000);
Timer1.attachInterrupt(timer_one_isr);
// VREF
analogReference(EXTERNAL);
// ADC
adc.begin();
while (!adc.detectDevice()) {
lcd.clear();
lcd.print("ADC ERROR");
delay(300);
}
adc.init();
// FIXME: Calibration data should be gotten from EEPROM
adc.setCalibData(AD7190_CONF_GAIN_1, 0.99955, 2.5);
adc.setCalibData(AD7190_CONF_GAIN_8, 0.99880, 0);
// Buttons
pinMode(BUTTON_1_PIN, INPUT);
pinMode(BUTTON_2_PIN, INPUT);
pinMode(BUTTON_3_PIN, INPUT);
pinMode(BUTTON_4_PIN, INPUT);
// FAN
pinMode(FAN_SW_PIN, OUTPUT);
digitalWrite(FAN_SW_PIN, g_cb.fan_is_on);
// DAC
ad5541.begin();
ad5541.setValue(g_cb.dac_set_point);
// get lcd ready for using information
delay(3000);
lcd.clear();
}
void loop()
{
// Read Information
UpdateSensors();
// TODO: Controller logic
ProcessControl();
// Output:
UpdateDisplay();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: AttrTransformerAction.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2005-03-29 14:15:01 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _XMLOFF_ATTRTRANSFORMERACTION_HXX
#define _XMLOFF_ATTRTRANSFORMERACTION_HXX
#ifndef _XMLOFF_TRANSFORMERACTION_HXX
#include "TransformerAction.hxx"
#endif
enum XMLAttrTransformerAction
{
XML_ATACTION_EOT=XML_TACTION_EOT, // uses for initialization only
XML_ATACTION_COPY, // copy attr
XML_ATACTION_RENAME, // rename attr:
// - param1: namespace +
// token of local name
XML_ATACTION_REMOVE, // remove attr
XML_ATACTION_IN2INCH, // replace "in" with "inch"
XML_ATACTION_INS2INCHS, // replace "in" with "inch"
// multiple times
XML_ATACTION_IN2TWIPS, // replace "in" with "inch" and
// convert value from inch to twips
// but only for writer documents
XML_ATACTION_RENAME_IN2INCH, // replace "in" with "inch" and rename
// attr:
// - param1: namespace +
// token of local name
XML_ATACTION_INCH2IN, // replace "inch" with "in"
XML_ATACTION_INCHS2INS, // replace "inch" with "in"
// multiple times
XML_ATACTION_TWIPS2IN, // replace "inch" with "in" and for writer
// documents convert measure value from twips
// to inch
XML_ATACTION_RENAME_INCH2IN, // replace "inch" with "in" and rename
// attr:
// - param1: namespace +
// token of local name
XML_ATACTION_STYLE_FAMILY, // NOP, used for style:family
XML_ATACTION_DECODE_STYLE_NAME, // NOP, used for style:name
// - param1: style family
XML_ATACTION_STYLE_DISPLAY_NAME, // NOP, used for style:display_name
// - param1: style family
XML_ATACTION_DECODE_STYLE_NAME_REF, // NOP, used for style:name reference
// - param1: style family
XML_ATACTION_RENAME_DECODE_STYLE_NAME_REF, // NOP, used for style:name
// - param1: namespace +
// token of local name
XML_ATACTION_ENCODE_STYLE_NAME, // NOP, used for style:name
XML_ATACTION_ENCODE_STYLE_NAME_REF, // NOP, used for style:name
XML_ATACTION_RENAME_ENCODE_STYLE_NAME_REF, // NOP, used for style:name
// - param1: namespace +
// token of local name
// - param2: style family
XML_ATACTION_MOVE_TO_ELEM, // turn attr into an elem
// - param1: namespace +
// token of local name
XML_ATACTION_MOVE_FROM_ELEM, // turn elem into an attr:
// - param1: namespace +
// token of local name
XML_ATACTION_NEG_PERCENT, // replace % val with 100-%
XML_ATACTION_RENAME_NEG_PERCENT, // replace % val with 100-%, rename attr
// - param1: namespace +
// token of local name
XML_ATACTION_HREF, // xmlink:href
XML_ATACTION_ADD_NAMESPACE_PREFIX, // add a namespace prefix
// - param1: prefix
XML_ATACTION_ADD_APP_NAMESPACE_PREFIX, // add a namespace prefix
// - param1: default prefix
XML_ATACTION_RENAME_ADD_NAMESPACE_PREFIX, // add a namespace prefix
// - param1: namespace +
// token of local name
// - param2: prefix
XML_ATACTION_REMOVE_NAMESPACE_PREFIX,// remove a namespace prefix
// - param1: prefix
XML_ATACTION_REMOVE_ANY_NAMESPACE_PREFIX,// remove any namespace prefix
XML_ATACTION_RENAME_REMOVE_NAMESPACE_PREFIX,// remove a namespace prefix
// - param1: namespace +
// token of local name
// - param2: prefix
XML_ATACTION_EVENT_NAME,
XML_ATACTION_MACRO_NAME,
XML_ATACTION_MACRO_LOCATION,
XML_ATACTION_DLG_BORDER,
XML_ATACTION_URI_OOO, // an URI in OOo notation
// - param1: pacakage URI are supported
XML_ATACTION_URI_OASIS, // an URI in OASIS notation
// - param1: pacakage URI are supported
XML_ATACTION_RENAME_ATTRIBUTE, // rename up to 3 different possible values of an attrbiute
// - param1: token of old attribute value (lower 16 bit)
// + token of new attribute value (upper 16 bit)
// - param2: token of old attribute value
// + token of new attribute value
// - param3: token of old attribute value
// + token of new attribute value
// if param2 or param3 are unused they must contain
// XML_TOKEN_INVALID
XML_ATACTION_RNG2ISO_DATETIME, // converts . into , in datetimes
XML_ATACTION_RENAME_RNG2ISO_DATETIME,// converts . into , in datetimes and renames the attribute
// - param1: namespace +
// token of local name
XML_ATACTION_MOVE_FROM_ELEM_RNG2ISO_DATETIME, // turn elem into an attr and convert . to , in datetimes
// - param1: namespace +
// token of local name
XML_ATACTION_SVG_WIDTH_HEIGHT_OOO, // replace "inch" with "in" and subtracts 1/100th mm
XML_ATACTION_SVG_WIDTH_HEIGHT_OASIS, // replace "in" with "inch" and adds 1/100th mm
XML_ATACTION_DRAW_MIRROR_OOO, // renames draw:mirror to style:mirror and adapts values
XML_ATACTION_DRAW_MIRROR_OASIS, // renames style:mirror to draw:mirror and adapts values
XML_ATACTION_GAMMA_OASIS, // converts percentage to double value
XML_ATACTION_GAMMA_OOO, // converts double value to percentage
XML_ATACTION_DECODE_ID, // converts strings with non numeric characters to only numeric character ids
XML_ATACTION_USER_DEFINED=0x80000000,// user defined actions start here
XML_ATACTION_END=XML_TACTION_END
};
#endif // _XMLOFF_ATTRTRANSFORMERACTION_HXX
<commit_msg>INTEGRATION: CWS swqbugfixes32 (1.8.30); FILE MERGED 2005/05/13 08:46:07 od 1.8.30.1: #i49139# - adapt attribute values for attribute <style::mirror> on import/export of OpenOffice.org file format.<commit_after>/*************************************************************************
*
* $RCSfile: AttrTransformerAction.hxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: rt $ $Date: 2005-05-18 09:44:48 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _XMLOFF_ATTRTRANSFORMERACTION_HXX
#define _XMLOFF_ATTRTRANSFORMERACTION_HXX
#ifndef _XMLOFF_TRANSFORMERACTION_HXX
#include "TransformerAction.hxx"
#endif
enum XMLAttrTransformerAction
{
XML_ATACTION_EOT=XML_TACTION_EOT, // uses for initialization only
XML_ATACTION_COPY, // copy attr
XML_ATACTION_RENAME, // rename attr:
// - param1: namespace +
// token of local name
XML_ATACTION_REMOVE, // remove attr
XML_ATACTION_IN2INCH, // replace "in" with "inch"
XML_ATACTION_INS2INCHS, // replace "in" with "inch"
// multiple times
XML_ATACTION_IN2TWIPS, // replace "in" with "inch" and
// convert value from inch to twips
// but only for writer documents
XML_ATACTION_RENAME_IN2INCH, // replace "in" with "inch" and rename
// attr:
// - param1: namespace +
// token of local name
XML_ATACTION_INCH2IN, // replace "inch" with "in"
XML_ATACTION_INCHS2INS, // replace "inch" with "in"
// multiple times
XML_ATACTION_TWIPS2IN, // replace "inch" with "in" and for writer
// documents convert measure value from twips
// to inch
XML_ATACTION_RENAME_INCH2IN, // replace "inch" with "in" and rename
// attr:
// - param1: namespace +
// token of local name
XML_ATACTION_STYLE_FAMILY, // NOP, used for style:family
XML_ATACTION_DECODE_STYLE_NAME, // NOP, used for style:name
// - param1: style family
XML_ATACTION_STYLE_DISPLAY_NAME, // NOP, used for style:display_name
// - param1: style family
XML_ATACTION_DECODE_STYLE_NAME_REF, // NOP, used for style:name reference
// - param1: style family
XML_ATACTION_RENAME_DECODE_STYLE_NAME_REF, // NOP, used for style:name
// - param1: namespace +
// token of local name
XML_ATACTION_ENCODE_STYLE_NAME, // NOP, used for style:name
XML_ATACTION_ENCODE_STYLE_NAME_REF, // NOP, used for style:name
XML_ATACTION_RENAME_ENCODE_STYLE_NAME_REF, // NOP, used for style:name
// - param1: namespace +
// token of local name
// - param2: style family
XML_ATACTION_MOVE_TO_ELEM, // turn attr into an elem
// - param1: namespace +
// token of local name
XML_ATACTION_MOVE_FROM_ELEM, // turn elem into an attr:
// - param1: namespace +
// token of local name
XML_ATACTION_NEG_PERCENT, // replace % val with 100-%
XML_ATACTION_RENAME_NEG_PERCENT, // replace % val with 100-%, rename attr
// - param1: namespace +
// token of local name
XML_ATACTION_HREF, // xmlink:href
XML_ATACTION_ADD_NAMESPACE_PREFIX, // add a namespace prefix
// - param1: prefix
XML_ATACTION_ADD_APP_NAMESPACE_PREFIX, // add a namespace prefix
// - param1: default prefix
XML_ATACTION_RENAME_ADD_NAMESPACE_PREFIX, // add a namespace prefix
// - param1: namespace +
// token of local name
// - param2: prefix
XML_ATACTION_REMOVE_NAMESPACE_PREFIX,// remove a namespace prefix
// - param1: prefix
XML_ATACTION_REMOVE_ANY_NAMESPACE_PREFIX,// remove any namespace prefix
XML_ATACTION_RENAME_REMOVE_NAMESPACE_PREFIX,// remove a namespace prefix
// - param1: namespace +
// token of local name
// - param2: prefix
XML_ATACTION_EVENT_NAME,
XML_ATACTION_MACRO_NAME,
XML_ATACTION_MACRO_LOCATION,
XML_ATACTION_DLG_BORDER,
XML_ATACTION_URI_OOO, // an URI in OOo notation
// - param1: pacakage URI are supported
XML_ATACTION_URI_OASIS, // an URI in OASIS notation
// - param1: pacakage URI are supported
XML_ATACTION_RENAME_ATTRIBUTE, // rename up to 3 different possible values of an attrbiute
// - param1: token of old attribute value (lower 16 bit)
// + token of new attribute value (upper 16 bit)
// - param2: token of old attribute value
// + token of new attribute value
// - param3: token of old attribute value
// + token of new attribute value
// if param2 or param3 are unused they must contain
// XML_TOKEN_INVALID
XML_ATACTION_RNG2ISO_DATETIME, // converts . into , in datetimes
XML_ATACTION_RENAME_RNG2ISO_DATETIME,// converts . into , in datetimes and renames the attribute
// - param1: namespace +
// token of local name
XML_ATACTION_MOVE_FROM_ELEM_RNG2ISO_DATETIME, // turn elem into an attr and convert . to , in datetimes
// - param1: namespace +
// token of local name
XML_ATACTION_SVG_WIDTH_HEIGHT_OOO, // replace "inch" with "in" and subtracts 1/100th mm
XML_ATACTION_SVG_WIDTH_HEIGHT_OASIS, // replace "in" with "inch" and adds 1/100th mm
XML_ATACTION_DRAW_MIRROR_OOO, // renames draw:mirror to style:mirror and adapts values
// --> OD 2005-05-12 #i49139#
XML_ATACTION_STYLE_MIRROR_OOO, // adapts style:mirror values
// <--
XML_ATACTION_DRAW_MIRROR_OASIS, // renames style:mirror to draw:mirror and adapts values
XML_ATACTION_GAMMA_OASIS, // converts percentage to double value
XML_ATACTION_GAMMA_OOO, // converts double value to percentage
XML_ATACTION_DECODE_ID, // converts strings with non numeric characters to only numeric character ids
XML_ATACTION_USER_DEFINED=0x80000000,// user defined actions start here
XML_ATACTION_END=XML_TACTION_END
};
#endif // _XMLOFF_ATTRTRANSFORMERACTION_HXX
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: togglebuttontoolbarcontroller.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: vg $ $Date: 2006-11-21 17:21:50 $
*
* 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_framework.hxx"
#ifndef __FRAMEWORK_UIELEMENT_TOGGLEBUTTONTOOLBARCONTROLLER_HXX
#include "uielement/togglebuttontoolbarcontroller.hxx"
#endif
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_CLASSES_ADDONSOPTIONS_HXX_
#include <classes/addonsoptions.hxx>
#endif
#ifndef __FRAMEWORK_TOOLBAR_HXX_
#include "uielement/toolbar.hxx"
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_
#include <com/sun/star/util/XURLTransformer.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_
#include <com/sun/star/frame/XDispatchProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCONTROLNOTIFICATIONLISTENER_HPP_
#include <com/sun/star/frame/XControlNotificationListener.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XMACROEXPANDER_HPP_
#include "com/sun/star/util/XMacroExpander.hpp"
#endif
#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include "com/sun/star/uno/XComponentContext.hpp"
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include "com/sun/star/beans/XPropertySet.hpp"
#endif
//_________________________________________________________________________________________________________________
// other includes
//_________________________________________________________________________________________________________________
#include <rtl/uri.hxx>
#include <vos/mutex.hxx>
#include <comphelper/processfactory.hxx>
#include <unotools/ucbstreamhelper.hxx>
#include <tools/urlobj.hxx>
#include <vcl/svapp.hxx>
#include <vcl/mnemonic.hxx>
#include <vcl/window.hxx>
#include <vcl/graph.hxx>
#include <vcl/bitmap.hxx>
#include <svtools/filter.hxx>
#include <svtools/miscopt.hxx>
using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::awt;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::util;
namespace framework
{
// ------------------------------------------------------------------
ToggleButtonToolbarController::ToggleButtonToolbarController(
const Reference< XMultiServiceFactory >& rServiceManager,
const Reference< XFrame >& rFrame,
ToolBar* pToolbar,
USHORT nID,
Style eStyle,
const OUString& aCommand ) :
ComplexToolbarController( rServiceManager, rFrame, pToolbar, nID, aCommand ),
m_eStyle( eStyle )
{
if ( eStyle == STYLE_DROPDOWNBUTTON )
m_pToolbar->SetItemBits( m_nID, TIB_DROPDOWNONLY | m_pToolbar->GetItemBits( m_nID ) );
else if ( eStyle == STYLE_TOGGLE_DROPDOWNBUTTON )
m_pToolbar->SetItemBits( m_nID, TIB_DROPDOWN | m_pToolbar->GetItemBits( m_nID ) );
}
// ------------------------------------------------------------------
ToggleButtonToolbarController::~ToggleButtonToolbarController()
{
}
// ------------------------------------------------------------------
void SAL_CALL ToggleButtonToolbarController::dispose()
throw ( RuntimeException )
{
vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
ComplexToolbarController::dispose();
}
// ------------------------------------------------------------------
void SAL_CALL ToggleButtonToolbarController::execute( sal_Int16 KeyModifier )
throw ( RuntimeException )
{
Reference< XDispatch > xDispatch;
Reference< XURLTransformer > xURLTransformer;
OUString aCommandURL;
OUString aSelectedText;
::com::sun::star::util::URL aTargetURL;
{
vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
if ( m_bDisposed )
throw DisposedException();
if ( m_bInitialized &&
m_xFrame.is() &&
m_xServiceManager.is() &&
m_aCommandURL.getLength() )
{
xURLTransformer = m_xURLTransformer;
xDispatch = getDispatchFromCommand( m_aCommandURL );
aCommandURL = m_aCommandURL;
aTargetURL = getInitializedURL();
aSelectedText = m_aCurrentSelection;
}
}
if ( xDispatch.is() && aTargetURL.Complete.getLength() > 0 )
{
Sequence<PropertyValue> aArgs( 2 );
// Add key modifier to argument list
aArgs[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "KeyModifier" ));
aArgs[0].Value <<= KeyModifier;
aArgs[1].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Text" ));
aArgs[1].Value <<= aSelectedText;
// Execute dispatch asynchronously
ExecuteInfo* pExecuteInfo = new ExecuteInfo;
pExecuteInfo->xDispatch = xDispatch;
pExecuteInfo->aTargetURL = aTargetURL;
pExecuteInfo->aArgs = aArgs;
Application::PostUserEvent( STATIC_LINK(0, ComplexToolbarController , ExecuteHdl_Impl), pExecuteInfo );
}
}
// ------------------------------------------------------------------
uno::Reference< awt::XWindow > SAL_CALL ToggleButtonToolbarController::createPopupWindow()
throw (::com::sun::star::uno::RuntimeException)
{
uno::Reference< awt::XWindow > xWindow;
vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
if (( m_eStyle == STYLE_DROPDOWNBUTTON ) ||
( m_eStyle == STYLE_TOGGLE_DROPDOWNBUTTON ))
{
// create popup menu
PopupMenu aPopup;
for ( sal_uInt32 i = 0; i < m_aDropdownMenuList.size(); i++ )
{
rtl::OUString aLabel( m_aDropdownMenuList[i] );
aPopup.InsertItem( sal_uInt16( i+1 ), aLabel );
if ( aLabel == m_aCurrentSelection )
aPopup.CheckItem( sal_uInt16( i+1 ), sal_True );
else
aPopup.CheckItem( sal_uInt16( i+1 ), sal_False );
}
aPopup.SetSelectHdl( LINK( this, ToggleButtonToolbarController, MenuSelectHdl ));
aPopup.Execute( m_pToolbar, m_pToolbar->GetItemRect( m_nID ));
}
return xWindow;
}
// ------------------------------------------------------------------
void ToggleButtonToolbarController::executeControlCommand( const ::com::sun::star::frame::ControlCommand& rControlCommand )
{
vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
if (( m_eStyle == STYLE_DROPDOWNBUTTON ) ||
( m_eStyle == STYLE_TOGGLE_DROPDOWNBUTTON ))
{
if ( rControlCommand.Command.equalsAsciiL( "SetList", 7 ))
{
for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
{
if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "List", 4 ))
{
Sequence< OUString > aList;
m_aDropdownMenuList.clear();
rControlCommand.Arguments[i].Value >>= aList;
for ( sal_Int32 j = 0; j < aList.getLength(); j++ )
m_aDropdownMenuList.push_back( aList[j] );
// send notification
uno::Sequence< beans::NamedValue > aInfo( 1 );
aInfo[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "List" ));
aInfo[0].Value <<= aList;
addNotifyInfo( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ListChanged" )),
getDispatchFromCommand( m_aCommandURL ),
aInfo );
break;
}
}
}
else if ( rControlCommand.Command.equalsAsciiL( "CheckItemPos", 12 ))
{
for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
{
if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Pos", 3 ))
{
sal_Int32 nPos( -1 );
rControlCommand.Arguments[i].Value >>= nPos;
if ( nPos >= 0 &&
( sal::static_int_cast< sal_uInt32 >(nPos)
< m_aDropdownMenuList.size() ) )
{
m_aCurrentSelection = m_aDropdownMenuList[nPos];
m_pToolbar->SetItemText( m_nID, m_aCurrentSelection );
// send notification
uno::Sequence< beans::NamedValue > aInfo( 1 );
aInfo[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ItemChecked" ));
aInfo[0].Value <<= nPos;
addNotifyInfo( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Pos" )),
getDispatchFromCommand( m_aCommandURL ),
aInfo );
}
break;
}
}
}
else if ( rControlCommand.Command.equalsAsciiL( "AddEntry", 8 ))
{
rtl::OUString aText;
for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
{
if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Text", 4 ))
{
if ( rControlCommand.Arguments[i].Value >>= aText )
m_aDropdownMenuList.push_back( aText );
break;
}
}
}
else if ( rControlCommand.Command.equalsAsciiL( "InsertEntry", 11 ))
{
sal_Int32 nPos( COMBOBOX_APPEND );
sal_Int32 nSize = sal_Int32( m_aDropdownMenuList.size() );
rtl::OUString aText;
for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
{
if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Pos", 3 ))
{
sal_Int32 nTmpPos = 0;
if ( rControlCommand.Arguments[i].Value >>= nTmpPos )
{
if (( nTmpPos >= 0 ) && ( nTmpPos < sal_Int32( nSize )))
nPos = nTmpPos;
}
}
else if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Text", 4 ))
rControlCommand.Arguments[i].Value >>= aText;
}
std::vector< ::rtl::OUString >::iterator aIter = m_aDropdownMenuList.begin();
aIter += nPos;
m_aDropdownMenuList.insert( aIter, aText );
}
else if ( rControlCommand.Command.equalsAsciiL( "RemoveEntryPos", 14 ))
{
for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
{
if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Pos", 3 ))
{
sal_Int32 nPos( -1 );
if ( rControlCommand.Arguments[i].Value >>= nPos )
{
if ( nPos < sal_Int32( m_aDropdownMenuList.size() ))
{
std::vector< ::rtl::OUString >::iterator aIter = m_aDropdownMenuList.begin();
aIter += nPos;
m_aDropdownMenuList.erase( aIter );
}
}
break;
}
}
}
else if ( rControlCommand.Command.equalsAsciiL( "RemoveEntryText", 15 ))
{
for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
{
if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Text", 4 ))
{
rtl::OUString aText;
if ( rControlCommand.Arguments[i].Value >>= aText )
{
sal_Int32 nSize = sal_Int32( m_aDropdownMenuList.size() );
for ( sal_Int32 j = 0; j < nSize; j++ )
{
if ( m_aDropdownMenuList[j] == aText )
{
std::vector< ::rtl::OUString >::iterator aIter = m_aDropdownMenuList.begin();
aIter += j;
m_aDropdownMenuList.erase( aIter );
break;
}
}
}
break;
}
}
}
}
}
IMPL_LINK( ToggleButtonToolbarController, MenuSelectHdl, Menu *, pMenu )
{
vos::OGuard aGuard( Application::GetSolarMutex() );
sal_uInt16 nItemId = pMenu->GetCurItemId();
if ( nItemId > 0 && nItemId <= m_aDropdownMenuList.size() )
{
m_aCurrentSelection = m_aDropdownMenuList[nItemId-1];
m_pToolbar->SetItemText( m_nID, m_aCurrentSelection );
execute( 0 );
}
return 0;
}
} // namespace
<commit_msg>INTEGRATION: CWS fwk60 (1.6.38); FILE MERGED 2007/01/17 07:53:51 cd 1.6.38.1: #i73531# Fixed problem to click dropdown button twice to open menu<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: togglebuttontoolbarcontroller.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2007-01-29 14:51:52 $
*
* 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_framework.hxx"
#ifndef __FRAMEWORK_UIELEMENT_TOGGLEBUTTONTOOLBARCONTROLLER_HXX
#include "uielement/togglebuttontoolbarcontroller.hxx"
#endif
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_CLASSES_ADDONSOPTIONS_HXX_
#include <classes/addonsoptions.hxx>
#endif
#ifndef __FRAMEWORK_TOOLBAR_HXX_
#include "uielement/toolbar.hxx"
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_
#include <com/sun/star/util/XURLTransformer.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_
#include <com/sun/star/frame/XDispatchProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCONTROLNOTIFICATIONLISTENER_HPP_
#include <com/sun/star/frame/XControlNotificationListener.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XMACROEXPANDER_HPP_
#include "com/sun/star/util/XMacroExpander.hpp"
#endif
#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include "com/sun/star/uno/XComponentContext.hpp"
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include "com/sun/star/beans/XPropertySet.hpp"
#endif
//_________________________________________________________________________________________________________________
// other includes
//_________________________________________________________________________________________________________________
#include <rtl/uri.hxx>
#include <vos/mutex.hxx>
#include <comphelper/processfactory.hxx>
#include <unotools/ucbstreamhelper.hxx>
#include <tools/urlobj.hxx>
#include <vcl/svapp.hxx>
#include <vcl/mnemonic.hxx>
#include <vcl/window.hxx>
#include <vcl/graph.hxx>
#include <vcl/bitmap.hxx>
#include <svtools/filter.hxx>
#include <svtools/miscopt.hxx>
using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::awt;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::util;
namespace framework
{
// ------------------------------------------------------------------
ToggleButtonToolbarController::ToggleButtonToolbarController(
const Reference< XMultiServiceFactory >& rServiceManager,
const Reference< XFrame >& rFrame,
ToolBar* pToolbar,
USHORT nID,
Style eStyle,
const OUString& aCommand ) :
ComplexToolbarController( rServiceManager, rFrame, pToolbar, nID, aCommand ),
m_eStyle( eStyle )
{
if ( eStyle == STYLE_DROPDOWNBUTTON )
m_pToolbar->SetItemBits( m_nID, TIB_DROPDOWNONLY | m_pToolbar->GetItemBits( m_nID ) );
else if ( eStyle == STYLE_TOGGLE_DROPDOWNBUTTON )
m_pToolbar->SetItemBits( m_nID, TIB_DROPDOWN | m_pToolbar->GetItemBits( m_nID ) );
}
// ------------------------------------------------------------------
ToggleButtonToolbarController::~ToggleButtonToolbarController()
{
}
// ------------------------------------------------------------------
void SAL_CALL ToggleButtonToolbarController::dispose()
throw ( RuntimeException )
{
vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
ComplexToolbarController::dispose();
}
// ------------------------------------------------------------------
void SAL_CALL ToggleButtonToolbarController::execute( sal_Int16 KeyModifier )
throw ( RuntimeException )
{
Reference< XDispatch > xDispatch;
Reference< XURLTransformer > xURLTransformer;
OUString aCommandURL;
OUString aSelectedText;
::com::sun::star::util::URL aTargetURL;
{
vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
if ( m_bDisposed )
throw DisposedException();
if ( m_bInitialized &&
m_xFrame.is() &&
m_xServiceManager.is() &&
m_aCommandURL.getLength() )
{
xURLTransformer = m_xURLTransformer;
xDispatch = getDispatchFromCommand( m_aCommandURL );
aCommandURL = m_aCommandURL;
aTargetURL = getInitializedURL();
aSelectedText = m_aCurrentSelection;
}
}
if ( xDispatch.is() && aTargetURL.Complete.getLength() > 0 )
{
Sequence<PropertyValue> aArgs( 2 );
// Add key modifier to argument list
aArgs[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "KeyModifier" ));
aArgs[0].Value <<= KeyModifier;
aArgs[1].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Text" ));
aArgs[1].Value <<= aSelectedText;
// Execute dispatch asynchronously
ExecuteInfo* pExecuteInfo = new ExecuteInfo;
pExecuteInfo->xDispatch = xDispatch;
pExecuteInfo->aTargetURL = aTargetURL;
pExecuteInfo->aArgs = aArgs;
Application::PostUserEvent( STATIC_LINK(0, ComplexToolbarController , ExecuteHdl_Impl), pExecuteInfo );
}
}
// ------------------------------------------------------------------
uno::Reference< awt::XWindow > SAL_CALL ToggleButtonToolbarController::createPopupWindow()
throw (::com::sun::star::uno::RuntimeException)
{
uno::Reference< awt::XWindow > xWindow;
vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
if (( m_eStyle == STYLE_DROPDOWNBUTTON ) ||
( m_eStyle == STYLE_TOGGLE_DROPDOWNBUTTON ))
{
// create popup menu
PopupMenu aPopup;
for ( sal_uInt32 i = 0; i < m_aDropdownMenuList.size(); i++ )
{
rtl::OUString aLabel( m_aDropdownMenuList[i] );
aPopup.InsertItem( sal_uInt16( i+1 ), aLabel );
if ( aLabel == m_aCurrentSelection )
aPopup.CheckItem( sal_uInt16( i+1 ), sal_True );
else
aPopup.CheckItem( sal_uInt16( i+1 ), sal_False );
}
m_pToolbar->SetItemDown( m_nID, TRUE );
aPopup.SetSelectHdl( LINK( this, ToggleButtonToolbarController, MenuSelectHdl ));
aPopup.Execute( m_pToolbar, m_pToolbar->GetItemRect( m_nID ));
m_pToolbar->SetItemDown( m_nID, FALSE );
}
return xWindow;
}
// ------------------------------------------------------------------
void ToggleButtonToolbarController::executeControlCommand( const ::com::sun::star::frame::ControlCommand& rControlCommand )
{
vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
if (( m_eStyle == STYLE_DROPDOWNBUTTON ) ||
( m_eStyle == STYLE_TOGGLE_DROPDOWNBUTTON ))
{
if ( rControlCommand.Command.equalsAsciiL( "SetList", 7 ))
{
for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
{
if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "List", 4 ))
{
Sequence< OUString > aList;
m_aDropdownMenuList.clear();
rControlCommand.Arguments[i].Value >>= aList;
for ( sal_Int32 j = 0; j < aList.getLength(); j++ )
m_aDropdownMenuList.push_back( aList[j] );
// send notification
uno::Sequence< beans::NamedValue > aInfo( 1 );
aInfo[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "List" ));
aInfo[0].Value <<= aList;
addNotifyInfo( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ListChanged" )),
getDispatchFromCommand( m_aCommandURL ),
aInfo );
break;
}
}
}
else if ( rControlCommand.Command.equalsAsciiL( "CheckItemPos", 12 ))
{
for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
{
if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Pos", 3 ))
{
sal_Int32 nPos( -1 );
rControlCommand.Arguments[i].Value >>= nPos;
if ( nPos >= 0 &&
( sal::static_int_cast< sal_uInt32 >(nPos)
< m_aDropdownMenuList.size() ) )
{
m_aCurrentSelection = m_aDropdownMenuList[nPos];
m_pToolbar->SetItemText( m_nID, m_aCurrentSelection );
// send notification
uno::Sequence< beans::NamedValue > aInfo( 1 );
aInfo[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ItemChecked" ));
aInfo[0].Value <<= nPos;
addNotifyInfo( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Pos" )),
getDispatchFromCommand( m_aCommandURL ),
aInfo );
}
break;
}
}
}
else if ( rControlCommand.Command.equalsAsciiL( "AddEntry", 8 ))
{
rtl::OUString aText;
for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
{
if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Text", 4 ))
{
if ( rControlCommand.Arguments[i].Value >>= aText )
m_aDropdownMenuList.push_back( aText );
break;
}
}
}
else if ( rControlCommand.Command.equalsAsciiL( "InsertEntry", 11 ))
{
sal_Int32 nPos( COMBOBOX_APPEND );
sal_Int32 nSize = sal_Int32( m_aDropdownMenuList.size() );
rtl::OUString aText;
for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
{
if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Pos", 3 ))
{
sal_Int32 nTmpPos = 0;
if ( rControlCommand.Arguments[i].Value >>= nTmpPos )
{
if (( nTmpPos >= 0 ) && ( nTmpPos < sal_Int32( nSize )))
nPos = nTmpPos;
}
}
else if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Text", 4 ))
rControlCommand.Arguments[i].Value >>= aText;
}
std::vector< ::rtl::OUString >::iterator aIter = m_aDropdownMenuList.begin();
aIter += nPos;
m_aDropdownMenuList.insert( aIter, aText );
}
else if ( rControlCommand.Command.equalsAsciiL( "RemoveEntryPos", 14 ))
{
for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
{
if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Pos", 3 ))
{
sal_Int32 nPos( -1 );
if ( rControlCommand.Arguments[i].Value >>= nPos )
{
if ( nPos < sal_Int32( m_aDropdownMenuList.size() ))
{
std::vector< ::rtl::OUString >::iterator aIter = m_aDropdownMenuList.begin();
aIter += nPos;
m_aDropdownMenuList.erase( aIter );
}
}
break;
}
}
}
else if ( rControlCommand.Command.equalsAsciiL( "RemoveEntryText", 15 ))
{
for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
{
if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Text", 4 ))
{
rtl::OUString aText;
if ( rControlCommand.Arguments[i].Value >>= aText )
{
sal_Int32 nSize = sal_Int32( m_aDropdownMenuList.size() );
for ( sal_Int32 j = 0; j < nSize; j++ )
{
if ( m_aDropdownMenuList[j] == aText )
{
std::vector< ::rtl::OUString >::iterator aIter = m_aDropdownMenuList.begin();
aIter += j;
m_aDropdownMenuList.erase( aIter );
break;
}
}
}
break;
}
}
}
}
}
IMPL_LINK( ToggleButtonToolbarController, MenuSelectHdl, Menu *, pMenu )
{
vos::OGuard aGuard( Application::GetSolarMutex() );
sal_uInt16 nItemId = pMenu->GetCurItemId();
if ( nItemId > 0 && nItemId <= m_aDropdownMenuList.size() )
{
m_aCurrentSelection = m_aDropdownMenuList[nItemId-1];
m_pToolbar->SetItemText( m_nID, m_aCurrentSelection );
execute( 0 );
}
return 0;
}
} // namespace
<|endoftext|> |
<commit_before>/* BEGIN_COPYRIGHT
*
* Copyright 2009-2014 CRS4.
*
* 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.
*
* END_COPYRIGHT
*/
#include "hdfs_file.h"
PyObject* FileClass_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
FileInfo *self;
self = (FileInfo *)type->tp_alloc(type, 0);
if (self != NULL) {
self->fs = NULL;
self->file = NULL;
self->flags = 0;
self->buff_size = 0;
self->replication = 1;
self->blocksize = 0;
self->readline_chunk_size = 16 * 1024; // 16 KB
#ifdef HADOOP_LIBHDFS_V1
self->stream_type = 0;
#endif
}
return (PyObject *)self;
}
#ifdef HADOOP_LIBHDFS_V1
static bool hdfsFileIsOpenForWrite(FileInfo *f){
return f->stream_type == OUTPUT;
}
static bool hdfsFileIsOpenForRead(FileInfo *f){
return f->stream_type == INPUT;
}
#endif
void FileClass_dealloc(FileInfo* self)
{
self->file = NULL;
self->ob_type->tp_free((PyObject*)self);
}
int FileClass_init(FileInfo *self, PyObject *args, PyObject *kwds)
{
if (! PyArg_ParseTuple(args, "OO", &(self->fs), &(self->file))) {
return -1;
}
return 0;
}
int FileClass_init_internal(FileInfo *self, hdfsFS fs, hdfsFile file)
{
self->fs = fs;
self->file = file;
return 0;
}
PyObject* FileClass_close(FileInfo* self){
int result = hdfsCloseFile(self->fs, self->file);
if (result < 0) {
return PyErr_SetFromErrno(PyExc_IOError);
}
else
return PyBool_FromLong(1);
}
PyObject* FileClass_mode(FileInfo* self){
return FileClass_get_mode(self);
}
PyObject* FileClass_get_mode(FileInfo *self){
return PyLong_FromLong(self->flags);
}
PyObject* FileClass_available(FileInfo *self){
int available = hdfsAvailable(self->fs, self->file);
if (available < 0)
return PyErr_SetFromErrno(PyExc_IOError);
else
return PyLong_FromLong(available);
}
static int _ensure_open_for_reading(FileInfo* self) {
#ifdef HADOOP_LIBHDFS_V1
if(!hdfsFileIsOpenForRead(self)){
#else
if(!hdfsFileIsOpenForRead(self->file)){
#endif
PyErr_SetString(PyExc_IOError, "File is not opened in READ ('r') mode");
return 0; // False
}
return 1; // True
}
static int _ensure_open_for_writing(FileInfo* self) {
#ifdef HADOOP_LIBHDFS_V1
if(!hdfsFileIsOpenForWrite(self)){
#else
if(!hdfsFileIsOpenForWrite(self->file)){
#endif
PyErr_SetString(PyExc_IOError, "File is not opened in WRITE ('w') mode");
return 0; // False
}
return 1; // True
}
static Py_ssize_t _read_into_str(FileInfo *self, char* buf, Py_ssize_t nbytes) {
if (nbytes < 0) {
PyErr_SetString(PyExc_ValueError, "nbytes must be >= 0");
return -1;
}
tSize bytes_read = hdfsRead(self->fs, self->file, buf, nbytes);
if (bytes_read < 0) { // error
PyErr_SetFromErrno(PyExc_IOError);
return -1;
}
return bytes_read;
}
static PyObject* _read_new_pystr(FileInfo* self, Py_ssize_t nbytes) {
if (nbytes < 0) {
PyErr_SetString(PyExc_ValueError, "nbytes must be >= 0");
return NULL;
}
// Allocate an uninitialized string object.
// We then access and directly modify the string's internal memory. This is
// ok until we release this string "into the wild".
PyObject* retval = PyString_FromStringAndSize(NULL, nbytes);
if (!retval) return PyErr_NoMemory();
Py_ssize_t bytes_read = _read_into_str(self, PyString_AS_STRING(retval), nbytes);
if (bytes_read >= 0) {
// If bytes_read >= 0, read worked properly. But, if bytes_read < nbytes
// we got fewer bytes than requested (maybe we reached EOF?). We need
// to shrink the string to the correct length. In case of error the
// call to _PyString_Resize frees the original string, sets the
// appropriate python exception and returns -1.
if (bytes_read >= nbytes || _PyString_Resize(&retval, bytes_read) >= 0)
return retval; // all good
}
// If we get here something's gone wrong. The exception should already be set.
Py_DECREF(retval);
return NULL;
}
/*
* Seek to `pos` and read `nbytes` bytes into a the provided buffer.
*
* \return: Number of bytes read. In case of error this function sets
* the appropriate Python exception and returns -1.
*/
static Py_ssize_t _pread_into_str(FileInfo *self, char* buffer, Py_ssize_t pos, Py_ssize_t nbytes) {
Py_ssize_t orig_position = hdfsTell(self->fs, self->file);
if (orig_position < 0) {
PyErr_SetFromErrno(PyExc_IOError);
return -1;
}
if (hdfsSeek(self->fs, self->file, pos) < 0) {
PyErr_SetFromErrno(PyExc_IOError);
return -1;
}
tSize bytes_read = _read_into_str(self, buffer, nbytes);
if (bytes_read < 0) {
PyErr_SetFromErrno(PyExc_IOError);
return -1;
}
if (hdfsSeek(self->fs, self->file, orig_position) < 0) {
PyErr_SetFromErrno(PyExc_IOError);
return -1;
}
return bytes_read;
}
static PyObject* _pread_new_pystr(FileInfo* self, Py_ssize_t pos, Py_ssize_t nbytes) {
if (nbytes < 0) {
PyErr_SetString(PyExc_ValueError, "nbytes must be >= 0");
return NULL;
}
// Allocate an uninitialized string object.
PyObject* retval = PyString_FromStringAndSize(NULL, nbytes);
if (!retval) return PyErr_NoMemory();
Py_ssize_t bytes_read = _pread_into_str(self, PyString_AS_STRING(retval), pos, nbytes);
if (bytes_read >= 0) {
// If bytes_read >= 0, read worked properly. But, if bytes_read < nbytes
// we got fewer bytes than requested (maybe we reached EOF?). We need
// to shrink the string to the correct length. In case of error the
// call to _PyString_Resize frees the original string, sets the
// appropriate python exception and returns -1.
if (bytes_read >= nbytes || _PyString_Resize(&retval, bytes_read) >= 0)
return retval; // all good
}
// If we get here something's gone wrong. The exception should already be set.
Py_DECREF(retval);
return NULL;
}
PyObject* FileClass_read(FileInfo *self, PyObject *args, PyObject *kwds){
Py_ssize_t nbytes;
if (!_ensure_open_for_reading(self))
return NULL;
if (! PyArg_ParseTuple(args, "n", &(nbytes)))
return NULL;
if (nbytes < 0) {
PyErr_SetString(PyExc_ValueError, "nbytes must be >= 0");
return NULL;
}
else if (nbytes == 0) {
return PyString_FromString("");
}
// else nbytes > 0
return _read_new_pystr(self, nbytes);
}
PyObject* FileClass_read_chunk(FileInfo *self, PyObject *args, PyObject *kwds){
Py_buffer buffer;
if (!_ensure_open_for_reading(self))
return NULL;
if (! PyArg_ParseTuple(args, "w*", &buffer))
return NULL;
Py_ssize_t bytes_read = _read_into_str(self, (char*)buffer.buf, buffer.len);
PyBuffer_Release(&buffer);
if (bytes_read >= 0)
return Py_BuildValue("n", bytes_read);
else
return NULL;
}
PyObject* FileClass_pread(FileInfo *self, PyObject *args, PyObject *kwds){
Py_ssize_t position;
Py_ssize_t nbytes;
if (!_ensure_open_for_reading(self))
return NULL;
if (! PyArg_ParseTuple(args, "nn", &position, &nbytes))
return NULL;
if (position < 0) {
PyErr_SetString(PyExc_ValueError, "position must be >= 0");
return NULL;
}
if (nbytes == 0)
return PyString_FromString("");
// else
return _pread_new_pystr(self, position, nbytes);
}
PyObject* FileClass_pread_chunk(FileInfo *self, PyObject *args, PyObject *kwds){
Py_buffer buffer;
Py_ssize_t position;
if (!_ensure_open_for_reading(self))
return NULL;
if (! PyArg_ParseTuple(args, "nw*", &position, &buffer))
return NULL;
if (position < 0) {
PyErr_SetString(PyExc_ValueError, "position must be >= 0");
return NULL;
}
Py_ssize_t bytes_read = _pread_into_str(self, (char*)buffer.buf, position, buffer.len);
PyBuffer_Release(&buffer);
if (bytes_read >= 0)
return Py_BuildValue("n", bytes_read);
else
return NULL;
}
PyObject* FileClass_seek(FileInfo *self, PyObject *args, PyObject *kwds){
tOffset position;
if (! PyArg_ParseTuple(args, "n", &position))
return NULL;
if (position < 0) {
// raise an IOError like a regular python file
errno = EINVAL;
PyErr_SetFromErrno(PyExc_IOError);
errno = 0;
return NULL;
}
int result = hdfsSeek(self->fs, self->file, position);
if (result >= 0)
Py_RETURN_NONE;
else {
PyErr_SetFromErrno(PyExc_IOError);
return NULL;
}
}
PyObject* FileClass_tell(FileInfo *self, PyObject *args, PyObject *kwds){
tOffset offset = hdfsTell(self->fs, self->file);
if (offset >= 0)
return Py_BuildValue("n", offset);
else {
PyErr_SetFromErrno(PyExc_IOError);
return NULL;
}
}
PyObject* FileClass_write(FileInfo* self, PyObject *args, PyObject *kwds)
{
PyObject *input, *encoded = NULL, *retval = NULL;
Py_buffer buffer;
if (!_ensure_open_for_writing(self))
return NULL;
if (! PyArg_ParseTuple(args, "O", &input))
return NULL;
/* If we get a unicode object we serialized it using the
* system's default codec. Any other object we try to access
* it directly through a Python buffer.
*/
if (PyUnicode_Check(input)) {
encoded = PyUnicode_AsEncodedString(input, NULL, NULL);
if (!encoded) // error
return NULL;
input = encoded; // override original input with encoded string
}
if (PyObject_GetBuffer(input, &buffer, PyBUF_SIMPLE) < 0) {
PyErr_SetString(PyExc_TypeError, "Argument is not accessible as a Python buffer");
}
else {
Py_ssize_t written = hdfsWrite(self->fs, self->file, buffer.buf, buffer.len);
PyBuffer_Release(&buffer);
if (written >= 0)
retval = Py_BuildValue("n", written);
else {
PyErr_SetFromErrno(PyExc_IOError);
retval = NULL;
}
}
Py_XDECREF(encoded);
return retval;
}
PyObject* FileClass_flush(FileInfo *self){
int result = hdfsFlush(self->fs, self->file);
if (result >= 0) {
Py_RETURN_NONE;
}
else {
PyErr_SetFromErrno(PyExc_IOError);
return NULL;
}
}
<commit_msg>Encode unicode strings as utf-8 when writing through the C extension for HDFS<commit_after>/* BEGIN_COPYRIGHT
*
* Copyright 2009-2014 CRS4.
*
* 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.
*
* END_COPYRIGHT
*/
#include "hdfs_file.h"
#define PYDOOP_TEXT_ENCODING "utf-8"
PyObject* FileClass_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
FileInfo *self;
self = (FileInfo *)type->tp_alloc(type, 0);
if (self != NULL) {
self->fs = NULL;
self->file = NULL;
self->flags = 0;
self->buff_size = 0;
self->replication = 1;
self->blocksize = 0;
self->readline_chunk_size = 16 * 1024; // 16 KB
#ifdef HADOOP_LIBHDFS_V1
self->stream_type = 0;
#endif
}
return (PyObject *)self;
}
#ifdef HADOOP_LIBHDFS_V1
static bool hdfsFileIsOpenForWrite(FileInfo *f){
return f->stream_type == OUTPUT;
}
static bool hdfsFileIsOpenForRead(FileInfo *f){
return f->stream_type == INPUT;
}
#endif
void FileClass_dealloc(FileInfo* self)
{
self->file = NULL;
self->ob_type->tp_free((PyObject*)self);
}
int FileClass_init(FileInfo *self, PyObject *args, PyObject *kwds)
{
if (! PyArg_ParseTuple(args, "OO", &(self->fs), &(self->file))) {
return -1;
}
return 0;
}
int FileClass_init_internal(FileInfo *self, hdfsFS fs, hdfsFile file)
{
self->fs = fs;
self->file = file;
return 0;
}
PyObject* FileClass_close(FileInfo* self){
int result = hdfsCloseFile(self->fs, self->file);
if (result < 0) {
return PyErr_SetFromErrno(PyExc_IOError);
}
else
return PyBool_FromLong(1);
}
PyObject* FileClass_mode(FileInfo* self){
return FileClass_get_mode(self);
}
PyObject* FileClass_get_mode(FileInfo *self){
return PyLong_FromLong(self->flags);
}
PyObject* FileClass_available(FileInfo *self){
int available = hdfsAvailable(self->fs, self->file);
if (available < 0)
return PyErr_SetFromErrno(PyExc_IOError);
else
return PyLong_FromLong(available);
}
static int _ensure_open_for_reading(FileInfo* self) {
#ifdef HADOOP_LIBHDFS_V1
if(!hdfsFileIsOpenForRead(self)){
#else
if(!hdfsFileIsOpenForRead(self->file)){
#endif
PyErr_SetString(PyExc_IOError, "File is not opened in READ ('r') mode");
return 0; // False
}
return 1; // True
}
static int _ensure_open_for_writing(FileInfo* self) {
#ifdef HADOOP_LIBHDFS_V1
if(!hdfsFileIsOpenForWrite(self)){
#else
if(!hdfsFileIsOpenForWrite(self->file)){
#endif
PyErr_SetString(PyExc_IOError, "File is not opened in WRITE ('w') mode");
return 0; // False
}
return 1; // True
}
static Py_ssize_t _read_into_str(FileInfo *self, char* buf, Py_ssize_t nbytes) {
if (nbytes < 0) {
PyErr_SetString(PyExc_ValueError, "nbytes must be >= 0");
return -1;
}
tSize bytes_read = hdfsRead(self->fs, self->file, buf, nbytes);
if (bytes_read < 0) { // error
PyErr_SetFromErrno(PyExc_IOError);
return -1;
}
return bytes_read;
}
static PyObject* _read_new_pystr(FileInfo* self, Py_ssize_t nbytes) {
if (nbytes < 0) {
PyErr_SetString(PyExc_ValueError, "nbytes must be >= 0");
return NULL;
}
// Allocate an uninitialized string object.
// We then access and directly modify the string's internal memory. This is
// ok until we release this string "into the wild".
PyObject* retval = PyString_FromStringAndSize(NULL, nbytes);
if (!retval) return PyErr_NoMemory();
Py_ssize_t bytes_read = _read_into_str(self, PyString_AS_STRING(retval), nbytes);
if (bytes_read >= 0) {
// If bytes_read >= 0, read worked properly. But, if bytes_read < nbytes
// we got fewer bytes than requested (maybe we reached EOF?). We need
// to shrink the string to the correct length. In case of error the
// call to _PyString_Resize frees the original string, sets the
// appropriate python exception and returns -1.
if (bytes_read >= nbytes || _PyString_Resize(&retval, bytes_read) >= 0)
return retval; // all good
}
// If we get here something's gone wrong. The exception should already be set.
Py_DECREF(retval);
return NULL;
}
/*
* Seek to `pos` and read `nbytes` bytes into a the provided buffer.
*
* \return: Number of bytes read. In case of error this function sets
* the appropriate Python exception and returns -1.
*/
static Py_ssize_t _pread_into_str(FileInfo *self, char* buffer, Py_ssize_t pos, Py_ssize_t nbytes) {
Py_ssize_t orig_position = hdfsTell(self->fs, self->file);
if (orig_position < 0) {
PyErr_SetFromErrno(PyExc_IOError);
return -1;
}
if (hdfsSeek(self->fs, self->file, pos) < 0) {
PyErr_SetFromErrno(PyExc_IOError);
return -1;
}
tSize bytes_read = _read_into_str(self, buffer, nbytes);
if (bytes_read < 0) {
PyErr_SetFromErrno(PyExc_IOError);
return -1;
}
if (hdfsSeek(self->fs, self->file, orig_position) < 0) {
PyErr_SetFromErrno(PyExc_IOError);
return -1;
}
return bytes_read;
}
static PyObject* _pread_new_pystr(FileInfo* self, Py_ssize_t pos, Py_ssize_t nbytes) {
if (nbytes < 0) {
PyErr_SetString(PyExc_ValueError, "nbytes must be >= 0");
return NULL;
}
// Allocate an uninitialized string object.
PyObject* retval = PyString_FromStringAndSize(NULL, nbytes);
if (!retval) return PyErr_NoMemory();
Py_ssize_t bytes_read = _pread_into_str(self, PyString_AS_STRING(retval), pos, nbytes);
if (bytes_read >= 0) {
// If bytes_read >= 0, read worked properly. But, if bytes_read < nbytes
// we got fewer bytes than requested (maybe we reached EOF?). We need
// to shrink the string to the correct length. In case of error the
// call to _PyString_Resize frees the original string, sets the
// appropriate python exception and returns -1.
if (bytes_read >= nbytes || _PyString_Resize(&retval, bytes_read) >= 0)
return retval; // all good
}
// If we get here something's gone wrong. The exception should already be set.
Py_DECREF(retval);
return NULL;
}
PyObject* FileClass_read(FileInfo *self, PyObject *args, PyObject *kwds){
Py_ssize_t nbytes;
if (!_ensure_open_for_reading(self))
return NULL;
if (! PyArg_ParseTuple(args, "n", &(nbytes)))
return NULL;
if (nbytes < 0) {
PyErr_SetString(PyExc_ValueError, "nbytes must be >= 0");
return NULL;
}
else if (nbytes == 0) {
return PyString_FromString("");
}
// else nbytes > 0
return _read_new_pystr(self, nbytes);
}
PyObject* FileClass_read_chunk(FileInfo *self, PyObject *args, PyObject *kwds){
Py_buffer buffer;
if (!_ensure_open_for_reading(self))
return NULL;
if (! PyArg_ParseTuple(args, "w*", &buffer))
return NULL;
Py_ssize_t bytes_read = _read_into_str(self, (char*)buffer.buf, buffer.len);
PyBuffer_Release(&buffer);
if (bytes_read >= 0)
return Py_BuildValue("n", bytes_read);
else
return NULL;
}
PyObject* FileClass_pread(FileInfo *self, PyObject *args, PyObject *kwds){
Py_ssize_t position;
Py_ssize_t nbytes;
if (!_ensure_open_for_reading(self))
return NULL;
if (! PyArg_ParseTuple(args, "nn", &position, &nbytes))
return NULL;
if (position < 0) {
PyErr_SetString(PyExc_ValueError, "position must be >= 0");
return NULL;
}
if (nbytes == 0)
return PyString_FromString("");
// else
return _pread_new_pystr(self, position, nbytes);
}
PyObject* FileClass_pread_chunk(FileInfo *self, PyObject *args, PyObject *kwds){
Py_buffer buffer;
Py_ssize_t position;
if (!_ensure_open_for_reading(self))
return NULL;
if (! PyArg_ParseTuple(args, "nw*", &position, &buffer))
return NULL;
if (position < 0) {
PyErr_SetString(PyExc_ValueError, "position must be >= 0");
return NULL;
}
Py_ssize_t bytes_read = _pread_into_str(self, (char*)buffer.buf, position, buffer.len);
PyBuffer_Release(&buffer);
if (bytes_read >= 0)
return Py_BuildValue("n", bytes_read);
else
return NULL;
}
PyObject* FileClass_seek(FileInfo *self, PyObject *args, PyObject *kwds){
tOffset position;
if (! PyArg_ParseTuple(args, "n", &position))
return NULL;
if (position < 0) {
// raise an IOError like a regular python file
errno = EINVAL;
PyErr_SetFromErrno(PyExc_IOError);
errno = 0;
return NULL;
}
int result = hdfsSeek(self->fs, self->file, position);
if (result >= 0)
Py_RETURN_NONE;
else {
PyErr_SetFromErrno(PyExc_IOError);
return NULL;
}
}
PyObject* FileClass_tell(FileInfo *self, PyObject *args, PyObject *kwds){
tOffset offset = hdfsTell(self->fs, self->file);
if (offset >= 0)
return Py_BuildValue("n", offset);
else {
PyErr_SetFromErrno(PyExc_IOError);
return NULL;
}
}
PyObject* FileClass_write(FileInfo* self, PyObject *args, PyObject *kwds)
{
PyObject *input, *encoded = NULL, *retval = NULL;
Py_buffer buffer;
if (!_ensure_open_for_writing(self))
return NULL;
if (! PyArg_ParseTuple(args, "O", &input))
return NULL;
/* If we get a unicode object we serialized it using the
* system's default codec. Any other object we try to access
* it directly through a Python buffer.
*/
if (PyUnicode_Check(input)) {
encoded = PyUnicode_AsEncodedString(input, PYDOOP_TEXT_ENCODING, NULL);
if (!encoded) // error
return NULL;
input = encoded; // override original input with encoded string
}
if (PyObject_GetBuffer(input, &buffer, PyBUF_SIMPLE) < 0) {
PyErr_SetString(PyExc_TypeError, "Argument is not accessible as a Python buffer");
}
else {
Py_ssize_t written = hdfsWrite(self->fs, self->file, buffer.buf, buffer.len);
PyBuffer_Release(&buffer);
if (written >= 0)
retval = Py_BuildValue("n", written);
else {
PyErr_SetFromErrno(PyExc_IOError);
retval = NULL;
}
}
Py_XDECREF(encoded);
return retval;
}
PyObject* FileClass_flush(FileInfo *self){
int result = hdfsFlush(self->fs, self->file);
if (result >= 0) {
Py_RETURN_NONE;
}
else {
PyErr_SetFromErrno(PyExc_IOError);
return NULL;
}
}
<|endoftext|> |
<commit_before>/*
Copyright (C) 2014 David Edmundson <[email protected]>
Copyright (C) 2014 Alexandr Akulich <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "contact-cache.h"
#include "ktp_kded_debug.h"
#include <KTp/core.h>
#include <KTp/contact.h>
#include <TelepathyQt/Account>
#include <TelepathyQt/AccountManager>
#include <TelepathyQt/AvatarData>
#include <TelepathyQt/Connection>
#include <TelepathyQt/ContactManager>
#include <TelepathyQt/PendingOperation>
#include <TelepathyQt/PendingReady>
#include <QStandardPaths>
#include <QDir>
#include <QSqlQuery>
#include <QSqlDriver>
#include <QSqlField>
/*
* This class waits for a connection to load then saves the pernament
* data from all contacts into a database that can be loaded by the kpeople plugin
* It will not stay up-to-date, applications should load from the database, then
* fetch volatile and up-to-date data from TpQt
*
* We don't hold a reference to the contact to keep things light
*/
inline QString formatString(const QSqlQuery &query, const QString &str)
{
QSqlField f(QLatin1String(""), QVariant::String);
f.setValue(str);
return query.driver()->formatValue(f);
}
ContactCache::ContactCache(QObject *parent):
QObject(parent),
m_db(QSqlDatabase::addDatabase(QLatin1String("QSQLITE")))
{
QString path(QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QStringLiteral("/ktp"));
QDir dir(path);
dir.mkpath(path);
m_db.setDatabaseName(dir.absolutePath() + QStringLiteral("/cache.db"));
if (!m_db.open()) {
qWarning() << "couldn't open database" << m_db.databaseName();
}
// This is the query that creates the contacts table,
// SQLite will store this within the sqlite_master table
QString createTableQuery = QStringLiteral("CREATE TABLE contacts (accountId VARCHAR NOT NULL, contactId VARCHAR NOT NULL, alias VARCHAR, avatarFileName VARCHAR, isBlocked INT, groupsIds VARCHAR);");
// Now let's verify that the table we currently have in the database
// is the same one as above - get the stored query and compare them,
// if they are different (for example when the table structure was
// changed), the table will be dropped and recreated
QSqlQuery verifyTableQuery(QStringLiteral("SELECT sql FROM sqlite_master WHERE tbl_name = 'contacts' AND type = 'table';"), m_db);
verifyTableQuery.exec();
verifyTableQuery.first();
bool match = verifyTableQuery.value(QStringLiteral("sql")).toString() == createTableQuery;
verifyTableQuery.finish();
if (!m_db.tables().contains(QLatin1String("groups")) || !match) {
QSqlQuery preparationsQuery(m_db);
if (m_db.tables().contains(QLatin1String("contacts"))) {
preparationsQuery.exec(QStringLiteral("DROP TABLE 'contacts';"));
// Also drop the groups table
preparationsQuery.exec(QStringLiteral("DROP TABLE 'groups';"));
}
preparationsQuery.exec(createTableQuery);
preparationsQuery.exec(QLatin1String("CREATE TABLE groups (groupId INTEGER, groupName VARCHAR);"));
preparationsQuery.exec(QLatin1String("CREATE UNIQUE INDEX idIndex ON contacts (accountId, contactId);"));
}
connect(KTp::accountManager()->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(onAccountManagerReady(Tp::PendingOperation*)));
}
void ContactCache::onAccountManagerReady(Tp::PendingOperation *op)
{
if (!op || op->isError()) {
qCWarning(KTP_KDED_MODULE) << "ContactCache: Failed to initialize AccountManager:" << op->errorName();
qCWarning(KTP_KDED_MODULE) << op->errorMessage();
return;
}
connect(KTp::accountManager().data(), SIGNAL(newAccount(Tp::AccountPtr)), SLOT(onNewAccount(Tp::AccountPtr)));
QSqlQuery purgeQuery(m_db);
QStringList formattedAccountsIds;
Q_FOREACH (const Tp::AccountPtr &account, KTp::accountManager()->allAccounts()) {
if (!accountIsInteresting(account)) {
continue;
}
connectToAccount(account);
if (!account->connection().isNull()) {
onAccountConnectionChanged(account->connection());
}
formattedAccountsIds.append(formatString(purgeQuery, account->uniqueIdentifier()));
}
// Cleanup contacts
if (formattedAccountsIds.isEmpty()) {
purgeQuery.prepare(QLatin1String("DELETE * FROM contacts;"));
} else {
purgeQuery.prepare(QString(QLatin1String("DELETE FROM contacts WHERE accountId not in (%1);")).arg(formattedAccountsIds.join(QLatin1String(","))));
}
purgeQuery.exec();
// Cleanup groups
QStringList usedGroups;
QSqlQuery usedGroupsQuery(m_db);
usedGroupsQuery.prepare(QLatin1String("SELECT groupsIds FROM contacts;"));
usedGroupsQuery.exec();
while (usedGroupsQuery.next()) {
usedGroups.append(usedGroupsQuery.value(0).toString().split(QLatin1String(",")));
}
usedGroups.removeDuplicates();
purgeQuery.prepare(QString(QLatin1String("UPDATE groups SET groupName = '' WHERE groupId not in (%1);")).arg(usedGroups.join(QLatin1String(","))));
purgeQuery.exec();
// Load groups
QSqlQuery groupsQuery(m_db);
groupsQuery.exec(QLatin1String("SELECT groupName FROM groups ORDER BY groupId;"));
while (groupsQuery.next()) {
m_groups.append(groupsQuery.value(0).toString());
}
}
void ContactCache::onNewAccount(const Tp::AccountPtr &account)
{
if (!accountIsInteresting(account)) {
return;
}
connectToAccount(account);
if (!account->connection().isNull()) {
onAccountConnectionChanged(account->connection());
}
}
void ContactCache::onAccountRemoved()
{
Tp::Account *account = qobject_cast<Tp::Account*>(sender());
if (!account) {
return;
}
QSqlQuery purgeQuery(m_db);
purgeQuery.prepare(QLatin1String("DELETE FROM contacts WHERE accountId = ?;"));
purgeQuery.bindValue(0, account->uniqueIdentifier());
purgeQuery.exec();
}
void ContactCache::onContactManagerStateChanged()
{
Tp::ContactManagerPtr contactManager(qobject_cast<Tp::ContactManager*>(sender()));
checkContactManagerState(Tp::ContactManagerPtr(contactManager));
}
void ContactCache::onAccountConnectionChanged(const Tp::ConnectionPtr &connection)
{
if (connection.isNull() || (connection->status() != Tp::ConnectionStatusConnected)) {
return;
}
//this is needed to make the contact manager roster
//when this finishes the contact manager will change state
connection->becomeReady(Tp::Features() << Tp::Connection::FeatureRoster << Tp::Connection::FeatureRosterGroups);
if (connect(connection->contactManager().data(), SIGNAL(stateChanged(Tp::ContactListState)), this, SLOT(onContactManagerStateChanged()), Qt::UniqueConnection)) {
/* Check current contactManager state and do sync contact only if it is not performed due to already connected contactManager. */
checkContactManagerState(connection->contactManager());
}
}
void ContactCache::onAllKnownContactsChanged(const Tp::Contacts &added, const Tp::Contacts &removed)
{
/* Delete both added and removed contacts, because it's faster than accurate comparsion and partial update of exist contacts. */
Tp::Contacts toBeRemoved = added;
toBeRemoved.unite(removed);
m_db.transaction();
QSqlQuery removeQuery(m_db);
removeQuery.prepare(QLatin1String("DELETE FROM contacts WHERE accountId = ? AND contactId = ?;"));
Q_FOREACH (const Tp::ContactPtr &c, toBeRemoved) {
const KTp::ContactPtr &contact = KTp::ContactPtr::qObjectCast(c);
removeQuery.bindValue(0, contact->accountUniqueIdentifier());
removeQuery.bindValue(1, contact->id());
removeQuery.exec();
}
QSqlQuery insertQuery(m_db);
insertQuery.prepare(QLatin1String("INSERT INTO contacts (accountId, contactId, alias, avatarFileName, isBlocked, groupsIds) VALUES (?, ?, ?, ?, ?, ?);"));
Q_FOREACH (const Tp::ContactPtr &c, added) {
if (c->manager()->connection()->protocolName() == QLatin1String("local-xmpp")) {
continue;
}
bindContactToQuery(&insertQuery, c);
insertQuery.exec();
}
m_db.commit();
}
void ContactCache::connectToAccount(const Tp::AccountPtr &account)
{
connect(account.data(), SIGNAL(removed()), SLOT(onAccountRemoved()));
connect(account.data(), SIGNAL(connectionChanged(Tp::ConnectionPtr)), SLOT(onAccountConnectionChanged(Tp::ConnectionPtr)));
}
bool ContactCache::accountIsInteresting(const Tp::AccountPtr &account) const
{
if (account->protocolName() == QLatin1String("local-xmpp")) {// We don't want to cache local-xmpp contacts
return false;
}
/* There may be more filters. */
return true;
}
void ContactCache::syncContactsOfAccount(const Tp::AccountPtr &account)
{
m_db.transaction();
QSqlQuery purgeQuery(m_db);
purgeQuery.prepare(QLatin1String("DELETE FROM contacts WHERE accountId = ?;"));
purgeQuery.bindValue(0, account->uniqueIdentifier());
purgeQuery.exec();
QSqlQuery insertQuery(m_db);
insertQuery.prepare(QLatin1String("INSERT INTO contacts (accountId, contactId, alias, avatarFileName, isBlocked, groupsIds) VALUES (?, ?, ?, ?, ?, ?);"));
Q_FOREACH (const Tp::ContactPtr &c, account->connection()->contactManager()->allKnownContacts()) {
bindContactToQuery(&insertQuery, c);
insertQuery.exec();
}
m_db.commit();
connect(account->connection()->contactManager().data(),
SIGNAL(allKnownContactsChanged(Tp::Contacts,Tp::Contacts,Tp::Channel::GroupMemberChangeDetails)),
SLOT(onAllKnownContactsChanged(Tp::Contacts,Tp::Contacts)), Qt::UniqueConnection);
}
void ContactCache::checkContactManagerState(const Tp::ContactManagerPtr &contactManager)
{
if (contactManager->state() == Tp::ContactListStateSuccess) {
const QString accountPath = TP_QT_ACCOUNT_OBJECT_PATH_BASE + QLatin1Char('/') + contactManager->connection()->property("accountUID").toString();
Tp::AccountPtr account = KTp::accountManager()->accountForObjectPath(accountPath);
if (!account.isNull()) {
syncContactsOfAccount(account);
} else {
qCWarning(KTP_KDED_MODULE) << "Can't access to account by contactManager";
}
}
}
int ContactCache::askIdFromGroup(const QString &groupName)
{
int index = m_groups.indexOf(groupName);
if (index >= 0) {
return index;
}
QSqlQuery updateGroupsQuery(m_db);
for (index = 0; index < m_groups.count(); ++index) {
if (m_groups.at(index).isEmpty()) {
m_groups[index] = groupName;
updateGroupsQuery.prepare(QLatin1String("UPDATE groups SET groupName = :newGroupName WHERE groupId = :index;"));
break;
}
}
if (index >= m_groups.count()) {
m_groups.append(groupName);
updateGroupsQuery.prepare(QLatin1String("INSERT INTO groups (groupId, groupName) VALUES (:index, :newGroupName);"));
}
updateGroupsQuery.bindValue(QLatin1String(":newGroupName"), groupName);
updateGroupsQuery.bindValue(QLatin1String(":index"), index);
updateGroupsQuery.exec();
return index;
}
void ContactCache::bindContactToQuery(QSqlQuery *query, const Tp::ContactPtr &contact)
{
const KTp::ContactPtr &ktpContact = KTp::ContactPtr::qObjectCast(contact);
query->bindValue(0, ktpContact->accountUniqueIdentifier());
query->bindValue(1, ktpContact->id());
query->bindValue(2, ktpContact->alias());
query->bindValue(3, ktpContact->avatarData().fileName);
query->bindValue(4, ktpContact->isBlocked());
QStringList groupsIds;
Q_FOREACH (const QString &group, ktpContact->groups()) {
groupsIds.append(QString::number(askIdFromGroup(group)));
}
query->bindValue(5, groupsIds.join(QLatin1String(",")));
}
<commit_msg>Make the groupId UNIQUE<commit_after>/*
Copyright (C) 2014 David Edmundson <[email protected]>
Copyright (C) 2014 Alexandr Akulich <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "contact-cache.h"
#include "ktp_kded_debug.h"
#include <KTp/core.h>
#include <KTp/contact.h>
#include <TelepathyQt/Account>
#include <TelepathyQt/AccountManager>
#include <TelepathyQt/AvatarData>
#include <TelepathyQt/Connection>
#include <TelepathyQt/ContactManager>
#include <TelepathyQt/PendingOperation>
#include <TelepathyQt/PendingReady>
#include <QStandardPaths>
#include <QDir>
#include <QSqlQuery>
#include <QSqlDriver>
#include <QSqlField>
/*
* This class waits for a connection to load then saves the pernament
* data from all contacts into a database that can be loaded by the kpeople plugin
* It will not stay up-to-date, applications should load from the database, then
* fetch volatile and up-to-date data from TpQt
*
* We don't hold a reference to the contact to keep things light
*/
inline QString formatString(const QSqlQuery &query, const QString &str)
{
QSqlField f(QLatin1String(""), QVariant::String);
f.setValue(str);
return query.driver()->formatValue(f);
}
ContactCache::ContactCache(QObject *parent):
QObject(parent),
m_db(QSqlDatabase::addDatabase(QLatin1String("QSQLITE")))
{
QString path(QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QStringLiteral("/ktp"));
QDir dir(path);
dir.mkpath(path);
m_db.setDatabaseName(dir.absolutePath() + QStringLiteral("/cache.db"));
if (!m_db.open()) {
qWarning() << "couldn't open database" << m_db.databaseName();
}
// This is the query that creates the contacts table,
// SQLite will store this within the sqlite_master table
QString createTableQuery = QStringLiteral("CREATE TABLE contacts (accountId VARCHAR NOT NULL, contactId VARCHAR NOT NULL, alias VARCHAR, avatarFileName VARCHAR, isBlocked INT, groupsIds VARCHAR);");
// Now let's verify that the table we currently have in the database
// is the same one as above - get the stored query and compare them,
// if they are different (for example when the table structure was
// changed), the table will be dropped and recreated
QSqlQuery verifyTableQuery(QStringLiteral("SELECT sql FROM sqlite_master WHERE tbl_name = 'contacts' AND type = 'table';"), m_db);
verifyTableQuery.exec();
verifyTableQuery.first();
bool match = verifyTableQuery.value(QStringLiteral("sql")).toString() == createTableQuery;
verifyTableQuery.finish();
if (!m_db.tables().contains(QLatin1String("groups")) || !match) {
QSqlQuery preparationsQuery(m_db);
if (m_db.tables().contains(QLatin1String("contacts"))) {
preparationsQuery.exec(QStringLiteral("DROP TABLE 'contacts';"));
// Also drop the groups table
preparationsQuery.exec(QStringLiteral("DROP TABLE 'groups';"));
}
preparationsQuery.exec(createTableQuery);
preparationsQuery.exec(QLatin1String("CREATE TABLE groups (groupId INTEGER UNIQUE, groupName VARCHAR);"));
preparationsQuery.exec(QLatin1String("CREATE UNIQUE INDEX idIndex ON contacts (accountId, contactId);"));
}
connect(KTp::accountManager()->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(onAccountManagerReady(Tp::PendingOperation*)));
}
void ContactCache::onAccountManagerReady(Tp::PendingOperation *op)
{
if (!op || op->isError()) {
qCWarning(KTP_KDED_MODULE) << "ContactCache: Failed to initialize AccountManager:" << op->errorName();
qCWarning(KTP_KDED_MODULE) << op->errorMessage();
return;
}
connect(KTp::accountManager().data(), SIGNAL(newAccount(Tp::AccountPtr)), SLOT(onNewAccount(Tp::AccountPtr)));
QSqlQuery purgeQuery(m_db);
QStringList formattedAccountsIds;
Q_FOREACH (const Tp::AccountPtr &account, KTp::accountManager()->allAccounts()) {
if (!accountIsInteresting(account)) {
continue;
}
connectToAccount(account);
if (!account->connection().isNull()) {
onAccountConnectionChanged(account->connection());
}
formattedAccountsIds.append(formatString(purgeQuery, account->uniqueIdentifier()));
}
// Cleanup contacts
if (formattedAccountsIds.isEmpty()) {
purgeQuery.prepare(QLatin1String("DELETE * FROM contacts;"));
} else {
purgeQuery.prepare(QString(QLatin1String("DELETE FROM contacts WHERE accountId not in (%1);")).arg(formattedAccountsIds.join(QLatin1String(","))));
}
purgeQuery.exec();
// Cleanup groups
QStringList usedGroups;
QSqlQuery usedGroupsQuery(m_db);
usedGroupsQuery.prepare(QLatin1String("SELECT groupsIds FROM contacts;"));
usedGroupsQuery.exec();
while (usedGroupsQuery.next()) {
usedGroups.append(usedGroupsQuery.value(0).toString().split(QLatin1String(",")));
}
usedGroups.removeDuplicates();
purgeQuery.prepare(QString(QLatin1String("UPDATE groups SET groupName = '' WHERE groupId not in (%1);")).arg(usedGroups.join(QLatin1String(","))));
purgeQuery.exec();
// Load groups
QSqlQuery groupsQuery(m_db);
groupsQuery.exec(QLatin1String("SELECT groupName FROM groups ORDER BY groupId;"));
while (groupsQuery.next()) {
m_groups.append(groupsQuery.value(0).toString());
}
}
void ContactCache::onNewAccount(const Tp::AccountPtr &account)
{
if (!accountIsInteresting(account)) {
return;
}
connectToAccount(account);
if (!account->connection().isNull()) {
onAccountConnectionChanged(account->connection());
}
}
void ContactCache::onAccountRemoved()
{
Tp::Account *account = qobject_cast<Tp::Account*>(sender());
if (!account) {
return;
}
QSqlQuery purgeQuery(m_db);
purgeQuery.prepare(QLatin1String("DELETE FROM contacts WHERE accountId = ?;"));
purgeQuery.bindValue(0, account->uniqueIdentifier());
purgeQuery.exec();
}
void ContactCache::onContactManagerStateChanged()
{
Tp::ContactManagerPtr contactManager(qobject_cast<Tp::ContactManager*>(sender()));
checkContactManagerState(Tp::ContactManagerPtr(contactManager));
}
void ContactCache::onAccountConnectionChanged(const Tp::ConnectionPtr &connection)
{
if (connection.isNull() || (connection->status() != Tp::ConnectionStatusConnected)) {
return;
}
//this is needed to make the contact manager roster
//when this finishes the contact manager will change state
connection->becomeReady(Tp::Features() << Tp::Connection::FeatureRoster << Tp::Connection::FeatureRosterGroups);
if (connect(connection->contactManager().data(), SIGNAL(stateChanged(Tp::ContactListState)), this, SLOT(onContactManagerStateChanged()), Qt::UniqueConnection)) {
/* Check current contactManager state and do sync contact only if it is not performed due to already connected contactManager. */
checkContactManagerState(connection->contactManager());
}
}
void ContactCache::onAllKnownContactsChanged(const Tp::Contacts &added, const Tp::Contacts &removed)
{
/* Delete both added and removed contacts, because it's faster than accurate comparsion and partial update of exist contacts. */
Tp::Contacts toBeRemoved = added;
toBeRemoved.unite(removed);
m_db.transaction();
QSqlQuery removeQuery(m_db);
removeQuery.prepare(QLatin1String("DELETE FROM contacts WHERE accountId = ? AND contactId = ?;"));
Q_FOREACH (const Tp::ContactPtr &c, toBeRemoved) {
const KTp::ContactPtr &contact = KTp::ContactPtr::qObjectCast(c);
removeQuery.bindValue(0, contact->accountUniqueIdentifier());
removeQuery.bindValue(1, contact->id());
removeQuery.exec();
}
QSqlQuery insertQuery(m_db);
insertQuery.prepare(QLatin1String("INSERT INTO contacts (accountId, contactId, alias, avatarFileName, isBlocked, groupsIds) VALUES (?, ?, ?, ?, ?, ?);"));
Q_FOREACH (const Tp::ContactPtr &c, added) {
if (c->manager()->connection()->protocolName() == QLatin1String("local-xmpp")) {
continue;
}
bindContactToQuery(&insertQuery, c);
insertQuery.exec();
}
m_db.commit();
}
void ContactCache::connectToAccount(const Tp::AccountPtr &account)
{
connect(account.data(), SIGNAL(removed()), SLOT(onAccountRemoved()));
connect(account.data(), SIGNAL(connectionChanged(Tp::ConnectionPtr)), SLOT(onAccountConnectionChanged(Tp::ConnectionPtr)));
}
bool ContactCache::accountIsInteresting(const Tp::AccountPtr &account) const
{
if (account->protocolName() == QLatin1String("local-xmpp")) {// We don't want to cache local-xmpp contacts
return false;
}
/* There may be more filters. */
return true;
}
void ContactCache::syncContactsOfAccount(const Tp::AccountPtr &account)
{
m_db.transaction();
QSqlQuery purgeQuery(m_db);
purgeQuery.prepare(QLatin1String("DELETE FROM contacts WHERE accountId = ?;"));
purgeQuery.bindValue(0, account->uniqueIdentifier());
purgeQuery.exec();
QSqlQuery insertQuery(m_db);
insertQuery.prepare(QLatin1String("INSERT INTO contacts (accountId, contactId, alias, avatarFileName, isBlocked, groupsIds) VALUES (?, ?, ?, ?, ?, ?);"));
Q_FOREACH (const Tp::ContactPtr &c, account->connection()->contactManager()->allKnownContacts()) {
bindContactToQuery(&insertQuery, c);
insertQuery.exec();
}
m_db.commit();
connect(account->connection()->contactManager().data(),
SIGNAL(allKnownContactsChanged(Tp::Contacts,Tp::Contacts,Tp::Channel::GroupMemberChangeDetails)),
SLOT(onAllKnownContactsChanged(Tp::Contacts,Tp::Contacts)), Qt::UniqueConnection);
}
void ContactCache::checkContactManagerState(const Tp::ContactManagerPtr &contactManager)
{
if (contactManager->state() == Tp::ContactListStateSuccess) {
const QString accountPath = TP_QT_ACCOUNT_OBJECT_PATH_BASE + QLatin1Char('/') + contactManager->connection()->property("accountUID").toString();
Tp::AccountPtr account = KTp::accountManager()->accountForObjectPath(accountPath);
if (!account.isNull()) {
syncContactsOfAccount(account);
} else {
qCWarning(KTP_KDED_MODULE) << "Can't access to account by contactManager";
}
}
}
int ContactCache::askIdFromGroup(const QString &groupName)
{
int index = m_groups.indexOf(groupName);
if (index >= 0) {
return index;
}
QSqlQuery updateGroupsQuery(m_db);
for (index = 0; index < m_groups.count(); ++index) {
if (m_groups.at(index).isEmpty()) {
m_groups[index] = groupName;
updateGroupsQuery.prepare(QLatin1String("UPDATE groups SET groupName = :newGroupName WHERE groupId = :index;"));
break;
}
}
if (index >= m_groups.count()) {
m_groups.append(groupName);
updateGroupsQuery.prepare(QLatin1String("INSERT INTO groups (groupId, groupName) VALUES (:index, :newGroupName);"));
}
updateGroupsQuery.bindValue(QLatin1String(":newGroupName"), groupName);
updateGroupsQuery.bindValue(QLatin1String(":index"), index);
updateGroupsQuery.exec();
return index;
}
void ContactCache::bindContactToQuery(QSqlQuery *query, const Tp::ContactPtr &contact)
{
const KTp::ContactPtr &ktpContact = KTp::ContactPtr::qObjectCast(contact);
query->bindValue(0, ktpContact->accountUniqueIdentifier());
query->bindValue(1, ktpContact->id());
query->bindValue(2, ktpContact->alias());
query->bindValue(3, ktpContact->avatarData().fileName);
query->bindValue(4, ktpContact->isBlocked());
QStringList groupsIds;
Q_FOREACH (const QString &group, ktpContact->groups()) {
groupsIds.append(QString::number(askIdFromGroup(group)));
}
query->bindValue(5, groupsIds.join(QLatin1String(",")));
}
<|endoftext|> |
<commit_before>//==============================================================================
// Viewer widget
//==============================================================================
#include "viewerwidget.h"
//==============================================================================
#include <QPainter>
#include <QPaintEvent>
//==============================================================================
#include "qwt_mathml_text_engine.h"
//==============================================================================
namespace OpenCOR {
namespace Viewer {
//==============================================================================
ViewerWidget::ViewerWidget(QWidget *pParent) :
Widget(pParent),
mMathmlDocument(QwtMathMLDocument()),
mOneOverMathmlDocumentWidth(0),
mOneOverMathmlDocumentHeight(0),
mOptimiseFontSize(true)
{
// Customise the family of our font
QFont newFont = font();
newFont.setFamily("Times New Roman");
setFont(newFont);
//---GRY--- THE BELOW CODE IS JUST FOR TESTING THE WIDGET...
setContent("<math><mrow><msub><mi>i</mi><mi>Na</mi></msub><mo>=</mo><mfrac><mrow><msub><mi>g</mi><mi>Na</mi></msub><mo>·</mo><msup><mi>m</mi><mn>3</mn></msup><mo>·</mo><mi>h</mi><mo>·</mo><msub><mi>Na</mi><mi>o</mi></msub><mo>·</mo><mfrac><msup><mi>F</mi><mn>2</mn></msup><mrow><mi>R</mi><mo>·</mo><mi>T</mi></mrow></mfrac><mo>·</mo><mo>(</mo><mrow><msup><mi>e</mi><mrow><mo>(</mo><mi>V</mi><mo>-</mo><msub><mi>E</mi><mn>Na</mn></msub><mo>)</mo><mo>·</mo><mfrac><mrow><mi>F</mi></mrow><mrow><mi>R</mi><mo>·</mo><mi>T</mi></mrow></mfrac></mrow></msup><mo>-</mo><mn>1</mn></mrow><mo>)</mo></mrow><mrow><msup><mi>e</mi><mrow><mi>V</mi><mo>·</mo><mfrac><mrow><mi>F</mi></mrow><mrow><mi>R</mi><mo>·</mo><mi>T</mi></mrow></mfrac></mrow></msup><mo>-</mo><mn>1</mn></mrow></mfrac><mo>·</mo><mi>V</mi></mrow></math>");
// Some presentation MathML that we use as test
// Note #1: taken from http://www.xmlmind.com/tutorials/MathML/...
// Note #2: http://www.mathmlcentral.com/Tools/FromMathML.jsp can be used to
// test...
// Basic elements
// setContent("<math><mrow><mrow><mi>x</mi><mo>+</mo><mi>y</mi></mrow><mo>=</mo><mn>2</mn></mrow></math>");
// Fraction: mfrac
// setContent("<math><mfrac><mrow><mi>x</mi><mo>-</mo><mn>1</mn></mrow><mn>100</mn></mfrac></math>");
// Radicals: msqrt and mroot
// setContent("<math><msqrt><mi>x</mi><mo>+</mo><mi>y</mi></msqrt></math>");
// setContent("<math><mroot><mi>x</mi><mn>3</mn></mroot></math>");
// Subscripts and superscripts: msub, msup and msubsup
// setContent("<math><msub><mi>x</mi><mi>i</mi></msub></math>");
// setContent("<math><msup><mi>x</mi><mi>j</mi></msup></math>");
// setContent("<math><msubsup><mi>x</mi><mi>i</mi><mi>j</mi></msubsup></math>");
// Underscripts and overscripts: munder, mover and munderover
// setContent("<math><munder><mi>x</mi><mo>─</mo></munder></math>");
// setContent("<math><mover><mi>v</mi><mo>→</mo></mover></math>");
// setContent("<math><munderover><mi>x</mi><mi>a</mi><mi>b</mi></munderover></math>");
// The ubiquitous mo element
// setContent("<math><mrow><munderover><mo>∫</mo><mn>-1</mn><mn>+1</mn></munderover><mfrac><mrow><mi>d</mi><mi>x</mi></mrow><mi>x</mi></mfrac></mrow></math>");
// setContent("<math><mrow><mi>x</mi><munder><mo>→</mo><mtext>maps to</mtext></munder><mi>y</mi></mrow></math>");
// Matrices
// setContent("<math><mrow><mo>[</mo><mtable><mtr><mtd><mn>1</mn></mtd><mtd><mn>0</mn></mtd><mtd><mn>0</mn></mtd></mtr><mtr><mtd><mn>0</mn></mtd><mtd><mn>1</mn></mtd><mtd><mn>0</mn></mtd></mtr><mtr><mtd><mn>0</mn></mtd><mtd><mn>0</mn></mtd><mtd><mn>1</mn></mtd></mtr></mtable><mo>]</mo></mrow></math>");
// Some equations
// setContent("<math><mrow><mo>{</mo><mtable><mtr><mtd><mrow><mrow><mrow><mn>2</mn><mo>⁢</mo><mi>x</mi></mrow><mo>+</mo><mi>y</mi></mrow><mo>=</mo><mn>8</mn></mrow></mtd></mtr><mtr><mtd><mrow><mrow><mi>x</mi><mo>+</mo><mi>y</mi></mrow><mo>=</mo><mn>6</mn></mrow></mtd></mtr></mtable></mrow></math>");
// setContent("<math><mtable side=\"left\"><mlabeledtr><mtd><mtext>Gauss' law</mtext></mtd><mtd><mrow><mrow><mo>∇</mo><mo>∙</mo><mi mathvariant=\"normal\">E</mi></mrow><mo>=</mo><mfrac><mi>ρ</mi><msub><mi>ε</mi><mn>0</mn></msub></mfrac></mrow></mtd></mlabeledtr><mlabeledtr><mtd><mtext>Gauss's law for magnetism</mtext></mtd><mtd><mrow><mrow><mo>∇</mo><mo>∙</mo><mi mathvariant=\"normal\">B</mi></mrow><mo>=</mo><mn>0</mn></mrow></mtd></mlabeledtr></mtable></math>");
// setContent("<math><mstyle mathbackground=\"yellow\" mathcolor=\"navy\" mathsize=\"16pt\"mathvariant=\"bold\"><mrow><mi>x</mi><mo>+</mo><mi>y</mi></mrow><mo>=</mo><mn mathcolor=\"red\">2</mn></mstyle></math>");
// setContent("<math><mfrac><mrow><mi> x </mi><mo> + </mo><mi> y </mi><mo> + </mo><mi> z </mi></mrow><mrow><mi> x </mi><mphantom><mo form=\"infix\"> + </mo><mi> y </mi></mphantom><mo> + </mo><mi> z </mi></mrow></mfrac></math>");
}
//==============================================================================
QString ViewerWidget::content() const
{
// Return our content
return mContent;
}
//==============================================================================
void ViewerWidget::setContent(const QString &pContent)
{
// Set our content
if (!pContent.compare(mContent))
return;
// Keep track of our content
mContent = pContent;
// Determine (the inverse of) the size of our content when rendered using a
// font size of 100 points
// Note: when setting the content, QwtMathMLDocument recomputes its layout.
// Now, because we want the content to be rendered as optimally as
// possible, we use a big font size, so that when we actually need to
// render the content (see paintEvent()), we can do so optimally...
mMathmlDocument.setBaseFontPointSize(100);
mMathmlDocument.setContent(mContent);
QSize mathmlDocumentSize = mMathmlDocument.size();
mOneOverMathmlDocumentWidth = 1.0/mathmlDocumentSize.width();
mOneOverMathmlDocumentHeight = 1.0/mathmlDocumentSize.height();
}
//==============================================================================
bool ViewerWidget::optimiseFontSize() const
{
// Return whether we optimise our font size
return mOptimiseFontSize;
}
//==============================================================================
void ViewerWidget::setOptimiseFontSize(const bool &pOptimiseFontSize)
{
// Keep track of whether we should optimise our font size
if (pOptimiseFontSize == mOptimiseFontSize)
return;
mOptimiseFontSize = pOptimiseFontSize;
// Repaint ourselves
repaint();
}
//==============================================================================
void ViewerWidget::paintEvent(QPaintEvent *pEvent)
{
QPainter painter(this);
// Clear our background
painter.fillRect(pEvent->rect(), QColor(palette().color(QPalette::Base)));
// Set our base font size and font name
mMathmlDocument.setBaseFontPointSize(mOptimiseFontSize?
qRound(100.0*qMin(mOneOverMathmlDocumentWidth*width(),
mOneOverMathmlDocumentHeight*height())):
font().pointSize());
mMathmlDocument.setFontName(QwtMathMLDocument::NormalFont, font().family());
// Render our content
QSize mathmlDocumentSize = mMathmlDocument.size();
mMathmlDocument.paint(&painter, QPoint(0.5*(width()-mathmlDocumentSize.width()),
0.5*(height()-mathmlDocumentSize.height())));
// Accept the event
pEvent->accept();
}
//==============================================================================
QSize ViewerWidget::minimumSizeHint() const
{
// Suggest a default minimum size for our viewer widget
return defaultSize(0.03);
}
//==============================================================================
QSize ViewerWidget::sizeHint() const
{
// Suggest a default size for our viewer widget
// Note: this is critical if we want a docked widget, with a viewer widget
// on it, to have a decent size when docked to the main window...
return defaultSize(0.1);
}
//==============================================================================
} // namespace Viewer
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<commit_msg>Slight improvement to our Viewer widget.<commit_after>//==============================================================================
// Viewer widget
//==============================================================================
#include "viewerwidget.h"
//==============================================================================
#include <QPainter>
#include <QPaintEvent>
//==============================================================================
#include "qwt_mathml_text_engine.h"
//==============================================================================
namespace OpenCOR {
namespace Viewer {
//==============================================================================
ViewerWidget::ViewerWidget(QWidget *pParent) :
Widget(pParent),
mMathmlDocument(QwtMathMLDocument()),
mOneOverMathmlDocumentWidth(0),
mOneOverMathmlDocumentHeight(0),
mOptimiseFontSize(true)
{
// Customise the family of our font
QFont newFont = font();
newFont.setFamily("Times New Roman");
setFont(newFont);
//---GRY--- THE BELOW CODE IS JUST FOR TESTING THE WIDGET...
setContent("<math><mrow><msub><mi>i</mi><mi>Na</mi></msub><mo>=</mo><mfrac><mrow><msub><mi>g</mi><mi>Na</mi></msub><mo>·</mo><msup><mi>m</mi><mn>3</mn></msup><mo>·</mo><mi>h</mi><mo>·</mo><msub><mi>Na</mi><mi>o</mi></msub><mo>·</mo><mfrac><msup><mi>F</mi><mn>2</mn></msup><mrow><mi>R</mi><mo>·</mo><mi>T</mi></mrow></mfrac><mo>·</mo><mo>(</mo><mrow><msup><mi>e</mi><mrow><mo>(</mo><mi>V</mi><mo>-</mo><msub><mi>E</mi><mn>Na</mn></msub><mo>)</mo><mo>·</mo><mfrac><mrow><mi>F</mi></mrow><mrow><mi>R</mi><mo>·</mo><mi>T</mi></mrow></mfrac></mrow></msup><mo>-</mo><mn>1</mn></mrow><mo>)</mo></mrow><mrow><msup><mi>e</mi><mrow><mi>V</mi><mo>·</mo><mfrac><mrow><mi>F</mi></mrow><mrow><mi>R</mi><mo>·</mo><mi>T</mi></mrow></mfrac></mrow></msup><mo>-</mo><mn>1</mn></mrow></mfrac><mo>·</mo><mi>V</mi></mrow></math>");
// Some presentation MathML that we use as test
// Note #1: taken from http://www.xmlmind.com/tutorials/MathML/...
// Note #2: http://www.mathmlcentral.com/Tools/FromMathML.jsp can be used to
// test...
// Basic elements
// setContent("<math><mrow><mrow><mi>x</mi><mo>+</mo><mi>y</mi></mrow><mo>=</mo><mn>2</mn></mrow></math>");
// Fraction: mfrac
// setContent("<math><mfrac><mrow><mi>x</mi><mo>-</mo><mn>1</mn></mrow><mn>100</mn></mfrac></math>");
// Radicals: msqrt and mroot
// setContent("<math><msqrt><mi>x</mi><mo>+</mo><mi>y</mi></msqrt></math>");
// setContent("<math><mroot><mi>x</mi><mn>3</mn></mroot></math>");
// Subscripts and superscripts: msub, msup and msubsup
// setContent("<math><msub><mi>x</mi><mi>i</mi></msub></math>");
// setContent("<math><msup><mi>x</mi><mi>j</mi></msup></math>");
// setContent("<math><msubsup><mi>x</mi><mi>i</mi><mi>j</mi></msubsup></math>");
// Underscripts and overscripts: munder, mover and munderover
// setContent("<math><munder><mi>x</mi><mo>─</mo></munder></math>");
// setContent("<math><mover><mi>v</mi><mo>→</mo></mover></math>");
// setContent("<math><munderover><mi>x</mi><mi>a</mi><mi>b</mi></munderover></math>");
// The ubiquitous mo element
// setContent("<math><mrow><munderover><mo>∫</mo><mn>-1</mn><mn>+1</mn></munderover><mfrac><mrow><mi>d</mi><mi>x</mi></mrow><mi>x</mi></mfrac></mrow></math>");
// setContent("<math><mrow><mi>x</mi><munder><mo>→</mo><mtext>maps to</mtext></munder><mi>y</mi></mrow></math>");
// Matrices
// setContent("<math><mrow><mo>[</mo><mtable><mtr><mtd><mn>1</mn></mtd><mtd><mn>0</mn></mtd><mtd><mn>0</mn></mtd></mtr><mtr><mtd><mn>0</mn></mtd><mtd><mn>1</mn></mtd><mtd><mn>0</mn></mtd></mtr><mtr><mtd><mn>0</mn></mtd><mtd><mn>0</mn></mtd><mtd><mn>1</mn></mtd></mtr></mtable><mo>]</mo></mrow></math>");
// Some equations
// setContent("<math><mrow><mo>{</mo><mtable><mtr><mtd><mrow><mrow><mrow><mn>2</mn><mo>⁢</mo><mi>x</mi></mrow><mo>+</mo><mi>y</mi></mrow><mo>=</mo><mn>8</mn></mrow></mtd></mtr><mtr><mtd><mrow><mrow><mi>x</mi><mo>+</mo><mi>y</mi></mrow><mo>=</mo><mn>6</mn></mrow></mtd></mtr></mtable></mrow></math>");
// setContent("<math><mtable side=\"left\"><mlabeledtr><mtd><mtext>Gauss' law</mtext></mtd><mtd><mrow><mrow><mo>∇</mo><mo>∙</mo><mi mathvariant=\"normal\">E</mi></mrow><mo>=</mo><mfrac><mi>ρ</mi><msub><mi>ε</mi><mn>0</mn></msub></mfrac></mrow></mtd></mlabeledtr><mlabeledtr><mtd><mtext>Gauss's law for magnetism</mtext></mtd><mtd><mrow><mrow><mo>∇</mo><mo>∙</mo><mi mathvariant=\"normal\">B</mi></mrow><mo>=</mo><mn>0</mn></mrow></mtd></mlabeledtr></mtable></math>");
// setContent("<math><mstyle mathbackground=\"yellow\" mathcolor=\"navy\" mathsize=\"16pt\"mathvariant=\"bold\"><mrow><mi>x</mi><mo>+</mo><mi>y</mi></mrow><mo>=</mo><mn mathcolor=\"red\">2</mn></mstyle></math>");
// setContent("<math><mfrac><mrow><mi> x </mi><mo> + </mo><mi> y </mi><mo> + </mo><mi> z </mi></mrow><mrow><mi> x </mi><mphantom><mo form=\"infix\"> + </mo><mi> y </mi></mphantom><mo> + </mo><mi> z </mi></mrow></mfrac></math>");
}
//==============================================================================
QString ViewerWidget::content() const
{
// Return our content
return mContent;
}
//==============================================================================
void ViewerWidget::setContent(const QString &pContent)
{
// Set our content
if (!pContent.compare(mContent))
return;
// Keep track of our content
mContent = pContent;
// Determine (the inverse of) the size of our content when rendered using a
// font size of 100 points
// Note: when setting the content, QwtMathMLDocument recomputes its layout.
// Now, because we want the content to be rendered as optimally as
// possible, we use a big font size, so that when we actually need to
// render the content (see paintEvent()), we can do so optimally...
mMathmlDocument.setBaseFontPointSize(100);
mMathmlDocument.setContent(mContent);
QSize mathmlDocumentSize = mMathmlDocument.size();
mOneOverMathmlDocumentWidth = 1.0/mathmlDocumentSize.width();
mOneOverMathmlDocumentHeight = 1.0/mathmlDocumentSize.height();
}
//==============================================================================
bool ViewerWidget::optimiseFontSize() const
{
// Return whether we optimise our font size
return mOptimiseFontSize;
}
//==============================================================================
void ViewerWidget::setOptimiseFontSize(const bool &pOptimiseFontSize)
{
// Keep track of whether we should optimise our font size
if (pOptimiseFontSize == mOptimiseFontSize)
return;
mOptimiseFontSize = pOptimiseFontSize;
// Repaint ourselves
repaint();
}
//==============================================================================
void ViewerWidget::paintEvent(QPaintEvent *pEvent)
{
QPainter painter(this);
// Clear our background
painter.fillRect(pEvent->rect(), QColor(palette().color(QPalette::Base)));
// Set our base font size and font name
// Note: to go for 100% of the 'optimal' font size might result in the edges
// of the content being clipped once Windows, hence we go for 93% of
// it instead...
#ifdef Q_OS_WIN
static const double Scaling = 93.0;
#else
static const double Scaling = 100.0;
#endif
mMathmlDocument.setBaseFontPointSize(mOptimiseFontSize?
qRound(Scaling*qMin(mOneOverMathmlDocumentWidth*width(),
mOneOverMathmlDocumentHeight*height())):
font().pointSize());
mMathmlDocument.setFontName(QwtMathMLDocument::NormalFont, font().family());
// Render our content
QSize mathmlDocumentSize = mMathmlDocument.size();
mMathmlDocument.paint(&painter, QPoint(0.5*(width()-mathmlDocumentSize.width()),
0.5*(height()-mathmlDocumentSize.height())));
// Accept the event
pEvent->accept();
}
//==============================================================================
QSize ViewerWidget::minimumSizeHint() const
{
// Suggest a default minimum size for our viewer widget
return defaultSize(0.03);
}
//==============================================================================
QSize ViewerWidget::sizeHint() const
{
// Suggest a default size for our viewer widget
// Note: this is critical if we want a docked widget, with a viewer widget
// on it, to have a decent size when docked to the main window...
return defaultSize(0.1);
}
//==============================================================================
} // namespace Viewer
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: XMLFilterRegistration.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2006-06-19 18:56:30 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <string.h>
#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_
#include <com/sun/star/registry/XRegistryKey.hpp>
#endif
#ifndef _CPPUHELPER_FACTORY_HXX_
#include <cppuhelper/factory.hxx>
#endif
using namespace ::com::sun::star;
#define DECLARE_SERVICE( classname ) \
extern ::rtl::OUString SAL_CALL classname##_getImplementationName() throw(); \
extern uno::Sequence< ::rtl::OUString > SAL_CALL classname##_getSupportedServiceNames() throw(); \
extern uno::Reference< uno::XInterface > SAL_CALL classname##_createInstance( \
const uno::Reference< lang::XMultiServiceFactory > & rSMgr ) throw( uno::Exception );
#define ENUMERATE_SERVICE( classname ) \
{ classname##_getImplementationName, classname##_getSupportedServiceNames, classname##_createInstance }
// ============================================================================
DECLARE_SERVICE( OOo2OasisTransformer )
DECLARE_SERVICE( Oasis2OOoTransformer )
DECLARE_SERVICE( XMLAutoTextEventImportOOO )
DECLARE_SERVICE( XMLMetaImportOOO )
DECLARE_SERVICE( XMLMathSettingsImportOOO )
DECLARE_SERVICE( XMLMathMetaImportOOO )
DECLARE_SERVICE( XMLCalcSettingsImportOOO )
DECLARE_SERVICE( XMLCalcMetaImportOOO )
DECLARE_SERVICE( XMLCalcContentImportOOO )
DECLARE_SERVICE( XMLCalcStylesImportOOO )
DECLARE_SERVICE( XMLCalcImportOOO )
DECLARE_SERVICE( XMLWriterSettingsImportOOO )
DECLARE_SERVICE( XMLWriterMetaImportOOO )
DECLARE_SERVICE( XMLWriterContentImportOOO )
DECLARE_SERVICE( XMLWriterStylesImportOOO )
DECLARE_SERVICE( XMLWriterImportOOO )
DECLARE_SERVICE( XMLChartContentImportOOO )
DECLARE_SERVICE( XMLChartStylesImportOOO )
DECLARE_SERVICE( XMLChartImportOOO )
DECLARE_SERVICE( XMLDrawSettingsImportOOO )
DECLARE_SERVICE( XMLDrawMetaImportOOO )
DECLARE_SERVICE( XMLDrawContentImportOOO )
DECLARE_SERVICE( XMLDrawStylesImportOOO )
DECLARE_SERVICE( XMLDrawImportOOO )
DECLARE_SERVICE( XMLImpressSettingsImportOOO )
DECLARE_SERVICE( XMLImpressMetaImportOOO )
DECLARE_SERVICE( XMLImpressContentImportOOO )
DECLARE_SERVICE( XMLImpressStylesImportOOO )
DECLARE_SERVICE( XMLImpressImportOOO )
// ============================================================================
// ----------------------------------------------------------------------------
namespace
{
typedef ::rtl::OUString (SAL_CALL * GetImplementationName)();
typedef uno::Sequence< ::rtl::OUString > (SAL_CALL * GetSupportedServiceNames)();
typedef uno::Reference< ::uno::XInterface > (SAL_CALL * CreateInstance)(
const uno::Reference< lang::XMultiServiceFactory >& );
struct ServiceDescriptor
{
GetImplementationName getImplementationName;
GetSupportedServiceNames getSupportedServiceNames;
CreateInstance createInstance;
};
// ------------------------------------------------------------------------
static const ServiceDescriptor* getServiceDescriptors()
{
static const ServiceDescriptor aDescriptors[] =
{
// ================================================================
ENUMERATE_SERVICE( OOo2OasisTransformer ),
ENUMERATE_SERVICE( Oasis2OOoTransformer ),
ENUMERATE_SERVICE( XMLAutoTextEventImportOOO ),
ENUMERATE_SERVICE( XMLMetaImportOOO ),
ENUMERATE_SERVICE( XMLMathSettingsImportOOO ),
ENUMERATE_SERVICE( XMLMathMetaImportOOO ),
ENUMERATE_SERVICE( XMLCalcSettingsImportOOO ),
ENUMERATE_SERVICE( XMLCalcMetaImportOOO ),
ENUMERATE_SERVICE( XMLCalcContentImportOOO ),
ENUMERATE_SERVICE( XMLCalcStylesImportOOO ),
ENUMERATE_SERVICE( XMLCalcImportOOO ),
ENUMERATE_SERVICE( XMLWriterSettingsImportOOO ),
ENUMERATE_SERVICE( XMLWriterMetaImportOOO ),
ENUMERATE_SERVICE( XMLWriterContentImportOOO ),
ENUMERATE_SERVICE( XMLWriterStylesImportOOO ),
ENUMERATE_SERVICE( XMLWriterImportOOO ),
ENUMERATE_SERVICE( XMLChartContentImportOOO ),
ENUMERATE_SERVICE( XMLChartStylesImportOOO ),
ENUMERATE_SERVICE( XMLChartImportOOO ),
ENUMERATE_SERVICE( XMLDrawSettingsImportOOO ),
ENUMERATE_SERVICE( XMLDrawMetaImportOOO ),
ENUMERATE_SERVICE( XMLDrawContentImportOOO ),
ENUMERATE_SERVICE( XMLDrawStylesImportOOO ),
ENUMERATE_SERVICE( XMLDrawImportOOO ),
ENUMERATE_SERVICE( XMLImpressSettingsImportOOO ),
ENUMERATE_SERVICE( XMLImpressMetaImportOOO ),
ENUMERATE_SERVICE( XMLImpressContentImportOOO ),
ENUMERATE_SERVICE( XMLImpressStylesImportOOO ),
ENUMERATE_SERVICE( XMLImpressImportOOO ),
// ================================================================
{ NULL, NULL, NULL }
};
return aDescriptors;
};
}
// ----------------------------------------------------------------------------
#ifdef __cplusplus
extern "C"
{
#endif
void SAL_CALL component_getImplementationEnvironment( const sal_Char ** ppEnvTypeName, uno_Environment ** )
{
*ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
sal_Bool SAL_CALL component_writeInfo( void * /*pServiceManager*/, void * pRegistryKey )
{
if( pRegistryKey )
{
try
{
uno::Reference< registry::XRegistryKey > xMasterKey( reinterpret_cast< registry::XRegistryKey * >( pRegistryKey ) );
const ServiceDescriptor* pDescriptor = getServiceDescriptors();
while ( pDescriptor->getImplementationName )
{
::rtl::OUString sNewKeyName( RTL_CONSTASCII_USTRINGPARAM("/") );
sNewKeyName += pDescriptor->getImplementationName();
sNewKeyName += ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "/UNO/SERVICES") );
uno::Reference< registry::XRegistryKey > xNewKey( xMasterKey->createKey( sNewKeyName ) );
uno::Sequence< ::rtl::OUString > aServices = pDescriptor->getSupportedServiceNames();
const ::rtl::OUString* pServices = aServices.getConstArray();
for( sal_Int32 i = 0; i < aServices.getLength(); ++i, ++pServices )
xNewKey->createKey( *pServices);
++pDescriptor;
}
}
catch (registry::InvalidRegistryException &)
{
OSL_ENSURE( sal_False, "xof::component_writeInfo: InvalidRegistryException!" );
}
}
return sal_True;
}
void * SAL_CALL component_getFactory( const sal_Char * pImplName, void * pServiceManager, void * /*pRegistryKey*/ )
{
void * pRet = NULL;
if( pServiceManager )
{
try
{
uno::Reference< lang::XMultiServiceFactory > xMSF( reinterpret_cast< lang::XMultiServiceFactory * >( pServiceManager ) );
const sal_Int32 nImplNameLen = strlen( pImplName );
const ServiceDescriptor* pDescriptor = getServiceDescriptors();
while ( pDescriptor->getImplementationName )
{
if ( pDescriptor->getImplementationName().equalsAsciiL( pImplName, nImplNameLen ) )
{
uno::Reference< lang::XSingleServiceFactory > xFactory =
::cppu::createSingleFactory( xMSF,
pDescriptor->getImplementationName(),
pDescriptor->createInstance,
pDescriptor->getSupportedServiceNames()
);
if ( xFactory.is() )
{
xFactory->acquire();
pRet = xFactory.get();
break;
}
}
++pDescriptor;
}
}
catch( uno::Exception& )
{
OSL_ENSURE( sal_False, "xof::component_getFactory: Exception!" );
}
}
return pRet;
}
#ifdef __cplusplus
}
#endif
<commit_msg>INTEGRATION: CWS pchfix02 (1.4.34); FILE MERGED 2006/09/01 18:00:20 kaib 1.4.34.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: XMLFilterRegistration.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2006-09-17 11:29:48 $
*
* 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_xmloff.hxx"
#include <string.h>
#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_
#include <com/sun/star/registry/XRegistryKey.hpp>
#endif
#ifndef _CPPUHELPER_FACTORY_HXX_
#include <cppuhelper/factory.hxx>
#endif
using namespace ::com::sun::star;
#define DECLARE_SERVICE( classname ) \
extern ::rtl::OUString SAL_CALL classname##_getImplementationName() throw(); \
extern uno::Sequence< ::rtl::OUString > SAL_CALL classname##_getSupportedServiceNames() throw(); \
extern uno::Reference< uno::XInterface > SAL_CALL classname##_createInstance( \
const uno::Reference< lang::XMultiServiceFactory > & rSMgr ) throw( uno::Exception );
#define ENUMERATE_SERVICE( classname ) \
{ classname##_getImplementationName, classname##_getSupportedServiceNames, classname##_createInstance }
// ============================================================================
DECLARE_SERVICE( OOo2OasisTransformer )
DECLARE_SERVICE( Oasis2OOoTransformer )
DECLARE_SERVICE( XMLAutoTextEventImportOOO )
DECLARE_SERVICE( XMLMetaImportOOO )
DECLARE_SERVICE( XMLMathSettingsImportOOO )
DECLARE_SERVICE( XMLMathMetaImportOOO )
DECLARE_SERVICE( XMLCalcSettingsImportOOO )
DECLARE_SERVICE( XMLCalcMetaImportOOO )
DECLARE_SERVICE( XMLCalcContentImportOOO )
DECLARE_SERVICE( XMLCalcStylesImportOOO )
DECLARE_SERVICE( XMLCalcImportOOO )
DECLARE_SERVICE( XMLWriterSettingsImportOOO )
DECLARE_SERVICE( XMLWriterMetaImportOOO )
DECLARE_SERVICE( XMLWriterContentImportOOO )
DECLARE_SERVICE( XMLWriterStylesImportOOO )
DECLARE_SERVICE( XMLWriterImportOOO )
DECLARE_SERVICE( XMLChartContentImportOOO )
DECLARE_SERVICE( XMLChartStylesImportOOO )
DECLARE_SERVICE( XMLChartImportOOO )
DECLARE_SERVICE( XMLDrawSettingsImportOOO )
DECLARE_SERVICE( XMLDrawMetaImportOOO )
DECLARE_SERVICE( XMLDrawContentImportOOO )
DECLARE_SERVICE( XMLDrawStylesImportOOO )
DECLARE_SERVICE( XMLDrawImportOOO )
DECLARE_SERVICE( XMLImpressSettingsImportOOO )
DECLARE_SERVICE( XMLImpressMetaImportOOO )
DECLARE_SERVICE( XMLImpressContentImportOOO )
DECLARE_SERVICE( XMLImpressStylesImportOOO )
DECLARE_SERVICE( XMLImpressImportOOO )
// ============================================================================
// ----------------------------------------------------------------------------
namespace
{
typedef ::rtl::OUString (SAL_CALL * GetImplementationName)();
typedef uno::Sequence< ::rtl::OUString > (SAL_CALL * GetSupportedServiceNames)();
typedef uno::Reference< ::uno::XInterface > (SAL_CALL * CreateInstance)(
const uno::Reference< lang::XMultiServiceFactory >& );
struct ServiceDescriptor
{
GetImplementationName getImplementationName;
GetSupportedServiceNames getSupportedServiceNames;
CreateInstance createInstance;
};
// ------------------------------------------------------------------------
static const ServiceDescriptor* getServiceDescriptors()
{
static const ServiceDescriptor aDescriptors[] =
{
// ================================================================
ENUMERATE_SERVICE( OOo2OasisTransformer ),
ENUMERATE_SERVICE( Oasis2OOoTransformer ),
ENUMERATE_SERVICE( XMLAutoTextEventImportOOO ),
ENUMERATE_SERVICE( XMLMetaImportOOO ),
ENUMERATE_SERVICE( XMLMathSettingsImportOOO ),
ENUMERATE_SERVICE( XMLMathMetaImportOOO ),
ENUMERATE_SERVICE( XMLCalcSettingsImportOOO ),
ENUMERATE_SERVICE( XMLCalcMetaImportOOO ),
ENUMERATE_SERVICE( XMLCalcContentImportOOO ),
ENUMERATE_SERVICE( XMLCalcStylesImportOOO ),
ENUMERATE_SERVICE( XMLCalcImportOOO ),
ENUMERATE_SERVICE( XMLWriterSettingsImportOOO ),
ENUMERATE_SERVICE( XMLWriterMetaImportOOO ),
ENUMERATE_SERVICE( XMLWriterContentImportOOO ),
ENUMERATE_SERVICE( XMLWriterStylesImportOOO ),
ENUMERATE_SERVICE( XMLWriterImportOOO ),
ENUMERATE_SERVICE( XMLChartContentImportOOO ),
ENUMERATE_SERVICE( XMLChartStylesImportOOO ),
ENUMERATE_SERVICE( XMLChartImportOOO ),
ENUMERATE_SERVICE( XMLDrawSettingsImportOOO ),
ENUMERATE_SERVICE( XMLDrawMetaImportOOO ),
ENUMERATE_SERVICE( XMLDrawContentImportOOO ),
ENUMERATE_SERVICE( XMLDrawStylesImportOOO ),
ENUMERATE_SERVICE( XMLDrawImportOOO ),
ENUMERATE_SERVICE( XMLImpressSettingsImportOOO ),
ENUMERATE_SERVICE( XMLImpressMetaImportOOO ),
ENUMERATE_SERVICE( XMLImpressContentImportOOO ),
ENUMERATE_SERVICE( XMLImpressStylesImportOOO ),
ENUMERATE_SERVICE( XMLImpressImportOOO ),
// ================================================================
{ NULL, NULL, NULL }
};
return aDescriptors;
};
}
// ----------------------------------------------------------------------------
#ifdef __cplusplus
extern "C"
{
#endif
void SAL_CALL component_getImplementationEnvironment( const sal_Char ** ppEnvTypeName, uno_Environment ** )
{
*ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
sal_Bool SAL_CALL component_writeInfo( void * /*pServiceManager*/, void * pRegistryKey )
{
if( pRegistryKey )
{
try
{
uno::Reference< registry::XRegistryKey > xMasterKey( reinterpret_cast< registry::XRegistryKey * >( pRegistryKey ) );
const ServiceDescriptor* pDescriptor = getServiceDescriptors();
while ( pDescriptor->getImplementationName )
{
::rtl::OUString sNewKeyName( RTL_CONSTASCII_USTRINGPARAM("/") );
sNewKeyName += pDescriptor->getImplementationName();
sNewKeyName += ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "/UNO/SERVICES") );
uno::Reference< registry::XRegistryKey > xNewKey( xMasterKey->createKey( sNewKeyName ) );
uno::Sequence< ::rtl::OUString > aServices = pDescriptor->getSupportedServiceNames();
const ::rtl::OUString* pServices = aServices.getConstArray();
for( sal_Int32 i = 0; i < aServices.getLength(); ++i, ++pServices )
xNewKey->createKey( *pServices);
++pDescriptor;
}
}
catch (registry::InvalidRegistryException &)
{
OSL_ENSURE( sal_False, "xof::component_writeInfo: InvalidRegistryException!" );
}
}
return sal_True;
}
void * SAL_CALL component_getFactory( const sal_Char * pImplName, void * pServiceManager, void * /*pRegistryKey*/ )
{
void * pRet = NULL;
if( pServiceManager )
{
try
{
uno::Reference< lang::XMultiServiceFactory > xMSF( reinterpret_cast< lang::XMultiServiceFactory * >( pServiceManager ) );
const sal_Int32 nImplNameLen = strlen( pImplName );
const ServiceDescriptor* pDescriptor = getServiceDescriptors();
while ( pDescriptor->getImplementationName )
{
if ( pDescriptor->getImplementationName().equalsAsciiL( pImplName, nImplNameLen ) )
{
uno::Reference< lang::XSingleServiceFactory > xFactory =
::cppu::createSingleFactory( xMSF,
pDescriptor->getImplementationName(),
pDescriptor->createInstance,
pDescriptor->getSupportedServiceNames()
);
if ( xFactory.is() )
{
xFactory->acquire();
pRet = xFactory.get();
break;
}
}
++pDescriptor;
}
}
catch( uno::Exception& )
{
OSL_ENSURE( sal_False, "xof::component_getFactory: Exception!" );
}
}
return pRet;
}
#ifdef __cplusplus
}
#endif
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2004-2009 See the AUTHORS file for details.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
* Email Monitor / Retrieval
* Author: imaginos <[email protected]>
*/
#include "MD5.h"
#include "User.h"
#include "znc.h"
#include <sstream>
using std::stringstream;
struct EmailST
{
CString sFrom;
CString sSubject;
CString sUidl;
u_int iSize;
};
class CEmailJob : public CTimer
{
public:
CEmailJob(CModule* pModule, unsigned int uInterval, unsigned int uCycles, const CString& sLabel, const CString& sDescription)
: CTimer(pModule, uInterval, uCycles, sLabel, sDescription) {}
virtual ~CEmailJob() {}
protected:
virtual void RunJob();
};
class CEmail : public CModule
{
public:
MODCONSTRUCTOR(CEmail)
{
m_iLastCheck = 0;
m_bInitialized = false;
}
virtual ~CEmail() {}
virtual bool OnLoad(const CString & sArgs, CString& sMessage) {
m_sMailPath = sArgs;
StartParser();
if (m_pUser->IsUserAttached())
StartTimer();
return true;
}
virtual void OnClientLogin()
{
stringstream s;
s << "You have " << m_ssUidls.size() << " emails.";
PutModule(s.str());
StartTimer();
}
virtual void OnClientDisconnect()
{
RemTimer("EMAIL::" + m_pUser->GetUserName());
}
void StartTimer()
{
if (!FindTimer("EMAIL::" + m_pUser->GetUserName()))
{
CEmailJob *p = new CEmailJob(this, 60, 0, "EmailMonitor", "Monitors email activity");
AddTimer(p);
}
}
virtual void OnModCommand(const CString& sCommand);
void StartParser();
void ParseEmails(const vector<EmailST> & vEmails)
{
if (!m_bInitialized)
{
m_bInitialized = true;
for (u_int a = 0; a < vEmails.size(); a++)
m_ssUidls.insert(vEmails[a].sUidl);
stringstream s;
s << "You have " << vEmails.size() << " emails.";
PutModule(s.str());
} else
{
set<CString> ssUidls;
CTable Table;
Table.AddColumn("From");
Table.AddColumn("Size");
Table.AddColumn("Subject");
for (u_int a = 0; a < vEmails.size(); a++)
{
if (m_ssUidls.find(vEmails[a].sUidl) == m_ssUidls.end())
{
//PutModule("------------------- New Email -------------------");
Table.AddRow();
Table.SetCell("From", vEmails[a].sFrom.Ellipsize(32));
Table.SetCell("Size", CString(vEmails[a].iSize));
Table.SetCell("Subject", vEmails[a].sSubject.Ellipsize(64));
}
ssUidls.insert(vEmails[a].sUidl);
}
m_ssUidls = ssUidls; // keep the list in synch
if (Table.size()) {
PutModule(Table);
stringstream s;
s << "You have " << vEmails.size() << " emails.";
PutModule(s.str());
}
}
}
private:
CString m_sMailPath;
u_int m_iLastCheck;
set<CString> m_ssUidls;
bool m_bInitialized;
};
class CEmailFolder : public CSocket
{
public:
CEmailFolder(CEmail *pModule, const CString & sMailbox) : CSocket(pModule)
{
m_pModule = pModule;
m_sMailbox = sMailbox;
EnableReadLine();
}
virtual ~CEmailFolder()
{
if (!m_sMailBuffer.empty())
ProcessMail(); // get the last one
if (!m_vEmails.empty())
m_pModule->ParseEmails(m_vEmails);
}
virtual void ReadLine(const CS_STRING & sLine)
{
if (sLine.substr(0, 5) == "From ")
{
if (!m_sMailBuffer.empty())
{
ProcessMail();
m_sMailBuffer.clear();
}
}
m_sMailBuffer += sLine;
}
void ProcessMail()
{
EmailST tmp;
tmp.sUidl = (char *)CMD5(m_sMailBuffer.substr(0, 255));
VCString vsLines;
VCString::iterator it;
m_sMailBuffer.Split("\n", vsLines);
for (it = vsLines.begin(); it != vsLines.end(); it++) {
CString sLine(*it);
sLine.Trim();
if (sLine.empty())
break; // out of the headers
if (sLine.Equals("From: ", false, 6))
tmp.sFrom = sLine.substr(6, CString::npos);
else if (sLine.Equals("Subject: ", false, 9))
tmp.sSubject = sLine.substr(9, CString::npos);
if ((!tmp.sFrom.empty()) && (!tmp.sSubject.empty()))
break;
}
tmp.iSize = m_sMailBuffer.length();
m_vEmails.push_back(tmp);
}
private:
CEmail *m_pModule;
CString m_sMailbox;
CString m_sMailBuffer;
vector<EmailST> m_vEmails;
};
void CEmail::OnModCommand(const CString& sCommand)
{
CString::size_type iPos = sCommand.find(" ");
CString sCom, sArgs;
if (iPos == CString::npos)
sCom = sCommand;
else
{
sCom = sCommand.substr(0, iPos);
sArgs = sCommand.substr(iPos + 1, CString::npos);
}
if (sCom == "timers")
{
ListTimers();
} else
PutModule("Error, no such command [" + sCom + "]");
}
void CEmail::StartParser()
{
CString sParserName = "EMAIL::" + m_pUser->GetUserName();
if (m_pManager->FindSockByName(sParserName))
return; // one at a time sucker
CFile cFile(m_sMailPath);
if ((!cFile.Exists()) || (cFile.GetSize() == 0))
{
m_bInitialized = true;
return; // der
}
if (cFile.GetMTime() <= m_iLastCheck)
return; // only check if modified
int iFD = open(m_sMailPath.c_str(), O_RDONLY);
if (iFD >= 0)
{
m_iLastCheck = time(NULL);
CEmailFolder *p = new CEmailFolder(this, m_sMailPath);
p->SetRSock(iFD);
p->SetWSock(iFD);
m_pManager->AddSock(p, "EMAIL::" + m_pUser->GetUserName());
}
}
void CEmailJob::RunJob()
{
CEmail *p = (CEmail *)m_pModule;
p->StartParser();
}
MODULEDEFS(CEmail, "Monitors Email activity on local disk /var/mail/user")
<commit_msg>Fix a compiler warning in email<commit_after>/*
* Copyright (C) 2004-2009 See the AUTHORS file for details.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
* Email Monitor / Retrieval
* Author: imaginos <[email protected]>
*/
#include "MD5.h"
#include "User.h"
#include "znc.h"
#include <sstream>
using std::stringstream;
struct EmailST
{
CString sFrom;
CString sSubject;
CString sUidl;
u_int iSize;
};
class CEmailJob : public CTimer
{
public:
CEmailJob(CModule* pModule, unsigned int uInterval, unsigned int uCycles, const CString& sLabel, const CString& sDescription)
: CTimer(pModule, uInterval, uCycles, sLabel, sDescription) {}
virtual ~CEmailJob() {}
protected:
virtual void RunJob();
};
class CEmail : public CModule
{
public:
MODCONSTRUCTOR(CEmail)
{
m_iLastCheck = 0;
m_bInitialized = false;
}
virtual ~CEmail() {}
virtual bool OnLoad(const CString & sArgs, CString& sMessage) {
m_sMailPath = sArgs;
StartParser();
if (m_pUser->IsUserAttached())
StartTimer();
return true;
}
virtual void OnClientLogin()
{
stringstream s;
s << "You have " << m_ssUidls.size() << " emails.";
PutModule(s.str());
StartTimer();
}
virtual void OnClientDisconnect()
{
RemTimer("EMAIL::" + m_pUser->GetUserName());
}
void StartTimer()
{
if (!FindTimer("EMAIL::" + m_pUser->GetUserName()))
{
CEmailJob *p = new CEmailJob(this, 60, 0, "EmailMonitor", "Monitors email activity");
AddTimer(p);
}
}
virtual void OnModCommand(const CString& sCommand);
void StartParser();
void ParseEmails(const vector<EmailST> & vEmails)
{
if (!m_bInitialized)
{
m_bInitialized = true;
for (u_int a = 0; a < vEmails.size(); a++)
m_ssUidls.insert(vEmails[a].sUidl);
stringstream s;
s << "You have " << vEmails.size() << " emails.";
PutModule(s.str());
} else
{
set<CString> ssUidls;
CTable Table;
Table.AddColumn("From");
Table.AddColumn("Size");
Table.AddColumn("Subject");
for (u_int a = 0; a < vEmails.size(); a++)
{
if (m_ssUidls.find(vEmails[a].sUidl) == m_ssUidls.end())
{
//PutModule("------------------- New Email -------------------");
Table.AddRow();
Table.SetCell("From", vEmails[a].sFrom.Ellipsize(32));
Table.SetCell("Size", CString(vEmails[a].iSize));
Table.SetCell("Subject", vEmails[a].sSubject.Ellipsize(64));
}
ssUidls.insert(vEmails[a].sUidl);
}
m_ssUidls = ssUidls; // keep the list in synch
if (Table.size()) {
PutModule(Table);
stringstream s;
s << "You have " << vEmails.size() << " emails.";
PutModule(s.str());
}
}
}
private:
CString m_sMailPath;
time_t m_iLastCheck;
set<CString> m_ssUidls;
bool m_bInitialized;
};
class CEmailFolder : public CSocket
{
public:
CEmailFolder(CEmail *pModule, const CString & sMailbox) : CSocket(pModule)
{
m_pModule = pModule;
m_sMailbox = sMailbox;
EnableReadLine();
}
virtual ~CEmailFolder()
{
if (!m_sMailBuffer.empty())
ProcessMail(); // get the last one
if (!m_vEmails.empty())
m_pModule->ParseEmails(m_vEmails);
}
virtual void ReadLine(const CS_STRING & sLine)
{
if (sLine.substr(0, 5) == "From ")
{
if (!m_sMailBuffer.empty())
{
ProcessMail();
m_sMailBuffer.clear();
}
}
m_sMailBuffer += sLine;
}
void ProcessMail()
{
EmailST tmp;
tmp.sUidl = (char *)CMD5(m_sMailBuffer.substr(0, 255));
VCString vsLines;
VCString::iterator it;
m_sMailBuffer.Split("\n", vsLines);
for (it = vsLines.begin(); it != vsLines.end(); it++) {
CString sLine(*it);
sLine.Trim();
if (sLine.empty())
break; // out of the headers
if (sLine.Equals("From: ", false, 6))
tmp.sFrom = sLine.substr(6, CString::npos);
else if (sLine.Equals("Subject: ", false, 9))
tmp.sSubject = sLine.substr(9, CString::npos);
if ((!tmp.sFrom.empty()) && (!tmp.sSubject.empty()))
break;
}
tmp.iSize = m_sMailBuffer.length();
m_vEmails.push_back(tmp);
}
private:
CEmail *m_pModule;
CString m_sMailbox;
CString m_sMailBuffer;
vector<EmailST> m_vEmails;
};
void CEmail::OnModCommand(const CString& sCommand)
{
CString::size_type iPos = sCommand.find(" ");
CString sCom, sArgs;
if (iPos == CString::npos)
sCom = sCommand;
else
{
sCom = sCommand.substr(0, iPos);
sArgs = sCommand.substr(iPos + 1, CString::npos);
}
if (sCom == "timers")
{
ListTimers();
} else
PutModule("Error, no such command [" + sCom + "]");
}
void CEmail::StartParser()
{
CString sParserName = "EMAIL::" + m_pUser->GetUserName();
if (m_pManager->FindSockByName(sParserName))
return; // one at a time sucker
CFile cFile(m_sMailPath);
if ((!cFile.Exists()) || (cFile.GetSize() == 0))
{
m_bInitialized = true;
return; // der
}
if (cFile.GetMTime() <= m_iLastCheck)
return; // only check if modified
int iFD = open(m_sMailPath.c_str(), O_RDONLY);
if (iFD >= 0)
{
m_iLastCheck = time(NULL);
CEmailFolder *p = new CEmailFolder(this, m_sMailPath);
p->SetRSock(iFD);
p->SetWSock(iFD);
m_pManager->AddSock(p, "EMAIL::" + m_pUser->GetUserName());
}
}
void CEmailJob::RunJob()
{
CEmail *p = (CEmail *)m_pModule;
p->StartParser();
}
MODULEDEFS(CEmail, "Monitors Email activity on local disk /var/mail/user")
<|endoftext|> |
<commit_before>/* Copyright (C) 2013, Morris Moraes <[email protected]>
Copyright (C) 2014, Stefan Hacker <[email protected]>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
- Neither the name of the Mumble Developers 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 FOUNDATION 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 "murmur_pch.h"
#include "PBKDF2.h"
int PBKDF2::benchmark() {
const QString pseudopass(QLatin1String("aboutAvg"));
const QString hexSalt = getSalt(); // Could tolerate not getting a salt here, will likely only make it harder.
int maxIterations = -1;
QElapsedTimer timer;
timer.start();
for (size_t i = 0; i < BENCHMARK_N; ++i) {
int iterations = BENCHMARK_MINIMUM_ITERATION_COUNT / 2;
timer.restart();
do {
iterations *= 2;
// Store return value in a volatile to prevent optimizer
// from ever removing these side-effect-free calls. I don't
// think the compiler can prove they have no side-effects but
// better safe than sorry.
volatile QString result = getHash(hexSalt, pseudopass, iterations);
Q_UNUSED(result);
} while (timer.restart() < BENCHMARK_DURATION_TARGET_IN_MS && (iterations / 2) < std::numeric_limits<int>::max());
if (iterations > maxIterations) {
maxIterations = iterations;
}
}
return maxIterations;
}
QString PBKDF2::getHash(const QString &hexSalt, const QString &password, int iterationCount) {
#if OPENSSL_VERSION >= 0x00090900fL
QByteArray hash(DERIVED_KEY_LENGTH, 0);
const QByteArray utf8Password = password.toUtf8();
const QByteArray salt = QByteArray::fromHex(hexSalt.toLatin1());
if (PKCS5_PBKDF2_HMAC(utf8Password.constData(), utf8Password.size(),
reinterpret_cast<const unsigned char*>(salt.constData()), salt.size(),
iterationCount,
EVP_sha384(),
DERIVED_KEY_LENGTH, reinterpret_cast<unsigned char*>(hash.data())) == 0) {
qFatal("PBKDF2: PKCS5_PBKDF2_HMAC failed: %s", ERR_error_string(ERR_get_error(), NULL));
return QString();
}
return hash.toHex();
#else
Q_UNUSED(hexSalt);
Q_UNUSED(password);
Q_UNUSED(iterationCount);
qFatal("PBKDF2::getHash() is not implemented. System's OpenSSL is too old.");
return QString();
#endif
}
QString PBKDF2::getSalt() {
QByteArray salt(SALT_LENGTH, 0);
if (RAND_bytes(reinterpret_cast<unsigned char*>(salt.data()), salt.size()) != 1) {
qFatal("PBKDF2: RAND_bytes for salt failed: %s", ERR_error_string(ERR_get_error(), NULL));
return QString();
}
return salt.toHex();
}
<commit_msg>Murmur: use OPENSSL_VERSION_NUMBER instead of OPENSSL_VERSION.<commit_after>/* Copyright (C) 2013, Morris Moraes <[email protected]>
Copyright (C) 2014, Stefan Hacker <[email protected]>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
- Neither the name of the Mumble Developers 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 FOUNDATION 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 "murmur_pch.h"
#include "PBKDF2.h"
int PBKDF2::benchmark() {
const QString pseudopass(QLatin1String("aboutAvg"));
const QString hexSalt = getSalt(); // Could tolerate not getting a salt here, will likely only make it harder.
int maxIterations = -1;
QElapsedTimer timer;
timer.start();
for (size_t i = 0; i < BENCHMARK_N; ++i) {
int iterations = BENCHMARK_MINIMUM_ITERATION_COUNT / 2;
timer.restart();
do {
iterations *= 2;
// Store return value in a volatile to prevent optimizer
// from ever removing these side-effect-free calls. I don't
// think the compiler can prove they have no side-effects but
// better safe than sorry.
volatile QString result = getHash(hexSalt, pseudopass, iterations);
Q_UNUSED(result);
} while (timer.restart() < BENCHMARK_DURATION_TARGET_IN_MS && (iterations / 2) < std::numeric_limits<int>::max());
if (iterations > maxIterations) {
maxIterations = iterations;
}
}
return maxIterations;
}
QString PBKDF2::getHash(const QString &hexSalt, const QString &password, int iterationCount) {
#if OPENSSL_VERSION_NUMBER >= 0x00090900fL
QByteArray hash(DERIVED_KEY_LENGTH, 0);
const QByteArray utf8Password = password.toUtf8();
const QByteArray salt = QByteArray::fromHex(hexSalt.toLatin1());
if (PKCS5_PBKDF2_HMAC(utf8Password.constData(), utf8Password.size(),
reinterpret_cast<const unsigned char*>(salt.constData()), salt.size(),
iterationCount,
EVP_sha384(),
DERIVED_KEY_LENGTH, reinterpret_cast<unsigned char*>(hash.data())) == 0) {
qFatal("PBKDF2: PKCS5_PBKDF2_HMAC failed: %s", ERR_error_string(ERR_get_error(), NULL));
return QString();
}
return hash.toHex();
#else
Q_UNUSED(hexSalt);
Q_UNUSED(password);
Q_UNUSED(iterationCount);
qFatal("PBKDF2::getHash() is not implemented. System's OpenSSL is too old.");
return QString();
#endif
}
QString PBKDF2::getSalt() {
QByteArray salt(SALT_LENGTH, 0);
if (RAND_bytes(reinterpret_cast<unsigned char*>(salt.data()), salt.size()) != 1) {
qFatal("PBKDF2: RAND_bytes for salt failed: %s", ERR_error_string(ERR_get_error(), NULL));
return QString();
}
return salt.toHex();
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2015, Potion Design LLC
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of copyright holder 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 "poSpritesheetAnimation.h"
#include "cinder/app/App.h"
namespace po
{
SpritesheetAnimationRef SpritesheetAnimation::create( SpritesheetRef spritesheet, float fps )
{
SpritesheetAnimationRef ref( new SpritesheetAnimation() );
ref->setup( spritesheet, fps );
return ref;
}
SpritesheetAnimation::SpritesheetAnimation()
: mCurrentFrame( 0 )
, mIsPlaying( false )
, mIsLooping( false )
, mFPS( 12.f )
, mPreviousTime( 0.f )
, mCurrentTime( 0.f )
, mIsReverse( false )
{}
SpritesheetAnimation::~SpritesheetAnimation()
{}
void SpritesheetAnimation::setup( SpritesheetRef spritesheet, float fps )
{
mSpritesheet = spritesheet;
setFrameRate( fps );
mLastFrame = mSpritesheet->getNumFrames() - 1;
}
//
// Goto the next frame based on fps
//
void SpritesheetAnimation::update()
{
if( mIsPlaying ) {
mCurrentTime = ci::app::getElapsedSeconds() * 1000;
float timeDiff = mCurrentTime - mPreviousTime;
if( timeDiff > mFrameRate ) {
float over = timeDiff - mFrameRate;
mPreviousTime = mCurrentTime - over;
nextFrame();
}
}
}
//
// Draw the current frame in the texture
//
void SpritesheetAnimation::draw()
{
mSpritesheet->drawFrame( mCurrentFrame );
}
//
// Set the frame rate
//
void SpritesheetAnimation::setFrameRate( float frameRate )
{
mFPS = frameRate;
mFrameRate = 1000.f / mFPS;
}
//
// Go to the next frame
//
void SpritesheetAnimation::nextFrame()
{
if( mIsPlaying ) {
if( mIsReverse ) {
mCurrentFrame = ( mCurrentFrame -= 1 ) % mSpritesheet->getNumFrames();
}
else {
mCurrentFrame = ( mCurrentFrame += 1 ) % mSpritesheet->getNumFrames();
}
if( !mIsLooping ) {
int targetFrame = !mIsReverse ? mLastFrame : 0;
if( mCurrentFrame == targetFrame ) {
mIsPlaying = false;
mPlayCompleteSignal.emit( shared_from_this() );
}
}
}
}
//
// Start Playing
//
void SpritesheetAnimation::play()
{
mPreviousTime = ci::app::getElapsedSeconds() * 1000.0f;
mIsPlaying = true;
}
//
// Stop playing
//
void SpritesheetAnimation::stop()
{
mIsPlaying = false;
if( mIsReverse ) {
mCurrentFrame = mSpritesheet->getNumFrames() - 1;
}
else {
mCurrentFrame = 0;
}
}
//
// Play in reverse
//
void SpritesheetAnimation::setIsReverse( bool reverse, bool andSkipToStartFrame )
{
mIsReverse = reverse;
if( andSkipToStartFrame ) {
if( mIsReverse ) {
if( mCurrentFrame == 0 ) {
mCurrentFrame = mSpritesheet->getNumFrames() - 1;
}
mLastFrame = 0;
}
else {
mLastFrame = mSpritesheet->getNumFrames() - 1;
}
}
}
}<commit_msg>Guarding against going too far forward or backward on update<commit_after>/*
Copyright (c) 2015, Potion Design LLC
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of copyright holder 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 "poSpritesheetAnimation.h"
#include "cinder/app/App.h"
namespace po
{
SpritesheetAnimationRef SpritesheetAnimation::create( SpritesheetRef spritesheet, float fps )
{
SpritesheetAnimationRef ref( new SpritesheetAnimation() );
ref->setup( spritesheet, fps );
return ref;
}
SpritesheetAnimation::SpritesheetAnimation()
: mCurrentFrame( 0 )
, mIsPlaying( false )
, mIsLooping( false )
, mFPS( 12.f )
, mPreviousTime( 0.f )
, mCurrentTime( 0.f )
, mIsReverse( false )
{}
SpritesheetAnimation::~SpritesheetAnimation()
{}
void SpritesheetAnimation::setup( SpritesheetRef spritesheet, float fps )
{
mSpritesheet = spritesheet;
setFrameRate( fps );
mLastFrame = mSpritesheet->getNumFrames() - 1;
}
//
// Goto the next frame based on fps
//
void SpritesheetAnimation::update()
{
if( mIsPlaying ) {
mCurrentTime = ci::app::getElapsedSeconds() * 1000;
float timeDiff = mCurrentTime - mPreviousTime;
if( timeDiff > mFrameRate ) {
float over = timeDiff - mFrameRate;
mPreviousTime = mCurrentTime - over;
nextFrame();
}
}
}
//
// Draw the current frame in the texture
//
void SpritesheetAnimation::draw()
{
mSpritesheet->drawFrame( mCurrentFrame );
}
//
// Set the frame rate
//
void SpritesheetAnimation::setFrameRate( float frameRate )
{
mFPS = frameRate;
mFrameRate = 1000.f / mFPS;
}
//
// Go to the next frame
//
void SpritesheetAnimation::nextFrame()
{
if( mIsPlaying ) {
if( mIsReverse ) {
mCurrentFrame = ( mCurrentFrame -= 1 ) % mSpritesheet->getNumFrames();
if( mCurrentFrame < 0 ) { mCurrentFrame = 0; }
}
else {
mCurrentFrame = ( mCurrentFrame += 1 ) % mSpritesheet->getNumFrames();
if( mCurrentFrame > mLastFrame ) { mCurrentFrame = mLastFrame; }
}
if( !mIsLooping ) {
int targetFrame = !mIsReverse ? mLastFrame : 0;
if( mCurrentFrame == targetFrame ) {
mIsPlaying = false;
mPlayCompleteSignal.emit( shared_from_this() );
}
}
}
}
//
// Start Playing
//
void SpritesheetAnimation::play()
{
mPreviousTime = ci::app::getElapsedSeconds() * 1000.0f;
mIsPlaying = true;
}
//
// Stop playing
//
void SpritesheetAnimation::stop()
{
mIsPlaying = false;
if( mIsReverse ) {
mCurrentFrame = mSpritesheet->getNumFrames() - 1;
}
else {
mCurrentFrame = 0;
}
}
//
// Play in reverse
//
void SpritesheetAnimation::setIsReverse( bool reverse, bool andSkipToStartFrame )
{
mIsReverse = reverse;
if( andSkipToStartFrame ) {
if( mIsReverse ) {
if( mCurrentFrame == 0 ) {
mCurrentFrame = mSpritesheet->getNumFrames() - 1;
}
mLastFrame = 0;
}
else {
mLastFrame = mSpritesheet->getNumFrames() - 1;
}
}
}
}<|endoftext|> |
<commit_before>#include <cassert>
#include "Channel.h"
#include "EventLoop.h"
using namespace dodo::net;
namespace dodo
{
namespace net
{
#ifdef PLATFORM_WINDOWS
class WakeupChannel final : public Channel, public NonCopyable
{
public:
WakeupChannel(HANDLE iocp) : mIOCP(iocp), mWakeupOvl(EventLoop::OLV_VALUE::OVL_RECV)
{
}
void wakeup()
{
PostQueuedCompletionStatus(mIOCP, 0, (ULONG_PTR)this, (OVERLAPPED*)&mWakeupOvl);
}
private:
void canRecv() override
{
}
void canSend() override
{
}
void onClose() override
{
}
private:
HANDLE mIOCP;
EventLoop::ovl_ext_s mWakeupOvl;
};
#else
class WakeupChannel final : public Channel, public NonCopyable
{
public:
explicit WakeupChannel(sock fd) : mFd(fd)
{
}
void wakeup()
{
uint64_t one = 1;
write(mFd, &one, sizeof one);
}
~WakeupChannel()
{
close(mFd);
mFd = SOCKET_ERROR;
}
private:
void canRecv() override
{
char temp[1024 * 10];
while (true)
{
auto n = read(mFd, temp, sizeof(temp));
if (n == -1)
{
break;
}
}
}
void canSend() override
{
}
void onClose() override
{
}
private:
sock mFd;
};
#endif
}
}
EventLoop::EventLoop()
#ifdef PLATFORM_WINDOWS
: mIOCP(CreateIoCompletionPort(INVALID_HANDLE_VALUE, 0, 0, 1)), mWakeupChannel(new WakeupChannel(mIOCP))
#else
: mEpollFd = epoll_create(1)
#endif
{
#ifdef PLATFORM_WINDOWS
mPGetQueuedCompletionStatusEx = NULL;
auto kernel32_module = GetModuleHandleA("kernel32.dll");
if (kernel32_module != NULL) {
mPGetQueuedCompletionStatusEx = (sGetQueuedCompletionStatusEx)GetProcAddress(
kernel32_module,
"GetQueuedCompletionStatusEx");
FreeLibrary(kernel32_module);
}
#else
auto eventfd = ::eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
mWakeupChannel.reset(new WakeupChannel(eventfd));
linkChannel(eventfd, mWakeupChannel.get());
#endif
mIsAlreadyPostWakeup = false;
mIsInBlock = true;
mEventEntries = NULL;
mEventEntriesNum = 0;
reallocEventSize(1024);
mSelfThreadid = -1;
mIsInitThreadID = false;
mTimer = std::make_shared<TimerMgr>();
}
EventLoop::~EventLoop()
{
#ifdef PLATFORM_WINDOWS
CloseHandle(mIOCP);
mIOCP = INVALID_HANDLE_VALUE;
#else
close(mEpollFd);
mEpollFd = -1;
#endif
delete[] mEventEntries;
mEventEntries = nullptr;
}
dodo::TimerMgr::PTR EventLoop::getTimerMgr()
{
tryInitThreadID();
assert(isInLoopThread());
return isInLoopThread() ? mTimer : nullptr;
}
inline void EventLoop::tryInitThreadID()
{
if (!mIsInitThreadID && !mIsInitThreadID.exchange(true))
{
mSelfThreadid = CurrentThread::tid();
}
}
void EventLoop::loop(int64_t timeout)
{
tryInitThreadID();
#ifndef NDEBUG
assert(isInLoopThread());
#endif
if (!isInLoopThread())
{
return;
}
/* warn::mAfterLoopProcsΪգĿǰһloop(ʱ֮ǰ˻صijỰϿỰϢ²callbacktimeoutΪ0ʾiocp/epoll wait */
if (!mAfterLoopProcs.empty())
{
timeout = 0;
}
#ifdef PLATFORM_WINDOWS
ULONG numComplete = 0;
if (mPGetQueuedCompletionStatusEx != nullptr)
{
if (!mPGetQueuedCompletionStatusEx(mIOCP, mEventEntries, static_cast<ULONG>(mEventEntriesNum), &numComplete, static_cast<DWORD>(timeout), false))
{
numComplete = 0;
}
}
else
{
/*GQCSʧܲ账ֻϲclosesocketŷonRecvеõ(ͷŻỰԴ)*/
do
{
GetQueuedCompletionStatus(mIOCP,
&mEventEntries[numComplete].dwNumberOfBytesTransferred,
&mEventEntries[numComplete].lpCompletionKey,
&mEventEntries[numComplete].lpOverlapped,
(numComplete == 0) ? static_cast<DWORD>(timeout) : 0);
} while (mEventEntries[numComplete].lpOverlapped != nullptr && ++numComplete < mEventEntriesNum);
}
mIsInBlock = false;
for (ULONG i = 0; i < numComplete; ++i)
{
auto channel = (Channel*)mEventEntries[i].lpCompletionKey;
auto ovl = (EventLoop::ovl_ext_s*)mEventEntries[i].lpOverlapped;
if (ovl->OP == EventLoop::OLV_VALUE::OVL_RECV)
{
channel->canRecv();
}
else if (ovl->OP == EventLoop::OLV_VALUE::OVL_SEND)
{
channel->canSend();
}
else
{
assert(false);
}
}
#else
int numComplete = epoll_wait(mEpollFd, mEventEntries, mEventEntriesNum, timeout);
mIsInBlock = false;
for (int i = 0; i < numComplete; ++i)
{
auto channel = (Channel*)(mEventEntries[i].data.ptr);
auto event_data = mEventEntries[i].events;
if (event_data & EPOLLRDHUP)
{
channel->canRecv();
channel->onClose(); /* öϿ(ȫģظclose)ԷcanRecvûrecv Ͽ֪ͨ*/
}
else
{
if (event_data & EPOLLIN)
{
channel->canRecv();
}
if (event_data & EPOLLOUT)
{
channel->canSend();
}
}
}
#endif
mIsAlreadyPostWakeup = false;
mIsInBlock = true;
processAsyncProcs();
processAfterLoopProcs();
if (numComplete == mEventEntriesNum)
{
/* ¼ˣ¼дСһepoll/iocp waitþܸ֪ͨ */
reallocEventSize(mEventEntriesNum + 128);
}
mTimer->schedule();
}
void EventLoop::processAfterLoopProcs()
{
mCopyAfterLoopProcs.swap(mAfterLoopProcs);
for (auto& x : mCopyAfterLoopProcs)
{
x();
}
mCopyAfterLoopProcs.clear();
}
void EventLoop::processAsyncProcs()
{
mAsyncProcsMutex.lock();
mCopyAsyncProcs.swap(mAsyncProcs);
mAsyncProcsMutex.unlock();
for (auto& x : mCopyAsyncProcs)
{
x();
}
mCopyAsyncProcs.clear();
}
bool EventLoop::wakeup()
{
bool ret = false;
if (!isInLoopThread() && mIsInBlock && !mIsAlreadyPostWakeup.exchange(true))
{
mWakeupChannel->wakeup();
ret = true;
}
return ret;
}
bool EventLoop::linkChannel(sock fd, Channel* ptr)
{
#ifdef PLATFORM_WINDOWS
return CreateIoCompletionPort((HANDLE)fd, mIOCP, (ULONG_PTR)ptr, 0) != nullptr;
#else
struct epoll_event ev = { 0, { 0 } };
ev.events = EPOLLET | EPOLLIN | EPOLLRDHUP;
ev.data.ptr = ptr;
return epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &ev) == 0;
#endif
}
void EventLoop::pushAsyncProc(const USER_PROC& f)
{
if (!isInLoopThread())
{
mAsyncProcsMutex.lock();
mAsyncProcs.push_back(f);
mAsyncProcsMutex.unlock();
wakeup();
}
else
{
f();
}
}
void EventLoop::pushAsyncProc(USER_PROC&& f)
{
if (!isInLoopThread())
{
mAsyncProcsMutex.lock();
mAsyncProcs.push_back(std::move(f));
mAsyncProcsMutex.unlock();
wakeup();
}
else
{
f();
}
}
void EventLoop::pushAfterLoopProc(const USER_PROC& f)
{
assert(isInLoopThread());
if (isInLoopThread())
{
mAfterLoopProcs.push_back(f);
}
}
void EventLoop::pushAfterLoopProc(USER_PROC&& f)
{
assert(isInLoopThread());
if (isInLoopThread())
{
mAfterLoopProcs.push_back(std::move(f));
}
}
#ifndef PLATFORM_WINDOWS
int EventLoop::getEpollHandle() const
{
return mEpollFd;
}
#endif
void EventLoop::reallocEventSize(size_t size)
{
if (mEventEntries != NULL)
{
delete[] mEventEntries;
}
#ifdef PLATFORM_WINDOWS
mEventEntries = new OVERLAPPED_ENTRY[size];
#else
mEventEntries = new epoll_event[size];
#endif
mEventEntriesNum = size;
}<commit_msg>1:fixed compiler error<commit_after>#include <cassert>
#include "Channel.h"
#include "EventLoop.h"
using namespace dodo::net;
namespace dodo
{
namespace net
{
#ifdef PLATFORM_WINDOWS
class WakeupChannel final : public Channel, public NonCopyable
{
public:
WakeupChannel(HANDLE iocp) : mIOCP(iocp), mWakeupOvl(EventLoop::OLV_VALUE::OVL_RECV)
{
}
void wakeup()
{
PostQueuedCompletionStatus(mIOCP, 0, (ULONG_PTR)this, (OVERLAPPED*)&mWakeupOvl);
}
private:
void canRecv() override
{
}
void canSend() override
{
}
void onClose() override
{
}
private:
HANDLE mIOCP;
EventLoop::ovl_ext_s mWakeupOvl;
};
#else
class WakeupChannel final : public Channel, public NonCopyable
{
public:
explicit WakeupChannel(sock fd) : mFd(fd)
{
}
void wakeup()
{
uint64_t one = 1;
write(mFd, &one, sizeof one);
}
~WakeupChannel()
{
close(mFd);
mFd = SOCKET_ERROR;
}
private:
void canRecv() override
{
char temp[1024 * 10];
while (true)
{
auto n = read(mFd, temp, sizeof(temp));
if (n == -1)
{
break;
}
}
}
void canSend() override
{
}
void onClose() override
{
}
private:
sock mFd;
};
#endif
}
}
EventLoop::EventLoop()
#ifdef PLATFORM_WINDOWS
: mIOCP(CreateIoCompletionPort(INVALID_HANDLE_VALUE, 0, 0, 1)), mWakeupChannel(new WakeupChannel(mIOCP))
#else
: mEpollFd(epoll_create(1))
#endif
{
#ifdef PLATFORM_WINDOWS
mPGetQueuedCompletionStatusEx = NULL;
auto kernel32_module = GetModuleHandleA("kernel32.dll");
if (kernel32_module != NULL) {
mPGetQueuedCompletionStatusEx = (sGetQueuedCompletionStatusEx)GetProcAddress(
kernel32_module,
"GetQueuedCompletionStatusEx");
FreeLibrary(kernel32_module);
}
#else
auto eventfd = ::eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
mWakeupChannel.reset(new WakeupChannel(eventfd));
linkChannel(eventfd, mWakeupChannel.get());
#endif
mIsAlreadyPostWakeup = false;
mIsInBlock = true;
mEventEntries = NULL;
mEventEntriesNum = 0;
reallocEventSize(1024);
mSelfThreadid = -1;
mIsInitThreadID = false;
mTimer = std::make_shared<TimerMgr>();
}
EventLoop::~EventLoop()
{
#ifdef PLATFORM_WINDOWS
CloseHandle(mIOCP);
mIOCP = INVALID_HANDLE_VALUE;
#else
close(mEpollFd);
mEpollFd = -1;
#endif
delete[] mEventEntries;
mEventEntries = nullptr;
}
dodo::TimerMgr::PTR EventLoop::getTimerMgr()
{
tryInitThreadID();
assert(isInLoopThread());
return isInLoopThread() ? mTimer : nullptr;
}
inline void EventLoop::tryInitThreadID()
{
if (!mIsInitThreadID && !mIsInitThreadID.exchange(true))
{
mSelfThreadid = CurrentThread::tid();
}
}
void EventLoop::loop(int64_t timeout)
{
tryInitThreadID();
#ifndef NDEBUG
assert(isInLoopThread());
#endif
if (!isInLoopThread())
{
return;
}
/* warn::mAfterLoopProcsΪգĿǰһloop(ʱ֮ǰ˻صijỰϿỰϢ²callbacktimeoutΪ0ʾiocp/epoll wait */
if (!mAfterLoopProcs.empty())
{
timeout = 0;
}
#ifdef PLATFORM_WINDOWS
ULONG numComplete = 0;
if (mPGetQueuedCompletionStatusEx != nullptr)
{
if (!mPGetQueuedCompletionStatusEx(mIOCP, mEventEntries, static_cast<ULONG>(mEventEntriesNum), &numComplete, static_cast<DWORD>(timeout), false))
{
numComplete = 0;
}
}
else
{
/*GQCSʧܲ账ֻϲclosesocketŷonRecvеõ(ͷŻỰԴ)*/
do
{
GetQueuedCompletionStatus(mIOCP,
&mEventEntries[numComplete].dwNumberOfBytesTransferred,
&mEventEntries[numComplete].lpCompletionKey,
&mEventEntries[numComplete].lpOverlapped,
(numComplete == 0) ? static_cast<DWORD>(timeout) : 0);
} while (mEventEntries[numComplete].lpOverlapped != nullptr && ++numComplete < mEventEntriesNum);
}
mIsInBlock = false;
for (ULONG i = 0; i < numComplete; ++i)
{
auto channel = (Channel*)mEventEntries[i].lpCompletionKey;
auto ovl = (EventLoop::ovl_ext_s*)mEventEntries[i].lpOverlapped;
if (ovl->OP == EventLoop::OLV_VALUE::OVL_RECV)
{
channel->canRecv();
}
else if (ovl->OP == EventLoop::OLV_VALUE::OVL_SEND)
{
channel->canSend();
}
else
{
assert(false);
}
}
#else
int numComplete = epoll_wait(mEpollFd, mEventEntries, mEventEntriesNum, timeout);
mIsInBlock = false;
for (int i = 0; i < numComplete; ++i)
{
auto channel = (Channel*)(mEventEntries[i].data.ptr);
auto event_data = mEventEntries[i].events;
if (event_data & EPOLLRDHUP)
{
channel->canRecv();
channel->onClose(); /* öϿ(ȫģظclose)ԷcanRecvûrecv Ͽ֪ͨ*/
}
else
{
if (event_data & EPOLLIN)
{
channel->canRecv();
}
if (event_data & EPOLLOUT)
{
channel->canSend();
}
}
}
#endif
mIsAlreadyPostWakeup = false;
mIsInBlock = true;
processAsyncProcs();
processAfterLoopProcs();
if (numComplete == mEventEntriesNum)
{
/* ¼ˣ¼дСһepoll/iocp waitþܸ֪ͨ */
reallocEventSize(mEventEntriesNum + 128);
}
mTimer->schedule();
}
void EventLoop::processAfterLoopProcs()
{
mCopyAfterLoopProcs.swap(mAfterLoopProcs);
for (auto& x : mCopyAfterLoopProcs)
{
x();
}
mCopyAfterLoopProcs.clear();
}
void EventLoop::processAsyncProcs()
{
mAsyncProcsMutex.lock();
mCopyAsyncProcs.swap(mAsyncProcs);
mAsyncProcsMutex.unlock();
for (auto& x : mCopyAsyncProcs)
{
x();
}
mCopyAsyncProcs.clear();
}
bool EventLoop::wakeup()
{
bool ret = false;
if (!isInLoopThread() && mIsInBlock && !mIsAlreadyPostWakeup.exchange(true))
{
mWakeupChannel->wakeup();
ret = true;
}
return ret;
}
bool EventLoop::linkChannel(sock fd, Channel* ptr)
{
#ifdef PLATFORM_WINDOWS
return CreateIoCompletionPort((HANDLE)fd, mIOCP, (ULONG_PTR)ptr, 0) != nullptr;
#else
struct epoll_event ev = { 0, { 0 } };
ev.events = EPOLLET | EPOLLIN | EPOLLRDHUP;
ev.data.ptr = ptr;
return epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &ev) == 0;
#endif
}
void EventLoop::pushAsyncProc(const USER_PROC& f)
{
if (!isInLoopThread())
{
mAsyncProcsMutex.lock();
mAsyncProcs.push_back(f);
mAsyncProcsMutex.unlock();
wakeup();
}
else
{
f();
}
}
void EventLoop::pushAsyncProc(USER_PROC&& f)
{
if (!isInLoopThread())
{
mAsyncProcsMutex.lock();
mAsyncProcs.push_back(std::move(f));
mAsyncProcsMutex.unlock();
wakeup();
}
else
{
f();
}
}
void EventLoop::pushAfterLoopProc(const USER_PROC& f)
{
assert(isInLoopThread());
if (isInLoopThread())
{
mAfterLoopProcs.push_back(f);
}
}
void EventLoop::pushAfterLoopProc(USER_PROC&& f)
{
assert(isInLoopThread());
if (isInLoopThread())
{
mAfterLoopProcs.push_back(std::move(f));
}
}
#ifndef PLATFORM_WINDOWS
int EventLoop::getEpollHandle() const
{
return mEpollFd;
}
#endif
void EventLoop::reallocEventSize(size_t size)
{
if (mEventEntries != NULL)
{
delete[] mEventEntries;
}
#ifdef PLATFORM_WINDOWS
mEventEntries = new OVERLAPPED_ENTRY[size];
#else
mEventEntries = new epoll_event[size];
#endif
mEventEntriesNum = size;
}
<|endoftext|> |
<commit_before>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2010 Belledonne Communications SARL.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "agent.hh"
class ContactRouteInserter : public Module {
public:
ContactRouteInserter(Agent *ag):Module(ag){
}
void onDeclare(ConfigStruct *module_config){
ConfigItemDescriptor items[]={
{ Boolean , "masquerade-contacts-for-invites", "Hack for workarounding Nortel CS2k gateways bug.","false"},
config_item_end
};
module_config->addChildrenValues(items);
}
void onLoad(Agent *agent, const ConfigStruct *module_config){
mContactRouteParamName=std::string("CtRt")+getAgent()->getUniqueId();
mMasqueradeInviteContacts=module_config->get<ConfigBoolean>("masquerade-contacts-for-invites")->read();
}
void onRequest(SipEvent *ev) {
sip_t *sip=ev->mSip;
if(sip->sip_request->rq_method == sip_method_register ||
((sip->sip_request->rq_method == sip_method_invite ) && mMasqueradeInviteContacts)){
//rewrite the request uri to the domain
//this assume the domain is also the proxy
sip->sip_request->rq_url->url_host=sip->sip_to->a_url->url_host;
sip->sip_request->rq_url->url_port=sip->sip_to->a_url->url_port;
if (sip->sip_contact!=NULL && sip->sip_contact->m_url!=NULL){
//rewrite contact, put local host instead and store previous contact host in new parameter
char ct_tport[32]="udp";
char* lParam;
url_t *ct_url=sip->sip_contact->m_url;
//grab the transport of the contact uri
if (url_param(sip->sip_contact->m_url->url_params,"transport",ct_tport,sizeof(ct_tport))>0){
}
/*add a parameter like "CtRt15.128.128.2=tcp:201.45.118.16:50025" in the contact, so that we know where is the client
when we later have to route an INVITE to him */
lParam=su_sprintf (ev->getHome(),"%s=%s:%s:%s",mContactRouteParamName.c_str()
,ct_tport
,ct_url->url_host
,ct_url->url_port);
LOGD("Rewriting contact with param [%s]",lParam);
if (url_param_add (ev->getHome(),ct_url,lParam)) {
LOGE("Cannot insert url param [%s]",lParam);
}
/*masquerade the contact, so that later requests (INVITEs) come to us */
ct_url->url_host = getAgent()->getLocAddr().c_str();
ct_url->url_port = su_sprintf (ev->getHome(),"%i",getAgent()->getPort());
/*remove the transport, in most case further requests should come back to us in UDP*/
ct_url->url_params = url_strip_param_string(su_strdup(ev->getHome(),ct_url->url_params),"transport");
}
}
if (sip->sip_request->rq_method != sip_method_register){
/* check if request-uri contains a contact-route parameter, so that we can route back to the client */
char contact_route_param[64];
url_t *dest=sip->sip_request->rq_url;
// now need to check if request uri has special param inserted by contact-route-inserter module
if (url_param(dest->url_params,mContactRouteParamName.c_str(),contact_route_param,sizeof(contact_route_param))) {
//first remove param
dest->url_params = url_strip_param_string(su_strdup(ev->getHome(),dest->url_params),mContactRouteParamName.c_str());
//test and remove maddr param
if (url_has_param(dest,"maddr")) {
dest->url_params = url_strip_param_string(su_strdup(ev->getHome(),dest->url_params),"maddr");
}
//second change dest to
char* tmp = strchr(contact_route_param, ':');
if (tmp){
char* transport=su_strndup(ev->getHome(),contact_route_param,tmp-contact_route_param);
char *tmp2=tmp+1;
tmp=strchr(tmp2, ':');
if (tmp){
dest->url_host=su_strndup(ev->getHome(), tmp2, tmp-tmp2 );
dest->url_port=su_strdup(ev->getHome(), tmp+1);
if (strcasecmp(transport,"udp")!=0){
char *t_param=su_sprintf (ev->getHome(),"transport=%s",transport);
url_param_add(ev->getHome(),dest,t_param);
}
}
}
}
}
}
void onResponse(SipEvent *ev) {/*nop*/};
private:
std::string mContactRouteParamName;
bool mMasqueradeInviteContacts;
static ModuleInfo<ContactRouteInserter> sInfo;
};
ModuleInfo<ContactRouteInserter> ContactRouteInserter::sInfo("ContactRouteInserter",
"The purpose of the ContactRouteInserter module is to masquerade the contact header of incoming registers that are not handled locally "
"(think about flexisip used as a SBC gateway) in such a way that it is then possible to route back outgoing invites to the original address. "
"It is a kind of similar mechanism as Record-Route, but for REGISTER.");
<commit_msg>enhance contact route inserter to masquerade contacts in 200Ok of responses that establish a dialog<commit_after>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2010 Belledonne Communications SARL.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "agent.hh"
class ContactRouteInserter : public Module {
public:
ContactRouteInserter(Agent *ag):Module(ag){
}
void onDeclare(ConfigStruct *module_config){
ConfigItemDescriptor items[]={
{ Boolean , "masquerade-contacts-for-invites", "Hack for workarounding Nortel CS2k gateways bug.","false"},
config_item_end
};
module_config->addChildrenValues(items);
}
void onLoad(Agent *agent, const ConfigStruct *module_config){
mContactRouteParamName=std::string("CtRt")+getAgent()->getUniqueId();
mMasqueradeInviteContacts=module_config->get<ConfigBoolean>("masquerade-contacts-for-invites")->read();
}
void onRequest(SipEvent *ev) {
sip_t *sip=ev->mSip;
if(sip->sip_request->rq_method == sip_method_register){
//rewrite the request uri to the domain
//this assume the domain is also the proxy
sip->sip_request->rq_url->url_host=sip->sip_to->a_url->url_host;
sip->sip_request->rq_url->url_port=sip->sip_to->a_url->url_port;
}
if(sip->sip_request->rq_method == sip_method_register ||
((sip->sip_request->rq_method == sip_method_invite ) && mMasqueradeInviteContacts)){
masqueradeContact(ev);
}
if (sip->sip_request->rq_method != sip_method_register){
/* check if request-uri contains a contact-route parameter, so that we can route back to the client */
char contact_route_param[64];
url_t *dest=sip->sip_request->rq_url;
// now need to check if request uri has special param inserted by contact-route-inserter module
if (url_param(dest->url_params,mContactRouteParamName.c_str(),contact_route_param,sizeof(contact_route_param))) {
//first remove param
dest->url_params = url_strip_param_string(su_strdup(ev->getHome(),dest->url_params),mContactRouteParamName.c_str());
//test and remove maddr param
if (url_has_param(dest,"maddr")) {
dest->url_params = url_strip_param_string(su_strdup(ev->getHome(),dest->url_params),"maddr");
}
//second change dest to
char* tmp = strchr(contact_route_param, ':');
if (tmp){
char* transport=su_strndup(ev->getHome(),contact_route_param,tmp-contact_route_param);
char *tmp2=tmp+1;
tmp=strchr(tmp2, ':');
if (tmp){
dest->url_host=su_strndup(ev->getHome(), tmp2, tmp-tmp2 );
dest->url_port=su_strdup(ev->getHome(), tmp+1);
if (strcasecmp(transport,"udp")!=0){
char *t_param=su_sprintf (ev->getHome(),"transport=%s",transport);
url_param_add(ev->getHome(),dest,t_param);
}
}
}
}
}
}
void onResponse(SipEvent *ev) {
sip_t *sip=ev->mSip;
if (mMasqueradeInviteContacts &&
(sip->sip_cseq->cs_method==sip_method_invite || sip->sip_cseq->cs_method==sip_method_subscribe)){
masqueradeContact(ev);
}
}
private:
void masqueradeContact(SipEvent *ev){
sip_t *sip=ev->mSip;
if (sip->sip_contact!=NULL && sip->sip_contact->m_url!=NULL){
//rewrite contact, put local host instead and store previous contact host in new parameter
char ct_tport[32]="udp";
char* lParam;
url_t *ct_url=sip->sip_contact->m_url;
//grab the transport of the contact uri
if (url_param(sip->sip_contact->m_url->url_params,"transport",ct_tport,sizeof(ct_tport))>0){
}
/*add a parameter like "CtRt15.128.128.2=tcp:201.45.118.16:50025" in the contact, so that we know where is the client
when we later have to route an INVITE to him */
lParam=su_sprintf (ev->getHome(),"%s=%s:%s:%s",mContactRouteParamName.c_str()
,ct_tport
,ct_url->url_host
,ct_url->url_port);
LOGD("Rewriting contact with param [%s]",lParam);
if (url_param_add (ev->getHome(),ct_url,lParam)) {
LOGE("Cannot insert url param [%s]",lParam);
}
/*masquerade the contact, so that later requests (INVITEs) come to us */
ct_url->url_host = getAgent()->getLocAddr().c_str();
ct_url->url_port = su_sprintf (ev->getHome(),"%i",getAgent()->getPort());
/*remove the transport, in most case further requests should come back to us in UDP*/
ct_url->url_params = url_strip_param_string(su_strdup(ev->getHome(),ct_url->url_params),"transport");
}
}
std::string mContactRouteParamName;
bool mMasqueradeInviteContacts;
static ModuleInfo<ContactRouteInserter> sInfo;
};
ModuleInfo<ContactRouteInserter> ContactRouteInserter::sInfo("ContactRouteInserter",
"The purpose of the ContactRouteInserter module is to masquerade the contact header of incoming registers that are not handled locally "
"(think about flexisip used as a SBC gateway) in such a way that it is then possible to route back outgoing invites to the original address. "
"It is a kind of similar mechanism as Record-Route, but for REGISTER.");
<|endoftext|> |
<commit_before>// Copyright 2016 Peter Georg
//
// 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 "completionqueue.hpp"
#include <stdexcept>
extern "C" {
#include <rdma/fi_errno.h>
}
pMR::ofi::CompletionQueue::~CompletionQueue()
{
if(mCompletionQueue)
{
fi_close(&mCompletionQueue->fid);
}
}
fid_cq *pMR::ofi::CompletionQueue::get()
{
return mCompletionQueue;
}
fid_cq const *pMR::ofi::CompletionQueue::get() const
{
return mCompletionQueue;
}
void pMR::ofi::CompletionQueue::open(
Domain &domain, std::size_t const size, fi_cq_format const format)
{
fi_cq_attr attr = {};
attr.size = {size};
attr.format = {format};
attr.wait_obj = FI_WAIT_UNSPEC;
attr.wait_cond = FI_CQ_COND_NONE;
if(fi_cq_open(domain.get(), &attr, &mCompletionQueue, &mContext))
{
throw std::runtime_error("pMR: Unable to create completion queue.");
}
}
void pMR::ofi::CompletionQueue::poll(void *entry)
{
#ifdef OFI_POLL_SPIN
decltype(fi_cq_read(mCompletionQueue, entry, 1)) ret;
do
{
ret = fi_cq_read(mCompletionQueue, entry, 1);
if(ret == 1)
return;
CPURelax();
} while(ret == -FI_EAGAIN);
#else
if(fi_cq_sread(mCompletionQueue, entry, 1, NULL, -1) != 1)
#endif // OFI_POLL_SPIN
{
throw std::runtime_error(
"pMR: Unable to retrieve Completion queue event.");
}
}
pMR::ofi::CompletionQueueContext::CompletionQueueContext(
Domain &domain, std::size_t size)
{
open(domain, size, FI_CQ_FORMAT_CONTEXT);
}
std::uintptr_t pMR::ofi::CompletionQueueContext::poll()
{
fi_cq_entry entry;
CompletionQueue::poll(&entry);
return {reinterpret_cast<std::uintptr_t>(entry.op_context)};
}
pMR::ofi::CompletionQueueData::CompletionQueueData(
Domain &domain, std::size_t size)
{
open(domain, size, FI_CQ_FORMAT_DATA);
}
std::pair<std::uintptr_t, std::uint64_t> pMR::ofi::CompletionQueueData::poll()
{
fi_cq_data_entry entry;
CompletionQueue::poll(&entry);
if(!(entry.flags & FI_REMOTE_CQ_DATA))
{
entry.data = 0;
}
return std::make_pair(
reinterpret_cast<std::uintptr_t>(entry.op_context), entry.data);
}
<commit_msg>Add missing include<commit_after>// Copyright 2016 Peter Georg
//
// 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 "completionqueue.hpp"
#include <stdexcept>
extern "C" {
#include <rdma/fi_errno.h>
}
#include "../../arch/processor.hpp"
pMR::ofi::CompletionQueue::~CompletionQueue()
{
if(mCompletionQueue)
{
fi_close(&mCompletionQueue->fid);
}
}
fid_cq *pMR::ofi::CompletionQueue::get()
{
return mCompletionQueue;
}
fid_cq const *pMR::ofi::CompletionQueue::get() const
{
return mCompletionQueue;
}
void pMR::ofi::CompletionQueue::open(
Domain &domain, std::size_t const size, fi_cq_format const format)
{
fi_cq_attr attr = {};
attr.size = {size};
attr.format = {format};
attr.wait_obj = FI_WAIT_UNSPEC;
attr.wait_cond = FI_CQ_COND_NONE;
if(fi_cq_open(domain.get(), &attr, &mCompletionQueue, &mContext))
{
throw std::runtime_error("pMR: Unable to create completion queue.");
}
}
void pMR::ofi::CompletionQueue::poll(void *entry)
{
#ifdef OFI_POLL_SPIN
decltype(fi_cq_read(mCompletionQueue, entry, 1)) ret;
do
{
ret = fi_cq_read(mCompletionQueue, entry, 1);
if(ret == 1)
return;
CPURelax();
} while(ret == -FI_EAGAIN);
#else
if(fi_cq_sread(mCompletionQueue, entry, 1, NULL, -1) != 1)
#endif // OFI_POLL_SPIN
{
throw std::runtime_error(
"pMR: Unable to retrieve Completion queue event.");
}
}
pMR::ofi::CompletionQueueContext::CompletionQueueContext(
Domain &domain, std::size_t size)
{
open(domain, size, FI_CQ_FORMAT_CONTEXT);
}
std::uintptr_t pMR::ofi::CompletionQueueContext::poll()
{
fi_cq_entry entry;
CompletionQueue::poll(&entry);
return {reinterpret_cast<std::uintptr_t>(entry.op_context)};
}
pMR::ofi::CompletionQueueData::CompletionQueueData(
Domain &domain, std::size_t size)
{
open(domain, size, FI_CQ_FORMAT_DATA);
}
std::pair<std::uintptr_t, std::uint64_t> pMR::ofi::CompletionQueueData::poll()
{
fi_cq_data_entry entry;
CompletionQueue::poll(&entry);
if(!(entry.flags & FI_REMOTE_CQ_DATA))
{
entry.data = 0;
}
return std::make_pair(
reinterpret_cast<std::uintptr_t>(entry.op_context), entry.data);
}
<|endoftext|> |
<commit_before>#pragma once
#include <iostream>
#include "global_config.hpp"
namespace mocc {
// Scattering matrix row
struct ScatteringRow {
public:
ScatteringRow(int min, int max, real_t const * const from):
min_g(min), max_g(max), from(from){}
int min_g;
int max_g;
real_t const * const from;
real_t operator[]( size_t g ) const {
return from[g-min_g];
}
const real_t* begin() const {
return from;
}
const real_t* end() const {
return from + max_g - min_g + 1;
}
};
/**
* This class provides an efficient means by which to store a matrix of
* scattering cross sections. Generally speaking, scattering matrices tend
* to be relatively sparse, since upscatter is not present at high energies
* (so the matrix is largely lower-triangular), and downscattering energy
* transfer is physically limited by the ratio of masses. Therefore we use a
* compressed representation, where each "row" of outscatter cross sections
* are stored contiguously, along with their group boundaries.
*/
class ScatteringMatrix{
public:
ScatteringMatrix():
ng_(0)
{ }
/**
* Construct a scattering matrix using a 2-dimensional vector<vector<>>.
* This full, dense representation of the scattering matrix will be
* densified.
*
* \param scat the dense representation of the scattering matrix.
* Indexing should be [to group][from group]
*/
ScatteringMatrix(std::vector<VecF> scat);
const ScatteringRow& to( int ig ) const {
return rows_[ig];
}
// Copy constructor. Need this in order to produce valid raw pointers to
// the scattering rows.
ScatteringMatrix( const ScatteringMatrix &other ):
ng_( other.ng_ ),
scat_( other.scat_ ),
out_( other.out_ )
{
// Pretty much everything can copy straight over, but we need to
// reach into the scattering rows and update their pointers to the
// location of the new scat_ vector
int pos = 0;
for( auto &row: other ) {
rows_.push_back( ScatteringRow(row.min_g, row.max_g,
&scat_[pos]) );
pos += row.max_g - row.min_g + 1;
}
return;
}
ScatteringMatrix& operator=( const ScatteringMatrix &rhs ) {
if( this != &rhs ) {
ng_ = rhs.ng_;
scat_ = rhs.scat_;
out_ = rhs.out_;
rows_.clear();
int pos = 0;
for( auto &row: rhs ) {
rows_.push_back( ScatteringRow(row.min_g, row.max_g, &scat_[pos]) );
pos += row.max_g - row.min_g + 1;
}
}
return *this;
}
/**
* Return the number of energy groups for which the scattering matrix is
* defined.
*/
size_t n_group() const {
return ng_;
}
/**
* Return the total out-scattering cross section for group ig
*/
real_t out( unsigned int ig ) const {
return out_[ig];
};
/**
* Return iterator to the first scattering row.
*/
std::vector<ScatteringRow>::const_iterator begin() const {
return rows_.cbegin();
}
/**
* Return iterator past the last scattering row.
*/
std::vector<ScatteringRow>::const_iterator end() const {
return rows_.cend();
}
/**
* \brief Return a 1-D, dense representation of the scattering matrix.
*
* The returned vector stores all of scattering cross sections as a
* row-major ng-by-ng matrix.
*/
VecF as_vector() const {
VecF sc(ng_*ng_, 0.0);
int ig = 0;
for( const auto &row: rows_ ) {
for( int igg=row.min_g; igg<=row.max_g; igg++ ) {
sc[ng_*ig + igg] = row[igg];
}
ig++;
}
return sc;
}
// Provide stream insertion support
friend std::ostream& operator<<(std::ostream& os,
const ScatteringMatrix &scat_mat);
private:
size_t ng_;
VecF scat_;
VecF out_;
std::vector<ScatteringRow> rows_;
};
}
<commit_msg>Add a self_scat routine to the scattering matrix<commit_after>#pragma once
#include <iostream>
#include "global_config.hpp"
namespace mocc {
// Scattering matrix row
struct ScatteringRow {
public:
ScatteringRow(int min, int max, real_t const * const from):
min_g(min), max_g(max), from(from){}
int min_g;
int max_g;
real_t const * const from;
real_t operator[]( size_t g ) const {
return from[g-min_g];
}
const real_t* begin() const {
return from;
}
const real_t* end() const {
return from + max_g - min_g + 1;
}
};
/**
* This class provides an efficient means by which to store a matrix of
* scattering cross sections. Generally speaking, scattering matrices tend
* to be relatively sparse, since upscatter is not present at high energies
* (so the matrix is largely lower-triangular), and downscattering energy
* transfer is physically limited by the ratio of masses. Therefore we use a
* compressed representation, where each "row" of outscatter cross sections
* are stored contiguously, along with their group boundaries.
*/
class ScatteringMatrix{
public:
ScatteringMatrix():
ng_(0)
{ }
/**
* Construct a scattering matrix using a 2-dimensional vector<vector<>>.
* This full, dense representation of the scattering matrix will be
* densified.
*
* \param scat the dense representation of the scattering matrix.
* Indexing should be [to group][from group]
*/
ScatteringMatrix(std::vector<VecF> scat);
const ScatteringRow& to( int ig ) const {
return rows_[ig];
}
/**
* Copy constructor. Need this in order to produce valid raw pointers to
* the scattering rows.
*/
ScatteringMatrix( const ScatteringMatrix &other ):
ng_( other.ng_ ),
scat_( other.scat_ ),
out_( other.out_ )
{
// Pretty much everything can copy straight over, but we need to
// reach into the scattering rows and update their pointers to the
// location of the new scat_ vector
int pos = 0;
for( auto &row: other ) {
rows_.push_back( ScatteringRow(row.min_g, row.max_g,
&scat_[pos]) );
pos += row.max_g - row.min_g + 1;
}
return;
}
ScatteringMatrix& operator=( const ScatteringMatrix &rhs ) {
if( this != &rhs ) {
ng_ = rhs.ng_;
scat_ = rhs.scat_;
out_ = rhs.out_;
rows_.clear();
int pos = 0;
for( auto &row: rhs ) {
rows_.push_back( ScatteringRow(row.min_g, row.max_g,
&scat_[pos]) );
pos += row.max_g - row.min_g + 1;
}
}
return *this;
}
/**
* \brief Return the self-scattering cross section for the indicated
* group.
*/
real_t self_scat( int group ) const {
return rows_[group][group];
}
/**
* Return the number of energy groups for which the scattering matrix is
* defined.
*/
size_t n_group() const {
return ng_;
}
/**
* Return the total out-scattering cross section for group ig
*/
real_t out( unsigned int ig ) const {
return out_[ig];
};
/**
* Return iterator to the first scattering row.
*/
std::vector<ScatteringRow>::const_iterator begin() const {
return rows_.cbegin();
}
/**
* Return iterator past the last scattering row.
*/
std::vector<ScatteringRow>::const_iterator end() const {
return rows_.cend();
}
/**
* \brief Return a 1-D, dense representation of the scattering matrix.
*
* The returned vector stores all of scattering cross sections as a
* row-major ng-by-ng matrix.
*/
VecF as_vector() const {
VecF sc(ng_*ng_, 0.0);
int ig = 0;
for( const auto &row: rows_ ) {
for( int igg=row.min_g; igg<=row.max_g; igg++ ) {
sc[ng_*ig + igg] = row[igg];
}
ig++;
}
return sc;
}
// Provide stream insertion support
friend std::ostream& operator<<(std::ostream& os,
const ScatteringMatrix &scat_mat);
private:
size_t ng_;
VecF scat_;
VecF out_;
std::vector<ScatteringRow> rows_;
};
}
<|endoftext|> |
<commit_before>/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2016. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
#include "Ultrasonic.h"
#include "Counter.h"
#include "DigitalInput.h"
#include "DigitalOutput.h"
#include "Timer.h"
#include "Utility.h"
#include "WPIErrors.h"
#include "LiveWindow/LiveWindow.h"
// Time (sec) for the ping trigger pulse.
constexpr double Ultrasonic::kPingTime;
// Priority that the ultrasonic round robin task runs.
const uint32_t Ultrasonic::kPriority;
// Max time (ms) between readings.
constexpr double Ultrasonic::kMaxUltrasonicTime;
constexpr double Ultrasonic::kSpeedOfSoundInchesPerSec;
Task Ultrasonic::m_task;
// automatic round robin mode
std::atomic<bool> Ultrasonic::m_automaticEnabled{false};
/**
* Background task that goes through the list of ultrasonic sensors and pings
* each one in turn. The counter
* is configured to read the timing of the returned echo pulse.
*
* DANGER WILL ROBINSON, DANGER WILL ROBINSON:
* This code runs as a task and assumes that none of the ultrasonic sensors
* will change while it's running. Make sure to disable automatic mode before
* touching the list.
*/
void Ultrasonic::UltrasonicChecker() {
while (m_automaticEnabled) {
for (auto& sensor : m_sensors) {
if (!m_automaticEnabled) break;
if (sensor->IsEnabled()) {
sensor->m_pingChannel->Pulse(kPingTime); // do the ping
}
Wait(0.1); // wait for ping to return
}
}
}
/**
* Initialize the Ultrasonic Sensor.
* This is the common code that initializes the ultrasonic sensor given that
* there
* are two digital I/O channels allocated. If the system was running in
* automatic mode (round robin)
* when the new sensor is added, it is stopped, the sensor is added, then
* automatic mode is
* restored.
*/
void Ultrasonic::Initialize() {
bool originalMode = m_automaticEnabled;
SetAutomaticMode(false); // kill task when adding a new sensor
// link this instance on the list
m_sensors.insert(this);
m_counter.SetMaxPeriod(1.0);
m_counter.SetSemiPeriodMode(true);
m_counter.Reset();
m_enabled = true; // make it available for round robin scheduling
SetAutomaticMode(originalMode);
static int instances = 0;
instances++;
HALReport(HALUsageReporting::kResourceType_Ultrasonic, instances);
LiveWindow::GetInstance()->AddSensor("Ultrasonic",
m_echoChannel->GetChannel(), this);
}
/**
* Create an instance of the Ultrasonic Sensor
* This is designed to supchannel the Daventech SRF04 and Vex ultrasonic
* sensors.
* @param pingChannel The digital output channel that sends the pulse to
* initiate the sensor sending
* the ping.
* @param echoChannel The digital input channel that receives the echo. The
* length of time that the
* echo is high represents the round trip time of the ping, and the distance.
* @param units The units returned in either kInches or kMilliMeters
*/
Ultrasonic::Ultrasonic(uint32_t pingChannel, uint32_t echoChannel,
DistanceUnit units)
: m_pingChannel(std::make_shared<DigitalOutput>(pingChannel)),
m_echoChannel(std::make_shared<DigitalInput>(echoChannel)),
m_counter(m_echoChannel) {
m_units = units;
Initialize();
}
/**
* Create an instance of an Ultrasonic Sensor from a DigitalInput for the echo
* channel and a DigitalOutput
* for the ping channel.
* @param pingChannel The digital output object that starts the sensor doing a
* ping. Requires a 10uS pulse to start.
* @param echoChannel The digital input object that times the return pulse to
* determine the range.
* @param units The units returned in either kInches or kMilliMeters
*/
Ultrasonic::Ultrasonic(DigitalOutput *pingChannel, DigitalInput *echoChannel,
DistanceUnit units)
: m_pingChannel(pingChannel, NullDeleter<DigitalOutput>()),
m_echoChannel(echoChannel, NullDeleter<DigitalInput>()),
m_counter(m_echoChannel) {
if (pingChannel == nullptr || echoChannel == nullptr) {
wpi_setWPIError(NullParameter);
m_units = units;
return;
}
m_units = units;
Initialize();
}
/**
* Create an instance of an Ultrasonic Sensor from a DigitalInput for the echo
* channel and a DigitalOutput
* for the ping channel.
* @param pingChannel The digital output object that starts the sensor doing a
* ping. Requires a 10uS pulse to start.
* @param echoChannel The digital input object that times the return pulse to
* determine the range.
* @param units The units returned in either kInches or kMilliMeters
*/
Ultrasonic::Ultrasonic(DigitalOutput &pingChannel, DigitalInput &echoChannel,
DistanceUnit units)
: m_pingChannel(&pingChannel, NullDeleter<DigitalOutput>()),
m_echoChannel(&echoChannel, NullDeleter<DigitalInput>()),
m_counter(m_echoChannel) {
m_units = units;
Initialize();
}
/**
* Create an instance of an Ultrasonic Sensor from a DigitalInput for the echo
* channel and a DigitalOutput
* for the ping channel.
* @param pingChannel The digital output object that starts the sensor doing a
* ping. Requires a 10uS pulse to start.
* @param echoChannel The digital input object that times the return pulse to
* determine the range.
* @param units The units returned in either kInches or kMilliMeters
*/
Ultrasonic::Ultrasonic(std::shared_ptr<DigitalOutput> pingChannel,
std::shared_ptr<DigitalInput> echoChannel,
DistanceUnit units)
: m_pingChannel(pingChannel),
m_echoChannel(echoChannel),
m_counter(m_echoChannel) {
m_units = units;
Initialize();
}
/**
* Destructor for the ultrasonic sensor.
* Delete the instance of the ultrasonic sensor by freeing the allocated digital
* channels.
* If the system was in automatic mode (round robin), then it is stopped, then
* started again
* after this sensor is removed (provided this wasn't the last sensor).
*/
Ultrasonic::~Ultrasonic() {
bool wasAutomaticMode = m_automaticEnabled;
SetAutomaticMode(false);
// No synchronization needed because the background task is stopped.
m_sensors.erase(this);
if (!m_sensors.empty() && wasAutomaticMode) {
SetAutomaticMode(true);
}
}
/**
* Turn Automatic mode on/off.
* When in Automatic mode, all sensors will fire in round robin, waiting a set
* time between each sensor.
* @param enabling Set to true if round robin scheduling should start for all
* the ultrasonic sensors. This
* scheduling method assures that the sensors are non-interfering because no two
* sensors fire at the same time.
* If another scheduling algorithm is prefered, it can be implemented by
* pinging the sensors manually and waiting
* for the results to come back.
*/
void Ultrasonic::SetAutomaticMode(bool enabling) {
if (enabling == m_automaticEnabled) return; // ignore the case of no change
m_automaticEnabled = enabling;
if (enabling) {
/* Clear all the counters so no data is valid. No synchronization is needed
* because the background task is stopped.
*/
for (auto& sensor : m_sensors) {
sensor->m_counter.Reset();
}
m_task = Task("UltrasonicChecker", &Ultrasonic::UltrasonicChecker);
// TODO: Currently, lvuser does not have permissions to set task priorities.
// Until that is the case, uncommenting this will break user code that calls
// Ultrasonic::SetAutomicMode().
//m_task.SetPriority(kPriority);
} else {
// Wait for background task to stop running
m_task.join();
/* Clear all the counters (data now invalid) since automatic mode is
* disabled. No synchronization is needed because the background task is
* stopped.
*/
for (auto& sensor : m_sensors) {
sensor->m_counter.Reset();
}
}
}
/**
* Single ping to ultrasonic sensor.
* Send out a single ping to the ultrasonic sensor. This only works if automatic
* (round robin) mode is disabled. A single ping is sent out, and the counter
* should count the semi-period when it comes in. The counter is reset to make
* the current value invalid.
*/
void Ultrasonic::Ping() {
wpi_assert(!m_automaticEnabled);
m_counter.Reset(); // reset the counter to zero (invalid data now)
m_pingChannel->Pulse(
kPingTime); // do the ping to start getting a single range
}
/**
* Check if there is a valid range measurement.
* The ranges are accumulated in a counter that will increment on each edge of
* the echo (return)
* signal. If the count is not at least 2, then the range has not yet been
* measured, and is invalid.
*/
bool Ultrasonic::IsRangeValid() const { return m_counter.Get() > 1; }
/**
* Get the range in inches from the ultrasonic sensor.
* @return double Range in inches of the target returned from the ultrasonic
* sensor. If there is no valid value yet, i.e. at least one measurement hasn't
* completed, then return 0.
*/
double Ultrasonic::GetRangeInches() const {
if (IsRangeValid())
return m_counter.GetPeriod() * kSpeedOfSoundInchesPerSec / 2.0;
else
return 0;
}
/**
* Get the range in millimeters from the ultrasonic sensor.
* @return double Range in millimeters of the target returned by the ultrasonic
* sensor.
* If there is no valid value yet, i.e. at least one measurement hasn't
* completed, then return 0.
*/
double Ultrasonic::GetRangeMM() const { return GetRangeInches() * 25.4; }
/**
* Get the range in the current DistanceUnit for the PIDSource base object.
*
* @return The range in DistanceUnit
*/
double Ultrasonic::PIDGet() {
switch (m_units) {
case Ultrasonic::kInches:
return GetRangeInches();
case Ultrasonic::kMilliMeters:
return GetRangeMM();
default:
return 0.0;
}
}
void Ultrasonic::SetPIDSourceType(PIDSourceType pidSource) {
if (wpi_assert(pidSource == PIDSourceType::kDisplacement)) {
m_pidSource = pidSource;
}
}
/**
* Set the current DistanceUnit that should be used for the PIDSource base
* object.
*
* @param units The DistanceUnit that should be used.
*/
void Ultrasonic::SetDistanceUnits(DistanceUnit units) { m_units = units; }
/**
* Get the current DistanceUnit that is used for the PIDSource base object.
*
* @return The type of DistanceUnit that is being used.
*/
Ultrasonic::DistanceUnit Ultrasonic::GetDistanceUnits() const {
return m_units;
}
void Ultrasonic::UpdateTable() {
if (m_table != nullptr) {
m_table->PutNumber("Value", GetRangeInches());
}
}
void Ultrasonic::StartLiveWindowMode() {}
void Ultrasonic::StopLiveWindowMode() {}
std::string Ultrasonic::GetSmartDashboardType() const { return "Ultrasonic"; }
void Ultrasonic::InitTable(std::shared_ptr<ITable> subTable) {
m_table = subTable;
UpdateTable();
}
std::shared_ptr<ITable> Ultrasonic::GetTable() const { return m_table; }
<commit_msg>Initialized the m_sensors variable to fix artf4798.<commit_after>/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2016. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
#include "Ultrasonic.h"
#include "Counter.h"
#include "DigitalInput.h"
#include "DigitalOutput.h"
#include "Timer.h"
#include "Utility.h"
#include "WPIErrors.h"
#include "LiveWindow/LiveWindow.h"
// Time (sec) for the ping trigger pulse.
constexpr double Ultrasonic::kPingTime;
// Priority that the ultrasonic round robin task runs.
const uint32_t Ultrasonic::kPriority;
// Max time (ms) between readings.
constexpr double Ultrasonic::kMaxUltrasonicTime;
constexpr double Ultrasonic::kSpeedOfSoundInchesPerSec;
Task Ultrasonic::m_task;
// automatic round robin mode
std::atomic<bool> Ultrasonic::m_automaticEnabled{false};
std::set<Ultrasonic*> Ultrasonic::m_sensors;
/**
* Background task that goes through the list of ultrasonic sensors and pings
* each one in turn. The counter
* is configured to read the timing of the returned echo pulse.
*
* DANGER WILL ROBINSON, DANGER WILL ROBINSON:
* This code runs as a task and assumes that none of the ultrasonic sensors
* will change while it's running. Make sure to disable automatic mode before
* touching the list.
*/
void Ultrasonic::UltrasonicChecker() {
while (m_automaticEnabled) {
for (auto& sensor : m_sensors) {
if (!m_automaticEnabled) break;
if (sensor->IsEnabled()) {
sensor->m_pingChannel->Pulse(kPingTime); // do the ping
}
Wait(0.1); // wait for ping to return
}
}
}
/**
* Initialize the Ultrasonic Sensor.
* This is the common code that initializes the ultrasonic sensor given that
* there
* are two digital I/O channels allocated. If the system was running in
* automatic mode (round robin)
* when the new sensor is added, it is stopped, the sensor is added, then
* automatic mode is
* restored.
*/
void Ultrasonic::Initialize() {
bool originalMode = m_automaticEnabled;
SetAutomaticMode(false); // kill task when adding a new sensor
// link this instance on the list
m_sensors.insert(this);
m_counter.SetMaxPeriod(1.0);
m_counter.SetSemiPeriodMode(true);
m_counter.Reset();
m_enabled = true; // make it available for round robin scheduling
SetAutomaticMode(originalMode);
static int instances = 0;
instances++;
HALReport(HALUsageReporting::kResourceType_Ultrasonic, instances);
LiveWindow::GetInstance()->AddSensor("Ultrasonic",
m_echoChannel->GetChannel(), this);
}
/**
* Create an instance of the Ultrasonic Sensor
* This is designed to supchannel the Daventech SRF04 and Vex ultrasonic
* sensors.
* @param pingChannel The digital output channel that sends the pulse to
* initiate the sensor sending
* the ping.
* @param echoChannel The digital input channel that receives the echo. The
* length of time that the
* echo is high represents the round trip time of the ping, and the distance.
* @param units The units returned in either kInches or kMilliMeters
*/
Ultrasonic::Ultrasonic(uint32_t pingChannel, uint32_t echoChannel,
DistanceUnit units)
: m_pingChannel(std::make_shared<DigitalOutput>(pingChannel)),
m_echoChannel(std::make_shared<DigitalInput>(echoChannel)),
m_counter(m_echoChannel) {
m_units = units;
Initialize();
}
/**
* Create an instance of an Ultrasonic Sensor from a DigitalInput for the echo
* channel and a DigitalOutput
* for the ping channel.
* @param pingChannel The digital output object that starts the sensor doing a
* ping. Requires a 10uS pulse to start.
* @param echoChannel The digital input object that times the return pulse to
* determine the range.
* @param units The units returned in either kInches or kMilliMeters
*/
Ultrasonic::Ultrasonic(DigitalOutput *pingChannel, DigitalInput *echoChannel,
DistanceUnit units)
: m_pingChannel(pingChannel, NullDeleter<DigitalOutput>()),
m_echoChannel(echoChannel, NullDeleter<DigitalInput>()),
m_counter(m_echoChannel) {
if (pingChannel == nullptr || echoChannel == nullptr) {
wpi_setWPIError(NullParameter);
m_units = units;
return;
}
m_units = units;
Initialize();
}
/**
* Create an instance of an Ultrasonic Sensor from a DigitalInput for the echo
* channel and a DigitalOutput
* for the ping channel.
* @param pingChannel The digital output object that starts the sensor doing a
* ping. Requires a 10uS pulse to start.
* @param echoChannel The digital input object that times the return pulse to
* determine the range.
* @param units The units returned in either kInches or kMilliMeters
*/
Ultrasonic::Ultrasonic(DigitalOutput &pingChannel, DigitalInput &echoChannel,
DistanceUnit units)
: m_pingChannel(&pingChannel, NullDeleter<DigitalOutput>()),
m_echoChannel(&echoChannel, NullDeleter<DigitalInput>()),
m_counter(m_echoChannel) {
m_units = units;
Initialize();
}
/**
* Create an instance of an Ultrasonic Sensor from a DigitalInput for the echo
* channel and a DigitalOutput
* for the ping channel.
* @param pingChannel The digital output object that starts the sensor doing a
* ping. Requires a 10uS pulse to start.
* @param echoChannel The digital input object that times the return pulse to
* determine the range.
* @param units The units returned in either kInches or kMilliMeters
*/
Ultrasonic::Ultrasonic(std::shared_ptr<DigitalOutput> pingChannel,
std::shared_ptr<DigitalInput> echoChannel,
DistanceUnit units)
: m_pingChannel(pingChannel),
m_echoChannel(echoChannel),
m_counter(m_echoChannel) {
m_units = units;
Initialize();
}
/**
* Destructor for the ultrasonic sensor.
* Delete the instance of the ultrasonic sensor by freeing the allocated digital
* channels.
* If the system was in automatic mode (round robin), then it is stopped, then
* started again
* after this sensor is removed (provided this wasn't the last sensor).
*/
Ultrasonic::~Ultrasonic() {
bool wasAutomaticMode = m_automaticEnabled;
SetAutomaticMode(false);
// No synchronization needed because the background task is stopped.
m_sensors.erase(this);
if (!m_sensors.empty() && wasAutomaticMode) {
SetAutomaticMode(true);
}
}
/**
* Turn Automatic mode on/off.
* When in Automatic mode, all sensors will fire in round robin, waiting a set
* time between each sensor.
* @param enabling Set to true if round robin scheduling should start for all
* the ultrasonic sensors. This
* scheduling method assures that the sensors are non-interfering because no two
* sensors fire at the same time.
* If another scheduling algorithm is prefered, it can be implemented by
* pinging the sensors manually and waiting
* for the results to come back.
*/
void Ultrasonic::SetAutomaticMode(bool enabling) {
if (enabling == m_automaticEnabled) return; // ignore the case of no change
m_automaticEnabled = enabling;
if (enabling) {
/* Clear all the counters so no data is valid. No synchronization is needed
* because the background task is stopped.
*/
for (auto& sensor : m_sensors) {
sensor->m_counter.Reset();
}
m_task = Task("UltrasonicChecker", &Ultrasonic::UltrasonicChecker);
// TODO: Currently, lvuser does not have permissions to set task priorities.
// Until that is the case, uncommenting this will break user code that calls
// Ultrasonic::SetAutomicMode().
//m_task.SetPriority(kPriority);
} else {
// Wait for background task to stop running
m_task.join();
/* Clear all the counters (data now invalid) since automatic mode is
* disabled. No synchronization is needed because the background task is
* stopped.
*/
for (auto& sensor : m_sensors) {
sensor->m_counter.Reset();
}
}
}
/**
* Single ping to ultrasonic sensor.
* Send out a single ping to the ultrasonic sensor. This only works if automatic
* (round robin) mode is disabled. A single ping is sent out, and the counter
* should count the semi-period when it comes in. The counter is reset to make
* the current value invalid.
*/
void Ultrasonic::Ping() {
wpi_assert(!m_automaticEnabled);
m_counter.Reset(); // reset the counter to zero (invalid data now)
m_pingChannel->Pulse(
kPingTime); // do the ping to start getting a single range
}
/**
* Check if there is a valid range measurement.
* The ranges are accumulated in a counter that will increment on each edge of
* the echo (return)
* signal. If the count is not at least 2, then the range has not yet been
* measured, and is invalid.
*/
bool Ultrasonic::IsRangeValid() const { return m_counter.Get() > 1; }
/**
* Get the range in inches from the ultrasonic sensor.
* @return double Range in inches of the target returned from the ultrasonic
* sensor. If there is no valid value yet, i.e. at least one measurement hasn't
* completed, then return 0.
*/
double Ultrasonic::GetRangeInches() const {
if (IsRangeValid())
return m_counter.GetPeriod() * kSpeedOfSoundInchesPerSec / 2.0;
else
return 0;
}
/**
* Get the range in millimeters from the ultrasonic sensor.
* @return double Range in millimeters of the target returned by the ultrasonic
* sensor.
* If there is no valid value yet, i.e. at least one measurement hasn't
* completed, then return 0.
*/
double Ultrasonic::GetRangeMM() const { return GetRangeInches() * 25.4; }
/**
* Get the range in the current DistanceUnit for the PIDSource base object.
*
* @return The range in DistanceUnit
*/
double Ultrasonic::PIDGet() {
switch (m_units) {
case Ultrasonic::kInches:
return GetRangeInches();
case Ultrasonic::kMilliMeters:
return GetRangeMM();
default:
return 0.0;
}
}
void Ultrasonic::SetPIDSourceType(PIDSourceType pidSource) {
if (wpi_assert(pidSource == PIDSourceType::kDisplacement)) {
m_pidSource = pidSource;
}
}
/**
* Set the current DistanceUnit that should be used for the PIDSource base
* object.
*
* @param units The DistanceUnit that should be used.
*/
void Ultrasonic::SetDistanceUnits(DistanceUnit units) { m_units = units; }
/**
* Get the current DistanceUnit that is used for the PIDSource base object.
*
* @return The type of DistanceUnit that is being used.
*/
Ultrasonic::DistanceUnit Ultrasonic::GetDistanceUnits() const {
return m_units;
}
void Ultrasonic::UpdateTable() {
if (m_table != nullptr) {
m_table->PutNumber("Value", GetRangeInches());
}
}
void Ultrasonic::StartLiveWindowMode() {}
void Ultrasonic::StopLiveWindowMode() {}
std::string Ultrasonic::GetSmartDashboardType() const { return "Ultrasonic"; }
void Ultrasonic::InitTable(std::shared_ptr<ITable> subTable) {
m_table = subTable;
UpdateTable();
}
std::shared_ptr<ITable> Ultrasonic::GetTable() const { return m_table; }
<|endoftext|> |
<commit_before>/*
* Copyright 2011 Esrille Inc.
*
* 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 "HTMLAnchorElementImp.h"
#include <iostream>
#include <boost/bind.hpp>
#include "utf.h"
namespace org
{
namespace w3c
{
namespace dom
{
namespace bootstrap
{
void HTMLAnchorElementImp::handleClick(events::Event event)
{
std::u16string href = getHref();
if (!href.empty())
getOwnerDocument().setLocation(href);
}
HTMLAnchorElementImp::HTMLAnchorElementImp(DocumentImp* ownerDocument) :
ObjectMixin(ownerDocument, u"a"),
clickListener(boost::bind(&HTMLAnchorElementImp::handleClick, this, _1))
{
addEventListener(u"click", &clickListener);
}
HTMLAnchorElementImp::HTMLAnchorElementImp(HTMLAnchorElementImp* org, bool deep) :
ObjectMixin(org, deep),
clickListener(boost::bind(&HTMLAnchorElementImp::handleClick, this, _1))
{
addEventListener(u"click", &clickListener);
}
HTMLAnchorElementImp::~HTMLAnchorElementImp()
{
}
std::u16string HTMLAnchorElementImp::getHref()
{
return getAttribute(u"href");
}
void HTMLAnchorElementImp::setHref(std::u16string href)
{
// TODO: implement me!
}
std::u16string HTMLAnchorElementImp::getTarget()
{
// TODO: implement me!
return u"";
}
void HTMLAnchorElementImp::setTarget(std::u16string target)
{
// TODO: implement me!
}
std::u16string HTMLAnchorElementImp::getPing()
{
// TODO: implement me!
return u"";
}
void HTMLAnchorElementImp::setPing(std::u16string ping)
{
// TODO: implement me!
}
std::u16string HTMLAnchorElementImp::getRel()
{
// TODO: implement me!
return u"";
}
void HTMLAnchorElementImp::setRel(std::u16string rel)
{
// TODO: implement me!
}
DOMTokenList HTMLAnchorElementImp::getRelList()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
std::u16string HTMLAnchorElementImp::getMedia()
{
// TODO: implement me!
return u"";
}
void HTMLAnchorElementImp::setMedia(std::u16string media)
{
// TODO: implement me!
}
std::u16string HTMLAnchorElementImp::getHreflang()
{
// TODO: implement me!
return u"";
}
void HTMLAnchorElementImp::setHreflang(std::u16string hreflang)
{
// TODO: implement me!
}
std::u16string HTMLAnchorElementImp::getType()
{
// TODO: implement me!
return u"";
}
void HTMLAnchorElementImp::setType(std::u16string type)
{
// TODO: implement me!
}
std::u16string HTMLAnchorElementImp::getText()
{
// TODO: implement me!
return u"";
}
void HTMLAnchorElementImp::setText(std::u16string text)
{
// TODO: implement me!
}
std::u16string HTMLAnchorElementImp::getProtocol()
{
// TODO: implement me!
return u"";
}
void HTMLAnchorElementImp::setProtocol(std::u16string protocol)
{
// TODO: implement me!
}
std::u16string HTMLAnchorElementImp::getHost()
{
// TODO: implement me!
return u"";
}
void HTMLAnchorElementImp::setHost(std::u16string host)
{
// TODO: implement me!
}
std::u16string HTMLAnchorElementImp::getHostname()
{
// TODO: implement me!
return u"";
}
void HTMLAnchorElementImp::setHostname(std::u16string hostname)
{
// TODO: implement me!
}
std::u16string HTMLAnchorElementImp::getPort()
{
// TODO: implement me!
return u"";
}
void HTMLAnchorElementImp::setPort(std::u16string port)
{
// TODO: implement me!
}
std::u16string HTMLAnchorElementImp::getPathname()
{
// TODO: implement me!
return u"";
}
void HTMLAnchorElementImp::setPathname(std::u16string pathname)
{
// TODO: implement me!
}
std::u16string HTMLAnchorElementImp::getSearch()
{
// TODO: implement me!
return u"";
}
void HTMLAnchorElementImp::setSearch(std::u16string search)
{
// TODO: implement me!
}
std::u16string HTMLAnchorElementImp::getHash()
{
// TODO: implement me!
return u"";
}
void HTMLAnchorElementImp::setHash(std::u16string hash)
{
// TODO: implement me!
}
std::u16string HTMLAnchorElementImp::getCoords()
{
// TODO: implement me!
return u"";
}
void HTMLAnchorElementImp::setCoords(std::u16string coords)
{
// TODO: implement me!
}
std::u16string HTMLAnchorElementImp::getCharset()
{
// TODO: implement me!
return u"";
}
void HTMLAnchorElementImp::setCharset(std::u16string charset)
{
// TODO: implement me!
}
std::u16string HTMLAnchorElementImp::getName()
{
// TODO: implement me!
return u"";
}
void HTMLAnchorElementImp::setName(std::u16string name)
{
// TODO: implement me!
}
std::u16string HTMLAnchorElementImp::getRev()
{
// TODO: implement me!
return u"";
}
void HTMLAnchorElementImp::setRev(std::u16string rev)
{
// TODO: implement me!
}
std::u16string HTMLAnchorElementImp::getShape()
{
// TODO: implement me!
return u"";
}
void HTMLAnchorElementImp::setShape(std::u16string shape)
{
// TODO: implement me!
}
}
}
}
}
<commit_msg>(HTMLAnchorElementImp::handleClick) : Fix a bug.<commit_after>/*
* Copyright 2011 Esrille Inc.
*
* 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 "HTMLAnchorElementImp.h"
#include <iostream>
#include <boost/bind.hpp>
#include "utf.h"
namespace org
{
namespace w3c
{
namespace dom
{
namespace bootstrap
{
void HTMLAnchorElementImp::handleClick(events::Event event)
{
if (event.getDefaultPrevented())
return;
std::u16string href = getHref();
if (!href.empty())
getOwnerDocument().setLocation(href);
}
HTMLAnchorElementImp::HTMLAnchorElementImp(DocumentImp* ownerDocument) :
ObjectMixin(ownerDocument, u"a"),
clickListener(boost::bind(&HTMLAnchorElementImp::handleClick, this, _1))
{
addEventListener(u"click", &clickListener);
}
HTMLAnchorElementImp::HTMLAnchorElementImp(HTMLAnchorElementImp* org, bool deep) :
ObjectMixin(org, deep),
clickListener(boost::bind(&HTMLAnchorElementImp::handleClick, this, _1))
{
addEventListener(u"click", &clickListener);
}
HTMLAnchorElementImp::~HTMLAnchorElementImp()
{
}
std::u16string HTMLAnchorElementImp::getHref()
{
return getAttribute(u"href");
}
void HTMLAnchorElementImp::setHref(std::u16string href)
{
// TODO: implement me!
}
std::u16string HTMLAnchorElementImp::getTarget()
{
// TODO: implement me!
return u"";
}
void HTMLAnchorElementImp::setTarget(std::u16string target)
{
// TODO: implement me!
}
std::u16string HTMLAnchorElementImp::getPing()
{
// TODO: implement me!
return u"";
}
void HTMLAnchorElementImp::setPing(std::u16string ping)
{
// TODO: implement me!
}
std::u16string HTMLAnchorElementImp::getRel()
{
// TODO: implement me!
return u"";
}
void HTMLAnchorElementImp::setRel(std::u16string rel)
{
// TODO: implement me!
}
DOMTokenList HTMLAnchorElementImp::getRelList()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
std::u16string HTMLAnchorElementImp::getMedia()
{
// TODO: implement me!
return u"";
}
void HTMLAnchorElementImp::setMedia(std::u16string media)
{
// TODO: implement me!
}
std::u16string HTMLAnchorElementImp::getHreflang()
{
// TODO: implement me!
return u"";
}
void HTMLAnchorElementImp::setHreflang(std::u16string hreflang)
{
// TODO: implement me!
}
std::u16string HTMLAnchorElementImp::getType()
{
// TODO: implement me!
return u"";
}
void HTMLAnchorElementImp::setType(std::u16string type)
{
// TODO: implement me!
}
std::u16string HTMLAnchorElementImp::getText()
{
// TODO: implement me!
return u"";
}
void HTMLAnchorElementImp::setText(std::u16string text)
{
// TODO: implement me!
}
std::u16string HTMLAnchorElementImp::getProtocol()
{
// TODO: implement me!
return u"";
}
void HTMLAnchorElementImp::setProtocol(std::u16string protocol)
{
// TODO: implement me!
}
std::u16string HTMLAnchorElementImp::getHost()
{
// TODO: implement me!
return u"";
}
void HTMLAnchorElementImp::setHost(std::u16string host)
{
// TODO: implement me!
}
std::u16string HTMLAnchorElementImp::getHostname()
{
// TODO: implement me!
return u"";
}
void HTMLAnchorElementImp::setHostname(std::u16string hostname)
{
// TODO: implement me!
}
std::u16string HTMLAnchorElementImp::getPort()
{
// TODO: implement me!
return u"";
}
void HTMLAnchorElementImp::setPort(std::u16string port)
{
// TODO: implement me!
}
std::u16string HTMLAnchorElementImp::getPathname()
{
// TODO: implement me!
return u"";
}
void HTMLAnchorElementImp::setPathname(std::u16string pathname)
{
// TODO: implement me!
}
std::u16string HTMLAnchorElementImp::getSearch()
{
// TODO: implement me!
return u"";
}
void HTMLAnchorElementImp::setSearch(std::u16string search)
{
// TODO: implement me!
}
std::u16string HTMLAnchorElementImp::getHash()
{
// TODO: implement me!
return u"";
}
void HTMLAnchorElementImp::setHash(std::u16string hash)
{
// TODO: implement me!
}
std::u16string HTMLAnchorElementImp::getCoords()
{
// TODO: implement me!
return u"";
}
void HTMLAnchorElementImp::setCoords(std::u16string coords)
{
// TODO: implement me!
}
std::u16string HTMLAnchorElementImp::getCharset()
{
// TODO: implement me!
return u"";
}
void HTMLAnchorElementImp::setCharset(std::u16string charset)
{
// TODO: implement me!
}
std::u16string HTMLAnchorElementImp::getName()
{
// TODO: implement me!
return u"";
}
void HTMLAnchorElementImp::setName(std::u16string name)
{
// TODO: implement me!
}
std::u16string HTMLAnchorElementImp::getRev()
{
// TODO: implement me!
return u"";
}
void HTMLAnchorElementImp::setRev(std::u16string rev)
{
// TODO: implement me!
}
std::u16string HTMLAnchorElementImp::getShape()
{
// TODO: implement me!
return u"";
}
void HTMLAnchorElementImp::setShape(std::u16string shape)
{
// TODO: implement me!
}
}
}
}
}
<|endoftext|> |
<commit_before>/*
* Copyright © 2012 Intel Corporation
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* 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, see <http://www.gnu.org/licenses/>.
*
* Author: Benjamin Segovia <[email protected]>
*/
/**
* \file lowering.cpp
* \author Benjamin Segovia <[email protected]>
*/
#include "ir/context.hpp"
#include "ir/value.hpp"
#include "ir/liveness.hpp"
#include "sys/set.hpp"
namespace gbe {
namespace ir {
/*! Small helper class to lower return instructions */
class ContextReturn : public Context
{
public:
/*! Initialize a context dedicated to return instruction lowering */
ContextReturn(Unit &unit) : Context(unit) {
this->usedLabels = GBE_NEW_NO_ARG(vector<uint8_t>);
}
/*! Lower the return instruction to gotos for the given function */
void lower(const std::string &functionName);
};
void ContextReturn::lower(const std::string &functionName) {
if ((this->fn = unit.getFunction(functionName)) == NULL)
return;
// Append a new block at the end of the function with a return instruction:
// the only one we are going to have
this->bb = &this->fn->getBottomBlock();
const LabelIndex index = this->label();
this->LABEL(index);
const BasicBlock *lastBlock = this->bb;
this->RET();
// Now traverse all instructions and replace all returns by GOTO index
fn->foreachInstruction([&](Instruction &insn) {
if (insn.getParent() == lastBlock) return; // This is the last block
if (insn.getOpcode() != OP_RET) return;
const Instruction bra = ir::BRA(index);
bra.replace(&insn);
});
}
void lowerReturn(Unit &unit, const std::string &functionName) {
ContextReturn ctx(unit);
ctx.lower(functionName);
}
/*! Characterizes how the argument is used (directly read, indirectly read,
* written)
*/
enum ArgUse {
ARG_DIRECT_READ = 0,
ARG_INDIRECT_READ = 1,
ARG_WRITTEN = 2
};
/*! Just to book keep the sequence of instructions that directly load an input
* argument
*/
struct LoadAddImm {
Instruction *load; //!< Load from the argument
Instruction *add; //!< Can be NULL if we only have load(arg)
Instruction *loadImm; //!< Can also be NULL
uint64_t offset; //!< Offset where to load in the structure
uint32_t argID; //!< Associated function argument
};
/*! List of direct loads */
typedef vector<LoadAddImm> LoadAddImmSeq;
/*! Helper class to lower function arguments if required */
class FunctionArgumentLowerer : public Context
{
public:
/*! Build the helper structure */
FunctionArgumentLowerer(Unit &unit);
/*! Free everything we needed */
virtual ~FunctionArgumentLowerer(void);
/*! Perform all function arguments substitution if needed */
void lower(const std::string &name);
/*! Lower the given function argument accesses */
void lower(uint32_t argID);
/*! Build the constant push for the function */
void buildConstantPush(void);
/*! Inspect the given function argument to see how it is used. If this is
* direct loads only, we also output the list of instructions used for each
* load
*/
ArgUse getArgUse(uint32_t argID);
/*! Recursively look if there is a store in the given use */
bool useStore(const ValueDef &def, set<const Instruction*> &visited);
/*! Look if the pointer use only load with immediate offsets */
bool matchLoadAddImm(uint32_t argID);
Liveness *liveness; //!< To compute the function graph
FunctionDAG *dag; //!< Contains complete dependency information
LoadAddImmSeq seq; //!< All the direct loads
};
INLINE uint64_t getOffsetFromImm(const Immediate &imm) {
switch (imm.type) {
// bit-cast these ones
case TYPE_DOUBLE:
case TYPE_FLOAT:
case TYPE_S64:
case TYPE_U64:
case TYPE_U32:
case TYPE_U16:
case TYPE_U8: return imm.data.u64;
// sign extend these ones
case TYPE_S32: return int64_t(imm.data.s32);
case TYPE_S16: return int64_t(imm.data.s16);
case TYPE_S8: return int64_t(imm.data.s8);
case TYPE_BOOL:
case TYPE_HALF: NOT_SUPPORTED; return 0;
}
return 0;
}
bool matchLoad(Instruction *insn,
Instruction *add,
Instruction *loadImm,
uint64_t offset,
uint32_t argID,
LoadAddImm &loadAddImm)
{
const Opcode opcode = insn->getOpcode();
if (opcode == OP_LOAD) {
LoadInstruction *load = cast<LoadInstruction>(insn);
if (load->getAddressSpace() != MEM_PRIVATE)
return false;
loadAddImm.load = insn;
loadAddImm.add = add;
loadAddImm.loadImm = loadImm;
loadAddImm.offset = offset;
loadAddImm.argID = argID;
return true;
} else
return false;
}
FunctionArgumentLowerer::FunctionArgumentLowerer(Unit &unit) :
Context(unit), liveness(NULL), dag(NULL) {}
FunctionArgumentLowerer::~FunctionArgumentLowerer(void) {
GBE_SAFE_DELETE(dag);
GBE_SAFE_DELETE(liveness);
}
void FunctionArgumentLowerer::lower(const std::string &functionName) {
if ((this->fn = unit.getFunction(functionName)) == NULL)
return;
GBE_SAFE_DELETE(dag);
GBE_SAFE_DELETE(liveness);
this->liveness = GBE_NEW(ir::Liveness, *fn);
this->dag = GBE_NEW(ir::FunctionDAG, *this->liveness);
// Process all structure arguments and find all the direct loads we can
// replace
const uint32_t argNum = fn->argNum();
for (uint32_t argID = 0; argID < argNum; ++argID) {
FunctionArgument &arg = fn->getArg(argID);
if (arg.type != FunctionArgument::STRUCTURE) continue;
this->lower(argID);
}
// Build the constant push description and remove the instruction that
// therefore become useless
this->buildConstantPush();
}
// Remove all the given instructions from the stream (if dead)
#define REMOVE_INSN(WHICH) \
for (const auto &loadAddImm : seq) { \
Instruction *WHICH = loadAddImm.WHICH; \
if (WHICH == NULL) continue; \
const UseSet &useSet = dag->getUse(WHICH, 0); \
bool isDead = true; \
for (auto use : useSet) { \
if (dead.contains(use->getInstruction()) == false) { \
isDead = false; \
break; \
} \
} \
if (isDead) { \
dead.insert(WHICH); \
WHICH->remove(); \
} \
}
void FunctionArgumentLowerer::buildConstantPush(void)
{
if (seq.size() == 0)
return;
// Track instructions we remove to recursively kill them properly
set<const Instruction*> dead;
// The argument location we already pushed (since the same argument location
// can be used several times)
set<PushLocation> inserted;
for (const auto &loadAddImm : seq) {
LoadInstruction *load = cast<LoadInstruction>(loadAddImm.load);
const uint32_t valueNum = load->getValueNum();
for (uint32_t valueID = 0; valueID < valueNum; ++valueID) {
const Type type = load->getValueType();
const RegisterFamily family = getFamily(type);
const uint32_t size = getFamilySize(family);
const uint32_t offset = loadAddImm.offset + valueID * size;
const PushLocation argLocation(*fn, loadAddImm.argID, offset);
if (inserted.contains(argLocation))
continue;
Register pushed;
const Register reg = load->getValue(valueID);
if (offset != 0) {
pushed = fn->newRegister(family);
this->appendPushedConstant(pushed, argLocation);
inserted.insert(argLocation);
} else {
pushed = fn->getArg(loadAddImm.argID).reg;
}
// TODO the MOV instruction can be most of the time avoided if the
// register is never written. We must however support the register
// replacement in the instruction interface to be able to patch all the
// instruction that uses "reg"
const Instruction mov = ir::MOV(type, reg, pushed);
mov.replace(load);
dead.insert(load);
}
}
// Remove all unused adds and load immediates
REMOVE_INSN(add)
REMOVE_INSN(loadImm)
}
#undef REMOVE_INSN
bool FunctionArgumentLowerer::useStore(const ValueDef &def, set<const Instruction*> &visited)
{
const UseSet &useSet = dag->getUse(def);
for (const auto &use : useSet) {
const Instruction *insn = use->getInstruction();
const uint32_t srcID = use->getSrcID();
const Opcode opcode = insn->getOpcode();
if (visited.contains(insn)) continue;
visited.insert(insn);
if (opcode == OP_STORE && srcID == StoreInstruction::addressIndex)
return true;
if (insn->isMemberOf<UnaryInstruction>() == false &&
insn->isMemberOf<BinaryInstruction>() == false)
continue;
else {
const uint32_t dstNum = insn->getDstNum();
for (uint32_t dstID = 0; dstID < dstNum; ++dstID)
if (this->useStore(ValueDef(insn, dstID), visited) == true)
return true;
}
}
return false;
}
bool FunctionArgumentLowerer::matchLoadAddImm(uint32_t argID)
{
const FunctionArgument &arg = fn->getArg(argID);
LoadAddImmSeq tmpSeq;
// Inspect all uses of the function argument pointer
const UseSet &useSet = dag->getUse(&arg);
for (auto use : useSet) {
Instruction *insn = const_cast<Instruction*>(use->getInstruction());
const Opcode opcode = insn->getOpcode();
// load dst arg
LoadAddImm loadAddImm;
if (matchLoad(insn, NULL, NULL, 0, argID, loadAddImm)) {
tmpSeq.push_back(loadAddImm);
continue;
}
// add.ptr_type dst ptr other
if (opcode != OP_ADD) return false;
BinaryInstruction *add = cast<BinaryInstruction>(insn);
const Type addType = add->getType();
const RegisterFamily family = getFamily(addType);
if (family != unit.getPointerFamily()) return false;
if (addType == TYPE_FLOAT) return false;
// step 1 -> check that the other source comes from a load immediate
const uint32_t srcID = use->getSrcID();
const uint32_t otherID = srcID ^ 1;
const DefSet &defSet = dag->getDef(insn, otherID);
const uint32_t defNum = defSet.size();
if (defNum == 0 || defNum > 1) continue; // undefined or more than one def
const ValueDef *otherDef = *defSet.begin();
if (otherDef->getType() != ValueDef::DEF_INSN_DST) return false;
Instruction *otherInsn = const_cast<Instruction*>(otherDef->getInstruction());
if (otherInsn->getOpcode() != OP_LOADI) return false;
LoadImmInstruction *loadImm = cast<LoadImmInstruction>(otherInsn);
const Immediate imm = loadImm->getImmediate();
const uint64_t offset = getOffsetFromImm(imm);
// step 2 -> check that the results of the add are loads from private
// memory
const UseSet &addUseSet = dag->getUse(add, 0);
for (auto addUse : addUseSet) {
Instruction *insn = const_cast<Instruction*>(addUse->getInstruction());
// We finally find something like load dst arg+imm
LoadAddImm loadAddImm;
if (matchLoad(insn, add, loadImm, offset, argID, loadAddImm)) {
tmpSeq.push_back(loadAddImm);
continue;
}
}
}
// OK, the argument only need direct loads. We can now append all the
// direct load definitions we found
for (const auto &loadImmSeq : tmpSeq)
seq.push_back(loadImmSeq);
return true;
}
ArgUse FunctionArgumentLowerer::getArgUse(uint32_t argID)
{
FunctionArgument &arg = fn->getArg(argID);
// case 1 - we may store something to the structure argument
set<const Instruction*> visited;
if (this->useStore(ValueDef(&arg), visited))
return ARG_WRITTEN;
// case 2 - we look for the patterns: LOAD(ptr) or LOAD(ptr+imm)
if (this->matchLoadAddImm(argID))
return ARG_DIRECT_READ;
// case 3 - LOAD(ptr+runtime_value)
return ARG_INDIRECT_READ;
}
void FunctionArgumentLowerer::lower(uint32_t argID) {
IF_DEBUG(const ArgUse argUse = )this->getArgUse(argID);
#if GBE_DEBUG
GBE_ASSERTM(argUse != ARG_WRITTEN,
"TODO A store to a structure argument "
"(i.e. not a char/short/int/float argument) has been found. "
"This is not supported yet");
GBE_ASSERTM(argUse != ARG_INDIRECT_READ,
"TODO Only direct loads of structure arguments are "
"supported now");
#endif /* GBE_DEBUG */
}
void lowerFunctionArguments(Unit &unit, const std::string &functionName) {
FunctionArgumentLowerer lowerer(unit);
lowerer.lower(functionName);
}
} /* namespace ir */
} /* namespace gbe */
<commit_msg>Fix utest compiler_function_argument3 error after move -O2 to backend.<commit_after>/*
* Copyright © 2012 Intel Corporation
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* 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, see <http://www.gnu.org/licenses/>.
*
* Author: Benjamin Segovia <[email protected]>
*/
/**
* \file lowering.cpp
* \author Benjamin Segovia <[email protected]>
*/
#include "ir/context.hpp"
#include "ir/value.hpp"
#include "ir/liveness.hpp"
#include "sys/set.hpp"
namespace gbe {
namespace ir {
/*! Small helper class to lower return instructions */
class ContextReturn : public Context
{
public:
/*! Initialize a context dedicated to return instruction lowering */
ContextReturn(Unit &unit) : Context(unit) {
this->usedLabels = GBE_NEW_NO_ARG(vector<uint8_t>);
}
/*! Lower the return instruction to gotos for the given function */
void lower(const std::string &functionName);
};
void ContextReturn::lower(const std::string &functionName) {
if ((this->fn = unit.getFunction(functionName)) == NULL)
return;
// Append a new block at the end of the function with a return instruction:
// the only one we are going to have
this->bb = &this->fn->getBottomBlock();
const LabelIndex index = this->label();
this->LABEL(index);
const BasicBlock *lastBlock = this->bb;
this->RET();
// Now traverse all instructions and replace all returns by GOTO index
fn->foreachInstruction([&](Instruction &insn) {
if (insn.getParent() == lastBlock) return; // This is the last block
if (insn.getOpcode() != OP_RET) return;
const Instruction bra = ir::BRA(index);
bra.replace(&insn);
});
}
void lowerReturn(Unit &unit, const std::string &functionName) {
ContextReturn ctx(unit);
ctx.lower(functionName);
}
/*! Characterizes how the argument is used (directly read, indirectly read,
* written)
*/
enum ArgUse {
ARG_DIRECT_READ = 0,
ARG_INDIRECT_READ = 1,
ARG_WRITTEN = 2
};
/*! Just to book keep the sequence of instructions that directly load an input
* argument
*/
struct LoadAddImm {
Instruction *load; //!< Load from the argument
Instruction *add; //!< Can be NULL if we only have load(arg)
Instruction *loadImm; //!< Can also be NULL
uint64_t offset; //!< Offset where to load in the structure
uint32_t argID; //!< Associated function argument
};
/*! List of direct loads */
typedef vector<LoadAddImm> LoadAddImmSeq;
/*! Helper class to lower function arguments if required */
class FunctionArgumentLowerer : public Context
{
public:
/*! Build the helper structure */
FunctionArgumentLowerer(Unit &unit);
/*! Free everything we needed */
virtual ~FunctionArgumentLowerer(void);
/*! Perform all function arguments substitution if needed */
void lower(const std::string &name);
/*! Lower the given function argument accesses */
void lower(uint32_t argID);
/*! Build the constant push for the function */
void buildConstantPush(void);
/*! Inspect the given function argument to see how it is used. If this is
* direct loads only, we also output the list of instructions used for each
* load
*/
ArgUse getArgUse(uint32_t argID);
/*! Recursively look if there is a store in the given use */
bool useStore(const ValueDef &def, set<const Instruction*> &visited);
/*! Look if the pointer use only load with immediate offsets */
bool matchLoadAddImm(uint32_t argID);
Liveness *liveness; //!< To compute the function graph
FunctionDAG *dag; //!< Contains complete dependency information
LoadAddImmSeq seq; //!< All the direct loads
};
INLINE uint64_t getOffsetFromImm(const Immediate &imm) {
switch (imm.type) {
// bit-cast these ones
case TYPE_DOUBLE:
case TYPE_FLOAT:
case TYPE_S64:
case TYPE_U64:
case TYPE_U32:
case TYPE_U16:
case TYPE_U8: return imm.data.u64;
// sign extend these ones
case TYPE_S32: return int64_t(imm.data.s32);
case TYPE_S16: return int64_t(imm.data.s16);
case TYPE_S8: return int64_t(imm.data.s8);
case TYPE_BOOL:
case TYPE_HALF: NOT_SUPPORTED; return 0;
}
return 0;
}
bool matchLoad(Instruction *insn,
Instruction *add,
Instruction *loadImm,
uint64_t offset,
uint32_t argID,
LoadAddImm &loadAddImm)
{
const Opcode opcode = insn->getOpcode();
if (opcode == OP_LOAD) {
LoadInstruction *load = cast<LoadInstruction>(insn);
if (load->getAddressSpace() != MEM_PRIVATE)
return false;
loadAddImm.load = insn;
loadAddImm.add = add;
loadAddImm.loadImm = loadImm;
loadAddImm.offset = offset;
loadAddImm.argID = argID;
return true;
} else
return false;
}
FunctionArgumentLowerer::FunctionArgumentLowerer(Unit &unit) :
Context(unit), liveness(NULL), dag(NULL) {}
FunctionArgumentLowerer::~FunctionArgumentLowerer(void) {
GBE_SAFE_DELETE(dag);
GBE_SAFE_DELETE(liveness);
}
void FunctionArgumentLowerer::lower(const std::string &functionName) {
if ((this->fn = unit.getFunction(functionName)) == NULL)
return;
GBE_SAFE_DELETE(dag);
GBE_SAFE_DELETE(liveness);
this->liveness = GBE_NEW(ir::Liveness, *fn);
this->dag = GBE_NEW(ir::FunctionDAG, *this->liveness);
// Process all structure arguments and find all the direct loads we can
// replace
const uint32_t argNum = fn->argNum();
for (uint32_t argID = 0; argID < argNum; ++argID) {
FunctionArgument &arg = fn->getArg(argID);
if (arg.type != FunctionArgument::STRUCTURE) continue;
this->lower(argID);
}
// Build the constant push description and remove the instruction that
// therefore become useless
this->buildConstantPush();
}
// Remove all the given instructions from the stream (if dead)
#define REMOVE_INSN(WHICH) \
for (const auto &loadAddImm : seq) { \
Instruction *WHICH = loadAddImm.WHICH; \
if (WHICH == NULL) continue; \
const UseSet &useSet = dag->getUse(WHICH, 0); \
bool isDead = true; \
for (auto use : useSet) { \
if (dead.contains(use->getInstruction()) == false) { \
isDead = false; \
break; \
} \
} \
if (isDead && !dead.contains(WHICH)) { \
dead.insert(WHICH); \
WHICH->remove(); \
} \
}
void FunctionArgumentLowerer::buildConstantPush(void)
{
if (seq.size() == 0)
return;
// Track instructions we remove to recursively kill them properly
set<const Instruction*> dead;
// The argument location we already pushed (since the same argument location
// can be used several times)
set<PushLocation> inserted;
for (const auto &loadAddImm : seq) {
LoadInstruction *load = cast<LoadInstruction>(loadAddImm.load);
const uint32_t valueNum = load->getValueNum();
for (uint32_t valueID = 0; valueID < valueNum; ++valueID) {
const Type type = load->getValueType();
const RegisterFamily family = getFamily(type);
const uint32_t size = getFamilySize(family);
const uint32_t offset = loadAddImm.offset + valueID * size;
const PushLocation argLocation(*fn, loadAddImm.argID, offset);
Register pushed;
const Register reg = load->getValue(valueID);
if (offset != 0) {
if(inserted.contains(argLocation)) {
pushed = argLocation.getRegister();
} else {
pushed = fn->newRegister(family);
this->appendPushedConstant(pushed, argLocation);
inserted.insert(argLocation);
}
} else {
pushed = fn->getArg(loadAddImm.argID).reg;
}
// TODO the MOV instruction can be most of the time avoided if the
// register is never written. We must however support the register
// replacement in the instruction interface to be able to patch all the
// instruction that uses "reg"
const Instruction mov = ir::MOV(type, reg, pushed);
mov.replace(load);
dead.insert(load);
}
}
REMOVE_INSN(add)
REMOVE_INSN(loadImm)
}
#undef REMOVE_INSN
bool FunctionArgumentLowerer::useStore(const ValueDef &def, set<const Instruction*> &visited)
{
const UseSet &useSet = dag->getUse(def);
for (const auto &use : useSet) {
const Instruction *insn = use->getInstruction();
const uint32_t srcID = use->getSrcID();
const Opcode opcode = insn->getOpcode();
if (visited.contains(insn)) continue;
visited.insert(insn);
if (opcode == OP_STORE && srcID == StoreInstruction::addressIndex)
return true;
if (insn->isMemberOf<UnaryInstruction>() == false &&
insn->isMemberOf<BinaryInstruction>() == false)
continue;
else {
const uint32_t dstNum = insn->getDstNum();
for (uint32_t dstID = 0; dstID < dstNum; ++dstID)
if (this->useStore(ValueDef(insn, dstID), visited) == true)
return true;
}
}
return false;
}
bool FunctionArgumentLowerer::matchLoadAddImm(uint32_t argID)
{
const FunctionArgument &arg = fn->getArg(argID);
LoadAddImmSeq tmpSeq;
// Inspect all uses of the function argument pointer
const UseSet &useSet = dag->getUse(&arg);
for (auto use : useSet) {
Instruction *insn = const_cast<Instruction*>(use->getInstruction());
const Opcode opcode = insn->getOpcode();
// load dst arg
LoadAddImm loadAddImm;
if (matchLoad(insn, NULL, NULL, 0, argID, loadAddImm)) {
tmpSeq.push_back(loadAddImm);
continue;
}
// add.ptr_type dst ptr other
if (opcode != OP_ADD) return false;
BinaryInstruction *add = cast<BinaryInstruction>(insn);
const Type addType = add->getType();
const RegisterFamily family = getFamily(addType);
if (family != unit.getPointerFamily()) return false;
if (addType == TYPE_FLOAT) return false;
// step 1 -> check that the other source comes from a load immediate
const uint32_t srcID = use->getSrcID();
const uint32_t otherID = srcID ^ 1;
const DefSet &defSet = dag->getDef(insn, otherID);
const uint32_t defNum = defSet.size();
if (defNum == 0 || defNum > 1) continue; // undefined or more than one def
const ValueDef *otherDef = *defSet.begin();
if (otherDef->getType() != ValueDef::DEF_INSN_DST) return false;
Instruction *otherInsn = const_cast<Instruction*>(otherDef->getInstruction());
if (otherInsn->getOpcode() != OP_LOADI) return false;
LoadImmInstruction *loadImm = cast<LoadImmInstruction>(otherInsn);
const Immediate imm = loadImm->getImmediate();
const uint64_t offset = getOffsetFromImm(imm);
// step 2 -> check that the results of the add are loads from private
// memory
const UseSet &addUseSet = dag->getUse(add, 0);
for (auto addUse : addUseSet) {
Instruction *insn = const_cast<Instruction*>(addUse->getInstruction());
// We finally find something like load dst arg+imm
LoadAddImm loadAddImm;
if (matchLoad(insn, add, loadImm, offset, argID, loadAddImm)) {
tmpSeq.push_back(loadAddImm);
continue;
}
}
}
// OK, the argument only need direct loads. We can now append all the
// direct load definitions we found
for (const auto &loadImmSeq : tmpSeq)
seq.push_back(loadImmSeq);
return true;
}
ArgUse FunctionArgumentLowerer::getArgUse(uint32_t argID)
{
FunctionArgument &arg = fn->getArg(argID);
// case 1 - we may store something to the structure argument
set<const Instruction*> visited;
if (this->useStore(ValueDef(&arg), visited))
return ARG_WRITTEN;
// case 2 - we look for the patterns: LOAD(ptr) or LOAD(ptr+imm)
if (this->matchLoadAddImm(argID))
return ARG_DIRECT_READ;
// case 3 - LOAD(ptr+runtime_value)
return ARG_INDIRECT_READ;
}
void FunctionArgumentLowerer::lower(uint32_t argID) {
IF_DEBUG(const ArgUse argUse = )this->getArgUse(argID);
#if GBE_DEBUG
GBE_ASSERTM(argUse != ARG_WRITTEN,
"TODO A store to a structure argument "
"(i.e. not a char/short/int/float argument) has been found. "
"This is not supported yet");
GBE_ASSERTM(argUse != ARG_INDIRECT_READ,
"TODO Only direct loads of structure arguments are "
"supported now");
#endif /* GBE_DEBUG */
}
void lowerFunctionArguments(Unit &unit, const std::string &functionName) {
FunctionArgumentLowerer lowerer(unit);
lowerer.lower(functionName);
}
} /* namespace ir */
} /* namespace gbe */
<|endoftext|> |
<commit_before>// Copyright (c) 2018, Joseph Mirabel
// Authors: Joseph Mirabel ([email protected])
//
// This file is part of gepetto-viewer.
// gepetto-viewer is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// gepetto-viewer 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
// General Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// gepetto-viewer. If not, see <http://www.gnu.org/licenses/>.
#include <gepetto/viewer/node-property.h>
namespace graphics {
int MetaEnum::from_string (const std::string& s)
{
for (std::size_t i = 0; i < names.size(); ++i)
if (s == names[i]) return values[i];
throw std::invalid_argument("Unknown name of enum (" + type + "): " + s);
}
std::string MetaEnum::to_string (const int& v)
{
for (std::size_t i = 0; i < names.size(); ++i)
if (v == values[i]) return names[i];
throw std::invalid_argument("Unknown enum value (" + type + ")");
}
MetaEnum* visibilityModeEnum ()
{
static MetaEnum vm;
if (vm.type.size() == 0) {
vm.type = "VisibilityMode";
vm.names .push_back ("ON" ); vm.values.push_back (VISIBILITY_ON );
vm.names .push_back ("ALWAYS_ON_TOP"); vm.values.push_back (ALWAYS_ON_TOP );
vm.names .push_back ("OFF" ); vm.values.push_back (VISIBILITY_OFF);
}
return &vm;
}
MetaEnum* wireFrameModeEnum ()
{
static MetaEnum wm;
if (wm.type.size() == 0) {
wm.type = "VisibilityMode";
wm.names .push_back ("FILL" ); wm.values.push_back (FILL );
wm.names .push_back ("WIREFRAME" ); wm.values.push_back (WIREFRAME );
wm.names .push_back ("FILL_AND_WIREFRAME"); wm.values.push_back (FILL_AND_WIREFRAME);
}
return &wm;
}
MetaEnum* lightingModeEnum ()
{
static MetaEnum lm;
if (lm.type.size() == 0) {
lm.type = "LightingMode";
lm.names .push_back ("ON" ); lm.values.push_back (LIGHT_INFLUENCE_ON );
lm.names .push_back ("OFF"); lm.values.push_back (LIGHT_INFLUENCE_OFF);
}
return &lm;
}
MetaEnum* glImmediateModeEnum ()
{
static MetaEnum lm;
if (lm.type.size() == 0) {
lm.type = "GLImmediateMode";
lm.names.push_back ("GL_LINES "); lm.values.push_back (GL_LINES );
lm.names.push_back ("GL_POINTS "); lm.values.push_back (GL_POINTS );
lm.names.push_back ("GL_LINE_STRIP "); lm.values.push_back (GL_LINE_STRIP );
lm.names.push_back ("GL_LINE_LOOP "); lm.values.push_back (GL_LINE_LOOP );
lm.names.push_back ("GL_POLYGON "); lm.values.push_back (GL_POLYGON );
lm.names.push_back ("GL_QUADS "); lm.values.push_back (GL_QUADS );
lm.names.push_back ("GL_QUAD_STRIP "); lm.values.push_back (GL_QUAD_STRIP );
lm.names.push_back ("GL_TRIANGLE_STRIP"); lm.values.push_back (GL_TRIANGLE_STRIP);
lm.names.push_back ("GL_TRIANGLES "); lm.values.push_back (GL_TRIANGLES );
lm.names.push_back ("GL_TRIANGLE_FAN "); lm.values.push_back (GL_TRIANGLE_FAN );
}
return &lm;
}
} /* namespace graphics */
<commit_msg>Fix enum property glImmediateModeEnum<commit_after>// Copyright (c) 2018, Joseph Mirabel
// Authors: Joseph Mirabel ([email protected])
//
// This file is part of gepetto-viewer.
// gepetto-viewer is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// gepetto-viewer 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
// General Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// gepetto-viewer. If not, see <http://www.gnu.org/licenses/>.
#include <gepetto/viewer/node-property.h>
namespace graphics {
int MetaEnum::from_string (const std::string& s)
{
for (std::size_t i = 0; i < names.size(); ++i)
if (s == names[i]) return values[i];
throw std::invalid_argument("Unknown name of enum (" + type + "): " + s);
}
std::string MetaEnum::to_string (const int& v)
{
for (std::size_t i = 0; i < names.size(); ++i)
if (v == values[i]) return names[i];
throw std::invalid_argument("Unknown enum value (" + type + ")");
}
MetaEnum* visibilityModeEnum ()
{
static MetaEnum vm;
if (vm.type.size() == 0) {
vm.type = "VisibilityMode";
vm.names .push_back ("ON" ); vm.values.push_back (VISIBILITY_ON );
vm.names .push_back ("ALWAYS_ON_TOP"); vm.values.push_back (ALWAYS_ON_TOP );
vm.names .push_back ("OFF" ); vm.values.push_back (VISIBILITY_OFF);
}
return &vm;
}
MetaEnum* wireFrameModeEnum ()
{
static MetaEnum wm;
if (wm.type.size() == 0) {
wm.type = "VisibilityMode";
wm.names .push_back ("FILL" ); wm.values.push_back (FILL );
wm.names .push_back ("WIREFRAME" ); wm.values.push_back (WIREFRAME );
wm.names .push_back ("FILL_AND_WIREFRAME"); wm.values.push_back (FILL_AND_WIREFRAME);
}
return &wm;
}
MetaEnum* lightingModeEnum ()
{
static MetaEnum lm;
if (lm.type.size() == 0) {
lm.type = "LightingMode";
lm.names .push_back ("ON" ); lm.values.push_back (LIGHT_INFLUENCE_ON );
lm.names .push_back ("OFF"); lm.values.push_back (LIGHT_INFLUENCE_OFF);
}
return &lm;
}
MetaEnum* glImmediateModeEnum ()
{
static MetaEnum lm;
if (lm.type.size() == 0) {
lm.type = "GLImmediateMode";
lm.names.push_back ("GL_LINES" ); lm.values.push_back (GL_LINES );
lm.names.push_back ("GL_POINTS" ); lm.values.push_back (GL_POINTS );
lm.names.push_back ("GL_LINE_STRIP" ); lm.values.push_back (GL_LINE_STRIP );
lm.names.push_back ("GL_LINE_LOOP" ); lm.values.push_back (GL_LINE_LOOP );
lm.names.push_back ("GL_POLYGON" ); lm.values.push_back (GL_POLYGON );
lm.names.push_back ("GL_QUADS" ); lm.values.push_back (GL_QUADS );
lm.names.push_back ("GL_QUAD_STRIP" ); lm.values.push_back (GL_QUAD_STRIP );
lm.names.push_back ("GL_TRIANGLE_STRIP"); lm.values.push_back (GL_TRIANGLE_STRIP);
lm.names.push_back ("GL_TRIANGLES" ); lm.values.push_back (GL_TRIANGLES );
lm.names.push_back ("GL_TRIANGLE_FAN" ); lm.values.push_back (GL_TRIANGLE_FAN );
}
return &lm;
}
} /* namespace graphics */
<|endoftext|> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.