<commit_before>// -------------------------------------------------------------------------
//    @FileName      :    NFCDataBaseModule.h
//    @Author           :    LvSheng.Huang
//    @Date             :    2012-12-15
//    @Module           :    NFCDataBaseModule
//    Row,Col; ; ; ; ; ; ;
// -------------------------------------------------------------------------

//#include "stdafx.h"
#include <algorithm>
#include "NFCMysqlDriver.h"
#include "NFCMysqlClusterModule.h"

std::string NFCMysqlClusterModule::strDefaultKey = "id";
std::string NFCMysqlClusterModule::strDefaultTable = "role_info";

NFCMysqlClusterModule::NFCMysqlClusterModule(NFIPluginManager* p)
{
	pPluginManager = p;
}

NFCMysqlClusterModule::~NFCMysqlClusterModule()
{

}

bool NFCMysqlClusterModule::Init()
{
//     m_pShareMemoryModule = dynamic_cast<NFIShareMemoryModule*>(pPluginManager->FindModule("NFCShareMemoryModule"));
//
//     otl_connect::otl_initialize();
//
//     bool bLoad = mConfig.Load(mstrDataBaseConfigFile);
//
//     mstrUID = mConfig["UID"].str();
//     mstrPWD = mConfig["PWD"].str();
//     mstrDSN = mConfig["DSN"].str();
//     mstrMasterName = mConfig["MST"].str();
//
//     mstrAccountTableName = mConfig["AccountTBL"].str();
//     mstrPlayerTableName = mConfig["RoleTBL"].str();
//     mstrGlobalTableName = mConfig["GlobalTBL"].str();
//
//
//     m_pDataBaseDriver->OTLConnect(mstrUID, mstrPWD, mstrDSN, motlConnect);

    return true;
}

bool NFCMysqlClusterModule::Shut()
{
    //m_pDataBaseDriver->OTLDisconnect(motlConnect);

    return true;
}

bool NFCMysqlClusterModule::AfterInit()
{
    m_pMysqlConnectMgrManager = dynamic_cast<NFIMysqlConnectMgrModule*>(pPluginManager->FindModule("NFCMysqlConnectMgrModule"));

    assert(NULL != m_pMysqlConnectMgrManager);

    return true;
}

bool NFCMysqlClusterModule::Execute(const float fLasFrametime, const float fStartedTime)
{
    return true;
}

bool NFCMysqlClusterModule::Updata( const std::string& strKey, const std::vector<std::string>& fieldVec, const std::vector<std::string>& valueVec )
{
	return Updata(strDefaultTable, strKey, fieldVec, valueVec);
}

bool NFCMysqlClusterModule::Updata( const std::string& strRecordName, const std::string& strKey, const std::vector<std::string>& fieldVec, const std::vector<std::string>& valueVec )
{
    mysqlpp::Connection* pConnection = m_pMysqlConnectMgrManager->GetMysqlDriver()->GetConnection();
    if (NULL == pConnection)
    {
        return false;
    }

    bool bExist = false;
    if (!Exists(strRecordName, strKey, bExist))
    {
        return false;
    }

    if (fieldVec.size() != valueVec.size())
    {
        return false;
    }

    NFMYSQLTRYBEGIN
        mysqlpp::Query query = pConnection->query();
        if (bExist)
        {
            // update
            query << "UPDATE " << strRecordName << " ";
            for (int i = 0; i < fieldVec.size(); ++i)
            {
                if (i == 0)
                {
                    query << fieldVec[i] << " = " << valueVec[i];
                }
                else
                {
                    query << "," << fieldVec[i] << " = " << valueVec[i];
                }
            }
        }
        else
        {
            // insert
            query << "INSERT INTO " << strRecordName << "(";
            for (int i = 0; i < fieldVec.size(); ++i)
            {
                if (i == 0)
                {
                    query << fieldVec[i];
                }
                else
                {
                    query << ", " << fieldVec[i];
                }
            }

            query << ") VALUES(";
            for (int i = 0; i < valueVec.size(); ++i)
            {
                if (i == 0)
                {
                    query << mysqlpp::quote << valueVec[i];
                }
                else
                {
                    query << ", " << mysqlpp::quote << valueVec[i];
                }
            }

            query << ")";
        }

        query << ";";

        query.execute();
        query.reset();
    NFMYSQLTRYEND("update or insert error")

	return true;
}

bool NFCMysqlClusterModule::Query( const std::string& strKey, const std::vector<std::string>& fieldVec, std::vector<std::string>& valueVec )
{
    return Query(strDefaultTable, strKey, fieldVec, valueVec);
}

bool NFCMysqlClusterModule::Query( const std::string& strRecordName, const std::string& strKey, const std::vector<std::string>& fieldVec, std::vector<std::string>& valueVec )
{
    mysqlpp::Connection* pConnection = m_pMysqlConnectMgrManager->GetMysqlDriver()->GetConnection();
    if (NULL == pConnection)
    {
        return false;
    }

    NFMYSQLTRYBEGIN
        mysqlpp::Query query = pConnection->query();
        query << "SELECT ";
        for (std::vector<std::string>::const_iterator iter = fieldVec.begin(); iter != fieldVec.end(); ++iter)
        {
            if (iter == fieldVec.begin())
            {
                query << *iter;
            }
            else
            {
                query << "," << *iter;
            }
        }
        query << " FROM " << strRecordName << " WHERE " << strDefaultKey << " = " << mysqlpp::quote << strKey << ";";
        query.execute();
        mysqlpp::StoreQueryResult xResult = query.store();
        query.reset();

        if (xResult.empty() || !xResult)
        {
            return false;
        }

        // xResultӦֻһеģΪԺֵܳĶѭ
        for (int i = 0; i < xResult.size(); ++i)
        {
            for (int j = 0; j < fieldVec.size(); ++j)
            {
                const std::string& strFieldName = fieldVec[j];
                std::string strValue(xResult[i][strFieldName.data()].data(), xResult[i][strFieldName.data()].length());
                valueVec.push_back(strValue);
            }
        }
    NFMYSQLTRYEND("query error")

	return true;
}

bool NFCMysqlClusterModule::Delete( const std::string& strKey )
{
    return Delete(strDefaultTable, strKey);
}

bool NFCMysqlClusterModule::Delete( const std::string& strRecordName, const std::string& strKey )
{
    mysqlpp::Connection* pConnection = m_pMysqlConnectMgrManager->GetMysqlDriver()->GetConnection();
    if (NULL == pConnection)
    {
        return false;
    }

    NFMYSQLTRYBEGIN
        mysqlpp::Query query = pConnection->query();
        query << "DELETE FROM " << strRecordName << " WHERE " << strDefaultKey << " = " << mysqlpp::quote << strKey << ";";

        query.execute();
        query.reset();
    NFMYSQLTRYEND("delete error")

	return true;
}

bool NFCMysqlClusterModule::Exists( const std::string& strKey, bool& bExit )
{
    //select 1 from table where col_name = col_value limit 1;
	return Exists(strDefaultTable, strKey, bExit);
}

bool NFCMysqlClusterModule::Exists( const std::string& strRecordName, const std::string& strKey, bool& bExit )
{
    mysqlpp::Connection* pConnection = m_pMysqlConnectMgrManager->GetMysqlDriver()->GetConnection();
    if (NULL == pConnection)
    {
        return false;
    }

    NFMYSQLTRYBEGIN
        mysqlpp::Query query = pConnection->query();
        query << "SELECT 1 FROM " << strRecordName << " WHERE " << strDefaultKey << " = " << mysqlpp::quote << strKey << " LIMIT 1;";

        query.execute();
        mysqlpp::StoreQueryResult result = query.store();
        query.reset();

        if (!result || result.empty())
        {
            bExit = false;
            return false;
        }

    NFMYSQLTRYEND("exist error")

    bExit = true;
	return true;
}

bool NFCMysqlClusterModule::Select( const std::string& strKey, const std::vector<std::string>& fieldVec, std::vector<std::string>& valueVec )
{
	return false;
}

bool NFCMysqlClusterModule::Select( const std::string& strRecordName, const std::string& strKey, const std::vector<std::string>& fieldVec, std::vector<std::string>& valueVec )
{
	return false;
}<commit_msg>fix query fuction<commit_after>// -------------------------------------------------------------------------
//    @FileName      :    NFCDataBaseModule.h
//    @Author           :    LvSheng.Huang
//    @Date             :    2012-12-15
//    @Module           :    NFCDataBaseModule
//    Row,Col; ; ; ; ; ; ;
// -------------------------------------------------------------------------

//#include "stdafx.h"
#include <algorithm>
#include "NFCMysqlDriver.h"
#include "NFCMysqlClusterModule.h"

std::string NFCMysqlClusterModule::strDefaultKey = "id";
std::string NFCMysqlClusterModule::strDefaultTable = "role_info";

NFCMysqlClusterModule::NFCMysqlClusterModule(NFIPluginManager* p)
{
	pPluginManager = p;
}

NFCMysqlClusterModule::~NFCMysqlClusterModule()
{

}

bool NFCMysqlClusterModule::Init()
{
//     m_pShareMemoryModule = dynamic_cast<NFIShareMemoryModule*>(pPluginManager->FindModule("NFCShareMemoryModule"));
//
//     otl_connect::otl_initialize();
//
//     bool bLoad = mConfig.Load(mstrDataBaseConfigFile);
//
//     mstrUID = mConfig["UID"].str();
//     mstrPWD = mConfig["PWD"].str();
//     mstrDSN = mConfig["DSN"].str();
//     mstrMasterName = mConfig["MST"].str();
//
//     mstrAccountTableName = mConfig["AccountTBL"].str();
//     mstrPlayerTableName = mConfig["RoleTBL"].str();
//     mstrGlobalTableName = mConfig["GlobalTBL"].str();
//
//
//     m_pDataBaseDriver->OTLConnect(mstrUID, mstrPWD, mstrDSN, motlConnect);

    return true;
}

bool NFCMysqlClusterModule::Shut()
{
    //m_pDataBaseDriver->OTLDisconnect(motlConnect);

    return true;
}

bool NFCMysqlClusterModule::AfterInit()
{
    m_pMysqlConnectMgrManager = dynamic_cast<NFIMysqlConnectMgrModule*>(pPluginManager->FindModule("NFCMysqlConnectMgrModule"));

    assert(NULL != m_pMysqlConnectMgrManager);

    return true;
}

bool NFCMysqlClusterModule::Execute(const float fLasFrametime, const float fStartedTime)
{
    return true;
}

bool NFCMysqlClusterModule::Updata( const std::string& strKey, const std::vector<std::string>& fieldVec, const std::vector<std::string>& valueVec )
{
	return Updata(strDefaultTable, strKey, fieldVec, valueVec);
}

bool NFCMysqlClusterModule::Updata( const std::string& strRecordName, const std::string& strKey, const std::vector<std::string>& fieldVec, const std::vector<std::string>& valueVec )
{
    mysqlpp::Connection* pConnection = m_pMysqlConnectMgrManager->GetMysqlDriver()->GetConnection();
    if (NULL == pConnection)
    {
        return false;
    }

    bool bExist = false;
    if (!Exists(strRecordName, strKey, bExist))
    {
        return false;
    }

    if (fieldVec.size() != valueVec.size())
    {
        return false;
    }

    NFMYSQLTRYBEGIN
        mysqlpp::Query query = pConnection->query();
        if (bExist)
        {
            // update
            query << "UPDATE " << strRecordName << " ";
            for (int i = 0; i < fieldVec.size(); ++i)
            {
                if (i == 0)
                {
                    query << fieldVec[i] << " = " << valueVec[i];
                }
                else
                {
                    query << "," << fieldVec[i] << " = " << valueVec[i];
                }
            }
        }
        else
        {
            // insert
            query << "INSERT INTO " << strRecordName << "(";
            for (int i = 0; i < fieldVec.size(); ++i)
            {
                if (i == 0)
                {
                    query << fieldVec[i];
                }
                else
                {
                    query << ", " << fieldVec[i];
                }
            }

            query << ") VALUES(";
            for (int i = 0; i < valueVec.size(); ++i)
            {
                if (i == 0)
                {
                    query << mysqlpp::quote << valueVec[i];
                }
                else
                {
                    query << ", " << mysqlpp::quote << valueVec[i];
                }
            }

            query << ")";
        }

        query << ";";

        query.execute();
        query.reset();
    NFMYSQLTRYEND("update or insert error")

	return true;
}

bool NFCMysqlClusterModule::Query( const std::string& strKey, const std::vector<std::string>& fieldVec, std::vector<std::string>& valueVec )
{
    return Query(strDefaultTable, strKey, fieldVec, valueVec);
}

bool NFCMysqlClusterModule::Query( const std::string& strRecordName, const std::string& strKey, const std::vector<std::string>& fieldVec, std::vector<std::string>& valueVec )
{
    mysqlpp::Connection* pConnection = m_pMysqlConnectMgrManager->GetMysqlDriver()->GetConnection();
    if (NULL == pConnection)
    {
        return false;
    }

    NFMYSQLTRYBEGIN
        mysqlpp::Query query = pConnection->query();
        query << "SELECT ";
        for (std::vector<std::string>::const_iterator iter = fieldVec.begin(); iter != fieldVec.end(); ++iter)
        {
            if (iter == fieldVec.begin())
            {
                query << *iter;
            }
            else
            {
                query << "," << *iter;
            }
        }
        query << " FROM " << strRecordName << " WHERE " << strDefaultKey << " = " << mysqlpp::quote << strKey << ";";
        //query.execute(); // ӲҪexecute
        mysqlpp::StoreQueryResult xResult = query.store();
        query.reset();

        if (xResult.empty() || !xResult)
        {
            return false;
        }

        // xResultӦֻһеģΪԺֵܳĶѭ
        for (int i = 0; i < xResult.size(); ++i)
        {
            for (int j = 0; j < fieldVec.size(); ++j)
            {
                const std::string& strFieldName = fieldVec[j];
                std::string strValue(xResult[i][strFieldName.data()].data(), xResult[i][strFieldName.data()].length());
                valueVec.push_back(strValue);
            }
        }
    NFMYSQLTRYEND("query error")

	return true;
}

bool NFCMysqlClusterModule::Delete( const std::string& strKey )
{
    return Delete(strDefaultTable, strKey);
}

bool NFCMysqlClusterModule::Delete( const std::string& strRecordName, const std::string& strKey )
{
    mysqlpp::Connection* pConnection = m_pMysqlConnectMgrManager->GetMysqlDriver()->GetConnection();
    if (NULL == pConnection)
    {
        return false;
    }

    NFMYSQLTRYBEGIN
        mysqlpp::Query query = pConnection->query();
        query << "DELETE FROM " << strRecordName << " WHERE " << strDefaultKey << " = " << mysqlpp::quote << strKey << ";";

        query.execute();
        query.reset();
    NFMYSQLTRYEND("delete error")

	return true;
}

bool NFCMysqlClusterModule::Exists( const std::string& strKey, bool& bExit )
{
    //select 1 from table where col_name = col_value limit 1;
	return Exists(strDefaultTable, strKey, bExit);
}

bool NFCMysqlClusterModule::Exists( const std::string& strRecordName, const std::string& strKey, bool& bExit )
{
    mysqlpp::Connection* pConnection = m_pMysqlConnectMgrManager->GetMysqlDriver()->GetConnection();
    if (NULL == pConnection)
    {
        return false;
    }

    NFMYSQLTRYBEGIN
        mysqlpp::Query query = pConnection->query();
        query << "SELECT 1 FROM " << strRecordName << " WHERE " << strDefaultKey << " = " << mysqlpp::quote << strKey << " LIMIT 1;";

        query.execute();
        mysqlpp::StoreQueryResult result = query.store();
        query.reset();

        if (!result || result.empty())
        {
            bExit = false;
            return false;
        }

    NFMYSQLTRYEND("exist error")

    bExit = true;
	return true;
}

bool NFCMysqlClusterModule::Select( const std::string& strKey, const std::vector<std::string>& fieldVec, std::vector<std::string>& valueVec )
{
	return false;
}

bool NFCMysqlClusterModule::Select( const std::string& strRecordName, const std::string& strKey, const std::vector<std::string>& fieldVec, std::vector<std::string>& valueVec )
{
	return false;
}<|endoftext|>


<commit_before>/****************************************************************************
 *
 *   Copyright (c) 2015, 2016 Airmind 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 Airmind 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 rgbled_pwm.cpp
 *
 * Driver for the onboard RGB LED controller by PWM.
 * this driver is based the PX4 led driver
 *
 */

#include <nuttx/config.h>

//#include <drivers/device/i2c.h>

#include <sys/types.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <ctype.h>

#include <nuttx/wqueue.h>
#include <drivers/drv_hrt.h>

#include <perf/perf_counter.h>
#include <systemlib/err.h>

#include <board_config.h>

#include <drivers/drv_led.h>
#include <lib/led/led.h>
#include <drivers/device/device.h>
#include <systemlib/err.h>

#define RGBLED_ONTIME 120
#define RGBLED_OFFTIME 120

class RGBLED_PWM : public device::CDev
{
public:
	RGBLED_PWM();
	virtual ~RGBLED_PWM();

	virtual int		init();
	virtual int		probe();
	int		status();

private:
	work_s			_work;

	uint8_t			_r;
	uint8_t			_g;
	uint8_t			_b;
	float			_brightness;

	volatile bool		_running;
	volatile bool		_should_run;

	LedController		_led_controller;

	static void		led_trampoline(void *arg);
	void			led();

	int			send_led_rgb();
	int			get(bool &on, bool &powersave, uint8_t &r, uint8_t &g, uint8_t &b);
};

extern "C" __EXPORT int rgbled_pwm_main(int argc, char *argv[]);
extern int led_pwm_servo_set(unsigned channel, uint8_t  value);
extern unsigned led_pwm_servo_get(unsigned channel);
extern int led_pwm_servo_init(void);
extern void led_pwm_servo_deinit(void);

/* for now, we only support one RGBLED */
namespace
{
RGBLED_PWM *g_rgbled = nullptr;
}

RGBLED_PWM::RGBLED_PWM() :
	CDev("rgbled_pwm", RGBLED_PWM0_DEVICE_PATH),
	_work{},
	_r(0),
	_g(0),
	_b(0),
	_brightness(1.0f),
	_running(false),
	_should_run(true)
{
}

RGBLED_PWM::~RGBLED_PWM()
{
	_should_run = false;
	int counter = 0;

	while (_running && ++counter < 10) {
		usleep(100000);
	}
}

int
RGBLED_PWM::init()
{
	/* switch off LED on start */
	CDev::init();
	led_pwm_servo_init();
	send_led_rgb();

	_running = true;
	// kick off work queue
	work_queue(LPWORK, &_work, (worker_t)&RGBLED_PWM::led_trampoline, this, 0);

	return OK;
}

int
RGBLED_PWM::status()
{
	int ret;
	bool on, powersave;
	uint8_t r, g, b;

	ret = get(on, powersave, r, g, b);

	if (ret == OK) {
		/* we don't care about power-save mode */
		DEVICE_LOG("state: %s", on ? "ON" : "OFF");
		DEVICE_LOG("red: %u, green: %u, blue: %u", (unsigned)r, (unsigned)g, (unsigned)b);

	} else {
		PX4_WARN("failed to read led");
	}

	return ret;
}
int
RGBLED_PWM::probe()
{
	return (OK);
}

void
RGBLED_PWM::led_trampoline(void *arg)
{
	RGBLED_PWM *rgbl = reinterpret_cast<RGBLED_PWM *>(arg);

	rgbl->led();
}

/**
 * Main loop function
 */
void
RGBLED_PWM::led()
{
	if (!_should_run) {
		int led_control_sub = _led_controller.led_control_subscription();

		if (led_control_sub >= 0) {
			orb_unsubscribe(led_control_sub);
		}

		_running = false;
		return;
	}

	if (!_led_controller.is_init()) {
		int led_control_sub = orb_subscribe(ORB_ID(led_control));
		_led_controller.init(led_control_sub);
	}

	LedControlData led_control_data;

	if (_led_controller.update(led_control_data) == 1) {
		switch (led_control_data.leds[0].color) {
		case led_control_s::COLOR_RED:
			_r = 255; _g = 0; _b = 0;
			break;

		case led_control_s::COLOR_GREEN:
			_r = 0; _g = 255; _b = 0;
			break;

		case led_control_s::COLOR_BLUE:
			_r = 0; _g = 0; _b = 255;
			break;

		case led_control_s::COLOR_AMBER: //make it the same as yellow
		case led_control_s::COLOR_YELLOW:
			_r = 255; _g = 255; _b = 0;
			break;

		case led_control_s::COLOR_PURPLE:
			_r = 255; _g = 0; _b = 255;
			break;

		case led_control_s::COLOR_CYAN:
			_r = 0; _g = 255; _b = 255;
			break;

		case led_control_s::COLOR_WHITE:
			_r = 255; _g = 255; _b = 255;
			break;

		default: // led_control_s::COLOR_OFF
			_r = 0; _g = 0; _b = 0;
			break;
		}

		_brightness = (float)led_control_data.leds[0].brightness / 255.f;

		send_led_rgb();
	}

	/* re-queue ourselves to run again later */
	work_queue(LPWORK, &_work, (worker_t)&RGBLED_PWM::led_trampoline, this,
		   USEC2TICK(_led_controller.maximum_update_interval()));
}

/**
 * Send RGB PWM settings to LED driver according to current color and brightness
 */
int
RGBLED_PWM::send_led_rgb()
{
#if defined(BOARD_HAS_LED_PWM)
	led_pwm_servo_set(0, _r);
	led_pwm_servo_set(1, _g);
	led_pwm_servo_set(2, _b);
#endif

#if defined(BOARD_HAS_UI_LED_PWM)
	led_pwm_servo_set(3, _r);
	led_pwm_servo_set(4, _g);
	led_pwm_servo_set(5, _b);
#endif

	return (OK);
}

int
RGBLED_PWM::get(bool &on, bool &powersave, uint8_t &r, uint8_t &g, uint8_t &b)
{
	powersave = OK;
	on = _r > 0 || _g > 0 || _b > 0;
	r = _r;
	g = _g;
	b = _b;
	return OK;
}

static void
rgbled_usage()
{
	PX4_INFO("missing command: try 'start', 'status', 'stop'");
}

int
rgbled_pwm_main(int argc, char *argv[])
{
	int ch;

	/* jump over start/off/etc and look at options first */
	while ((ch = getopt(argc, argv, "a:b:")) != EOF) {
		switch (ch) {
		case 'a':
			break;

		case 'b':
			break;

		default:
			rgbled_usage();
			exit(0);
		}
	}

	if (optind >= argc) {
		rgbled_usage();
		exit(1);
	}

	const char *verb = argv[optind];

	if (!strcmp(verb, "start")) {
		if (g_rgbled != nullptr) {
			errx(1, "already started");
		}

		if (g_rgbled == nullptr) {
			g_rgbled = new RGBLED_PWM();

			if (g_rgbled == nullptr) {
				errx(1, "new failed");
			}

			if (OK != g_rgbled->init()) {
				delete g_rgbled;
				g_rgbled = nullptr;
				errx(1, "init failed");
			}
		}

		exit(0);
	}

	/* need the driver past this point */
	if (g_rgbled == nullptr) {
		PX4_WARN("not started");
		rgbled_usage();
		exit(1);
	}

	if (!strcmp(verb, "status")) {
		g_rgbled->status();
		exit(0);
	}

	if (!strcmp(verb, "stop")) {
		delete g_rgbled;
		g_rgbled = nullptr;
		exit(0);
	}

	rgbled_usage();
	exit(0);
}
<commit_msg>fixed rgb pwm led breathing.<commit_after>/****************************************************************************
 *
 *   Copyright (c) 2015, 2016 Airmind 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 Airmind 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 rgbled_pwm.cpp
 *
 * Driver for the onboard RGB LED controller by PWM.
 * this driver is based the PX4 led driver
 *
 */

#include <nuttx/config.h>

//#include <drivers/device/i2c.h>

#include <sys/types.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <ctype.h>

#include <nuttx/wqueue.h>
#include <drivers/drv_hrt.h>

#include <perf/perf_counter.h>
#include <systemlib/err.h>

#include <board_config.h>

#include <drivers/drv_led.h>
#include <lib/led/led.h>
#include <drivers/device/device.h>
#include <systemlib/err.h>

#define RGBLED_ONTIME 120
#define RGBLED_OFFTIME 120

class RGBLED_PWM : public device::CDev
{
public:
	RGBLED_PWM();
	virtual ~RGBLED_PWM();

	virtual int		init();
	virtual int		probe();
	int		status();

private:
	work_s			_work;

	uint8_t			_r;
	uint8_t			_g;
	uint8_t			_b;
	uint8_t			_brightness;

	volatile bool		_running;
	volatile bool		_should_run;

	LedController		_led_controller;

	static void		led_trampoline(void *arg);
	void			led();

	int			send_led_rgb();
	int			get(bool &on, bool &powersave, uint8_t &r, uint8_t &g, uint8_t &b);
};

extern "C" __EXPORT int rgbled_pwm_main(int argc, char *argv[]);
extern int led_pwm_servo_set(unsigned channel, uint8_t  value);
extern unsigned led_pwm_servo_get(unsigned channel);
extern int led_pwm_servo_init(void);
extern void led_pwm_servo_deinit(void);

/* for now, we only support one RGBLED */
namespace
{
RGBLED_PWM *g_rgbled = nullptr;
}

RGBLED_PWM::RGBLED_PWM() :
	CDev("rgbled_pwm", RGBLED_PWM0_DEVICE_PATH),
	_work{},
	_r(0),
	_g(0),
	_b(0),
	_brightness(1.0f),
	_running(false),
	_should_run(true)
{
}

RGBLED_PWM::~RGBLED_PWM()
{
	_should_run = false;
	int counter = 0;

	while (_running && ++counter < 10) {
		usleep(100000);
	}
}

int
RGBLED_PWM::init()
{
	/* switch off LED on start */
	CDev::init();
	led_pwm_servo_init();
	send_led_rgb();

	_running = true;
	// kick off work queue
	work_queue(LPWORK, &_work, (worker_t)&RGBLED_PWM::led_trampoline, this, 0);

	return OK;
}

int
RGBLED_PWM::status()
{
	int ret;
	bool on, powersave;
	uint8_t r, g, b;

	ret = get(on, powersave, r, g, b);

	if (ret == OK) {
		/* we don't care about power-save mode */
		DEVICE_LOG("state: %s", on ? "ON" : "OFF");
		DEVICE_LOG("red: %u, green: %u, blue: %u", (unsigned)r, (unsigned)g, (unsigned)b);

	} else {
		PX4_WARN("failed to read led");
	}

	return ret;
}
int
RGBLED_PWM::probe()
{
	return (OK);
}

void
RGBLED_PWM::led_trampoline(void *arg)
{
	RGBLED_PWM *rgbl = reinterpret_cast<RGBLED_PWM *>(arg);

	rgbl->led();
}

/**
 * Main loop function
 */
void
RGBLED_PWM::led()
{
	if (!_should_run) {
		int led_control_sub = _led_controller.led_control_subscription();

		if (led_control_sub >= 0) {
			orb_unsubscribe(led_control_sub);
		}

		_running = false;
		return;
	}

	if (!_led_controller.is_init()) {
		int led_control_sub = orb_subscribe(ORB_ID(led_control));
		_led_controller.init(led_control_sub);
	}

	LedControlData led_control_data;

	if (_led_controller.update(led_control_data) == 1) {
        _brightness = led_control_data.leds[0].brightness;
		switch (led_control_data.leds[0].color) {
		case led_control_s::COLOR_RED:
			_r = _brightness; _g = 0; _b = 0;
			break;

		case led_control_s::COLOR_GREEN:
			_r = 0; _g = _brightness; _b = 0;
			break;

		case led_control_s::COLOR_BLUE:
			_r = 0; _g = 0; _b = _brightness;
			break;

		case led_control_s::COLOR_AMBER: //make it the same as yellow
		case led_control_s::COLOR_YELLOW:
			_r = _brightness; _g = _brightness; _b = 0;
			break;

		case led_control_s::COLOR_PURPLE:
			_r = _brightness; _g = 0; _b = _brightness;
			break;

		case led_control_s::COLOR_CYAN:
			_r = 0; _g = _brightness; _b = _brightness;
			break;

		case led_control_s::COLOR_WHITE:
			_r = _brightness; _g = _brightness; _b = _brightness;
			break;

		default: // led_control_s::COLOR_OFF
			_r = 0; _g = 0; _b = 0;
			break;
		}

		send_led_rgb();
	}

	/* re-queue ourselves to run again later */
	work_queue(LPWORK, &_work, (worker_t)&RGBLED_PWM::led_trampoline, this,
		   USEC2TICK(_led_controller.maximum_update_interval()));
}

/**
 * Send RGB PWM settings to LED driver according to current color and brightness
 */
int
RGBLED_PWM::send_led_rgb()
{
#if defined(BOARD_HAS_LED_PWM)
	led_pwm_servo_set(0, _r);
	led_pwm_servo_set(1, _g);
	led_pwm_servo_set(2, _b);
#endif

#if defined(BOARD_HAS_UI_LED_PWM)
	led_pwm_servo_set(3, _r);
	led_pwm_servo_set(4, _g);
	led_pwm_servo_set(5, _b);
#endif

	return (OK);
}

int
RGBLED_PWM::get(bool &on, bool &powersave, uint8_t &r, uint8_t &g, uint8_t &b)
{
	powersave = OK;
	on = _r > 0 || _g > 0 || _b > 0;
	r = _r;
	g = _g;
	b = _b;
	return OK;
}

static void
rgbled_usage()
{
	PX4_INFO("missing command: try 'start', 'status', 'stop'");
}

int
rgbled_pwm_main(int argc, char *argv[])
{
	int ch;

	/* jump over start/off/etc and look at options first */
	while ((ch = getopt(argc, argv, "a:b:")) != EOF) {
		switch (ch) {
		case 'a':
			break;

		case 'b':
			break;

		default:
			rgbled_usage();
			exit(0);
		}
	}

	if (optind >= argc) {
		rgbled_usage();
		exit(1);
	}

	const char *verb = argv[optind];

	if (!strcmp(verb, "start")) {
		if (g_rgbled != nullptr) {
			errx(1, "already started");
		}

		if (g_rgbled == nullptr) {
			g_rgbled = new RGBLED_PWM();

			if (g_rgbled == nullptr) {
				errx(1, "new failed");
			}

			if (OK != g_rgbled->init()) {
				delete g_rgbled;
				g_rgbled = nullptr;
				errx(1, "init failed");
			}
		}

		exit(0);
	}

	/* need the driver past this point */
	if (g_rgbled == nullptr) {
		PX4_WARN("not started");
		rgbled_usage();
		exit(1);
	}

	if (!strcmp(verb, "status")) {
		g_rgbled->status();
		exit(0);
	}

	if (!strcmp(verb, "stop")) {
		delete g_rgbled;
		g_rgbled = nullptr;
		exit(0);
	}

	rgbled_usage();
	exit(0);
}
<|endoftext|>


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

#ifndef _DBAUI_DATASOURCEITEMS_HXX_
#define _DBAUI_DATASOURCEITEMS_HXX_

//========================================================================
//= item ids for the data source administration dialog

#define DSID_NAME                   1           // name of a data source, SfxStringItem
#define DSID_ORIGINALNAME           2           // orginal name, internal, SfxStringItem
#define DSID_CONNECTURL             3           // connection URL, SfxStringItem
#define DSID_TABLEFILTER            4           // table filter, OStringListItem
#define DSID_TYPECOLLECTION         5           // collection of data source types, ODsnTypeCollection
#define DSID_INVALID_SELECTION      6           // is the selection (thus the set data) invalid?, SfxBoolItem
#define DSID_READONLY               7           // is the selection (thus the set data) readonly?, SfxBoolItem
#define DSID_USER                   8           // the user name used for logon, SfxStringItem
#define DSID_PASSWORD               9           // the password used for logon, SfxStringItem
#define DSID_ADDITIONALOPTIONS      10          // additional options used for connecting, SfxStringItem
#define DSID_CHARSET                11          // character set to use, SfxStringItem by now
#define DSID_PASSWORDREQUIRED       12          // is the password required to connect?, SfxBoolItem
#define DSID_SHOWDELETEDROWS        13          // show deleted rows?, SfxBoolItem
#define DSID_ALLOWLONGTABLENAMES    14          // allow tables names longer than 8.3?, SfxBoolItem
#define DSID_JDBCDRIVERCLASS        15          // JDBC driver class, SfxStringItem
#define DSID_FIELDDELIMITER         16          // field delimiter, SfxUInt16Item
#define DSID_TEXTDELIMITER          17          // text delimiter, SfxUInt16Item
#define DSID_DECIMALDELIMITER       18          // decimal delimiter, SfxUInt16Item
#define DSID_THOUSANDSDELIMITER     19          // thousands delimiter, SfxUInt16Item
#define DSID_TEXTFILEEXTENSION      20          // extension for text files, SfxStringItem
#define DSID_TEXTFILEHEADER         21          // the text file contains a header?, SfxBoolItem
#define DSID_PARAMETERNAMESUBST     22
#define DSID_CONN_PORTNUMBER        23
#define DSID_SUPPRESSVERSIONCL      24          // meta data: sal_True if the data source described by the set is to-be-deleted
#define DSID_DATASOURCE_UNO         25          // meta data: OPropertySetItem, the data source the set represents
#define DSID_CONN_SHUTSERVICE       26
#define DSID_CONN_DATAINC           27
#define DSID_CONN_CACHESIZE         28
#define DSID_CONN_CTRLUSER          29
#define DSID_CONN_CTRLPWD           30
#define DSID_USECATALOG             31          // should the driver use the catalog name when the database is filebased
#define DSID_CONN_HOSTNAME          32
#define DSID_CONN_LDAP_BASEDN       33
#define DSID_CONN_LDAP_PORTNUMBER   34
#define DSID_CONN_LDAP_ROWCOUNT     35
#define DSID_SQL92CHECK             36
#define DSID_AUTOINCREMENTVALUE     37
#define DSID_AUTORETRIEVEVALUE      38
#define DSID_AUTORETRIEVEENABLED    39
#define DSID_APPEND_TABLE_ALIAS     40
#define DSID_MYSQL_PORTNUMBER       41
#define DSID_IGNOREDRIVER_PRIV      42
#define DSID_BOOLEANCOMPARISON      43
#define DSID_ORACLE_PORTNUMBER      44
#define DSID_ENABLEOUTERJOIN        45
#define DSID_CATALOG                46
#define DSID_SCHEMA                 47
#define DSID_INDEXAPPENDIX          48
#define DSID_CONN_LDAP_USESSL       49
#define DSID_DOCUMENT_URL           50
#define DSID_DOSLINEENDS            51
#define DSID_DATABASENAME           52

//========================================================================
//= item range. Adjust this if you introduce new items above

#define DSID_FIRST_ITEM_ID  DSID_NAME
#define DSID_LAST_ITEM_ID   DSID_DATABASENAME

#endif // _DBAUI_DATASOURCEITEMS_HXX_

<commit_msg>INTEGRATION: CWS dba22ui (1.21.204); FILE MERGED 2006/12/05 09:47:56 fs 1.21.204.1: copying the fix for #i72252# from CWS dba22b to dba22ui - intended for the latter, but wrongly checked in into the former<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dsitems.hxx,v $
 *
 *  $Revision: 1.22 $
 *
 *  last change: $Author: kz $ $Date: 2006-12-13 16:51:20 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _DBAUI_DATASOURCEITEMS_HXX_
#define _DBAUI_DATASOURCEITEMS_HXX_

//========================================================================
//= item ids for the data source administration dialog

#define DSID_NAME                   1           // name of a data source, SfxStringItem
#define DSID_ORIGINALNAME           2           // orginal name, internal, SfxStringItem
#define DSID_CONNECTURL             3           // connection URL, SfxStringItem
#define DSID_TABLEFILTER            4           // table filter, OStringListItem
#define DSID_TYPECOLLECTION         5           // collection of data source types, ODsnTypeCollection
#define DSID_INVALID_SELECTION      6           // is the selection (thus the set data) invalid?, SfxBoolItem
#define DSID_READONLY               7           // is the selection (thus the set data) readonly?, SfxBoolItem
#define DSID_USER                   8           // the user name used for logon, SfxStringItem
#define DSID_PASSWORD               9           // the password used for logon, SfxStringItem
#define DSID_ADDITIONALOPTIONS      10          // additional options used for connecting, SfxStringItem
#define DSID_CHARSET                11          // character set to use, SfxStringItem by now
#define DSID_PASSWORDREQUIRED       12          // is the password required to connect?, SfxBoolItem
#define DSID_SHOWDELETEDROWS        13          // show deleted rows?, SfxBoolItem
#define DSID_ALLOWLONGTABLENAMES    14          // allow tables names longer than 8.3?, SfxBoolItem
#define DSID_JDBCDRIVERCLASS        15          // JDBC driver class, SfxStringItem
#define DSID_FIELDDELIMITER         16          // field delimiter, SfxUInt16Item
#define DSID_TEXTDELIMITER          17          // text delimiter, SfxUInt16Item
#define DSID_DECIMALDELIMITER       18          // decimal delimiter, SfxUInt16Item
#define DSID_THOUSANDSDELIMITER     19          // thousands delimiter, SfxUInt16Item
#define DSID_TEXTFILEEXTENSION      20          // extension for text files, SfxStringItem
#define DSID_TEXTFILEHEADER         21          // the text file contains a header?, SfxBoolItem
#define DSID_PARAMETERNAMESUBST     22
#define DSID_CONN_PORTNUMBER        23
#define DSID_SUPPRESSVERSIONCL      24          // meta data: sal_True if the data source described by the set is to-be-deleted
#define DSID_DATASOURCE_UNO         25          // meta data: OPropertySetItem, the data source the set represents
#define DSID_CONN_SHUTSERVICE       26
#define DSID_CONN_DATAINC           27
#define DSID_CONN_CACHESIZE         28
#define DSID_CONN_CTRLUSER          29
#define DSID_CONN_CTRLPWD           30
#define DSID_USECATALOG             31          // should the driver use the catalog name when the database is filebased
#define DSID_CONN_HOSTNAME          32
#define DSID_CONN_LDAP_BASEDN       33
#define DSID_CONN_LDAP_PORTNUMBER   34
#define DSID_CONN_LDAP_ROWCOUNT     35
#define DSID_SQL92CHECK             36
#define DSID_AUTOINCREMENTVALUE     37
#define DSID_AUTORETRIEVEVALUE      38
#define DSID_AUTORETRIEVEENABLED    39
#define DSID_APPEND_TABLE_ALIAS     40
#define DSID_MYSQL_PORTNUMBER       41
#define DSID_IGNOREDRIVER_PRIV      42
#define DSID_BOOLEANCOMPARISON      43
#define DSID_ORACLE_PORTNUMBER      44
#define DSID_ENABLEOUTERJOIN        45
#define DSID_CATALOG                46
#define DSID_SCHEMA                 47
#define DSID_INDEXAPPENDIX          48
#define DSID_CONN_LDAP_USESSL       49
#define DSID_DOCUMENT_URL           50
#define DSID_DOSLINEENDS            51
#define DSID_DATABASENAME           52
#define DSID_AS_BEFORE_CORRNAME     53

//========================================================================
//= item range. Adjust this if you introduce new items above

#define DSID_FIRST_ITEM_ID  DSID_NAME
#define DSID_LAST_ITEM_ID   DSID_AS_BEFORE_CORRNAME

#endif // _DBAUI_DATASOURCEITEMS_HXX_

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: sqledit.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: oj $ $Date: 2001-04-18 13:19:01 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the License); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an AS IS basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef DBAUI_SQLEDIT_HXX
#define DBAUI_SQLEDIT_HXX

#ifndef _SVEDIT_HXX
#include <svtools/svmedit.hxx>
#endif

namespace dbaui
{
    class OQueryTextView;
    class OSqlEdit : public MultiLineEdit
    {
    private:
        Timer   m_timerInvalidate;
        Timer   m_timerUndoActionCreation;
        Link    m_lnkTextModifyHdl;
        String  m_strOrigText;      // wird beim Undo wiederhergestellt
        OQueryTextView* m_pView;
        BOOL    m_bAccelAction;     // Wird bei Cut, Copy, Paste gesetzt
        BOOL    m_bStopTimer;

        DECL_LINK(OnUndoActionTimer, void*);
        DECL_LINK(OnInvalidateTimer, void*);

    protected:
        virtual void KeyInput( const KeyEvent& rKEvt );
        virtual void GetFocus();

        DECL_LINK(ModifyHdl, void*);

    public:
        OSqlEdit( OQueryTextView* pParent,  WinBits nWinStyle = WB_LEFT | WB_VSCROLL |WB_BORDER);
        virtual ~OSqlEdit();

        void OverloadedSetText(const String& rNewText);
            // mieser name, ich weiss .... leider muss ich das SetText, dass die UndoActions an mir ausfuehren koennen, abfangen
            // die Alternative waere gewesen, allen oder nur den UndoActions Zugriff auf m_strOrigText zu geben ...

        BOOL IsInAccelAct();

        void SetTextModifyHdl(const Link& lnk) { m_lnkTextModifyHdl = lnk; }
            // bitte nicht SetModifyHdl benutzen, den brauche ich selber, der hier wird von dem damit gesetzten Handler
            // gerufen
            // der Link bekommt einen Pointer-to-string, der nach dem Link nicht mehr gueltig ist

        void stopTimer();
        void startTimer();
    };
}

#endif // DBAUI_SQLEDIT_HXX

<commit_msg>INTEGRATION: CWS ooo19126 (1.2.504); FILE MERGED 2005/09/05 17:35:00 rt 1.2.504.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: sqledit.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 16:03:18 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef DBAUI_SQLEDIT_HXX
#define DBAUI_SQLEDIT_HXX

#ifndef _SVEDIT_HXX
#include <svtools/svmedit.hxx>
#endif

namespace dbaui
{
    class OQueryTextView;
    class OSqlEdit : public MultiLineEdit
    {
    private:
        Timer   m_timerInvalidate;
        Timer   m_timerUndoActionCreation;
        Link    m_lnkTextModifyHdl;
        String  m_strOrigText;      // wird beim Undo wiederhergestellt
        OQueryTextView* m_pView;
        BOOL    m_bAccelAction;     // Wird bei Cut, Copy, Paste gesetzt
        BOOL    m_bStopTimer;

        DECL_LINK(OnUndoActionTimer, void*);
        DECL_LINK(OnInvalidateTimer, void*);

    protected:
        virtual void KeyInput( const KeyEvent& rKEvt );
        virtual void GetFocus();

        DECL_LINK(ModifyHdl, void*);

    public:
        OSqlEdit( OQueryTextView* pParent,  WinBits nWinStyle = WB_LEFT | WB_VSCROLL |WB_BORDER);
        virtual ~OSqlEdit();

        void OverloadedSetText(const String& rNewText);
            // mieser name, ich weiss .... leider muss ich das SetText, dass die UndoActions an mir ausfuehren koennen, abfangen
            // die Alternative waere gewesen, allen oder nur den UndoActions Zugriff auf m_strOrigText zu geben ...

        BOOL IsInAccelAct();

        void SetTextModifyHdl(const Link& lnk) { m_lnkTextModifyHdl = lnk; }
            // bitte nicht SetModifyHdl benutzen, den brauche ich selber, der hier wird von dem damit gesetzten Handler
            // gerufen
            // der Link bekommt einen Pointer-to-string, der nach dem Link nicht mehr gueltig ist

        void stopTimer();
        void startTimer();
    };
}

#endif // DBAUI_SQLEDIT_HXX

<|endoftext|>


<commit_before>/*****************************************************************************************
 *                                                                                *
 * GHOUL                                                                                *
 * General Helpful Open Utility Library                                                  *
 *                                                                                *
 * Copyright (c) 2012-2014                                                               *
 *                                                                                *
 * 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.                                         *
 ****************************************************************************************/

#if defined(WIN32)
#include <ghoul/filesystem/filesystem.h>

#include <ghoul/filesystem/cachemanager.h>
#include <ghoul/logging/logmanager.h>

#include <algorithm>
#include <cassert>
#include <regex>
#include <cstdio>

#include <direct.h>
#include <windows.h>
#include <Shlobj.h>

using std::string;

namespace {
    const string _loggerCat = "FileSystem";

	void CALLBACK completionHandler(
		DWORD dwErrorCode,
		DWORD dwNumberOfBytesTransferred,
		LPOVERLAPPED lpOverlapped);

	const unsigned int changeBufferSize = 16384u;

#define _CRT_SECURE_NO_WARNINGS
}

namespace ghoul {
namespace filesystem {
	struct DirectoryHandle {
		HANDLE _handle;
		unsigned char _activeBuffer;
		std::vector<BYTE> _changeBuffer[2];
		OVERLAPPED _overlappedBuffer;
	};

void FileSystem::deinitializeInternalWindows() {
	for (auto d : _fileSystem->_directories) {
		DirectoryHandle* dh = d.second;
		CancelIo(dh->_handle);
		CloseHandle(dh->_handle);
		delete dh;
	}
}

void FileSystem::addFileListener(File* file) {
	assert(file != nullptr);
	//LDEBUG("Trying to insert  " << file);
	std::string d = file->directoryName();
	auto f = _directories.find(d);
	if (f == _directories.end()) {
		LDEBUG("started watching: " << d);
		DirectoryHandle* handle = new DirectoryHandle;
		handle->_activeBuffer = 0;
		handle->_handle = nullptr;

		handle->_handle = CreateFile(
			d.c_str(),
			FILE_LIST_DIRECTORY,
			FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
			NULL,
			OPEN_EXISTING,
			FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED,
			NULL);

		if (handle->_handle == INVALID_HANDLE_VALUE) {
			LERROR("Directory handle for '" << d << "' could not be obtained");
			return;
		}

		_directories[d] = handle;
		beginRead(handle);
	}

#ifdef GHL_DEBUG
	auto eqRange = _trackedFiles.equal_range(file->path());
	for (auto it = eqRange.first; it != eqRange.second; ++it) {
		if (it->second == file) {
			LERROR("Already tracking fileobject");
			return;
		}
	}
#endif
	_trackedFiles.insert({ file->path(), file });
}

void FileSystem::removeFileListener(File* file) {
	assert(file != nullptr);
	auto eqRange = _trackedFiles.equal_range(file->path());
	for (auto it = eqRange.first; it != eqRange.second; ++it) {
		if (it->second == file) {
			_trackedFiles.erase(it);
			return;
		}
	}
    LWARNING("Could not find tracked '" << file <<"' for path '"<< file->path() << "'");
}

void FileSystem::callbackHandler(DirectoryHandle* directoryHandle, const std::string& file) {
	std::string fullPath;
	for (auto d : FileSys._directories) {
		if (d.second == directoryHandle)
			fullPath = d.first + PathSeparator + file;
	}

	size_t n = FileSys._trackedFiles.count(fullPath);
	if (n > 0) {
		auto eqRange = FileSys._trackedFiles.equal_range(fullPath);
		for (auto it = eqRange.first; it != eqRange.second; ++it) {
			File* f = (*it).second;
			f->_fileChangedCallback(*f);
		}
	}
}

void callbackHandler(DirectoryHandle* directoryHandle, const std::string& file) {
	FileSys.callbackHandler(directoryHandle, file);
}

void readStarter(DirectoryHandle* directoryHandle) {
	FileSys.beginRead(directoryHandle);
}
void CALLBACK completionHandler(
	DWORD /*dwErrorCode*/,
	DWORD /*dwNumberOfBytesTransferred*/,
	LPOVERLAPPED lpOverlapped)
{
	DirectoryHandle* directoryHandle = static_cast<DirectoryHandle*>(lpOverlapped->hEvent);

	unsigned char currentBuffer = directoryHandle->_activeBuffer;

	// Change active buffer (ping-pong buffering)
	directoryHandle->_activeBuffer = (directoryHandle->_activeBuffer + 1) % 2;

	// Restart change listener as soon as possible
	readStarter(directoryHandle);

	char* buffer = reinterpret_cast<char*>(&(directoryHandle->_changeBuffer[currentBuffer][0]));

	// data might have queued up, so we need to check all changes
	while (true) {
		// extract the information which file has changed
		FILE_NOTIFY_INFORMATION& information = (FILE_NOTIFY_INFORMATION&)*buffer;
		char* currentFilenameBuffer = new char[information.FileNameLength];
		size_t i;
		wcstombs_s(&i, currentFilenameBuffer, information.FileNameLength,
			information.FileName, information.FileNameLength);
		//std::wcstombs(currentFilenameBuffer,
		//information.FileName, information.FileNameLength);
		const string& currentFilename(currentFilenameBuffer);
		delete[] currentFilenameBuffer;

		callbackHandler(directoryHandle, currentFilename);
		if (!information.NextEntryOffset)
			// we are done with all entries and didn't find our file
			break;
		else
			//continue with the next entry
			buffer += information.NextEntryOffset;
	}
}

void FileSystem::beginRead(DirectoryHandle* directoryHandle) {

	HANDLE handle = directoryHandle->_handle;
	unsigned char activeBuffer = directoryHandle->_activeBuffer;
	std::vector<BYTE>* changeBuffer = directoryHandle->_changeBuffer;
	OVERLAPPED* overlappedBuffer = &directoryHandle->_overlappedBuffer;

	ZeroMemory(overlappedBuffer, sizeof(OVERLAPPED));
	overlappedBuffer->hEvent = directoryHandle;

	changeBuffer[activeBuffer].resize(changeBufferSize);
	ZeroMemory(&(changeBuffer[activeBuffer][0]), changeBufferSize);

	DWORD returnedBytes;
	BOOL success = ReadDirectoryChangesW(
		handle,
		&changeBuffer[activeBuffer][0],
		static_cast<DWORD>(changeBuffer[activeBuffer].size()),
		false,
		FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_SIZE,
		&returnedBytes,
		overlappedBuffer,
		&completionHandler);

	if (success == 0) {
		LERROR("Could not begin read directory");
		const DWORD error = GetLastError();
		LPTSTR errorBuffer = nullptr;
		FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
			FORMAT_MESSAGE_ALLOCATE_BUFFER |
			FORMAT_MESSAGE_IGNORE_INSERTS,
			NULL,
			error,
			MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
			(LPTSTR)&errorBuffer,
			0,
			NULL);
		if (errorBuffer != nullptr) {
			std::string errorString(errorBuffer);
			LocalFree(errorBuffer);
			LERROR("Error reading directory changes: " << errorString);
		}
		else {
			LERROR("Error reading directory changes: " << error);
		}
	}
}

} // namespace filesystem
} // namespace ghoul

#endif
<commit_msg>Fixed so callbacks works for Sublime Text 3<commit_after>/*****************************************************************************************
 *                                                                                *
 * GHOUL                                                                                *
 * General Helpful Open Utility Library                                                  *
 *                                                                                *
 * Copyright (c) 2012-2014                                                               *
 *                                                                                *
 * 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.                                         *
 ****************************************************************************************/

#if defined(WIN32)
#include <ghoul/filesystem/filesystem.h>

#include <ghoul/filesystem/cachemanager.h>
#include <ghoul/logging/logmanager.h>

#include <algorithm>
#include <cassert>
#include <regex>
#include <cstdio>

#include <direct.h>
#include <windows.h>
#include <Shlobj.h>

using std::string;

namespace {
    const string _loggerCat = "FileSystem";

	void CALLBACK completionHandler(
		DWORD dwErrorCode,
		DWORD dwNumberOfBytesTransferred,
		LPOVERLAPPED lpOverlapped);

	const unsigned int changeBufferSize = 16384u;

#define _CRT_SECURE_NO_WARNINGS
}

namespace ghoul {
namespace filesystem {
	struct DirectoryHandle {
		HANDLE _handle;
		unsigned char _activeBuffer;
		std::vector<BYTE> _changeBuffer[2];
		OVERLAPPED _overlappedBuffer;
	};

void FileSystem::deinitializeInternalWindows() {
	for (auto d : _fileSystem->_directories) {
		DirectoryHandle* dh = d.second;
		CancelIo(dh->_handle);
		CloseHandle(dh->_handle);
		delete dh;
	}
}

void FileSystem::addFileListener(File* file) {
	assert(file != nullptr);
	//LDEBUG("Trying to insert  " << file);
	std::string d = file->directoryName();
	auto f = _directories.find(d);
	if (f == _directories.end()) {
		LDEBUG("started watching: " << d);
		DirectoryHandle* handle = new DirectoryHandle;
		handle->_activeBuffer = 0;
		handle->_handle = nullptr;

		handle->_handle = CreateFile(
			d.c_str(),
			FILE_LIST_DIRECTORY,
			FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
			NULL,
			OPEN_EXISTING,
			FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED,
			NULL);

		if (handle->_handle == INVALID_HANDLE_VALUE) {
			LERROR("Directory handle for '" << d << "' could not be obtained");
			return;
		}

		_directories[d] = handle;
		beginRead(handle);
	}

#ifdef GHL_DEBUG
	auto eqRange = _trackedFiles.equal_range(file->path());
	for (auto it = eqRange.first; it != eqRange.second; ++it) {
		if (it->second == file) {
			LERROR("Already tracking fileobject");
			return;
		}
	}
#endif
	_trackedFiles.insert({ file->path(), file });
}

void FileSystem::removeFileListener(File* file) {
	assert(file != nullptr);
	auto eqRange = _trackedFiles.equal_range(file->path());
	for (auto it = eqRange.first; it != eqRange.second; ++it) {
		if (it->second == file) {
			_trackedFiles.erase(it);
			return;
		}
	}
    LWARNING("Could not find tracked '" << file <<"' for path '"<< file->path() << "'");
}

void FileSystem::callbackHandler(DirectoryHandle* directoryHandle, const std::string& file) {
	std::string fullPath;
	for (auto d : FileSys._directories) {
		if (d.second == directoryHandle)
			fullPath = d.first + PathSeparator + file;
	}

	size_t n = FileSys._trackedFiles.count(fullPath);
	if (n > 0) {
		auto eqRange = FileSys._trackedFiles.equal_range(fullPath);
		for (auto it = eqRange.first; it != eqRange.second; ++it) {
			File* f = (*it).second;
			f->_fileChangedCallback(*f);
		}
	}
}

void callbackHandler(DirectoryHandle* directoryHandle, const std::string& file) {
	FileSys.callbackHandler(directoryHandle, file);
}

void readStarter(DirectoryHandle* directoryHandle) {
	FileSys.beginRead(directoryHandle);
}
void CALLBACK completionHandler(
	DWORD /*dwErrorCode*/,
	DWORD /*dwNumberOfBytesTransferred*/,
	LPOVERLAPPED lpOverlapped)
{
	DirectoryHandle* directoryHandle = static_cast<DirectoryHandle*>(lpOverlapped->hEvent);

	unsigned char currentBuffer = directoryHandle->_activeBuffer;

	// Change active buffer (ping-pong buffering)
	directoryHandle->_activeBuffer = (directoryHandle->_activeBuffer + 1) % 2;

	// Restart change listener as soon as possible
	readStarter(directoryHandle);

	char* buffer = reinterpret_cast<char*>(&(directoryHandle->_changeBuffer[currentBuffer][0]));

	// data might have queued up, so we need to check all changes
	while (true) {
		// extract the information which file has changed
		FILE_NOTIFY_INFORMATION& information =
			reinterpret_cast<FILE_NOTIFY_INFORMATION&>(*buffer);

		if (information.Action == FILE_ACTION_MODIFIED) {

			// The size of DWORD is 2bytes
			const size_t currentFilenameLength =
				information.FileNameLength / sizeof(information.FileName) + 1;

			char* currentFilenameBuffer = new char[currentFilenameLength];

			// Convert from DWORD to char*
			size_t i;
			wcstombs_s(&i, currentFilenameBuffer, information.FileNameLength,
				information.FileName, information.FileNameLength);

			// make sure the last char is string terminating
			currentFilenameBuffer[currentFilenameLength-1] = '\0';
			const string currentFilename(currentFilenameBuffer, currentFilenameLength);
			delete[] currentFilenameBuffer;

			//switch (information.Action) {
			//case FILE_ACTION_ADDED:
			//	LDEBUG("Action:                 FILE_ACTION_ADDED");
			//	break;
			//case FILE_ACTION_REMOVED:
			//	LDEBUG("Action:                 FILE_ACTION_REMOVED");
			//	break;
			//case FILE_ACTION_MODIFIED:
			//	LDEBUG("Action:                 FILE_ACTION_MODIFIED");
			//	break;
			//case FILE_ACTION_RENAMED_OLD_NAME:
			//	LDEBUG("Action:                 FILE_ACTION_RENAMED_OLD_NAME");
			//	break;
			//case FILE_ACTION_RENAMED_NEW_NAME:
			//	LDEBUG("Action:                 FILE_ACTION_RENAMED_NEW_NAME");
			//	break;
			//default:
			//	LDEBUG("Action:                 UNKNOWN");
			//	break;
			//}
			//LDEBUG("FileNameLength:         " << information.FileNameLength);
			//LDEBUG("file:                   " << currentFilename);
			//LDEBUG("currentFilenamelength:  " << currentFilename.length());
			//LDEBUG("NextEntryOffset:        " << information.NextEntryOffset);

			callbackHandler(directoryHandle, currentFilename);
		}
		if (!information.NextEntryOffset)
			// we are done with all entries and didn't find our file
			break;
		else
			//continue with the next entry
			buffer += information.NextEntryOffset;
	}
	//LWARNING("================");
}

void FileSystem::beginRead(DirectoryHandle* directoryHandle) {

	HANDLE handle = directoryHandle->_handle;
	unsigned char activeBuffer = directoryHandle->_activeBuffer;
	std::vector<BYTE>* changeBuffer = directoryHandle->_changeBuffer;
	OVERLAPPED* overlappedBuffer = &directoryHandle->_overlappedBuffer;

	ZeroMemory(overlappedBuffer, sizeof(OVERLAPPED));
	overlappedBuffer->hEvent = directoryHandle;

	changeBuffer[activeBuffer].resize(changeBufferSize);
	ZeroMemory(&(changeBuffer[activeBuffer][0]), changeBufferSize);

	DWORD returnedBytes;
	BOOL success = ReadDirectoryChangesW(
		handle,
		&changeBuffer[activeBuffer][0],
		static_cast<DWORD>(changeBuffer[activeBuffer].size()),
		false,
		FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_SIZE |
		FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_CREATION,
		&returnedBytes,
		overlappedBuffer,
		&completionHandler);

	if (success == 0) {
		LERROR("Could not begin read directory");
		const DWORD error = GetLastError();
		LPTSTR errorBuffer = nullptr;
		FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
			FORMAT_MESSAGE_ALLOCATE_BUFFER |
			FORMAT_MESSAGE_IGNORE_INSERTS,
			NULL,
			error,
			MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
			(LPTSTR)&errorBuffer,
			0,
			NULL);
		if (errorBuffer != nullptr) {
			std::string errorString(errorBuffer);
			LocalFree(errorBuffer);
			LERROR("Error reading directory changes: " << errorString);
		}
		else {
			LERROR("Error reading directory changes: " << error);
		}
	}
}

} // namespace filesystem
} // namespace ghoul

#endif
<|endoftext|>


<commit_before><commit_msg>Troubleshooting the purify issue (bug 7921)<commit_after><|endoftext|>


<commit_before>#include <sdf/sdf.hh>
#include "gazebo/gazebo.hh"
#include "gazebo/common/Plugin.hh"
#include "gazebo/msgs/msgs.hh"
#include "gazebo/physics/physics.hh"
#include "gazebo/transport/transport.hh"
#include <iostream>

using namespace std;

namespace gazebo
{
  class SetupWorld : public WorldPlugin
  {
    public: void Load(physics::WorldPtr _parent, sdf::ElementPtr _sdf)
    {
      cout << "Setting up world..." << flush;

      // Create a new transport node
      transport::NodePtr node(new transport::Node());

      // Initialize the node with the world name
      node->Init(_parent->GetName());

      // Create a publisher on the ~/physics topic
      transport::PublisherPtr physicsPub =
        node->Advertise<msgs::Physics>("~/physics");

      msgs::Physics physicsMsg;
      physicsMsg.set_type(msgs::Physics::ODE);

      // Set the step time
      physicsMsg.set_max_step_size(0.001);

      // Set the real time update rate
      physicsMsg.set_real_time_update_rate(0.0);

      // Change gravity
      //msgs::Set(physicsMsg.mutable_gravity(), math::Vector3(0.01, 0, 0.1));

      physicsPub->Publish(physicsMsg);

      cout << " done." << endl;
    }
  };

  // Register this plugin with the simulator
  GZ_REGISTER_WORLD_PLUGIN(SetupWorld)
}
<commit_msg>Set gazebo to run at real time (if possible) for debugging The previous default was too fast for proper manual control of the robot<commit_after>#include <sdf/sdf.hh>
#include "gazebo/gazebo.hh"
#include "gazebo/common/Plugin.hh"
#include "gazebo/msgs/msgs.hh"
#include "gazebo/physics/physics.hh"
#include "gazebo/transport/transport.hh"
#include <iostream>

using namespace std;

namespace gazebo
{
  class SetupWorld : public WorldPlugin
  {
    public: void Load(physics::WorldPtr _parent, sdf::ElementPtr _sdf)
    {
      cout << "Setting up world..." << flush;

      // Create a new transport node
      transport::NodePtr node(new transport::Node());

      // Initialize the node with the world name
      node->Init(_parent->GetName());

      // Create a publisher on the ~/physics topic
      transport::PublisherPtr physicsPub =
        node->Advertise<msgs::Physics>("~/physics");

      msgs::Physics physicsMsg;
      physicsMsg.set_type(msgs::Physics::ODE);

      // Set the step time
      physicsMsg.set_max_step_size(0.001);

      // Set the real time update rate
      physicsMsg.set_real_time_update_rate(1000.0);

      // Change gravity
      //msgs::Set(physicsMsg.mutable_gravity(), math::Vector3(0.01, 0, 0.1));

      physicsPub->Publish(physicsMsg);

      cout << " done." << endl;
    }
  };

  // Register this plugin with the simulator
  GZ_REGISTER_WORLD_PLUGIN(SetupWorld)
}
<|endoftext|>


<commit_before>#include "generic_hierarchy.hpp"
#include "ostream_utility.hpp"

namespace
{
enum
  {
    splitting_size = 20,
  };

class Element
{
public:
  Element(const BoundingBox<float> &b, unsigned int r):
    m_box(b),
    m_reference(r)
  {}

  BoundingBox<float> m_box;
  unsigned int m_reference;
};

class TreeBase:fastuidraw::noncopyable
{
public:
  explicit
  TreeBase(const BoundingBox<float> &bbox):
    m_bbox(bbox)
  {}

  virtual
  ~TreeBase()
  {}

  TreeBase*
  add(const BoundingBox<float> &bbox, unsigned int reference)
  {
    if (bbox.intersects(m_bbox))
      {
        return add_implement(bbox, reference);
      }
    else
      {
        return this;
      }
  }

  void
  query(const BoundingBox<float> &bbox,
        std::vector<unsigned int> *output)
  {
    if(bbox.intersects(m_bbox))
      {
        query_implement(bbox, output);
      }
  }

  unsigned int
  query(const fastuidraw::vec2 &p,
        BoundingBox<float> *out_bb)
  {
    if (m_bbox.intersects(p))
      {
        return query_implement(p, out_bb);
      }
    else
      {
        return GenericHierarchy::not_found;
      }
  }

  const BoundingBox<float>&
  bounding_box(void)
  {
    return m_bbox;
  }

private:
  virtual
  TreeBase*
  add_implement(const BoundingBox<float> &bbox,
                unsigned int reference) = 0;

  virtual
  void
  query_implement(const BoundingBox<float> &bbox,
                  std::vector<unsigned int> *output) = 0;

  virtual
  unsigned int
  query_implement(const fastuidraw::vec2 &p,
                  BoundingBox<float> *out_bb) = 0;

  BoundingBox<float> m_bbox;
};

class Node:public TreeBase
{
public:
  Node(const BoundingBox<float> &bbox,
       const BoundingBox<float> &bbox0,
       const std::vector<Element> &elements0,
       const BoundingBox<float> &bbox1,
       const std::vector<Element> &elements1);

  ~Node();

private:
  virtual
  TreeBase*
  add_implement(const BoundingBox<float> &bbox,
                unsigned int reference);

  virtual
  void
  query_implement(const BoundingBox<float> &bbox,
                  std::vector<unsigned int> *output);

  virtual
  unsigned int
  query_implement(const fastuidraw::vec2 &p,
                  BoundingBox<float> *out_bb);

  fastuidraw::vecN<TreeBase*, 2> m_children;
};

class Leaf:public TreeBase
{
public:
  explicit
  Leaf(const BoundingBox<float> &bbox);

  Leaf(const BoundingBox<float> &bbox,
       const std::vector<Element> &elements);

  ~Leaf();

private:
  virtual
  TreeBase*
  add_implement(const BoundingBox<float> &bbox,
                unsigned int reference);

  virtual
  void
  query_implement(const BoundingBox<float> &bbox,
                  std::vector<unsigned int> *output);

  virtual
  unsigned int
  query_implement(const fastuidraw::vec2 &p,
                BoundingBox<float> *out_bb);

  std::vector<Element> m_elements;
};

}

///////////////////////////////////
// Node methods
Node::
Node(const BoundingBox<float> &bbox,
     const BoundingBox<float> &bbox0,
     const std::vector<Element> &elements0,
     const BoundingBox<float> &bbox1,
     const std::vector<Element> &elements1):
  TreeBase(bbox)
{
  m_children[0] = FASTUIDRAWnew Leaf(bbox0, elements0);
  m_children[1] = FASTUIDRAWnew Leaf(bbox1, elements1);
}

Node::
~Node()
{
  FASTUIDRAWdelete(m_children[0]);
  FASTUIDRAWdelete(m_children[1]);
}

TreeBase*
Node::
add_implement(const BoundingBox<float> &bbox, unsigned int reference)
{
  for (unsigned int i = 0; i < 2; ++i)
    {
      TreeBase *p;
      p = m_children[i]->add(bbox, reference);
      if (p != m_children[i])
        {
          FASTUIDRAWdelete(m_children[i]);
          m_children[i] = p;
        }
    }

  return this;
}

void
Node::
query_implement(const BoundingBox<float> &bbox,
      std::vector<unsigned int> *output)
{
  m_children[0]->query(bbox, output);
  m_children[1]->query(bbox, output);
}

unsigned int
Node::
query_implement(const fastuidraw::vec2 &p,
                BoundingBox<float> *out_bb)
{
  int R;
  R = m_children[0]->query(p, out_bb);
  if (R != GenericHierarchy::not_found)
    {
      return R;
    }
  return m_children[1]->query(p, out_bb);
}

///////////////////////////////////////////
// Leaf methods
Leaf::
Leaf(const BoundingBox<float> &bbox, const std::vector<Element> &elements):
  TreeBase(bbox),
  m_elements(elements)
{}

Leaf::
Leaf(const BoundingBox<float> &bbox):
  TreeBase(bbox)
{}

Leaf::
~Leaf()
{}

void
Leaf::
query_implement(const BoundingBox<float> &bbox,
                std::vector<unsigned int> *output)
{
  for (const auto &E : m_elements)
    {
      if (E.m_box.intersects(bbox))
        {
          output->push_back(E.m_reference);
        }
    }
}

unsigned int
Leaf::
query_implement(const fastuidraw::vec2 &p,
                BoundingBox<float> *out_bb)
{
  for (const auto &E : m_elements)
    {
      if (E.m_box.intersects(p))
        {
          *out_bb = E.m_box;
          return E.m_reference;
        }
    }
  return GenericHierarchy::not_found;
}

TreeBase*
Leaf::
add_implement(const BoundingBox<float> &bbox, unsigned int reference)
{
  m_elements.push_back(Element(bbox, reference));
  if (m_elements.size() > splitting_size)
    {
      fastuidraw::vecN<std::vector<Element>, 2> split_x, split_y;
      fastuidraw::vecN<BoundingBox<float>, 2> split_x_bb, split_y_bb;
      unsigned int split_x_size(0), split_y_size(0);

      split_x_bb = bounding_box().split(0);
      split_y_bb = bounding_box().split(1);

      for (const Element &E : m_elements)
        {
          for (unsigned int i = 0; i < 2; ++i)
            {
              if (split_x_bb[i].intersects(E.m_box))
                {
                  split_x[i].push_back(E);
                  ++split_x_size;
                }
              if (split_y_bb[i].intersects(E.m_box))
                {
                  split_y[i].push_back(E);
                  ++split_y_size;
                }
            }

          FASTUIDRAWassert(split_x_bb[0].intersects(E.m_box) || split_x_bb[1].intersects(E.m_box));
          FASTUIDRAWassert(split_y_bb[0].intersects(E.m_box) || split_y_bb[1].intersects(E.m_box));
        }

      unsigned int allow_split;
      const float max_overlap(1.5f);
      allow_split = static_cast<unsigned int>(max_overlap * static_cast<float>(m_elements.size()));

      if (fastuidraw::t_min(split_x_size, split_y_size) <= allow_split)
        {
          if (split_x_size < split_y_size)
            {
              return FASTUIDRAWnew Node(bounding_box(),
                                        split_x_bb[0], split_x[0],
                                        split_x_bb[1], split_x[1]);
            }
          else
            {
              return FASTUIDRAWnew Node(bounding_box(),
                                        split_y_bb[0], split_y[0],
                                        split_y_bb[1], split_y[1]);
            }
        }
    }
  return this;
}

///////////////////////////////////
// GenericHierarchy methods
GenericHierarchy::
GenericHierarchy(const BoundingBox<float> &bbox)
{
  m_root = FASTUIDRAWnew Leaf(bbox);
}

GenericHierarchy::
~GenericHierarchy()
{
  TreeBase *d;

  d = static_cast<TreeBase*>(m_root);
  FASTUIDRAWdelete(d);
}

void
GenericHierarchy::
add(const BoundingBox<float> &bbox, unsigned int reference)
{
  TreeBase *d, *p;

  d = static_cast<TreeBase*>(m_root);
  p = d->add(bbox, reference);
  if (p != d)
    {
      FASTUIDRAWdelete(d);
      m_root = p;
    }
}

void
GenericHierarchy::
query(const BoundingBox<float> &bbox, std::vector<unsigned int> *output)
{
  TreeBase *d;

  d = static_cast<TreeBase*>(m_root);
  d->query(bbox, output);
}

unsigned int
GenericHierarchy::
query(const fastuidraw::vec2 &p, BoundingBox<float> *out_bb)
{
  TreeBase *d;

  d = static_cast<TreeBase*>(m_root);
  return d->query(p, out_bb);
}
<commit_msg>demos/common/generic_hierarchy: make so that an element is only added once in query<commit_after>#include "generic_hierarchy.hpp"
#include "ostream_utility.hpp"

namespace
{
enum
  {
    splitting_size = 20,
  };

class Element
{
public:
  Element(const BoundingBox<float> &b, unsigned int r):
    m_box(b),
    m_reference(r)
  {}

  BoundingBox<float> m_box;
  unsigned int m_reference;
};

class TreeBase:fastuidraw::noncopyable
{
public:
  explicit
  TreeBase(const BoundingBox<float> &bbox):
    m_bbox(bbox)
  {}

  virtual
  ~TreeBase()
  {}

  TreeBase*
  add(const BoundingBox<float> &bbox, unsigned int reference)
  {
    FASTUIDRAWassert(bbox.intersects(m_bbox));
    return add_implement(bbox, reference);
  }

  void
  query(const BoundingBox<float> &bbox,
        std::vector<unsigned int> *output)
  {
    if(bbox.intersects(m_bbox))
      {
        query_implement(bbox, output);
      }
  }

  unsigned int
  query(const fastuidraw::vec2 &p,
        BoundingBox<float> *out_bb)
  {
    if (m_bbox.intersects(p))
      {
        return query_implement(p, out_bb);
      }
    else
      {
        return GenericHierarchy::not_found;
      }
  }

  const BoundingBox<float>&
  bounding_box(void)
  {
    return m_bbox;
  }

private:
  virtual
  TreeBase*
  add_implement(const BoundingBox<float> &bbox,
                unsigned int reference) = 0;

  virtual
  void
  query_implement(const BoundingBox<float> &bbox,
                  std::vector<unsigned int> *output) = 0;

  virtual
  unsigned int
  query_implement(const fastuidraw::vec2 &p,
                  BoundingBox<float> *out_bb) = 0;

  BoundingBox<float> m_bbox;
};

class Node:public TreeBase
{
public:
  Node(const BoundingBox<float> &bbox,
       const BoundingBox<float> &bbox0,
       const std::vector<Element> &elements0,
       const BoundingBox<float> &bbox1,
       const std::vector<Element> &elements1);

  ~Node();

private:
  virtual
  TreeBase*
  add_implement(const BoundingBox<float> &bbox,
                unsigned int reference);

  virtual
  void
  query_implement(const BoundingBox<float> &bbox,
                  std::vector<unsigned int> *output);

  virtual
  unsigned int
  query_implement(const fastuidraw::vec2 &p,
                  BoundingBox<float> *out_bb);

  fastuidraw::vecN<TreeBase*, 2> m_children;
  std::vector<Element> m_elements;
};

class Leaf:public TreeBase
{
public:
  explicit
  Leaf(const BoundingBox<float> &bbox);

  Leaf(const BoundingBox<float> &bbox,
       const std::vector<Element> &elements);

  ~Leaf();

private:
  virtual
  TreeBase*
  add_implement(const BoundingBox<float> &bbox,
                unsigned int reference);

  virtual
  void
  query_implement(const BoundingBox<float> &bbox,
                  std::vector<unsigned int> *output);

  virtual
  unsigned int
  query_implement(const fastuidraw::vec2 &p,
                BoundingBox<float> *out_bb);

  std::vector<Element> m_elements;
};

}

///////////////////////////////////
// Node methods
Node::
Node(const BoundingBox<float> &bbox,
     const BoundingBox<float> &bbox0,
     const std::vector<Element> &elements0,
     const BoundingBox<float> &bbox1,
     const std::vector<Element> &elements1):
  TreeBase(bbox)
{
  m_children[0] = FASTUIDRAWnew Leaf(bbox0, elements0);
  m_children[1] = FASTUIDRAWnew Leaf(bbox1, elements1);
}

Node::
~Node()
{
  FASTUIDRAWdelete(m_children[0]);
  FASTUIDRAWdelete(m_children[1]);
}

TreeBase*
Node::
add_implement(const BoundingBox<float> &bbox, unsigned int reference)
{
  fastuidraw::vecN<bool, 2> child_takes;

  for (unsigned int i = 0; i < 2; ++i)
    {
      child_takes[i] = m_children[i]->bounding_box().intersects(bbox);
    }

  if (child_takes[0] && child_takes[1])
    {
      Element E(bbox, reference);
      m_elements.push_back(E);
    }
  else
    {
      unsigned int IDX;
      TreeBase *p;

      IDX = child_takes[0] ? 0u : 1u;
      p = m_children[IDX]->add(bbox, reference);
      if (p != m_children[IDX])
        {
          FASTUIDRAWdelete(m_children[IDX]);
          m_children[IDX] = p;
        }
    }

  return this;
}

void
Node::
query_implement(const BoundingBox<float> &bbox,
      std::vector<unsigned int> *output)
{
  m_children[0]->query(bbox, output);
  m_children[1]->query(bbox, output);
  for (const auto &E : m_elements)
    {
      if (E.m_box.intersects(bbox))
        {
          output->push_back(E.m_reference);
        }
    }
}

unsigned int
Node::
query_implement(const fastuidraw::vec2 &p,
                BoundingBox<float> *out_bb)
{
  int R;

  R = m_children[0]->query(p, out_bb);
  if (R != GenericHierarchy::not_found)
    {
      return R;
    }
  R = m_children[1]->query(p, out_bb);
  if (R != GenericHierarchy::not_found)
    {
      return R;
    }

  for (const auto &E : m_elements)
    {
      if (E.m_box.intersects(p))
        {
          *out_bb = E.m_box;
          return E.m_reference;
        }
    }
  return GenericHierarchy::not_found;
}

///////////////////////////////////////////
// Leaf methods
Leaf::
Leaf(const BoundingBox<float> &bbox, const std::vector<Element> &elements):
  TreeBase(bbox),
  m_elements(elements)
{}

Leaf::
Leaf(const BoundingBox<float> &bbox):
  TreeBase(bbox)
{}

Leaf::
~Leaf()
{}

void
Leaf::
query_implement(const BoundingBox<float> &bbox,
                std::vector<unsigned int> *output)
{
  for (const auto &E : m_elements)
    {
      if (E.m_box.intersects(bbox))
        {
          output->push_back(E.m_reference);
        }
    }
}

unsigned int
Leaf::
query_implement(const fastuidraw::vec2 &p,
                BoundingBox<float> *out_bb)
{
  for (const auto &E : m_elements)
    {
      if (E.m_box.intersects(p))
        {
          *out_bb = E.m_box;
          return E.m_reference;
        }
    }
  return GenericHierarchy::not_found;
}

TreeBase*
Leaf::
add_implement(const BoundingBox<float> &bbox, unsigned int reference)
{
  m_elements.push_back(Element(bbox, reference));
  if (m_elements.size() > splitting_size)
    {
      fastuidraw::vecN<std::vector<Element>, 2> split_x, split_y;
      fastuidraw::vecN<BoundingBox<float>, 2> split_x_bb, split_y_bb;
      unsigned int split_x_size(0), split_y_size(0);

      split_x_bb = bounding_box().split(0);
      split_y_bb = bounding_box().split(1);

      for (const Element &E : m_elements)
        {
          for (unsigned int i = 0; i < 2; ++i)
            {
              if (split_x_bb[i].intersects(E.m_box))
                {
                  split_x[i].push_back(E);
                  ++split_x_size;
                }
              if (split_y_bb[i].intersects(E.m_box))
                {
                  split_y[i].push_back(E);
                  ++split_y_size;
                }
            }

          FASTUIDRAWassert(split_x_bb[0].intersects(E.m_box) || split_x_bb[1].intersects(E.m_box));
          FASTUIDRAWassert(split_y_bb[0].intersects(E.m_box) || split_y_bb[1].intersects(E.m_box));
        }

      unsigned int allow_split;
      const float max_overlap(1.5f);
      allow_split = static_cast<unsigned int>(max_overlap * static_cast<float>(m_elements.size()));

      if (fastuidraw::t_min(split_x_size, split_y_size) <= allow_split)
        {
          if (split_x_size < split_y_size)
            {
              return FASTUIDRAWnew Node(bounding_box(),
                                        split_x_bb[0], split_x[0],
                                        split_x_bb[1], split_x[1]);
            }
          else
            {
              return FASTUIDRAWnew Node(bounding_box(),
                                        split_y_bb[0], split_y[0],
                                        split_y_bb[1], split_y[1]);
            }
        }
    }
  return this;
}

///////////////////////////////////
// GenericHierarchy methods
GenericHierarchy::
GenericHierarchy(const BoundingBox<float> &bbox)
{
  m_root = FASTUIDRAWnew Leaf(bbox);
}

GenericHierarchy::
~GenericHierarchy()
{
  TreeBase *d;

  d = static_cast<TreeBase*>(m_root);
  FASTUIDRAWdelete(d);
}

void
GenericHierarchy::
add(const BoundingBox<float> &bbox, unsigned int reference)
{
  TreeBase *d, *p;

  d = static_cast<TreeBase*>(m_root);
  p = d->add(bbox, reference);
  if (p != d)
    {
      FASTUIDRAWdelete(d);
      m_root = p;
    }
}

void
GenericHierarchy::
query(const BoundingBox<float> &bbox, std::vector<unsigned int> *output)
{
  TreeBase *d;

  d = static_cast<TreeBase*>(m_root);
  d->query(bbox, output);
}

unsigned int
GenericHierarchy::
query(const fastuidraw::vec2 &p, BoundingBox<float> *out_bb)
{
  TreeBase *d;

  d = static_cast<TreeBase*>(m_root);
  return d->query(p, out_bb);
}
<|endoftext|>