<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.
 *
 ****************************************************************************/

/**
 * @file SDP3X.hpp
 *
 * Driver for Sensirion SDP3X Differential Pressure Sensor
 *
 */

#include "SDP3X.hpp"

using namespace time_literals;

int
SDP3X::probe()
{
	bool require_initialization = !init_sdp3x();

	if (require_initialization && _keep_retrying) {
		PX4_INFO("no sensor found, but will keep retrying");
		return 0;
	}

	return require_initialization ? -1 : 0;
}

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()
{
	if (get_device_address() == I2C_ADDRESS_1_SDP3X) { // since we are broadcasting, only do it for the first device address
		// reset on broadcast
		uint16_t prev_addr = get_device_address();
		set_device_address(SDP3X_RESET_ADDR);
		uint8_t reset_cmd = SDP3X_RESET_CMD;
		int ret = transfer(&reset_cmd, 1, nullptr, 0);
		set_device_address(prev_addr);

		if (ret != PX4_OK) {
			perf_count(_comms_errors);
			return false;
		}

		// wait until sensor is ready
		px4_usleep(20000);
	}

	return configure() == 0;
}

int
SDP3X::configure()
{
	int ret = write_command(SDP3X_CONT_MEAS_AVG_MODE);

	if (ret != PX4_OK) {
		perf_count(_comms_errors);
		DEVICE_DEBUG("config failed");
		_state = State::RequireConfig;
		return ret;
	}

	_state = State::Configuring;

	return ret;
}

int
SDP3X::read_scale()
{
	// get scale
	uint8_t val[9];
	int ret = transfer(nullptr, 0, &val[0], sizeof(val));

	if (ret != PX4_OK) {
		perf_count(_comms_errors);
		PX4_ERR("get scale failed");
		return ret;
	}

	// 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 PX4_ERROR;
	}

	_scale = (((uint16_t)val[6]) << 8) | val[7];

	switch (_scale) {
	case SDP3X_SCALE_PRESSURE_SDP31:
		_device_id.devid_s.devtype = DRV_DIFF_PRESS_DEVTYPE_SDP31;
		break;

	case SDP3X_SCALE_PRESSURE_SDP32:
		_device_id.devid_s.devtype = DRV_DIFF_PRESS_DEVTYPE_SDP32;
		break;

	case SDP3X_SCALE_PRESSURE_SDP33:
		_device_id.devid_s.devtype = DRV_DIFF_PRESS_DEVTYPE_SDP33;
		break;
	}

	return PX4_OK;
}

void SDP3X::start()
{
	// make sure to wait 10ms after configuring the measurement mode
	ScheduleDelayed(10_ms);
}

int
SDP3X::collect()
{
	perf_begin(_sample_perf);

	// read 6 bytes from the sensor
	uint8_t val[6];
	int ret = transfer(nullptr, 0, &val[0], sizeof(val));

	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;
	}

	int16_t P = (((int16_t)val[0]) << 8) | val[1];
	int16_t temp = (((int16_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);

	differential_pressure_s report{};

	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) - _diff_pres_offset;
	report.differential_pressure_raw_pa = diff_press_pa_raw - _diff_pres_offset;
	report.device_id = _device_id.devid;

	_airspeed_pub.publish(report);

	perf_end(_sample_perf);

	return ret;
}

void
SDP3X::RunImpl()
{
	switch (_state) {
	case State::RequireConfig:
		if (configure() == PX4_OK) {
			ScheduleDelayed(10_ms);

		} else {
			// periodically retry to configure
			ScheduleDelayed(300_ms);
		}

		break;

	case State::Configuring:
		if (read_scale() == 0) {
			_state = State::Running;

		} else {
			_state = State::RequireConfig;
		}

		ScheduleDelayed(10_ms);
		break;

	case State::Running:
		int ret = collect();

		if (ret != 0 && ret != -EAGAIN) {
			_sensor_ok = false;
			DEVICE_DEBUG("measure error");
			_state = State::RequireConfig;
		}

		ScheduleDelayed(CONVERSION_INTERVAL);
		break;
	}
}

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);
}
<commit_msg>sdp3x: remove reset during init<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.
 *
 ****************************************************************************/

/**
 * @file SDP3X.hpp
 *
 * Driver for Sensirion SDP3X Differential Pressure Sensor
 *
 */

#include "SDP3X.hpp"

using namespace time_literals;

int
SDP3X::probe()
{
	bool require_initialization = !init_sdp3x();

	if (require_initialization && _keep_retrying) {
		PX4_INFO("no sensor found, but will keep retrying");
		return 0;
	}

	return require_initialization ? -1 : 0;
}

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()
{
	return configure() == 0;
}

int
SDP3X::configure()
{
	int ret = write_command(SDP3X_CONT_MEAS_AVG_MODE);

	if (ret != PX4_OK) {
		perf_count(_comms_errors);
		DEVICE_DEBUG("config failed");
		_state = State::RequireConfig;
		return ret;
	}

	_state = State::Configuring;

	return ret;
}

int
SDP3X::read_scale()
{
	// get scale
	uint8_t val[9];
	int ret = transfer(nullptr, 0, &val[0], sizeof(val));

	if (ret != PX4_OK) {
		perf_count(_comms_errors);
		PX4_ERR("get scale failed");
		return ret;
	}

	// 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 PX4_ERROR;
	}

	_scale = (((uint16_t)val[6]) << 8) | val[7];

	switch (_scale) {
	case SDP3X_SCALE_PRESSURE_SDP31:
		_device_id.devid_s.devtype = DRV_DIFF_PRESS_DEVTYPE_SDP31;
		break;

	case SDP3X_SCALE_PRESSURE_SDP32:
		_device_id.devid_s.devtype = DRV_DIFF_PRESS_DEVTYPE_SDP32;
		break;

	case SDP3X_SCALE_PRESSURE_SDP33:
		_device_id.devid_s.devtype = DRV_DIFF_PRESS_DEVTYPE_SDP33;
		break;
	}

	return PX4_OK;
}

void SDP3X::start()
{
	// make sure to wait 10ms after configuring the measurement mode
	ScheduleDelayed(10_ms);
}

int
SDP3X::collect()
{
	perf_begin(_sample_perf);

	// read 6 bytes from the sensor
	uint8_t val[6];
	int ret = transfer(nullptr, 0, &val[0], sizeof(val));

	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;
	}

	int16_t P = (((int16_t)val[0]) << 8) | val[1];
	int16_t temp = (((int16_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);

	differential_pressure_s report{};

	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) - _diff_pres_offset;
	report.differential_pressure_raw_pa = diff_press_pa_raw - _diff_pres_offset;
	report.device_id = _device_id.devid;

	_airspeed_pub.publish(report);

	perf_end(_sample_perf);

	return ret;
}

void
SDP3X::RunImpl()
{
	switch (_state) {
	case State::RequireConfig:
		if (configure() == PX4_OK) {
			ScheduleDelayed(10_ms);

		} else {
			// periodically retry to configure
			ScheduleDelayed(300_ms);
		}

		break;

	case State::Configuring:
		if (read_scale() == 0) {
			_state = State::Running;

		} else {
			_state = State::RequireConfig;
		}

		ScheduleDelayed(10_ms);
		break;

	case State::Running:
		int ret = collect();

		if (ret != 0 && ret != -EAGAIN) {
			_sensor_ok = false;
			DEVICE_DEBUG("measure error");
			_state = State::RequireConfig;
		}

		ScheduleDelayed(CONVERSION_INTERVAL);
		break;
	}
}

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 Daniel Wallin 2006. Use, modification and distribution is
// subject to 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)

#include <boost/python.hpp>
#include <libtorrent/session.hpp>

using namespace boost::python;
using namespace libtorrent;

void bind_session_settings()
{
    class_<session_settings>("session_settings")
        .def_readwrite("user_agent", &session_settings::user_agent)
        .def_readwrite("tracker_completion_timeout", &session_settings::tracker_completion_timeout)
        .def_readwrite("tracker_receive_timeout", &session_settings::tracker_receive_timeout)
        .def_readwrite("tracker_maximum_response_length", &session_settings::tracker_maximum_response_length)
        .def_readwrite("piece_timeout", &session_settings::piece_timeout)
        .def_readwrite("request_queue_time", &session_settings::request_queue_time)
        .def_readwrite("max_allowed_in_request_queue", &session_settings::max_allowed_in_request_queue)
        .def_readwrite("max_out_request_queue", &session_settings::max_out_request_queue)
        .def_readwrite("whole_pieces_threshold", &session_settings::whole_pieces_threshold)
        .def_readwrite("peer_timeout", &session_settings::peer_timeout)
        .def_readwrite("urlseed_timeout", &session_settings::urlseed_timeout)
        .def_readwrite("urlseed_pipeline_size", &session_settings::urlseed_pipeline_size)
        .def_readwrite("file_pool_size", &session_settings::file_pool_size)
        .def_readwrite("allow_multiple_connections_per_ip", &session_settings::allow_multiple_connections_per_ip)
        .def_readwrite("max_failcount", &session_settings::max_failcount)
        .def_readwrite("min_reconnect_time", &session_settings::min_reconnect_time)
        .def_readwrite("peer_connect_timeout", &session_settings::peer_connect_timeout)
        .def_readwrite("ignore_limits_on_local_network", &session_settings::ignore_limits_on_local_network)
        .def_readwrite("connection_speed", &session_settings::connection_speed)
        .def_readwrite("send_redundant_have", &session_settings::send_redundant_have)
        .def_readwrite("lazy_bitfields", &session_settings::lazy_bitfields)
        .def_readwrite("inactivity_timeout", &session_settings::inactivity_timeout)
        .def_readwrite("unchoke_interval", &session_settings::unchoke_interval)
        .def_readwrite("active_downloads", &session_settings::active_downloads)
        .def_readwrite("active_seeds", &session_settings::active_seeds)
        .def_readwrite("active_limit", &session_settings::active_limit)
        .def_readwrite("auto_manage_prefer_seeds", &session_settings::auto_manage_prefer_seeds)
        .def_readwrite("dont_count_slow_torrents", &session_settings::dont_count_slow_torrents)
        .def_readwrite("auto_manage_interval", &session_settings::auto_manage_interval)
        .def_readwrite("share_ratio_limit", &session_settings::share_ratio_limit)
        .def_readwrite("seed_time_ratio_limit", &session_settings::seed_time_ratio_limit)
        .def_readwrite("seed_time_limit", &session_settings::seed_time_limit)
        .def_readwrite("auto_scraped_interval", &session_settings::auto_scrape_interval)
        .def_readwrite("peer_tos", &session_settings::peer_tos)
        .def_readwrite("rate_limit_ip_overhead", &session_settings::rate_limit_ip_overhead)
        .def_readwrite("outgoing_ports", &session_settings::outgoing_ports)
#ifndef TORRENT_DISABLE_DHT
        .def_readwrite("use_dht_as_fallback", &session_settings::use_dht_as_fallback)
#endif
    ;

    enum_<proxy_settings::proxy_type>("proxy_type")
        .value("none", proxy_settings::none)
        .value("socks4", proxy_settings::socks4)
        .value("socks5", proxy_settings::socks5)
        .value("socks5_pw", proxy_settings::socks5_pw)
        .value("http", proxy_settings::http)
        .value("http_pw", proxy_settings::http_pw)
    ;
    class_<proxy_settings>("proxy_settings")
        .def_readwrite("hostname", &proxy_settings::hostname)
        .def_readwrite("port", &proxy_settings::port)
        .def_readwrite("password", &proxy_settings::password)
        .def_readwrite("username", &proxy_settings::username)
        .def_readwrite("type", &proxy_settings::type)
    ;

#ifndef TORRENT_DISABLE_ENCRYPTION
    enum_<pe_settings::enc_policy>("enc_policy")
        .value("forced", pe_settings::forced)
        .value("enabled", pe_settings::enabled)
        .value("disabled", pe_settings::disabled)
    ;

    enum_<pe_settings::enc_level>("enc_level")
        .value("rc4", pe_settings::rc4)
        .value("plaintext", pe_settings::plaintext)
        .value("both", pe_settings::both)
    ;

    class_<pe_settings>("pe_settings")
        .def_readwrite("out_enc_policy", &pe_settings::out_enc_policy)
        .def_readwrite("in_enc_policy", &pe_settings::in_enc_policy)
        .def_readwrite("allowed_enc_level", &pe_settings::allowed_enc_level)
        .def_readwrite("prefer_rc4", &pe_settings::prefer_rc4)
    ;
#endif

}
<commit_msg>Add 'cache_size' and 'cache_expiry' session settings to the python bindings<commit_after>// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to 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)

#include <boost/python.hpp>
#include <libtorrent/session.hpp>

using namespace boost::python;
using namespace libtorrent;

void bind_session_settings()
{
    class_<session_settings>("session_settings")
        .def_readwrite("user_agent", &session_settings::user_agent)
        .def_readwrite("tracker_completion_timeout", &session_settings::tracker_completion_timeout)
        .def_readwrite("tracker_receive_timeout", &session_settings::tracker_receive_timeout)
        .def_readwrite("tracker_maximum_response_length", &session_settings::tracker_maximum_response_length)
        .def_readwrite("piece_timeout", &session_settings::piece_timeout)
        .def_readwrite("request_queue_time", &session_settings::request_queue_time)
        .def_readwrite("max_allowed_in_request_queue", &session_settings::max_allowed_in_request_queue)
        .def_readwrite("max_out_request_queue", &session_settings::max_out_request_queue)
        .def_readwrite("whole_pieces_threshold", &session_settings::whole_pieces_threshold)
        .def_readwrite("peer_timeout", &session_settings::peer_timeout)
        .def_readwrite("urlseed_timeout", &session_settings::urlseed_timeout)
        .def_readwrite("urlseed_pipeline_size", &session_settings::urlseed_pipeline_size)
        .def_readwrite("file_pool_size", &session_settings::file_pool_size)
        .def_readwrite("allow_multiple_connections_per_ip", &session_settings::allow_multiple_connections_per_ip)
        .def_readwrite("max_failcount", &session_settings::max_failcount)
        .def_readwrite("min_reconnect_time", &session_settings::min_reconnect_time)
        .def_readwrite("peer_connect_timeout", &session_settings::peer_connect_timeout)
        .def_readwrite("ignore_limits_on_local_network", &session_settings::ignore_limits_on_local_network)
        .def_readwrite("connection_speed", &session_settings::connection_speed)
        .def_readwrite("send_redundant_have", &session_settings::send_redundant_have)
        .def_readwrite("lazy_bitfields", &session_settings::lazy_bitfields)
        .def_readwrite("inactivity_timeout", &session_settings::inactivity_timeout)
        .def_readwrite("unchoke_interval", &session_settings::unchoke_interval)
        .def_readwrite("active_downloads", &session_settings::active_downloads)
        .def_readwrite("active_seeds", &session_settings::active_seeds)
        .def_readwrite("active_limit", &session_settings::active_limit)
        .def_readwrite("auto_manage_prefer_seeds", &session_settings::auto_manage_prefer_seeds)
        .def_readwrite("dont_count_slow_torrents", &session_settings::dont_count_slow_torrents)
        .def_readwrite("auto_manage_interval", &session_settings::auto_manage_interval)
        .def_readwrite("share_ratio_limit", &session_settings::share_ratio_limit)
        .def_readwrite("seed_time_ratio_limit", &session_settings::seed_time_ratio_limit)
        .def_readwrite("seed_time_limit", &session_settings::seed_time_limit)
        .def_readwrite("auto_scraped_interval", &session_settings::auto_scrape_interval)
        .def_readwrite("peer_tos", &session_settings::peer_tos)
        .def_readwrite("rate_limit_ip_overhead", &session_settings::rate_limit_ip_overhead)
        .def_readwrite("outgoing_ports", &session_settings::outgoing_ports)
        .def_readwrite("cache_size", &session_settings::cache_size)
        .def_readwrite("cache_expiry", &session_settings::cache_expiry)
#ifndef TORRENT_DISABLE_DHT
        .def_readwrite("use_dht_as_fallback", &session_settings::use_dht_as_fallback)
#endif
    ;

    enum_<proxy_settings::proxy_type>("proxy_type")
        .value("none", proxy_settings::none)
        .value("socks4", proxy_settings::socks4)
        .value("socks5", proxy_settings::socks5)
        .value("socks5_pw", proxy_settings::socks5_pw)
        .value("http", proxy_settings::http)
        .value("http_pw", proxy_settings::http_pw)
    ;
    class_<proxy_settings>("proxy_settings")
        .def_readwrite("hostname", &proxy_settings::hostname)
        .def_readwrite("port", &proxy_settings::port)
        .def_readwrite("password", &proxy_settings::password)
        .def_readwrite("username", &proxy_settings::username)
        .def_readwrite("type", &proxy_settings::type)
    ;

#ifndef TORRENT_DISABLE_ENCRYPTION
    enum_<pe_settings::enc_policy>("enc_policy")
        .value("forced", pe_settings::forced)
        .value("enabled", pe_settings::enabled)
        .value("disabled", pe_settings::disabled)
    ;

    enum_<pe_settings::enc_level>("enc_level")
        .value("rc4", pe_settings::rc4)
        .value("plaintext", pe_settings::plaintext)
        .value("both", pe_settings::both)
    ;

    class_<pe_settings>("pe_settings")
        .def_readwrite("out_enc_policy", &pe_settings::out_enc_policy)
        .def_readwrite("in_enc_policy", &pe_settings::in_enc_policy)
        .def_readwrite("allowed_enc_level", &pe_settings::allowed_enc_level)
        .def_readwrite("prefer_rc4", &pe_settings::prefer_rc4)
    ;
#endif

}
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2017 Artem Pavlenko
 *
 * 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 St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifdef HAVE_LIBXML2

// mapnik
#include <mapnik/xml_loader.hpp>
#include <mapnik/xml_node.hpp>
#include <mapnik/config_error.hpp>
#include <mapnik/util/trim.hpp>
#include <mapnik/util/noncopyable.hpp>
#include <mapnik/util/fs.hpp>

// libxml
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/parserInternals.h>
#include <libxml/xinclude.h>

// stl
#include <stdexcept>

#define DEFAULT_OPTIONS (XML_PARSE_NOERROR | XML_PARSE_NOENT | XML_PARSE_NOBLANKS | XML_PARSE_DTDLOAD | XML_PARSE_NOCDATA)

namespace mapnik
{
class libxml2_loader : util::noncopyable
{
public:
    libxml2_loader(const char *encoding = nullptr, int options = DEFAULT_OPTIONS, const char *url = nullptr) :
        ctx_(0),
        encoding_(encoding),
        options_(options),
        url_(url)
    {
        LIBXML_TEST_VERSION;
        ctx_ = xmlNewParserCtxt();
        if (!ctx_)
        {
            throw std::runtime_error("Failed to create parser context.");
        }
    }

    ~libxml2_loader()
    {
        if (ctx_)
        {
            xmlFreeParserCtxt(ctx_);
        }
    }

    void load(std::string const& filename, xml_node &node)
    {
        if (!mapnik::util::exists(filename))
        {
            throw config_error(std::string("Could not load map file: File does not exist"), 0, filename);
        }

        xmlDocPtr doc = xmlCtxtReadFile(ctx_, filename.c_str(), encoding_, options_);

        if (!doc)
        {
            xmlError * error = xmlCtxtGetLastError(ctx_);
            if (error)
            {
                std::string msg("XML document not well formed:\n");
                msg += error->message;
                // remove CR
                msg = msg.substr(0, msg.size() - 1);
                throw config_error(msg, error->line, error->file);
            }
        }
        load(doc, node);
    }

    void load(const int fd, xml_node &node)
    {
        xmlDocPtr doc = xmlCtxtReadFd(ctx_, fd, url_, encoding_, options_);
        load(doc, node);
    }

    void load_string(std::string const& buffer, xml_node &node, std::string const & base_path)
    {
        if (!base_path.empty())
        {
            if (!mapnik::util::exists(base_path)) {
                throw config_error(std::string("Could not locate base_path '") +
                                   base_path + "': file or directory does not exist");
            }
        }
        // NOTE: base_path here helps libxml2 resolve entities correctly: https://github.com/mapnik/mapnik/issues/440
        xmlDocPtr doc = xmlCtxtReadMemory(ctx_, buffer.data(), buffer.length(), base_path.c_str(), encoding_, options_);

        load(doc, node);
    }

    void load(const xmlDocPtr doc, xml_node &node)
    {
        if (!doc)
        {
            std::string msg("XML document not well formed");
            xmlError * error = xmlCtxtGetLastError( ctx_ );
            if (error)
            {
                msg += ":\n";
                msg += error->message;
                throw config_error(msg, error->line, error->file);
            }
            else
            {
                throw config_error(msg);
            }
        }

        int iXIncludeReturn = xmlXIncludeProcessFlags(doc, options_);

        if (iXIncludeReturn < 0)
        {
            xmlFreeDoc(doc);
            throw config_error("XML XInclude error.  One or more files failed to load.");
        }

        xmlNode * root = xmlDocGetRootElement(doc);
        if (!root) {
            xmlFreeDoc(doc);
            throw config_error("XML document is empty.");
        }

        populate_tree(root, node);
        xmlFreeDoc(doc);
    }

private:
    void inline append_attributes(xmlAttr *attributes, xml_node & node)
    {
        for (; attributes; attributes = attributes->next )
        {
            node.add_attribute(reinterpret_cast<const char *>(attributes->name),
                               reinterpret_cast<const char *>(attributes->children->content));
        }
    }

    void inline populate_tree(xmlNode *cur_node, xml_node &node)
    {
        for (; cur_node; cur_node = cur_node->next )
        {
            switch (cur_node->type)
            {
            case XML_ELEMENT_NODE:
            {
                xml_node &new_node = node.add_child(reinterpret_cast<const char *>(cur_node->name), cur_node->line, false);
                append_attributes(cur_node->properties, new_node);
                populate_tree(cur_node->children, new_node);
            }
            break;
            case XML_TEXT_NODE:
            {
                std::string trimmed(reinterpret_cast<const char *>(cur_node->content));
                mapnik::util::trim(trimmed);
                if (trimmed.empty()) break; //Don't add empty text nodes
                node.add_child(trimmed.c_str(), cur_node->line, true);
            }
            break;
            case XML_COMMENT_NODE:
                break;
            default:
                break;

            }
        }
    }

    xmlParserCtxtPtr ctx_;
    const char *encoding_;
    int options_;
    const char *url_;
};

void read_xml(std::string const & filename, xml_node &node)
{
    libxml2_loader loader;
    loader.load(filename, node);
}
void read_xml_string(std::string const & str, xml_node &node, std::string const & base_path)
{
    libxml2_loader loader;
    loader.load_string(str, node, base_path);
}

} // end of namespace mapnik

#endif
<commit_msg>libxml2: add support for huge XMLs<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2017 Artem Pavlenko
 *
 * 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 St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifdef HAVE_LIBXML2

// mapnik
#include <mapnik/xml_loader.hpp>
#include <mapnik/xml_node.hpp>
#include <mapnik/config_error.hpp>
#include <mapnik/util/trim.hpp>
#include <mapnik/util/noncopyable.hpp>
#include <mapnik/util/fs.hpp>

// libxml
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/parserInternals.h>
#include <libxml/xinclude.h>

// stl
#include <stdexcept>

#if LIBXML_VERSION >= 20900
#define DEFAULT_OPTIONS (XML_PARSE_NOERROR | XML_PARSE_NOENT | XML_PARSE_NOBLANKS | XML_PARSE_DTDLOAD | XML_PARSE_NOCDATA | XML_PARSE_HUGE | XML_PARSE_BIG_LINES)
#elif LIBXML_VERSION >= 20703
#define DEFAULT_OPTIONS (XML_PARSE_NOERROR | XML_PARSE_NOENT | XML_PARSE_NOBLANKS | XML_PARSE_DTDLOAD | XML_PARSE_NOCDATA | XML_PARSE_HUGE)
#else
#define DEFAULT_OPTIONS (XML_PARSE_NOERROR | XML_PARSE_NOENT | XML_PARSE_NOBLANKS | XML_PARSE_DTDLOAD | XML_PARSE_NOCDATA)
#endif

namespace mapnik
{
class libxml2_loader : util::noncopyable
{
public:
    libxml2_loader(const char *encoding = nullptr, int options = DEFAULT_OPTIONS, const char *url = nullptr) :
        ctx_(0),
        encoding_(encoding),
        options_(options),
        url_(url)
    {
        LIBXML_TEST_VERSION;
        ctx_ = xmlNewParserCtxt();
        if (!ctx_)
        {
            throw std::runtime_error("Failed to create parser context.");
        }
    }

    ~libxml2_loader()
    {
        if (ctx_)
        {
            xmlFreeParserCtxt(ctx_);
        }
    }

    void load(std::string const& filename, xml_node &node)
    {
        if (!mapnik::util::exists(filename))
        {
            throw config_error(std::string("Could not load map file: File does not exist"), 0, filename);
        }

        xmlDocPtr doc = xmlCtxtReadFile(ctx_, filename.c_str(), encoding_, options_);

        if (!doc)
        {
            xmlError * error = xmlCtxtGetLastError(ctx_);
            if (error)
            {
                std::string msg("XML document not well formed:\n");
                msg += error->message;
                // remove CR
                msg = msg.substr(0, msg.size() - 1);
                throw config_error(msg, error->line, error->file);
            }
        }
        load(doc, node);
    }

    void load(const int fd, xml_node &node)
    {
        xmlDocPtr doc = xmlCtxtReadFd(ctx_, fd, url_, encoding_, options_);
        load(doc, node);
    }

    void load_string(std::string const& buffer, xml_node &node, std::string const & base_path)
    {
        if (!base_path.empty())
        {
            if (!mapnik::util::exists(base_path)) {
                throw config_error(std::string("Could not locate base_path '") +
                                   base_path + "': file or directory does not exist");
            }
        }
        // NOTE: base_path here helps libxml2 resolve entities correctly: https://github.com/mapnik/mapnik/issues/440
        xmlDocPtr doc = xmlCtxtReadMemory(ctx_, buffer.data(), buffer.length(), base_path.c_str(), encoding_, options_);

        load(doc, node);
    }

    void load(const xmlDocPtr doc, xml_node &node)
    {
        if (!doc)
        {
            std::string msg("XML document not well formed");
            xmlError * error = xmlCtxtGetLastError( ctx_ );
            if (error)
            {
                msg += ":\n";
                msg += error->message;
                throw config_error(msg, error->line, error->file);
            }
            else
            {
                throw config_error(msg);
            }
        }

        int iXIncludeReturn = xmlXIncludeProcessFlags(doc, options_);

        if (iXIncludeReturn < 0)
        {
            xmlFreeDoc(doc);
            throw config_error("XML XInclude error.  One or more files failed to load.");
        }

        xmlNode * root = xmlDocGetRootElement(doc);
        if (!root) {
            xmlFreeDoc(doc);
            throw config_error("XML document is empty.");
        }

        populate_tree(root, node);
        xmlFreeDoc(doc);
    }

private:
    void inline append_attributes(xmlAttr *attributes, xml_node & node)
    {
        for (; attributes; attributes = attributes->next )
        {
            node.add_attribute(reinterpret_cast<const char *>(attributes->name),
                               reinterpret_cast<const char *>(attributes->children->content));
        }
    }

    void inline populate_tree(xmlNode *cur_node, xml_node &node)
    {
        for (; cur_node; cur_node = cur_node->next )
        {
            switch (cur_node->type)
            {
            case XML_ELEMENT_NODE:
            {
                xml_node &new_node = node.add_child(reinterpret_cast<const char *>(cur_node->name), cur_node->line, false);
                append_attributes(cur_node->properties, new_node);
                populate_tree(cur_node->children, new_node);
            }
            break;
            case XML_TEXT_NODE:
            {
                std::string trimmed(reinterpret_cast<const char *>(cur_node->content));
                mapnik::util::trim(trimmed);
                if (trimmed.empty()) break; //Don't add empty text nodes
                node.add_child(trimmed.c_str(), cur_node->line, true);
            }
            break;
            case XML_COMMENT_NODE:
                break;
            default:
                break;

            }
        }
    }

    xmlParserCtxtPtr ctx_;
    const char *encoding_;
    int options_;
    const char *url_;
};

void read_xml(std::string const & filename, xml_node &node)
{
    libxml2_loader loader;
    loader.load(filename, node);
}
void read_xml_string(std::string const & str, xml_node &node, std::string const & base_path)
{
    libxml2_loader loader;
    loader.load_string(str, node, base_path);
}

} // end of namespace mapnik

#endif
<|endoftext|>


<commit_before>/*******************************************************************************
 * Copyright (c) 2014, 2016  IBM Corporation and others
 *
 * 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 BasicLocalizer_hpp
#define BasicLocalizer_hpp

#include <iostream>
#include <string>

#include <boost/circular_buffer.hpp>

#include "StreamLocalizer.hpp"
#include "StreamParticleFilter.hpp"

#include "PoseRandomWalker.hpp"
#include "WeakPoseRandomWalker.hpp"

#include "GridResampler.hpp"
#include "StatusInitializerStub.hpp"
#include "StatusInitializerImpl.hpp"

#include "DataStore.hpp"
#include "DataStoreImpl.hpp"

#include "OrientationMeterAverage.hpp"
#include "PedometerWalkingState.hpp"
#include "OrientationAdjuster.hpp"

#include "GaussianProcessLDPLMultiModel.hpp"

// for pose random walker in building
#include "Building.hpp"
#include "RandomWalker.hpp"
#include "RandomWalkerMotion.hpp"
#include "SystemModelInBuilding.hpp"

#include "BeaconFilterChain.hpp"
#include "CleansingBeaconFilter.hpp"
#include "StrongestBeaconFilter.hpp"

#include "ObservationDependentInitializer.hpp"
#include "MetropolisSampler.hpp"

#include "SerializeUtils.hpp"
#include "LatLngConverter.hpp"

#define N_SMOOTH_MAX 10

namespace loc {

    class BasicLocalizerParameters;
    class BasicLocalizerOptions;
    class BasicLocalizer;

    typedef struct {
        BasicLocalizer* localizer;
    } UserData;

    typedef enum {
        ONESHOT = 0,
        RANDOM_WALK = 1,
        RANDOM_WALK_ACC = 2,
        RANDOM_WALK_ACC_ATT = 3,
        WEAK_POSE_RANDOM_WALKER = 4
    } LocalizeMode;

    /*
    typedef enum {
        UNKNOWN,
        LOCATING,
        TRACKING
    } LocalizeState;
    */

    typedef enum {
        NORMAL, TDIST
    } NormalFunction;

    typedef enum {
        SMOOTH_LOCATION,
        SMOOTH_RSSI
    } SmoothType;

    typedef enum{
        RAW_AVERAGE,
        TRANSFORMED_AVERAGE
    } OrientationMeterType;

    class LocalHeadingBuffer{
    protected:
        boost::circular_buffer<LocalHeading> buffer_;
        std::mutex mtx_;
    public:
        LocalHeadingBuffer(size_t);
        ~LocalHeadingBuffer() = default;
        LocalHeadingBuffer(const LocalHeadingBuffer&);
        LocalHeadingBuffer& operator=(const LocalHeadingBuffer&);
        void push_back(const LocalHeading&);
        LocalHeading& back();
        size_t size();
    };

    struct UserDataBridge{
        UserData* userData;
        void (*functionCalledAfterUpdateWithPtr)(void*, Status*) = NULL;
        BasicLocalizer* basicLocalizer;
    };

    class BasicLocalizerParameters{
    public:
        int nStates = 1000;
        double alphaWeaken = 0.3;
        int nSmooth = 10;
        int nSmoothTracking = 1;
        SmoothType smoothType = SMOOTH_LOCATION;
        LocalizeMode localizeMode = ONESHOT;

        double effectiveSampleSizeThreshold = 1000;
        int nStrongest = 10;
        bool enablesFloorUpdate = true;

        double walkDetectSigmaThreshold = 0.6;
        double meanVelocity = 1.0;
        double stdVelocity = 0.3;
        double diffusionVelocity = 0.1;
        double minVelocity = 0.1;
        double maxVelocity = 1.5;

        double stdRssiBias = 2.0;
        double diffusionRssiBias = 0.2;
        double stdOrientation = 3.0;
        double diffusionOrientationBias = 10;

        double angularVelocityLimit = 30;
        // Parametes for PoseRandomWalker
        bool doesUpdateWhenStopping = false;

        double maxIncidenceAngle = 45;
        double weightDecayHalfLife = 5; // 0.87055056329; // this^5 = 0.5

        // Parameters for RandomWalkerMotion and WeakPoseRandomWalker
        double sigmaStop = 0.1;
        double sigmaMove = 1.0;

        // Parameters for SystemModelInBuilding
        double velocityRateFloor = 1.0;
        double velocityRateElevator = 0.5;
        double velocityRateStair = 0.5;
        double velocityRateEscalator = 0.5;
        double relativeVelocityEscalator = 0.4; // m/s

        // Parameters for WeakPoseRandomWalker
        double probabilityOrientationBiasJump = 0.1;
        double poseRandomWalkRate = 1.0;
        double randomWalkRate = 0.2;
        double probabilityBackwardMove = 0.0;

        int nBurnIn = 1000;
        int burnInRadius2D = 10;
        int burnInInterval = 1;
        InitType burnInInitType = INIT_WITH_SAMPLE_LOCATIONS;

        double mixProba = 0.000;
        double rejectDistance = 5;
        double rejectFloorDifference = 0.99;
        int nBeaconsMinimum = 3;

        Location locLB{0.5, 0.5, 1e-6, 1e-6};

        bool usesAltimeterForFloorTransCheck = false;
        double coeffDiffFloorStdev = 5.0;

        OrientationMeterType orientationMeterType = RAW_AVERAGE;

        // parameter objects
        PoseProperty::Ptr poseProperty = std::make_shared<PoseProperty>();
        StateProperty::Ptr stateProperty = std::make_shared<StateProperty>();

        StreamParticleFilter::FloorTransitionParameters::Ptr pfFloorTransParams = std::make_shared<StreamParticleFilter::FloorTransitionParameters>();
        LocationStatusMonitorParameters::Ptr locationStatusMonitorParameters = std::make_shared<LocationStatusMonitorParameters>();
        SystemModelInBuildingProperty::Ptr prwBuildingProperty = std::make_shared<SystemModelInBuildingProperty>();

    protected:
        double meanRssiBias_ = 0.0;
        double minRssiBias_ = -10;
        double maxRssiBias_ = 10;

        double headingConfidenceForOrientationInit_ = 0.0;

    public:
        template<class Archive>
        void serialize(Archive & ar, std::uint32_t const version)
        {
            if (0 <= version) {
                ar(CEREAL_NVP(nStates));
                ar(CEREAL_NVP(alphaWeaken));
                ar(CEREAL_NVP(nSmooth));
                ar(CEREAL_NVP(nSmoothTracking));

                ar(CEREAL_NVP(smoothType));
                ar(CEREAL_NVP(localizeMode));

                ar(CEREAL_NVP(effectiveSampleSizeThreshold));
                ar(CEREAL_NVP(nStrongest));
                ar(CEREAL_NVP(enablesFloorUpdate));

                ar(CEREAL_NVP(walkDetectSigmaThreshold));
                ar(CEREAL_NVP(meanVelocity));
                ar(CEREAL_NVP(stdVelocity));
                ar(CEREAL_NVP(diffusionVelocity));
                ar(CEREAL_NVP(minVelocity));
                ar(CEREAL_NVP(maxVelocity));

                ar(CEREAL_NVP(stdRssiBias));
                ar(CEREAL_NVP(diffusionRssiBias));
                ar(CEREAL_NVP(stdOrientation));
                ar(CEREAL_NVP(diffusionOrientationBias));

                ar(CEREAL_NVP(angularVelocityLimit));

                // Parametes for PoseRandomWalker
                ar(CEREAL_NVP(doesUpdateWhenStopping));
                ar(CEREAL_NVP(maxIncidenceAngle));
                ar(CEREAL_NVP(weightDecayHalfLife));

                // Parameters for RandomWalkerMotion and WeakPoseRandomWalker
                ar(CEREAL_NVP(sigmaStop));
                ar(CEREAL_NVP(sigmaMove));

                // Parameters for SystemModelInBuilding
                ar(CEREAL_NVP(velocityRateFloor));
                ar(CEREAL_NVP(velocityRateElevator));
                ar(CEREAL_NVP(velocityRateStair));
                ar(CEREAL_NVP(velocityRateEscalator));
                ar(CEREAL_NVP(relativeVelocityEscalator));

                // Parameters for WeakPoseRandomWalker
                ar(CEREAL_NVP(probabilityOrientationBiasJump));
                ar(CEREAL_NVP(poseRandomWalkRate));
                ar(CEREAL_NVP(randomWalkRate));
                ar(CEREAL_NVP(probabilityBackwardMove));

                ar(CEREAL_NVP(nBurnIn));
                ar(CEREAL_NVP(burnInRadius2D));
                ar(CEREAL_NVP(burnInInterval));
                ar(CEREAL_NVP(burnInInitType));

                ar(CEREAL_NVP(mixProba));
                ar(CEREAL_NVP(rejectDistance));
                ar(CEREAL_NVP(rejectFloorDifference));
                ar(CEREAL_NVP(nBeaconsMinimum));

                ar(CEREAL_NVP(locLB));

                ar(CEREAL_NVP(usesAltimeterForFloorTransCheck));
                ar(CEREAL_NVP(coeffDiffFloorStdev));

                ar(CEREAL_NVP(orientationMeterType));

                // parameter objects
                ar(CEREAL_NVP(*poseProperty));
                ar(CEREAL_NVP(*stateProperty));

                ar(CEREAL_NVP(*pfFloorTransParams));
                ar(CEREAL_NVP(*locationStatusMonitorParameters));
                ar(CEREAL_NVP(*prwBuildingProperty));

                // protected
                ar(CEREAL_NVP(meanRssiBias_));
                ar(CEREAL_NVP(minRssiBias_));
                ar(CEREAL_NVP(maxRssiBias_));
                ar(CEREAL_NVP(headingConfidenceForOrientationInit_));
            }
        }

    };

    class BasicLocalizerOptions{
    public:
        GPType gpType = GPNORMAL;
    };

    class BasicLocalizer: public StreamLocalizer, public BasicLocalizerParameters{

    private:
        std::shared_ptr<StreamParticleFilter> mLocalizer;
        std::shared_ptr<GaussianProcessLDPLMultiModel<State, Beacons>> deserializedModel;
        UserData userData;
        double isReady = false;

        void (*mFunctionCalledAfterUpdate)(Status*) = NULL;
        void (*mFunctionCalledAfterUpdate2)(void*, Status*) = NULL;
        void (*mFunctionCalledToLog)(void*, std::string) = NULL;
        void *mUserData = NULL;
        void *mUserDataToLog = NULL;

        UserDataBridge userDataBridge;
        void *mUserDataBridge = NULL;

        //std::shared_ptr<loc::Status> mResult;
        std::shared_ptr<Status> mTrackedStatus;

        std::vector<loc::State> status_list[N_SMOOTH_MAX];
        std::vector<loc::Beacon> beacons_list[N_SMOOTH_MAX];

        int smooth_count = 0;
        double mEstimatedRssiBias = 0;

        bool isTrackingLocalizer() {
            switch(localizeMode) {
                case ONESHOT:
                    return false;
                case RANDOM_WALK:
                case RANDOM_WALK_ACC:
                case RANDOM_WALK_ACC_ATT:
                case WEAK_POSE_RANDOM_WALKER:
                default:
                    return true;
            }
        };

        void updateStateProperty();

        Anchor anchor;
        LatLngConverter::Ptr latLngConverter_;

        LocalHeadingBuffer mLocalHeadingBuffer = LocalHeadingBuffer(10); // buffer size 10 is not important.

        Status::LocationStatus mLocationStatus = Status::UNKNOWN;

        bool mDisableAcceleration = false;

    public:
        BasicLocalizer();
        ~BasicLocalizer();

        BasicLocalizer(const BasicLocalizerParameters& params): BasicLocalizerParameters(params){
            this->meanRssiBias(meanRssiBias_);
            this->minRssiBias(minRssiBias_);
            this->maxRssiBias(maxRssiBias_);
        }

        bool isVerboseLocalizer = false;

        std::shared_ptr<DataStoreImpl> dataStore;

        void normalFunction(NormalFunction type, double option);
        void meanRssiBias(double b);
        void maxRssiBias(double b);
        void minRssiBias(double b);
        /*
         void angularVelocityLimit(double a);
         */
        double estimatedRssiBias();

        bool forceTraining = false;
        BasicLocalizerOptions basicLocalizerOptions;

        OrientationMeterAverageParameters orientationMeterAverageParameters;
        std::shared_ptr<OrientationMeter> orientationMeter;

        PedometerWalkingStateParameters pedometerWSParams;
        std::shared_ptr<Pedometer> pedometer;

        // parameter objects
        PoseRandomWalkerProperty::Ptr poseRandomWalkerProperty = std::make_shared<PoseRandomWalkerProperty>();
        WeakPoseRandomWalkerProperty::Ptr wPRWproperty = std::make_shared<WeakPoseRandomWalkerProperty>();

        // system models
        std::shared_ptr<RandomWalker<State, SystemModelInput>>randomWalker;
        std::shared_ptr<PoseRandomWalker>poseRandomWalker;
        std::shared_ptr<PoseRandomWalkerInBuilding> poseRandomWalkerInBuilding;

        std::shared_ptr<Resampler<State>> resampler;

        std::shared_ptr<StatusInitializerImpl> statusInitializer;

        std::shared_ptr<StrongestBeaconFilter> beaconFilter;

        loc::Pose stdevPose;

        std::shared_ptr<MetropolisSampler<State, Beacons>> obsDepInitializer;

        MetropolisSampler<State, Beacons>::Parameters msParams;

        LatLngConverter::Ptr latLngConverter();

        StreamLocalizer& updateHandler(void (*functionCalledAfterUpdate)(Status*)) override;
        StreamLocalizer& updateHandler(void (*functionCalledAfterUpdate)(void*, Status*), void* inUserData) override;

        StreamLocalizer& logHandler(void (*functionCalledToLog)(void*, std::string), void* inUserData);

        StreamLocalizer& putAttitude(const Attitude attitude) override;
        StreamLocalizer& putAcceleration(const Acceleration acceleration) override;
        StreamLocalizer& putBeacons(const Beacons beacons) override;
        // StreamLocalizer& putWiFiAPs(const WiFiAPs wifiaps) override;
        StreamLocalizer& putLocalHeading(const LocalHeading heading) override;
        StreamLocalizer& putHeading(const Heading heading);
        StreamLocalizer& putAltimeter(const Altimeter altimeter) override;
        Status* getStatus() override;

        bool resetStatus() override;
        bool resetStatus(Pose pose) override;
        bool resetStatus(Pose meanPose, Pose stdevPose) override;
        bool resetStatus(Pose meanPose, Pose stdevPose, double rateContami) override;
        bool resetStatus(const Beacons& beacons) override;
        bool resetStatus(const Location& location, const Beacons& beacons) override;

        BasicLocalizer& setModel(std::string modelPath, std::string workingDir);

        bool tracksOrientation(){
            switch(localizeMode) {
                case ONESHOT:
                case RANDOM_WALK:
                case RANDOM_WALK_ACC:
                    return false;
                case RANDOM_WALK_ACC_ATT:
                case WEAK_POSE_RANDOM_WALKER:
                    return true;
                default:
                    return false;
            }
        };

        std::shared_ptr<GaussianProcessLDPLMultiModel<State, Beacons>> observationModel() const{
            return deserializedModel;
        };

        // for orientation initialization
        void headingConfidenceForOrientationInit(double confidence);

        void updateLocationStatus(Status*);
        void overwriteLocationStatus(Status::LocationStatus);

        // for yaw drift adjuster
        bool applysYawDriftAdjust = false;
        OrientationDriftAdjusterSimple::Ptr yawDriftAdjuster = std::make_shared<OrientationDriftAdjusterSimple>();

        // control disable/enable acceleration
        void disableAcceleration(bool);
    };
}

// assign version
CEREAL_CLASS_VERSION(loc::BasicLocalizerParameters, 0);
#endif /* BasicLocalizerBuilder_hpp */
<commit_msg>output applysYawDriftAdjust in basic localizer parameters<commit_after>/*******************************************************************************
 * Copyright (c) 2014, 2016  IBM Corporation and others
 *
 * 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 BasicLocalizer_hpp
#define BasicLocalizer_hpp

#include <iostream>
#include <string>

#include <boost/circular_buffer.hpp>

#include "StreamLocalizer.hpp"
#include "StreamParticleFilter.hpp"

#include "PoseRandomWalker.hpp"
#include "WeakPoseRandomWalker.hpp"

#include "GridResampler.hpp"
#include "StatusInitializerStub.hpp"
#include "StatusInitializerImpl.hpp"

#include "DataStore.hpp"
#include "DataStoreImpl.hpp"

#include "OrientationMeterAverage.hpp"
#include "PedometerWalkingState.hpp"
#include "OrientationAdjuster.hpp"

#include "GaussianProcessLDPLMultiModel.hpp"

// for pose random walker in building
#include "Building.hpp"
#include "RandomWalker.hpp"
#include "RandomWalkerMotion.hpp"
#include "SystemModelInBuilding.hpp"

#include "BeaconFilterChain.hpp"
#include "CleansingBeaconFilter.hpp"
#include "StrongestBeaconFilter.hpp"

#include "ObservationDependentInitializer.hpp"
#include "MetropolisSampler.hpp"

#include "SerializeUtils.hpp"
#include "LatLngConverter.hpp"

#define N_SMOOTH_MAX 10

namespace loc {

    class BasicLocalizerParameters;
    class BasicLocalizerOptions;
    class BasicLocalizer;

    typedef struct {
        BasicLocalizer* localizer;
    } UserData;

    typedef enum {
        ONESHOT = 0,
        RANDOM_WALK = 1,
        RANDOM_WALK_ACC = 2,
        RANDOM_WALK_ACC_ATT = 3,
        WEAK_POSE_RANDOM_WALKER = 4
    } LocalizeMode;

    /*
    typedef enum {
        UNKNOWN,
        LOCATING,
        TRACKING
    } LocalizeState;
    */

    typedef enum {
        NORMAL, TDIST
    } NormalFunction;

    typedef enum {
        SMOOTH_LOCATION,
        SMOOTH_RSSI
    } SmoothType;

    typedef enum{
        RAW_AVERAGE,
        TRANSFORMED_AVERAGE
    } OrientationMeterType;

    class LocalHeadingBuffer{
    protected:
        boost::circular_buffer<LocalHeading> buffer_;
        std::mutex mtx_;
    public:
        LocalHeadingBuffer(size_t);
        ~LocalHeadingBuffer() = default;
        LocalHeadingBuffer(const LocalHeadingBuffer&);
        LocalHeadingBuffer& operator=(const LocalHeadingBuffer&);
        void push_back(const LocalHeading&);
        LocalHeading& back();
        size_t size();
    };

    struct UserDataBridge{
        UserData* userData;
        void (*functionCalledAfterUpdateWithPtr)(void*, Status*) = NULL;
        BasicLocalizer* basicLocalizer;
    };

    class BasicLocalizerParameters{
    public:
        int nStates = 1000;
        double alphaWeaken = 0.3;
        int nSmooth = 10;
        int nSmoothTracking = 1;
        SmoothType smoothType = SMOOTH_LOCATION;
        LocalizeMode localizeMode = ONESHOT;

        double effectiveSampleSizeThreshold = 1000;
        int nStrongest = 10;
        bool enablesFloorUpdate = true;

        double walkDetectSigmaThreshold = 0.6;
        double meanVelocity = 1.0;
        double stdVelocity = 0.3;
        double diffusionVelocity = 0.1;
        double minVelocity = 0.1;
        double maxVelocity = 1.5;

        double stdRssiBias = 2.0;
        double diffusionRssiBias = 0.2;
        double stdOrientation = 3.0;
        double diffusionOrientationBias = 10;

        double angularVelocityLimit = 30;
        // Parametes for PoseRandomWalker
        bool doesUpdateWhenStopping = false;

        double maxIncidenceAngle = 45;
        double weightDecayHalfLife = 5; // 0.87055056329; // this^5 = 0.5

        // Parameters for RandomWalkerMotion and WeakPoseRandomWalker
        double sigmaStop = 0.1;
        double sigmaMove = 1.0;

        // Parameters for SystemModelInBuilding
        double velocityRateFloor = 1.0;
        double velocityRateElevator = 0.5;
        double velocityRateStair = 0.5;
        double velocityRateEscalator = 0.5;
        double relativeVelocityEscalator = 0.4; // m/s

        // Parameters for WeakPoseRandomWalker
        double probabilityOrientationBiasJump = 0.1;
        double poseRandomWalkRate = 1.0;
        double randomWalkRate = 0.2;
        double probabilityBackwardMove = 0.0;

        int nBurnIn = 1000;
        int burnInRadius2D = 10;
        int burnInInterval = 1;
        InitType burnInInitType = INIT_WITH_SAMPLE_LOCATIONS;

        double mixProba = 0.000;
        double rejectDistance = 5;
        double rejectFloorDifference = 0.99;
        int nBeaconsMinimum = 3;

        Location locLB{0.5, 0.5, 1e-6, 1e-6};

        bool usesAltimeterForFloorTransCheck = false;
        double coeffDiffFloorStdev = 5.0;

        OrientationMeterType orientationMeterType = RAW_AVERAGE;

        // parameter objects
        PoseProperty::Ptr poseProperty = std::make_shared<PoseProperty>();
        StateProperty::Ptr stateProperty = std::make_shared<StateProperty>();

        StreamParticleFilter::FloorTransitionParameters::Ptr pfFloorTransParams = std::make_shared<StreamParticleFilter::FloorTransitionParameters>();
        LocationStatusMonitorParameters::Ptr locationStatusMonitorParameters = std::make_shared<LocationStatusMonitorParameters>();
        SystemModelInBuildingProperty::Ptr prwBuildingProperty = std::make_shared<SystemModelInBuildingProperty>();

        // yaw drift adjuster
        bool applysYawDriftAdjust = false;

    protected:
        double meanRssiBias_ = 0.0;
        double minRssiBias_ = -10;
        double maxRssiBias_ = 10;

        double headingConfidenceForOrientationInit_ = 0.0;

    public:
        template<class Archive>
        void serialize(Archive & ar, std::uint32_t const version)
        {
            ar(CEREAL_NVP(nStates));
            ar(CEREAL_NVP(alphaWeaken));
            ar(CEREAL_NVP(nSmooth));
            ar(CEREAL_NVP(nSmoothTracking));

            ar(CEREAL_NVP(smoothType));
            ar(CEREAL_NVP(localizeMode));

            ar(CEREAL_NVP(effectiveSampleSizeThreshold));
            ar(CEREAL_NVP(nStrongest));
            ar(CEREAL_NVP(enablesFloorUpdate));

            ar(CEREAL_NVP(walkDetectSigmaThreshold));
            ar(CEREAL_NVP(meanVelocity));
            ar(CEREAL_NVP(stdVelocity));
            ar(CEREAL_NVP(diffusionVelocity));
            ar(CEREAL_NVP(minVelocity));
            ar(CEREAL_NVP(maxVelocity));

            ar(CEREAL_NVP(stdRssiBias));
            ar(CEREAL_NVP(diffusionRssiBias));
            ar(CEREAL_NVP(stdOrientation));
            ar(CEREAL_NVP(diffusionOrientationBias));

            ar(CEREAL_NVP(angularVelocityLimit));

            // Parametes for PoseRandomWalker
            ar(CEREAL_NVP(doesUpdateWhenStopping));
            ar(CEREAL_NVP(maxIncidenceAngle));
            ar(CEREAL_NVP(weightDecayHalfLife));

            // Parameters for RandomWalkerMotion and WeakPoseRandomWalker
            ar(CEREAL_NVP(sigmaStop));
            ar(CEREAL_NVP(sigmaMove));

            // Parameters for SystemModelInBuilding
            ar(CEREAL_NVP(velocityRateFloor));
            ar(CEREAL_NVP(velocityRateElevator));
            ar(CEREAL_NVP(velocityRateStair));
            ar(CEREAL_NVP(velocityRateEscalator));
            ar(CEREAL_NVP(relativeVelocityEscalator));

            // Parameters for WeakPoseRandomWalker
            ar(CEREAL_NVP(probabilityOrientationBiasJump));
            ar(CEREAL_NVP(poseRandomWalkRate));
            ar(CEREAL_NVP(randomWalkRate));
            ar(CEREAL_NVP(probabilityBackwardMove));

            ar(CEREAL_NVP(nBurnIn));
            ar(CEREAL_NVP(burnInRadius2D));
            ar(CEREAL_NVP(burnInInterval));
            ar(CEREAL_NVP(burnInInitType));

            ar(CEREAL_NVP(mixProba));
            ar(CEREAL_NVP(rejectDistance));
            ar(CEREAL_NVP(rejectFloorDifference));
            ar(CEREAL_NVP(nBeaconsMinimum));

            ar(CEREAL_NVP(locLB));

            ar(CEREAL_NVP(usesAltimeterForFloorTransCheck));
            ar(CEREAL_NVP(coeffDiffFloorStdev));

            ar(CEREAL_NVP(orientationMeterType));

            // parameter objects
            ar(CEREAL_NVP(*poseProperty));
            ar(CEREAL_NVP(*stateProperty));

            ar(CEREAL_NVP(*pfFloorTransParams));
            ar(CEREAL_NVP(*locationStatusMonitorParameters));
            ar(CEREAL_NVP(*prwBuildingProperty));

            // protected
            ar(CEREAL_NVP(meanRssiBias_));
            ar(CEREAL_NVP(minRssiBias_));
            ar(CEREAL_NVP(maxRssiBias_));
            ar(CEREAL_NVP(headingConfidenceForOrientationInit_));

            if(1<=version){
                ar(CEREAL_NVP(applysYawDriftAdjust));
            }
        }

    };

    class BasicLocalizerOptions{
    public:
        GPType gpType = GPNORMAL;
    };

    class BasicLocalizer: public StreamLocalizer, public BasicLocalizerParameters{

    private:
        std::shared_ptr<StreamParticleFilter> mLocalizer;
        std::shared_ptr<GaussianProcessLDPLMultiModel<State, Beacons>> deserializedModel;
        UserData userData;
        double isReady = false;

        void (*mFunctionCalledAfterUpdate)(Status*) = NULL;
        void (*mFunctionCalledAfterUpdate2)(void*, Status*) = NULL;
        void (*mFunctionCalledToLog)(void*, std::string) = NULL;
        void *mUserData = NULL;
        void *mUserDataToLog = NULL;

        UserDataBridge userDataBridge;
        void *mUserDataBridge = NULL;

        //std::shared_ptr<loc::Status> mResult;
        std::shared_ptr<Status> mTrackedStatus;

        std::vector<loc::State> status_list[N_SMOOTH_MAX];
        std::vector<loc::Beacon> beacons_list[N_SMOOTH_MAX];

        int smooth_count = 0;
        double mEstimatedRssiBias = 0;

        bool isTrackingLocalizer() {
            switch(localizeMode) {
                case ONESHOT:
                    return false;
                case RANDOM_WALK:
                case RANDOM_WALK_ACC:
                case RANDOM_WALK_ACC_ATT:
                case WEAK_POSE_RANDOM_WALKER:
                default:
                    return true;
            }
        };

        void updateStateProperty();

        Anchor anchor;
        LatLngConverter::Ptr latLngConverter_;

        LocalHeadingBuffer mLocalHeadingBuffer = LocalHeadingBuffer(10); // buffer size 10 is not important.

        Status::LocationStatus mLocationStatus = Status::UNKNOWN;

        bool mDisableAcceleration = false;

    public:
        BasicLocalizer();
        ~BasicLocalizer();

        BasicLocalizer(const BasicLocalizerParameters& params): BasicLocalizerParameters(params){
            this->meanRssiBias(meanRssiBias_);
            this->minRssiBias(minRssiBias_);
            this->maxRssiBias(maxRssiBias_);
        }

        bool isVerboseLocalizer = false;

        std::shared_ptr<DataStoreImpl> dataStore;

        void normalFunction(NormalFunction type, double option);
        void meanRssiBias(double b);
        void maxRssiBias(double b);
        void minRssiBias(double b);
        /*
         void angularVelocityLimit(double a);
         */
        double estimatedRssiBias();

        bool forceTraining = false;
        BasicLocalizerOptions basicLocalizerOptions;

        OrientationMeterAverageParameters orientationMeterAverageParameters;
        std::shared_ptr<OrientationMeter> orientationMeter;

        PedometerWalkingStateParameters pedometerWSParams;
        std::shared_ptr<Pedometer> pedometer;

        // parameter objects
        PoseRandomWalkerProperty::Ptr poseRandomWalkerProperty = std::make_shared<PoseRandomWalkerProperty>();
        WeakPoseRandomWalkerProperty::Ptr wPRWproperty = std::make_shared<WeakPoseRandomWalkerProperty>();

        // system models
        std::shared_ptr<RandomWalker<State, SystemModelInput>>randomWalker;
        std::shared_ptr<PoseRandomWalker>poseRandomWalker;
        std::shared_ptr<PoseRandomWalkerInBuilding> poseRandomWalkerInBuilding;

        std::shared_ptr<Resampler<State>> resampler;

        std::shared_ptr<StatusInitializerImpl> statusInitializer;

        std::shared_ptr<StrongestBeaconFilter> beaconFilter;

        loc::Pose stdevPose;

        std::shared_ptr<MetropolisSampler<State, Beacons>> obsDepInitializer;

        MetropolisSampler<State, Beacons>::Parameters msParams;

        LatLngConverter::Ptr latLngConverter();

        StreamLocalizer& updateHandler(void (*functionCalledAfterUpdate)(Status*)) override;
        StreamLocalizer& updateHandler(void (*functionCalledAfterUpdate)(void*, Status*), void* inUserData) override;

        StreamLocalizer& logHandler(void (*functionCalledToLog)(void*, std::string), void* inUserData);

        StreamLocalizer& putAttitude(const Attitude attitude) override;
        StreamLocalizer& putAcceleration(const Acceleration acceleration) override;
        StreamLocalizer& putBeacons(const Beacons beacons) override;
        // StreamLocalizer& putWiFiAPs(const WiFiAPs wifiaps) override;
        StreamLocalizer& putLocalHeading(const LocalHeading heading) override;
        StreamLocalizer& putHeading(const Heading heading);
        StreamLocalizer& putAltimeter(const Altimeter altimeter) override;
        Status* getStatus() override;

        bool resetStatus() override;
        bool resetStatus(Pose pose) override;
        bool resetStatus(Pose meanPose, Pose stdevPose) override;
        bool resetStatus(Pose meanPose, Pose stdevPose, double rateContami) override;
        bool resetStatus(const Beacons& beacons) override;
        bool resetStatus(const Location& location, const Beacons& beacons) override;

        BasicLocalizer& setModel(std::string modelPath, std::string workingDir);

        bool tracksOrientation(){
            switch(localizeMode) {
                case ONESHOT:
                case RANDOM_WALK:
                case RANDOM_WALK_ACC:
                    return false;
                case RANDOM_WALK_ACC_ATT:
                case WEAK_POSE_RANDOM_WALKER:
                    return true;
                default:
                    return false;
            }
        };

        std::shared_ptr<GaussianProcessLDPLMultiModel<State, Beacons>> observationModel() const{
            return deserializedModel;
        };

        // for orientation initialization
        void headingConfidenceForOrientationInit(double confidence);

        void updateLocationStatus(Status*);
        void overwriteLocationStatus(Status::LocationStatus);

        // for yaw drift adjuster
        OrientationDriftAdjusterSimple::Ptr yawDriftAdjuster = std::make_shared<OrientationDriftAdjusterSimple>();

        // control disable/enable acceleration
        void disableAcceleration(bool);
    };
}

// assign version
CEREAL_CLASS_VERSION(loc::BasicLocalizerParameters, 1);
#endif /* BasicLocalizerBuilder_hpp */
<|endoftext|>


<commit_before>// Copyright (c) 2017 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "shell/browser/native_browser_view_views.h"

#include <vector>

#include "shell/browser/ui/drag_util.h"
#include "shell/browser/ui/views/inspectable_web_contents_view_views.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/views/background.h"
#include "ui/views/view.h"

namespace electron {

NativeBrowserViewViews::NativeBrowserViewViews(
    InspectableWebContents* inspectable_web_contents)
    : NativeBrowserView(inspectable_web_contents) {}

NativeBrowserViewViews::~NativeBrowserViewViews() = default;

void NativeBrowserViewViews::SetAutoResizeFlags(uint8_t flags) {
  auto_resize_flags_ = flags;
  ResetAutoResizeProportions();
}

void NativeBrowserViewViews::UpdateDraggableRegions(
    const std::vector<mojom::DraggableRegionPtr>& regions) {
  // We need to snap the regions to the bounds of the current BrowserView.
  // For example, if an attached BrowserView is draggable but its bounds are
  // { x: 200,  y: 100, width: 300, height: 300 }
  // then we need to add 200 to the x-value and 100 to the
  // y-value of each of the passed regions or it will be incorrectly
  // assumed that the regions begin in the top left corner as they
  // would for the main client window.
  auto const offset = GetBounds().OffsetFromOrigin();
  auto snapped_regions = mojo::Clone(regions);
  for (auto& snapped_region : snapped_regions) {
    snapped_region->bounds.Offset(offset);
  }

  draggable_region_ = DraggableRegionsToSkRegion(snapped_regions);
}

void NativeBrowserViewViews::SetAutoResizeProportions(
    const gfx::Size& window_size) {
  if ((auto_resize_flags_ & AutoResizeFlags::kAutoResizeHorizontal) &&
      !auto_horizontal_proportion_set_) {
    InspectableWebContentsView* iwc_view = GetInspectableWebContentsView();
    if (!iwc_view)
      return;
    auto* view = iwc_view->GetView();
    auto view_bounds = view->bounds();
    auto_horizontal_proportion_width_ =
        static_cast<float>(window_size.width()) /
        static_cast<float>(view_bounds.width());
    auto_horizontal_proportion_left_ = static_cast<float>(window_size.width()) /
                                       static_cast<float>(view_bounds.x());
    auto_horizontal_proportion_set_ = true;
  }
  if ((auto_resize_flags_ & AutoResizeFlags::kAutoResizeVertical) &&
      !auto_vertical_proportion_set_) {
    InspectableWebContentsView* iwc_view = GetInspectableWebContentsView();
    if (!iwc_view)
      return;
    auto* view = iwc_view->GetView();
    auto view_bounds = view->bounds();
    auto_vertical_proportion_height_ =
        static_cast<float>(window_size.height()) /
        static_cast<float>(view_bounds.height());
    auto_vertical_proportion_top_ = static_cast<float>(window_size.height()) /
                                    static_cast<float>(view_bounds.y());
    auto_vertical_proportion_set_ = true;
  }
}

void NativeBrowserViewViews::AutoResize(const gfx::Rect& new_window,
                                        int width_delta,
                                        int height_delta) {
  InspectableWebContentsView* iwc_view = GetInspectableWebContentsView();
  if (!iwc_view)
    return;
  auto* view = iwc_view->GetView();
  const auto flags = GetAutoResizeFlags();
  if (!(flags & kAutoResizeWidth)) {
    width_delta = 0;
  }
  if (!(flags & kAutoResizeHeight)) {
    height_delta = 0;
  }
  if (height_delta || width_delta) {
    auto new_view_size = view->size();
    new_view_size.set_width(new_view_size.width() + width_delta);
    new_view_size.set_height(new_view_size.height() + height_delta);
    view->SetSize(new_view_size);
  }
  auto new_view_bounds = view->bounds();
  if (flags & kAutoResizeHorizontal) {
    new_view_bounds.set_width(new_window.width() /
                              auto_horizontal_proportion_width_);
    new_view_bounds.set_x(new_window.width() /
                          auto_horizontal_proportion_left_);
  }
  if (flags & kAutoResizeVertical) {
    new_view_bounds.set_height(new_window.height() /
                               auto_vertical_proportion_height_);
    new_view_bounds.set_y(new_window.height() / auto_vertical_proportion_top_);
  }
  if ((flags & kAutoResizeHorizontal) || (flags & kAutoResizeVertical)) {
    view->SetBoundsRect(new_view_bounds);
  }
}

void NativeBrowserViewViews::ResetAutoResizeProportions() {
  if (auto_resize_flags_ & AutoResizeFlags::kAutoResizeHorizontal) {
    auto_horizontal_proportion_set_ = false;
  }
  if (auto_resize_flags_ & AutoResizeFlags::kAutoResizeVertical) {
    auto_vertical_proportion_set_ = false;
  }
}

void NativeBrowserViewViews::SetBounds(const gfx::Rect& bounds) {
  InspectableWebContentsView* iwc_view = GetInspectableWebContentsView();
  if (!iwc_view)
    return;
  auto* view = iwc_view->GetView();
  view->SetBoundsRect(bounds);
  ResetAutoResizeProportions();
}

gfx::Rect NativeBrowserViewViews::GetBounds() {
  InspectableWebContentsView* iwc_view = GetInspectableWebContentsView();
  if (!iwc_view)
    return gfx::Rect();
  return iwc_view->GetView()->bounds();
}

void NativeBrowserViewViews::RenderViewReady() {
  InspectableWebContentsView* iwc_view = GetInspectableWebContentsView();
  if (iwc_view)
    iwc_view->GetView()->Layout();
}

void NativeBrowserViewViews::SetBackgroundColor(SkColor color) {
  InspectableWebContentsView* iwc_view = GetInspectableWebContentsView();
  if (!iwc_view)
    return;
  auto* view = iwc_view->GetView();
  view->SetBackground(views::CreateSolidBackground(color));
  view->SchedulePaint();
}

// static
NativeBrowserView* NativeBrowserView::Create(
    InspectableWebContents* inspectable_web_contents) {
  return new NativeBrowserViewViews(inspectable_web_contents);
}

}  // namespace electron
<commit_msg>fix: draggable regions updating on bounds change (#34582)<commit_after>// Copyright (c) 2017 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "shell/browser/native_browser_view_views.h"

#include <vector>

#include "shell/browser/ui/drag_util.h"
#include "shell/browser/ui/views/inspectable_web_contents_view_views.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/views/background.h"
#include "ui/views/view.h"

namespace electron {

NativeBrowserViewViews::NativeBrowserViewViews(
    InspectableWebContents* inspectable_web_contents)
    : NativeBrowserView(inspectable_web_contents) {}

NativeBrowserViewViews::~NativeBrowserViewViews() = default;

void NativeBrowserViewViews::SetAutoResizeFlags(uint8_t flags) {
  auto_resize_flags_ = flags;
  ResetAutoResizeProportions();
}

void NativeBrowserViewViews::UpdateDraggableRegions(
    const std::vector<mojom::DraggableRegionPtr>& regions) {
  if (&draggable_regions_ != &regions)
    draggable_regions_ = mojo::Clone(regions);

  // We need to snap the regions to the bounds of the current BrowserView.
  // For example, if an attached BrowserView is draggable but its bounds are
  // { x: 200,  y: 100, width: 300, height: 300 }
  // then we need to add 200 to the x-value and 100 to the
  // y-value of each of the passed regions or it will be incorrectly
  // assumed that the regions begin in the top left corner as they
  // would for the main client window.
  auto const offset = GetBounds().OffsetFromOrigin();
  for (auto& snapped_region : draggable_regions_) {
    snapped_region->bounds.Offset(offset);
  }
  draggable_region_ = DraggableRegionsToSkRegion(draggable_regions_);
}

void NativeBrowserViewViews::SetAutoResizeProportions(
    const gfx::Size& window_size) {
  if ((auto_resize_flags_ & AutoResizeFlags::kAutoResizeHorizontal) &&
      !auto_horizontal_proportion_set_) {
    InspectableWebContentsView* iwc_view = GetInspectableWebContentsView();
    if (!iwc_view)
      return;
    auto* view = iwc_view->GetView();
    auto view_bounds = view->bounds();
    auto_horizontal_proportion_width_ =
        static_cast<float>(window_size.width()) /
        static_cast<float>(view_bounds.width());
    auto_horizontal_proportion_left_ = static_cast<float>(window_size.width()) /
                                       static_cast<float>(view_bounds.x());
    auto_horizontal_proportion_set_ = true;
  }
  if ((auto_resize_flags_ & AutoResizeFlags::kAutoResizeVertical) &&
      !auto_vertical_proportion_set_) {
    InspectableWebContentsView* iwc_view = GetInspectableWebContentsView();
    if (!iwc_view)
      return;
    auto* view = iwc_view->GetView();
    auto view_bounds = view->bounds();
    auto_vertical_proportion_height_ =
        static_cast<float>(window_size.height()) /
        static_cast<float>(view_bounds.height());
    auto_vertical_proportion_top_ = static_cast<float>(window_size.height()) /
                                    static_cast<float>(view_bounds.y());
    auto_vertical_proportion_set_ = true;
  }
}

void NativeBrowserViewViews::AutoResize(const gfx::Rect& new_window,
                                        int width_delta,
                                        int height_delta) {
  InspectableWebContentsView* iwc_view = GetInspectableWebContentsView();
  if (!iwc_view)
    return;
  auto* view = iwc_view->GetView();
  const auto flags = GetAutoResizeFlags();
  if (!(flags & kAutoResizeWidth)) {
    width_delta = 0;
  }
  if (!(flags & kAutoResizeHeight)) {
    height_delta = 0;
  }
  if (height_delta || width_delta) {
    auto new_view_size = view->size();
    new_view_size.set_width(new_view_size.width() + width_delta);
    new_view_size.set_height(new_view_size.height() + height_delta);
    view->SetSize(new_view_size);
  }
  auto new_view_bounds = view->bounds();
  if (flags & kAutoResizeHorizontal) {
    new_view_bounds.set_width(new_window.width() /
                              auto_horizontal_proportion_width_);
    new_view_bounds.set_x(new_window.width() /
                          auto_horizontal_proportion_left_);
  }
  if (flags & kAutoResizeVertical) {
    new_view_bounds.set_height(new_window.height() /
                               auto_vertical_proportion_height_);
    new_view_bounds.set_y(new_window.height() / auto_vertical_proportion_top_);
  }
  if ((flags & kAutoResizeHorizontal) || (flags & kAutoResizeVertical)) {
    view->SetBoundsRect(new_view_bounds);
  }
}

void NativeBrowserViewViews::ResetAutoResizeProportions() {
  if (auto_resize_flags_ & AutoResizeFlags::kAutoResizeHorizontal) {
    auto_horizontal_proportion_set_ = false;
  }
  if (auto_resize_flags_ & AutoResizeFlags::kAutoResizeVertical) {
    auto_vertical_proportion_set_ = false;
  }
}

void NativeBrowserViewViews::SetBounds(const gfx::Rect& bounds) {
  InspectableWebContentsView* iwc_view = GetInspectableWebContentsView();
  if (!iwc_view)
    return;
  auto* view = iwc_view->GetView();
  view->SetBoundsRect(bounds);
  ResetAutoResizeProportions();

  // Ensure draggable regions are properly updated to reflect new bounds.
  UpdateDraggableRegions(draggable_regions_);
}

gfx::Rect NativeBrowserViewViews::GetBounds() {
  InspectableWebContentsView* iwc_view = GetInspectableWebContentsView();
  if (!iwc_view)
    return gfx::Rect();
  return iwc_view->GetView()->bounds();
}

void NativeBrowserViewViews::RenderViewReady() {
  InspectableWebContentsView* iwc_view = GetInspectableWebContentsView();
  if (iwc_view)
    iwc_view->GetView()->Layout();
}

void NativeBrowserViewViews::SetBackgroundColor(SkColor color) {
  InspectableWebContentsView* iwc_view = GetInspectableWebContentsView();
  if (!iwc_view)
    return;
  auto* view = iwc_view->GetView();
  view->SetBackground(views::CreateSolidBackground(color));
  view->SchedulePaint();
}

// static
NativeBrowserView* NativeBrowserView::Create(
    InspectableWebContents* inspectable_web_contents) {
  return new NativeBrowserViewViews(inspectable_web_contents);
}

}  // namespace electron
<|endoftext|>


<commit_before>//
// Copyright (C) 2007 SIPez LLC.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// Copyright (C) 2007 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// $$
///////////////////////////////////////////////////////////////////////////////

#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>
#include <sipxunit/TestUtilities.h>

#include <mp/MpMMTimer.h>
#include <os/OsDateTime.h>
#include <os/OsSysLog.h>

#ifdef WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <mp/MpMMTimerWnt.h>
#endif

/**
 * Unittest for MpMMTimer and its successors
 */
class MpMMTimerTest : public CppUnit::TestCase
{
   CPPUNIT_TEST_SUITE(MpMMTimerTest);
   CPPUNIT_TEST(testLinearTimer);
   CPPUNIT_TEST_SUITE_END();

public:
   void setUp()
   {
   }

   void tearDown()
   {
   }

   void testLinearTimer()
   {
      MpMMTimer* pMMTimer = NULL;
#ifdef WIN32
      MpMMTimerWnt mmTimerWnt(MpMMTimer::Linear);
      pMMTimer = &mmTimerWnt;
#else
      // Right now MMTimers are only implemented for win32.
      // as other platforms are implemented, change this.
      printf("MMTimer not implemented for this platform.  Test disabled.\n");
      return;
#endif

      // Test getting the resolution, and get it..
      unsigned resolution;
      CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMMTimer->getResolution(resolution));

      // Set the below variables and preprocessor defines to tweak this test.
      // TLT_LOOP_COUNT defines the number of timer fire repetitions to do
      // (set this to an even value),
      // and periodUSecs defines how long to wait in each one.
#     define TLT_LOOP_CNT 200
      unsigned periodUSecs = 10000;
      long lowerThresh = -3000;    // Assert when outside an error range
      long lowerMeanThresh = -50;  // specified below.
      long upperThresh = 3000;     // One for single values
      long upperMeanThresh = 50;   // One for mean values

      // Test the period range static method..
      unsigned unusedMin = 0;
      unsigned unusedMax = 0;
      CPPUNIT_ASSERT_EQUAL(OS_SUCCESS,
                           MpMMTimer::getPeriodRange(&unusedMin, &unusedMax));

#ifdef WIN32
      // Initialize performance counting measurement tools
      LARGE_INTEGER perfFreqPerSec;
      CPPUNIT_ASSERT(QueryPerformanceFrequency(&perfFreqPerSec) > 0);
      //printf("Performance frequency is %I64d ticks per sec\n",
      //       perfFreqPerSec.QuadPart);
      // Convert it to per usec instead of per sec.
      double perfFreqPerUSec = double(perfFreqPerSec.QuadPart) / double(1000000.0);
      //printf("Performance frequency is %f ticks per usec\n",
      //       perfFreqPerUSec);
      LARGE_INTEGER perfCount[TLT_LOOP_CNT];
#endif

      // Initialize the timer.
      printf("Minimum timer resolution is %d usecs\n", resolution);
      printf("Firing every %d usecs\n", periodUSecs);
      CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMMTimer->run(periodUSecs));

      // Perform the timing measurements.
      int i;
      for(i = 0; i < TLT_LOOP_CNT; i++)
      {
#ifdef WIN32
         CPPUNIT_ASSERT(QueryPerformanceCounter(&perfCount[i]) > 0);
#endif
         CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMMTimer->waitForNextTick());
      }

#ifdef WIN32
      printf("Timing values in microseconds, CSV: \n");
      long delta;
      long valOutsideThreshs = periodUSecs; // initialize to exactly what we want.
      long meanAvg = 0;
      for(i = 0; i < TLT_LOOP_CNT; i = i+2)
      {
         delta = (long)(__int64(perfCount[i+1].QuadPart / perfFreqPerUSec) -
                        __int64(perfCount[i].QuadPart / perfFreqPerUSec));

         // Tack on the current delta to our mean avg
         meanAvg += delta;

         // Print output in CSV format, for easy graphing.
         printf("%ld", delta);
         if(i < TLT_LOOP_CNT-2)
         {
            printf(", ");
         }
         else
         {
            printf("\n");
         }

         // Check if we're outside some reasonable thresholds.
         if(i > 0 && // don't include the first value in our tests - it's always high.
            valOutsideThreshs == periodUSecs) // Only check if we haven't already gone outside threshold.
         {
            if(delta-(long)periodUSecs < lowerThresh ||
               delta-(long)periodUSecs > upperThresh)
            {
               valOutsideThreshs = delta;
            }
         }
      }

      // Finalize determining mean.
      meanAvg /= (TLT_LOOP_CNT/2);
      printf("Mean: %ld\n", meanAvg);

      // Assert when single value outside error range specified above.
      char errStrBuf[256];
      snprintf(errStrBuf, 256,
               "Single timer value %ld falls outside threshold of %ld to %ldus",
               valOutsideThreshs, lowerThresh, upperThresh);

      CPPUNIT_ASSERT_MESSAGE(errStrBuf,
                             (valOutsideThreshs-(long)periodUSecs >= lowerThresh &&
                              valOutsideThreshs-(long)periodUSecs <= upperThresh));

      // Assert when mean is outside error range specified above.
      snprintf(errStrBuf, 256,
         "Mean timer value %ld falls outside threshold of %ld to %ldus",
         meanAvg, lowerMeanThresh, upperMeanThresh);

      CPPUNIT_ASSERT_MESSAGE(errStrBuf,
                             (meanAvg-(long)periodUSecs >= lowerMeanThresh &&
                              meanAvg-(long)periodUSecs <= upperMeanThresh));
#endif

      CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMMTimer->stop());
   }

protected:

};

CPPUNIT_TEST_SUITE_REGISTRATION(MpMMTimerTest);
<commit_msg>Modularize MpMMTimerTest test code  into reusable hunks in prep for timer test for OsNotification mode.<commit_after>//
// Copyright (C) 2007 SIPez LLC.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// Copyright (C) 2007 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// $$
///////////////////////////////////////////////////////////////////////////////

#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>
#include <sipxunit/TestUtilities.h>

#include <mp/MpMMTimer.h>
#include <os/OsDateTime.h>
#include <os/OsSysLog.h>

#ifdef WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <mp/MpMMTimerWnt.h>
#endif

/**
 * Unittest for MpMMTimer and its successors
 */
class MpMMTimerTest : public CppUnit::TestCase
{
   CPPUNIT_TEST_SUITE(MpMMTimerTest);
   CPPUNIT_TEST(testGetResolution);
   CPPUNIT_TEST(testPeriodRange);
   CPPUNIT_TEST(testLinearTimer);
   CPPUNIT_TEST_SUITE_END();

public:
   void setUp()
   {
   }

   void tearDown()
   {
   }

#ifdef WIN32
   double initializeWin32PerfMeasurementTools()
   {
      // Initialize performance counting measurement tools
      LARGE_INTEGER perfFreqPerSec;
      CPPUNIT_ASSERT(QueryPerformanceFrequency(&perfFreqPerSec) > 0);
      //printf("Performance frequency is %I64d ticks per sec\n",
      //       perfFreqPerSec.QuadPart);
      // Convert it to per usec instead of per sec.
      double perfFreqPerUSec = double(perfFreqPerSec.QuadPart) / double(1000000.0);
      //printf("Performance frequency is %f ticks per usec\n",
      //       perfFreqPerUSec);
      return perfFreqPerUSec;
   }
#endif

   void checkDeltasAgainstThresholds(long deltas[], unsigned nDeltas,
                                     unsigned targetDelta, // <-- was periodUSecs
                                     long lowerThresh, long upperThresh,
                                     long lowerMeanThresh, long upperMeanThresh)
   {
      CPPUNIT_ASSERT_MESSAGE("Timer didn't fire or deltas were not collected!",
                             nDeltas > 0);

      printf("Timing values in microseconds, CSV: \n");
      long valOutsideThreshs = targetDelta; // initialize to exactly what we want.
      long meanAvg = 0;
      unsigned i;
      for(i = 0; i < nDeltas; i++)
      {
         // Tack on the current delta to our mean avg
         meanAvg += deltas[i];

         // Print output in CSV format, for easy graphing.
         printf("%ld", deltas[i]);
         printf((i < nDeltas-1) ? ", " : "\n");

         // Check if we're outside some reasonable thresholds.
         if(i > 0 && // don't include the first value in our tests - it's always high.
            valOutsideThreshs == targetDelta) // Only check if we haven't already gone outside threshold.
         {
            if(deltas[i]-(long)targetDelta < lowerThresh ||
               deltas[i]-(long)targetDelta > upperThresh)
            {
               valOutsideThreshs = deltas[i];
            }
         }
      }

      // Finalize determining mean.
      meanAvg /= nDeltas;
      printf("Mean: %ld\n", meanAvg);

      // Assert when single value outside error range specified above.
      char errStrBuf[256];
      snprintf(errStrBuf, 256,
               "Single timer value %ld falls outside threshold of %ld to %ldus",
               valOutsideThreshs, lowerThresh, upperThresh);

      CPPUNIT_ASSERT_MESSAGE(errStrBuf,
                             (valOutsideThreshs-(long)targetDelta >= lowerThresh &&
                              valOutsideThreshs-(long)targetDelta <= upperThresh));

      // Assert when mean is outside error range specified above.
      snprintf(errStrBuf, 256,
         "Mean timer value %ld falls outside threshold of %ld to %ldus",
         meanAvg, lowerMeanThresh, upperMeanThresh);

      CPPUNIT_ASSERT_MESSAGE(errStrBuf,
                             (meanAvg-(long)targetDelta >= lowerMeanThresh &&
                              meanAvg-(long)targetDelta <= upperMeanThresh));
   }

   void testGetResolution()
   {
      // Test getting the resolution, and get it..
      unsigned resolution;
      CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, MpMMTimer::getResolution(resolution));
      printf("Minimum timer resolution is %d usecs\n", resolution);
   }

   void testPeriodRange()
   {
      // Test the period range static method..
      unsigned unusedMin = 0;
      unsigned unusedMax = 0;
      CPPUNIT_ASSERT_EQUAL(OS_SUCCESS,
         MpMMTimer::getPeriodRange(&unusedMin, &unusedMax));
   }

   void testLinearTimer()
   {
      // Set the below variables and preprocessor defines to tweak this test.
      // TLT_LOOP_COUNT defines the number of timer fire repetitions to do
      // (set this to an even value),
      // and periodUSecs defines how long to wait in each one.
#     define TLT_LOOP_CNT 200
      unsigned periodUSecs = 10000;
      long lowerThresh = -3000;    // Assert when outside an error range
      long lowerMeanThresh = -50;  // specified below.
      long upperThresh = 3000;     // One for single values
      long upperMeanThresh = 50;   // One for mean values

      MpMMTimer* pMMTimer = NULL;
#ifdef WIN32
      MpMMTimerWnt mmTimerWnt(MpMMTimer::Linear);
      pMMTimer = &mmTimerWnt;

      double perfFreqPerUSec = initializeWin32PerfMeasurementTools();
      LARGE_INTEGER perfCount[TLT_LOOP_CNT];
#else
      // Right now MMTimers are only implemented for win32.
      // as other platforms are implemented, change this.
      printf("MMTimer not implemented for this platform.  Test disabled.\n");
      return;
#endif

      // Initialize the timer.
      printf("Firing every %d usecs\n", periodUSecs);
      CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMMTimer->run(periodUSecs));

      // Perform the timing measurements.
      int i;
      for(i = 0; i < TLT_LOOP_CNT; i++)
      {
#ifdef WIN32
         CPPUNIT_ASSERT(QueryPerformanceCounter(&perfCount[i]) > 0);
#endif
         CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMMTimer->waitForNextTick());
      }

      // Determine delta times from individual time measurements..
      long deltas[TLT_LOOP_CNT/2];
      for(i = 0; i < TLT_LOOP_CNT; i = i+2)
      {
         deltas[(i+1)/2] =
#ifdef WIN32
            (long)(__int64(perfCount[i+1].QuadPart / perfFreqPerUSec) -
                   __int64(perfCount[i].QuadPart / perfFreqPerUSec));
#else
            0;
#endif
      }

      checkDeltasAgainstThresholds(deltas, TLT_LOOP_CNT/2,
                                   periodUSecs,
                                   lowerThresh, upperThresh,
                                   lowerMeanThresh, upperMeanThresh);

      CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMMTimer->stop());
   }

protected:

};

CPPUNIT_TEST_SUITE_REGISTRATION(MpMMTimerTest);
<|endoftext|>


<commit_before>/*
 * Copyright (c), Recep Aslantas.
 *
 * MIT License (MIT), http://opensource.org/licenses/MIT
 * Full license can be found in the LICENSE file
 */

#include "sig.h"
#include "sig-ctx.h"

__SIG_C_DECL void sig_attach(int signal, sig_observer_cb_t cb) {
  sig::__sig_def_ctx_mngr.add(signal, cb);
}

void sig_attach(int signal, sig_observer_cb2_t cb) {
  sig::__sig_def_ctx_mngr.add(signal, cb);
}

void sig_attach(const char * signal, sig_observer_cb2_t cb) {
  sig::__sig_def_ctx_mngr_s.add(signal, cb);
}

__SIG_C_DECL void sig_attach_s(const char * signal, sig_observer_cb_t cb) {
  sig::__sig_def_ctx_mngr_s.add(signal, cb);
}

__SIG_C_DECL void sig_fire(int signal, void * object) {
  sig::__sig_def_ctx_mngr.fire(signal, object);
}

void sig_fire(const char * signal, void * object) {
  sig::__sig_def_ctx_mngr_s.fire(signal, object);
}

__SIG_C_DECL void sig_fire_s(const char * signal, void * object) {
  sig::__sig_def_ctx_mngr_s.fire(signal, object);
}
<commit_msg>style<commit_after>/*
 * Copyright (c), Recep Aslantas.
 *
 * MIT License (MIT), http://opensource.org/licenses/MIT
 * Full license can be found in the LICENSE file
 */

#include "sig.h"
#include "sig-ctx.h"

__SIG_C_DECL void
sig_attach(int signal, sig_observer_cb_t cb) {
  sig::__sig_def_ctx_mngr.add(signal, cb);
}

void
sig_attach(int signal, sig_observer_cb2_t cb) {
  sig::__sig_def_ctx_mngr.add(signal, cb);
}

void
sig_attach(const char * signal, sig_observer_cb2_t cb) {
  sig::__sig_def_ctx_mngr_s.add(signal, cb);
}

__SIG_C_DECL void
sig_attach_s(const char * signal, sig_observer_cb_t cb) {
  sig::__sig_def_ctx_mngr_s.add(signal, cb);
}

__SIG_C_DECL void
sig_fire(int signal, void * object) {
  sig::__sig_def_ctx_mngr.fire(signal, object);
}

void
sig_fire(const char * signal, void * object) {
  sig::__sig_def_ctx_mngr_s.fire(signal, object);
}

__SIG_C_DECL void
sig_fire_s(const char * signal, void * object) {
  sig::__sig_def_ctx_mngr_s.fire(signal, object);
}
<|endoftext|>