text
stringlengths 54
60.6k
|
|---|
<commit_before>/*
* Copyright 2010-2011 DIMA Research Group, TU Berlin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author: Alexander Alexandrov <alexander.alexandrov@tu-berlin.de>
*/
#include "communication/Notifications.h"
#include "generator/GeneratorSubsystem.h"
#include <functional>
#include <Poco/ErrorHandler.h>
#include <Poco/Format.h>
#include <Poco/Stopwatch.h>
using namespace std;
using namespace Poco;
namespace Myriad {
// ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
// helper function objects
// ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
/**
* Function object handling RecordGenerator thread creation for ready generators.
*/
class ThreadExecutor: public unary_function<void, RecordGenerator*>
{
public:
ThreadExecutor(GeneratorSubsystem& caller) :
caller(caller)
{
}
void operator()(RecordGenerator* generator)
{
RecordGenerator::TaskPtrList::const_iterator it;
for (it = generator->executors().begin(); it != generator->executors().end(); ++it)
{
AbstractStageTask* task = (*it);
if (task->runnable())
{
caller._threadPool.start(*task);
}
}
}
private:
GeneratorSubsystem& caller;
};
/**
* An error handler to be registered with all generator threads spawned in the
* main loop.
*/
class GeneratorErrorHandler: public ErrorHandler
{
public:
GeneratorErrorHandler(GeneratorSubsystem& caller) :
_caller(caller), _invoked(false)
{
}
void exception(const Exception& exc)
{
_invoked = true;
_caller._logger.error(format("Exception caught in generator thread: %s", exc.displayText()));
}
void exception(const std::exception& exc)
{
_invoked = true;
_caller._logger.error(format("Exception caught in generator thread: %s", exc.what()));
}
void exception()
{
_invoked = true;
_caller._logger.error("Exception caught in generator thread");
}
void checkSanity()
{
if (!_invoked)
{
return; // handler was not invoked, so we're ok
}
if (_caller._logger.debug())
{
_caller._logger.debug("Cleaning up resources...");
}
// TODO: put basic resource cleaning of the generator subsystem here...
throw Poco::RuntimeException("Exception caught in generator thread");
}
private:
GeneratorSubsystem& _caller;
bool _invoked;
};
// ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
// method implementations
// ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
void GeneratorSubsystem::initialize(Application& app)
{
if (_initialized)
{
return;
}
try
{
// initialize the GeneratorConfig instance
_config.initialize(app.config());
_ui.information(format("Scaling factor is %s", toString(_config.scalingFactor())));
_ui.information(format("Job output will be written in %s", _config.getString("application.job-dir")));
// register all generators in the generator pool
registerGenerators();
list<RecordGenerator*>& generators = _generatorPool.getAll();
// initialize all registered generators
for(list<RecordGenerator*>::iterator it = generators.begin(); it != generators.end(); ++it)
{
(*it)->initialize();
}
_ui.information(format("Starting generation for node %hu from %hu", _config.chunkID(), _config.numberOfChunks()));
}
catch(const Exception& exc)
{
_logger.error(format("Exception caught in generator subsystem: %s", exc.displayText()));
exc.rethrow();
}
catch(const std::exception& exc)
{
_logger.error(format("Exception caught in generator subsystem: %s", string(exc.what())));
throw exc;
}
catch(...)
{
_logger.error("Unknown exception caught in generator subsystem");
throw;
}
_initialized = true;
}
void GeneratorSubsystem::uninitialize()
{
if (!_initialized)
{
return;
}
// TODO: clear the _config instance
_initialized = false;
}
void GeneratorSubsystem::prepareStage(RecordGenerator::Stage stage)
{
list<RecordGenerator*>& generators = _generatorPool.getAll();
if (_logger.debug())
{
_logger.debug(format("Preparing stage `%s`", stage.name()));
}
unsigned short runnableCount = 0;
for (RecordGenerator::PtrList::iterator it = generators.begin(); it != generators.end(); ++it)
{
(*it)->prepare(stage, _generatorPool);
runnableCount += (*it)->runnableTasksCount();
}
// increase the size of the thread pool if needed
if (_threadPool.capacity() < runnableCount)
{
_threadPool.addCapacity(runnableCount - _threadPool.capacity());
}
}
void GeneratorSubsystem::cleanupStage(RecordGenerator::Stage stage)
{
list<RecordGenerator*>& generators = _generatorPool.getAll();
for (RecordGenerator::PtrList::iterator it = generators.begin(); it != generators.end(); ++it)
{
(*it)->cleanup(stage);
}
}
void GeneratorSubsystem::start()
{
Stopwatch totalTimer, stageTimer;
double sf = _config.getDouble("application.scaling-factor");
_logger.information(format("Generating tables with scaling factor %.03f", sf));
GeneratorErrorHandler handler(*this);
ErrorHandler* oldHandler = ErrorHandler::set(&handler);
try
{
// mark node as alive
_notificationCenter.postNotification(new ChangeStatus(NodeState::ALIVE));
// start total timer
totalTimer.start();
list<RecordGenerator*>& generators = _generatorPool.getAll();
for (RecordGenerator::StageList::const_iterator it = RecordGenerator::STAGES.begin(); it != RecordGenerator::STAGES.end(); ++it)
{
if (!_executeStages[it->id()])
{
_logger.information(format("Skipping stage `%s`", it->name()));
continue;
}
_logger.information(format("Entering stage `%s`", it->name()));
// start stage timer
stageTimer.restart();
// announce next stage
_notificationCenter.postNotification(new StartStage(it->id()));
// prepare generators for the next stage
prepareStage(*it);
// spawn separate threads for each RUNNABLE task
ThreadExecutor execute(*this);
for_each(generators.begin(), generators.end(), execute);
// wait for all threads to finish
_threadPool.joinAll();
// cleanup generators upon stage execution
cleanupStage(*it);
// make sure that all threads exited correctly
handler.checkSanity();
// stop the stage timer
stageTimer.stop();
_logger.information(format("Stage `%s` completed in %d seconds, moving to the next stage", it->name(), stageTimer.elapsedSeconds()));
}
// stop the total timer
totalTimer.stop();
// reset error handler
ErrorHandler::set(oldHandler);
// mark node as ready
_notificationCenter.postNotification(new ChangeStatus(NodeState::READY));
}
catch(const Exception& exc)
{
_logger.error(format("Exception caught in generator subsystem: %s", exc.displayText()));
ErrorHandler::set(oldHandler);
exc.rethrow();
}
catch(const std::exception& exc)
{
_logger.error(format("Exception caught in generator subsystem: %s", string(exc.what())));
ErrorHandler::set(oldHandler);
throw exc;
}
catch(...)
{
_logger.error("Unknown exception caught in generator subsystem");
ErrorHandler::set(oldHandler);
throw;
}
_logger.information(format("Generation process completed in %d seconds", totalTimer.elapsedSeconds()));
}
} // namespace Myriad
<commit_msg>Added named task threads in the GeneratorSubsystem ThreadExecutor<commit_after>/*
* Copyright 2010-2011 DIMA Research Group, TU Berlin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author: Alexander Alexandrov <alexander.alexandrov@tu-berlin.de>
*/
#include "communication/Notifications.h"
#include "generator/GeneratorSubsystem.h"
#include <functional>
#include <Poco/ErrorHandler.h>
#include <Poco/Format.h>
#include <Poco/Stopwatch.h>
using namespace std;
using namespace Poco;
namespace Myriad {
// ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
// helper function objects
// ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
/**
* Function object handling RecordGenerator thread creation for ready generators.
*/
class ThreadExecutor: public unary_function<void, RecordGenerator*>
{
public:
ThreadExecutor(GeneratorSubsystem& caller) :
caller(caller)
{
}
void operator()(RecordGenerator* generator)
{
RecordGenerator::TaskPtrList::const_iterator it;
for (it = generator->executors().begin(); it != generator->executors().end(); ++it)
{
AbstractStageTask* task = (*it);
if (task->runnable())
{
caller._threadPool.start(*task, task->name());
}
}
}
private:
GeneratorSubsystem& caller;
};
/**
* An error handler to be registered with all generator threads spawned in the
* main loop.
*/
class GeneratorErrorHandler: public ErrorHandler
{
public:
GeneratorErrorHandler(GeneratorSubsystem& caller) :
_caller(caller), _invoked(false)
{
}
void exception(const Exception& exc)
{
_invoked = true;
_caller._logger.error(format("Exception caught in generator thread: %s", exc.displayText()));
}
void exception(const std::exception& exc)
{
_invoked = true;
_caller._logger.error(format("Exception caught in generator thread: %s", exc.what()));
}
void exception()
{
_invoked = true;
_caller._logger.error("Exception caught in generator thread");
}
void checkSanity()
{
if (!_invoked)
{
return; // handler was not invoked, so we're ok
}
if (_caller._logger.debug())
{
_caller._logger.debug("Cleaning up resources...");
}
// TODO: put basic resource cleaning of the generator subsystem here...
throw Poco::RuntimeException("Exception caught in generator thread");
}
private:
GeneratorSubsystem& _caller;
bool _invoked;
};
// ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
// method implementations
// ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
void GeneratorSubsystem::initialize(Application& app)
{
if (_initialized)
{
return;
}
try
{
// initialize the GeneratorConfig instance
_config.initialize(app.config());
_ui.information(format("Scaling factor is %s", toString(_config.scalingFactor())));
_ui.information(format("Job output will be written in %s", _config.getString("application.job-dir")));
// register all generators in the generator pool
registerGenerators();
list<RecordGenerator*>& generators = _generatorPool.getAll();
// initialize all registered generators
for(list<RecordGenerator*>::iterator it = generators.begin(); it != generators.end(); ++it)
{
(*it)->initialize();
}
_ui.information(format("Starting generation for node %hu from %hu", _config.chunkID(), _config.numberOfChunks()));
}
catch(const Exception& exc)
{
_logger.error(format("Exception caught in generator subsystem: %s", exc.displayText()));
exc.rethrow();
}
catch(const std::exception& exc)
{
_logger.error(format("Exception caught in generator subsystem: %s", string(exc.what())));
throw exc;
}
catch(...)
{
_logger.error("Unknown exception caught in generator subsystem");
throw;
}
_initialized = true;
}
void GeneratorSubsystem::uninitialize()
{
if (!_initialized)
{
return;
}
// TODO: clear the _config instance
_initialized = false;
}
void GeneratorSubsystem::prepareStage(RecordGenerator::Stage stage)
{
list<RecordGenerator*>& generators = _generatorPool.getAll();
if (_logger.debug())
{
_logger.debug(format("Preparing stage `%s`", stage.name()));
}
unsigned short runnableCount = 0;
for (RecordGenerator::PtrList::iterator it = generators.begin(); it != generators.end(); ++it)
{
(*it)->prepare(stage, _generatorPool);
runnableCount += (*it)->runnableTasksCount();
}
// increase the size of the thread pool if needed
if (_threadPool.capacity() < runnableCount)
{
_threadPool.addCapacity(runnableCount - _threadPool.capacity());
}
}
void GeneratorSubsystem::cleanupStage(RecordGenerator::Stage stage)
{
list<RecordGenerator*>& generators = _generatorPool.getAll();
for (RecordGenerator::PtrList::iterator it = generators.begin(); it != generators.end(); ++it)
{
(*it)->cleanup(stage);
}
}
void GeneratorSubsystem::start()
{
Stopwatch totalTimer, stageTimer;
double sf = _config.getDouble("application.scaling-factor");
_logger.information(format("Generating tables with scaling factor %.03f", sf));
GeneratorErrorHandler handler(*this);
ErrorHandler* oldHandler = ErrorHandler::set(&handler);
try
{
// mark node as alive
_notificationCenter.postNotification(new ChangeStatus(NodeState::ALIVE));
// start total timer
totalTimer.start();
list<RecordGenerator*>& generators = _generatorPool.getAll();
for (RecordGenerator::StageList::const_iterator it = RecordGenerator::STAGES.begin(); it != RecordGenerator::STAGES.end(); ++it)
{
if (!_executeStages[it->id()])
{
_logger.information(format("Skipping stage `%s`", it->name()));
continue;
}
_logger.information(format("Entering stage `%s`", it->name()));
// start stage timer
stageTimer.restart();
// announce next stage
_notificationCenter.postNotification(new StartStage(it->id()));
// prepare generators for the next stage
prepareStage(*it);
// spawn separate threads for each RUNNABLE task
ThreadExecutor execute(*this);
for_each(generators.begin(), generators.end(), execute);
// wait for all threads to finish
_threadPool.joinAll();
// cleanup generators upon stage execution
cleanupStage(*it);
// make sure that all threads exited correctly
handler.checkSanity();
// stop the stage timer
stageTimer.stop();
_logger.information(format("Stage `%s` completed in %d seconds, moving to the next stage", it->name(), stageTimer.elapsedSeconds()));
}
// stop the total timer
totalTimer.stop();
// reset error handler
ErrorHandler::set(oldHandler);
// mark node as ready
_notificationCenter.postNotification(new ChangeStatus(NodeState::READY));
}
catch(const Exception& exc)
{
_logger.error(format("Exception caught in generator subsystem: %s", exc.displayText()));
ErrorHandler::set(oldHandler);
exc.rethrow();
}
catch(const std::exception& exc)
{
_logger.error(format("Exception caught in generator subsystem: %s", string(exc.what())));
ErrorHandler::set(oldHandler);
throw exc;
}
catch(...)
{
_logger.error("Unknown exception caught in generator subsystem");
ErrorHandler::set(oldHandler);
throw;
}
_logger.information(format("Generation process completed in %d seconds", totalTimer.elapsedSeconds()));
}
} // namespace Myriad
<|endoftext|>
|
<commit_before>#define BOOST_TEST_NO_MAIN
#include <boost/test/unit_test.hpp>
#include "TestHelper.h"
#include <fstream>
#include <cstdlib>
int BOOST_TEST_CALL_DECL
main(int argc, char* argv[])
{
const char* const gEnvName = "BOOST_TEST_LOG_FILE";
const char* const gEnvValue = std::getenv(gEnvName);
std::ofstream ofs;
if (gEnvValue)
{
ofs.open(gEnvValue);
::boost::unit_test::unit_test_log.set_stream(ofs);
}
return ::boost::unit_test::unit_test_main(&init_unit_test, argc, argv);
}
<commit_msg>capture cout and cerr in boost test<commit_after>#define BOOST_TEST_NO_MAIN
#include <boost/test/unit_test.hpp>
#include <boost/test/output/xml_log_formatter.hpp>
#include "TestHelper.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstdlib>
class MyXmlLogFormatter : public boost::unit_test::output::xml_log_formatter
{
typedef boost::unit_test::output::xml_log_formatter super;
public:
MyXmlLogFormatter()
{
std::cout.rdbuf(out.rdbuf());
std::cerr.rdbuf(err.rdbuf());
}
void test_unit_start(std::ostream& ostr, boost::unit_test::test_unit const& tu)
{
out.str("");
err.str("");
super::test_unit_start(ostr, tu);
}
void test_unit_finish(std::ostream& ostr, boost::unit_test::test_unit const& tu, unsigned long elapsed)
{
if (tu.p_type == boost::unit_test::tut_case)
{
ostr << "<SystemOut><![CDATA[" << out.str() << "]]></SystemOut>";
ostr << "<SystemErr><![CDATA[" << err.str() << "]]></SystemErr>";
}
super::test_unit_finish(ostr, tu, elapsed);
}
private:
std::ostringstream out;
std::ostringstream err;
};
bool my_init_unit_test()
{
static std::ofstream ofs;
const char* const gEnvName = "BOOST_TEST_LOG_FILE";
const char* const gEnvValue = std::getenv(gEnvName);
if (gEnvValue)
{
ofs.open(gEnvValue);
boost::unit_test::unit_test_log.set_stream(ofs);
boost::unit_test::unit_test_log.set_formatter(new MyXmlLogFormatter);
}
return true;
}
int BOOST_TEST_CALL_DECL
main(int argc, char* argv[])
{
return boost::unit_test::unit_test_main(&my_init_unit_test, argc, argv);
}
<|endoftext|>
|
<commit_before>// Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @file ResourceEvent.cpp
*/
#include <fastdds/rtps/resources/ResourceEvent.h>
#include <fastdds/dds/log/Log.hpp>
#include "TimedEventImpl.h"
#include <cassert>
#include <thread>
namespace eprosima {
namespace fastrtps {
namespace rtps {
static bool event_compare(
TimedEventImpl* lhs,
TimedEventImpl* rhs)
{
return lhs->next_trigger_time() < rhs->next_trigger_time();
}
ResourceEvent::~ResourceEvent()
{
// All timer should be unregistered before destroying this object.
assert(pending_timers_.empty());
assert(timers_count_ == 0);
logInfo(RTPS_PARTICIPANT, "Removing event thread");
if (thread_.joinable())
{
{
std::unique_lock<TimedMutex> lock(mutex_);
stop_.store(true);
cv_.notify_one();
}
thread_.join();
}
}
void ResourceEvent::register_timer(
TimedEventImpl* /*event*/)
{
assert(!stop_.load());
std::lock_guard<TimedMutex> lock(mutex_);
++timers_count_;
// Notify the execution thread that something changed
cv_.notify_one();
}
void ResourceEvent::unregister_timer(
TimedEventImpl* event)
{
assert(!stop_.load());
std::unique_lock<TimedMutex> lock(mutex_);
cv_manipulation_.wait(lock, [&]()
{
return allow_vector_manipulation_;
});
bool should_notify = false;
std::vector<TimedEventImpl*>::iterator it;
// Remove from pending
it = std::find(pending_timers_.begin(), pending_timers_.end(), event);
if (it != pending_timers_.end())
{
pending_timers_.erase(it);
should_notify = true;
}
// Remove from active
it = std::find(active_timers_.begin(), active_timers_.end(), event);
if (it != active_timers_.end())
{
active_timers_.erase(it);
should_notify = true;
}
// Decrement counter of created timers
--timers_count_;
if (should_notify)
{
// Notify the execution thread that something changed
cv_.notify_one();
}
}
void ResourceEvent::notify(
TimedEventImpl* event)
{
std::lock_guard<TimedMutex> lock(mutex_);
if (register_timer_nts(event))
{
// Notify the execution thread that something changed
cv_.notify_one();
}
}
void ResourceEvent::notify(
TimedEventImpl* event,
const std::chrono::steady_clock::time_point& timeout)
{
std::unique_lock<TimedMutex> lock(mutex_, std::defer_lock);
if (lock.try_lock_until(timeout))
{
if (register_timer_nts(event))
{
// Notify the execution thread that something changed
cv_.notify_one();
}
}
}
bool ResourceEvent::register_timer_nts(
TimedEventImpl* event)
{
if (std::find(pending_timers_.begin(), pending_timers_.end(), event) == pending_timers_.end())
{
pending_timers_.push_back(event);
return true;
}
return false;
}
void ResourceEvent::event_service()
{
while (!stop_.load())
{
// Perform update and execution of timers
update_current_time();
do_timer_actions();
std::unique_lock<TimedMutex> lock(mutex_);
// If the thread has already been instructed to stop, do it.
if (stop_.load())
{
break;
}
// If pending timers exist, there is some work to be done, so no need to wait.
if (!pending_timers_.empty())
{
continue;
}
// Allow other threads to manipulate the timer collections while we wait.
allow_vector_manipulation_ = true;
cv_manipulation_.notify_all();
// Wait for the first timer to be triggered
std::chrono::steady_clock::time_point next_trigger =
active_timers_.empty() ?
current_time_ + std::chrono::seconds(1) :
active_timers_[0]->next_trigger_time();
cv_.wait_until(lock, next_trigger);
// Don't allow other threads to manipulate the timer collections
allow_vector_manipulation_ = false;
resize_collections();
}
}
void ResourceEvent::sort_timers()
{
std::sort(active_timers_.begin(), active_timers_.end(), event_compare);
}
void ResourceEvent::update_current_time()
{
current_time_ = std::chrono::steady_clock::now();
}
void ResourceEvent::do_timer_actions()
{
std::chrono::steady_clock::time_point cancel_time =
current_time_ + std::chrono::hours(24);
bool did_something = false;
// Process pending orders
{
std::lock_guard<TimedMutex> lock(mutex_);
for (TimedEventImpl* tp : pending_timers_)
{
// Remove item from active timers
auto current_pos = std::lower_bound(active_timers_.begin(), active_timers_.end(), tp, event_compare);
current_pos = std::find(current_pos, active_timers_.end(), tp);
if (current_pos != active_timers_.end())
{
active_timers_.erase(current_pos);
}
// Update timer info
if (tp->update(current_time_, cancel_time))
{
// Timer has to be activated: add to active timers
std::vector<TimedEventImpl*>::iterator low_bound;
// Insert on correct position
low_bound = std::lower_bound(active_timers_.begin(), active_timers_.end(), tp, event_compare);
active_timers_.emplace(low_bound, tp);
}
}
pending_timers_.clear();
}
// Trigger active timers
for (TimedEventImpl* tp : active_timers_)
{
if (tp->next_trigger_time() <= current_time_)
{
did_something = true;
tp->trigger(current_time_, cancel_time);
}
else
{
break;
}
}
// If an action was made, keep active_timers_ sorted
if (did_something)
{
sort_timers();
active_timers_.erase(
std::lower_bound(active_timers_.begin(), active_timers_.end(), nullptr,
[cancel_time](
TimedEventImpl* a,
TimedEventImpl* b)
{
(void)b;
return a->next_trigger_time() < cancel_time;
}),
active_timers_.end()
);
}
}
void ResourceEvent::init_thread()
{
std::lock_guard<TimedMutex> lock(mutex_);
allow_vector_manipulation_ = false;
resize_collections();
thread_ = std::thread(&ResourceEvent::event_service, this);
}
} /* namespace rtps */
} /* namespace fastrtps */
} /* namespace eprosima */
<commit_msg>Fix interval loop on events [11929] (#2041)<commit_after>// Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @file ResourceEvent.cpp
*/
#include <fastdds/rtps/resources/ResourceEvent.h>
#include <fastdds/dds/log/Log.hpp>
#include "TimedEventImpl.h"
#include <cassert>
#include <thread>
namespace eprosima {
namespace fastrtps {
namespace rtps {
static bool event_compare(
TimedEventImpl* lhs,
TimedEventImpl* rhs)
{
return lhs->next_trigger_time() < rhs->next_trigger_time();
}
ResourceEvent::~ResourceEvent()
{
// All timer should be unregistered before destroying this object.
assert(pending_timers_.empty());
assert(timers_count_ == 0);
logInfo(RTPS_PARTICIPANT, "Removing event thread");
if (thread_.joinable())
{
{
std::unique_lock<TimedMutex> lock(mutex_);
stop_.store(true);
cv_.notify_one();
}
thread_.join();
}
}
void ResourceEvent::register_timer(
TimedEventImpl* /*event*/)
{
assert(!stop_.load());
std::lock_guard<TimedMutex> lock(mutex_);
++timers_count_;
// Notify the execution thread that something changed
cv_.notify_one();
}
void ResourceEvent::unregister_timer(
TimedEventImpl* event)
{
assert(!stop_.load());
std::unique_lock<TimedMutex> lock(mutex_);
cv_manipulation_.wait(lock, [&]()
{
return allow_vector_manipulation_;
});
bool should_notify = false;
std::vector<TimedEventImpl*>::iterator it;
// Remove from pending
it = std::find(pending_timers_.begin(), pending_timers_.end(), event);
if (it != pending_timers_.end())
{
pending_timers_.erase(it);
should_notify = true;
}
// Remove from active
it = std::find(active_timers_.begin(), active_timers_.end(), event);
if (it != active_timers_.end())
{
active_timers_.erase(it);
should_notify = true;
}
// Decrement counter of created timers
--timers_count_;
if (should_notify)
{
// Notify the execution thread that something changed
cv_.notify_one();
}
}
void ResourceEvent::notify(
TimedEventImpl* event)
{
std::lock_guard<TimedMutex> lock(mutex_);
if (register_timer_nts(event))
{
// Notify the execution thread that something changed
cv_.notify_one();
}
}
void ResourceEvent::notify(
TimedEventImpl* event,
const std::chrono::steady_clock::time_point& timeout)
{
std::unique_lock<TimedMutex> lock(mutex_, std::defer_lock);
if (lock.try_lock_until(timeout))
{
if (register_timer_nts(event))
{
// Notify the execution thread that something changed
cv_.notify_one();
}
}
}
bool ResourceEvent::register_timer_nts(
TimedEventImpl* event)
{
if (std::find(pending_timers_.begin(), pending_timers_.end(), event) == pending_timers_.end())
{
pending_timers_.push_back(event);
return true;
}
return false;
}
void ResourceEvent::event_service()
{
while (!stop_.load())
{
// Perform update and execution of timers
update_current_time();
do_timer_actions();
std::unique_lock<TimedMutex> lock(mutex_);
// If the thread has already been instructed to stop, do it.
if (stop_.load())
{
break;
}
// If pending timers exist, there is some work to be done, so no need to wait.
if (!pending_timers_.empty())
{
continue;
}
// Allow other threads to manipulate the timer collections while we wait.
allow_vector_manipulation_ = true;
cv_manipulation_.notify_all();
// Wait for the first timer to be triggered
std::chrono::steady_clock::time_point next_trigger =
active_timers_.empty() ?
current_time_ + std::chrono::seconds(1) :
active_timers_[0]->next_trigger_time();
auto current_time = std::chrono::steady_clock::now();
if (current_time > next_trigger)
{
next_trigger = current_time + std::chrono::microseconds(10);
}
cv_.wait_until(lock, next_trigger);
// Don't allow other threads to manipulate the timer collections
allow_vector_manipulation_ = false;
resize_collections();
}
}
void ResourceEvent::sort_timers()
{
std::sort(active_timers_.begin(), active_timers_.end(), event_compare);
}
void ResourceEvent::update_current_time()
{
current_time_ = std::chrono::steady_clock::now();
}
void ResourceEvent::do_timer_actions()
{
std::chrono::steady_clock::time_point cancel_time =
current_time_ + std::chrono::hours(24);
bool did_something = false;
// Process pending orders
{
std::lock_guard<TimedMutex> lock(mutex_);
for (TimedEventImpl* tp : pending_timers_)
{
// Remove item from active timers
auto current_pos = std::lower_bound(active_timers_.begin(), active_timers_.end(), tp, event_compare);
current_pos = std::find(current_pos, active_timers_.end(), tp);
if (current_pos != active_timers_.end())
{
active_timers_.erase(current_pos);
}
// Update timer info
if (tp->update(current_time_, cancel_time))
{
// Timer has to be activated: add to active timers
std::vector<TimedEventImpl*>::iterator low_bound;
// Insert on correct position
low_bound = std::lower_bound(active_timers_.begin(), active_timers_.end(), tp, event_compare);
active_timers_.emplace(low_bound, tp);
}
}
pending_timers_.clear();
}
// Trigger active timers
for (TimedEventImpl* tp : active_timers_)
{
if (tp->next_trigger_time() <= current_time_)
{
did_something = true;
tp->trigger(current_time_, cancel_time);
}
else
{
break;
}
}
// If an action was made, keep active_timers_ sorted
if (did_something)
{
sort_timers();
active_timers_.erase(
std::lower_bound(active_timers_.begin(), active_timers_.end(), nullptr,
[cancel_time](
TimedEventImpl* a,
TimedEventImpl* b)
{
(void)b;
return a->next_trigger_time() < cancel_time;
}),
active_timers_.end()
);
}
}
void ResourceEvent::init_thread()
{
std::lock_guard<TimedMutex> lock(mutex_);
allow_vector_manipulation_ = false;
resize_collections();
thread_ = std::thread(&ResourceEvent::event_service, this);
}
} /* namespace rtps */
} /* namespace fastrtps */
} /* namespace eprosima */
<|endoftext|>
|
<commit_before>/*!
* \cond FILEINFO
******************************************************************************
* \file main.cpp
******************************************************************************
*
* Copyright (C) ATS Advanced Telematic Systems GmbH GmbH, 2016
*
* \author Moritz Klinger
*
******************************************************************************
*
* \brief The main file of the project.
*
*
******************************************************************************
*
* \endcond
*/
/*****************************************************************************/
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <iostream>
#include "aktualizr.h"
#include "config.h"
#include "logger.h"
#include "utils.h"
/*****************************************************************************/
namespace bpo = boost::program_options;
bpo::variables_map parse_options(int argc, char *argv[]) {
bpo::options_description description("CommandLine Options");
// clang-format off
description.add_options()
("help,h", "help screen")
("version,v", "Current aktualizr version")
("loglevel", bpo::value<int>(), "set log level 0-4 (trace, debug, warning, info, error)")
("config,c", bpo::value<std::string>()->required(), "toml configuration file")
("gateway-http", bpo::value<bool>(), "enable the http gateway")
("gateway-rvi", bpo::value<bool>(), "enable the rvi gateway")
("gateway-socket", bpo::value<bool>(), "enable the socket gateway")
("gateway-dbus", bpo::value<bool>(), "enable the D-Bus gateway")
("dbus-system-bus", "Use the D-Bus system bus (rather than the session bus)")
("tls-server", bpo::value<std::string>(), "url, used for auto provisioning")
("repo-server", bpo::value<std::string>(), "url of the uptane repo repository")
("director-server", bpo::value<std::string>(), "url of the uptane director repository")
("ostree-server", bpo::value<std::string>(), "url of the ostree repository")
("primary-ecu-serial", bpo::value<std::string>(), "serial number of primary ecu")
("primary-ecu-hardware-id", bpo::value<std::string>(), "hardware id of primary ecu")
("disable-keyid-validation", "Disable keyid validation on client side" )
("poll-once", "Check for updates only once and exit")
("secondary-config", bpo::value<std::vector<std::string> >()->composing(), "set config for secondary");
// clang-format on
bpo::variables_map vm;
try {
bpo::store(bpo::parse_command_line(argc, argv, description), vm);
bpo::notify(vm);
} catch (const bpo::required_option &ex) {
if (vm.count("help") != 0) {
std::cout << description << '\n';
exit(EXIT_SUCCESS);
}
if (vm.count("version") != 0) {
std::cout << "Current aktualizr version is: " << AKTUALIZR_VERSION << "\n";
exit(EXIT_SUCCESS);
}
if (ex.get_option_name() == "--config") {
std::cout << ex.get_option_name() << " is missing.\nYou have to provide a valid configuration "
"file using toml format. See the example configuration file "
"in config/config.toml.example"
<< std::endl;
exit(EXIT_FAILURE);
} else {
// print the error and append the default commandline option description
std::cout << ex.what() << std::endl << description;
exit(EXIT_SUCCESS);
}
} catch (const bpo::error &ex) {
// log boost error
LOGGER_LOG(LVL_warning, "boost command line option error: " << ex.what());
// print the error message to the standard output too, as the user provided
// a non-supported commandline option
std::cout << ex.what() << '\n';
// set the returnValue, thereby ctest will recognize
// that something went wrong
exit(EXIT_FAILURE);
}
return vm;
}
/*****************************************************************************/
int main(int argc, char *argv[]) {
loggerInit();
bpo::variables_map commandline_map = parse_options(argc, argv);
// check for loglevel
if (commandline_map.count("loglevel") != 0) {
// set the log level from command line option
LoggerLevels severity = static_cast<LoggerLevels>(commandline_map["loglevel"].as<int>());
if (severity < LVL_minimum) {
LOGGER_LOG(LVL_debug, "Invalid log level");
severity = LVL_trace;
}
if (LVL_maximum < severity) {
LOGGER_LOG(LVL_warning, "Invalid log level");
severity = LVL_error;
}
loggerSetSeverity(severity);
}
LOGGER_LOG(LVL_info, "Aktualizr version " AKTUALIZR_VERSION " starting");
LOGGER_LOG(LVL_debug, "Current directory: " << boost::filesystem::current_path().string());
// Initialize config with default values, the update with config, then with cmd
std::string sota_config_file = commandline_map["config"].as<std::string>();
boost::filesystem::path sota_config_path(sota_config_file);
if (false == boost::filesystem::exists(sota_config_path)) {
std::cout << "aktualizr: configuration file " << boost::filesystem::absolute(sota_config_path)
<< " not found. Exiting." << std::endl;
exit(EXIT_FAILURE);
}
try {
Config config(sota_config_path.string(), commandline_map);
Aktualizr aktualizr(config);
return aktualizr.run();
} catch (const std::exception &ex) {
LOGGER_LOG(LVL_error, ex.what());
return -1;
}
}
<commit_msg>Show help or version always if option is set<commit_after>/*!
* \cond FILEINFO
******************************************************************************
* \file main.cpp
******************************************************************************
*
* Copyright (C) ATS Advanced Telematic Systems GmbH GmbH, 2016
*
* \author Moritz Klinger
*
******************************************************************************
*
* \brief The main file of the project.
*
*
******************************************************************************
*
* \endcond
*/
/*****************************************************************************/
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <iostream>
#include "aktualizr.h"
#include "config.h"
#include "logger.h"
#include "utils.h"
/*****************************************************************************/
namespace bpo = boost::program_options;
void check_info_options(const bpo::options_description &description, const bpo::variables_map &vm) {
if (vm.count("help") != 0) {
std::cout << description << '\n';
exit(EXIT_SUCCESS);
}
if (vm.count("version") != 0) {
std::cout << "Current aktualizr version is: " << AKTUALIZR_VERSION << "\n";
exit(EXIT_SUCCESS);
}
}
bpo::variables_map parse_options(int argc, char *argv[]) {
bpo::options_description description("CommandLine Options");
// clang-format off
description.add_options()
("help,h", "help screen")
("version,v", "Current aktualizr version")
("loglevel", bpo::value<int>(), "set log level 0-4 (trace, debug, warning, info, error)")
("config,c", bpo::value<std::string>()->required(), "toml configuration file")
("gateway-http", bpo::value<bool>(), "enable the http gateway")
("gateway-rvi", bpo::value<bool>(), "enable the rvi gateway")
("gateway-socket", bpo::value<bool>(), "enable the socket gateway")
("gateway-dbus", bpo::value<bool>(), "enable the D-Bus gateway")
("dbus-system-bus", "Use the D-Bus system bus (rather than the session bus)")
("tls-server", bpo::value<std::string>(), "url, used for auto provisioning")
("repo-server", bpo::value<std::string>(), "url of the uptane repo repository")
("director-server", bpo::value<std::string>(), "url of the uptane director repository")
("ostree-server", bpo::value<std::string>(), "url of the ostree repository")
("primary-ecu-serial", bpo::value<std::string>(), "serial number of primary ecu")
("primary-ecu-hardware-id", bpo::value<std::string>(), "hardware id of primary ecu")
("disable-keyid-validation", "Disable keyid validation on client side" )
("poll-once", "Check for updates only once and exit")
("secondary-config", bpo::value<std::vector<std::string> >()->composing(), "set config for secondary");
// clang-format on
bpo::variables_map vm;
std::vector<std::string> unregistered_options;
try {
bpo::basic_parsed_options<char> parsed_options =
bpo::command_line_parser(argc, argv).options(description).allow_unregistered().run();
bpo::store(parsed_options, vm);
check_info_options(description, vm);
bpo::notify(vm);
unregistered_options = bpo::collect_unrecognized(parsed_options.options, bpo::include_positional);
std::cout << "size: " << unregistered_options.size() << "\n";
if (vm.count("help") == 0 && !unregistered_options.empty()) {
std::cout << description << "\n";
exit(EXIT_FAILURE);
}
} catch (const bpo::required_option &ex) {
if (ex.get_option_name() == "--config") {
std::cout << ex.get_option_name() << " is missing.\nYou have to provide a valid configuration "
"file using toml format. See the example configuration file "
"in config/config.toml.example"
<< std::endl;
exit(EXIT_FAILURE);
} else {
// print the error and append the default commandline option description
std::cout << ex.what() << std::endl << description;
exit(EXIT_SUCCESS);
}
} catch (const bpo::error &ex) {
check_info_options(description, vm);
// log boost error
LOGGER_LOG(LVL_warning, "boost command line option error: " << ex.what());
// print the error message to the standard output too, as the user provided
// a non-supported commandline option
std::cout << ex.what() << '\n';
// set the returnValue, thereby ctest will recognize
// that something went wrong
exit(EXIT_FAILURE);
}
return vm;
}
/*****************************************************************************/
int main(int argc, char *argv[]) {
loggerInit();
bpo::variables_map commandline_map = parse_options(argc, argv);
// check for loglevel
if (commandline_map.count("loglevel") != 0) {
// set the log level from command line option
LoggerLevels severity = static_cast<LoggerLevels>(commandline_map["loglevel"].as<int>());
if (severity < LVL_minimum) {
LOGGER_LOG(LVL_debug, "Invalid log level");
severity = LVL_trace;
}
if (LVL_maximum < severity) {
LOGGER_LOG(LVL_warning, "Invalid log level");
severity = LVL_error;
}
loggerSetSeverity(severity);
}
LOGGER_LOG(LVL_info, "Aktualizr version " AKTUALIZR_VERSION " starting");
LOGGER_LOG(LVL_debug, "Current directory: " << boost::filesystem::current_path().string());
// Initialize config with default values, the update with config, then with cmd
std::string sota_config_file = commandline_map["config"].as<std::string>();
boost::filesystem::path sota_config_path(sota_config_file);
if (false == boost::filesystem::exists(sota_config_path)) {
std::cout << "aktualizr: configuration file " << boost::filesystem::absolute(sota_config_path)
<< " not found. Exiting." << std::endl;
exit(EXIT_FAILURE);
}
try {
Config config(sota_config_path.string(), commandline_map);
Aktualizr aktualizr(config);
return aktualizr.run();
} catch (const std::exception &ex) {
LOGGER_LOG(LVL_error, ex.what());
return -1;
}
}
<|endoftext|>
|
<commit_before>/*
* SessionRPubs.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionRPubs.hpp"
#include <boost/bind.hpp>
#include <boost/utility.hpp>
#include <boost/format.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <core/Error.hpp>
#include <core/Exec.hpp>
#include <core/Log.hpp>
#include <core/Settings.hpp>
#include <core/FileSerializer.hpp>
#include <core/text/CsvParser.hpp>
#include <core/http/Util.hpp>
#include <core/system/Process.hpp>
#include <r/RSexp.hpp>
#include <r/RRoutines.hpp>
#include <session/SessionUserSettings.hpp>
#include <session/SessionModuleContext.hpp>
#include <session/projects/SessionProjects.hpp>
using namespace rstudio::core ;
namespace rstudio {
namespace session {
namespace {
// we get a fresh settings object for each read or write so multiple
// processes can all read and write without cache issues
void getUploadIdSettings(Settings* pSettings)
{
FilePath rpubsUploadIds =
module_context::scopedScratchPath().complete("rpubs_upload_ids");
Error error = pSettings->initialize(rpubsUploadIds);
if (error)
LOG_ERROR(error);
}
std::string pathIdentifier(const FilePath& filePath)
{
// use a relative path if we are in a project
std::string path;
projects::ProjectContext& projectContext = projects::projectContext();
if (projectContext.hasProject() &&
filePath.isWithin(projectContext.directory()))
{
path = filePath.relativePath(projectContext.directory());
}
else
{
path = filePath.absolutePath();
}
// urlencode so we can use it as a key
return http::util::urlEncode(path);
}
} // anonymous namespace
namespace modules {
namespace rpubs {
namespace {
void saveUploadId(const FilePath& filePath, const std::string& uploadId)
{
Settings settings;
getUploadIdSettings(&settings);
settings.set(pathIdentifier(filePath), uploadId);
}
class RPubsUpload : boost::noncopyable,
public boost::enable_shared_from_this<RPubsUpload>
{
public:
static boost::shared_ptr<RPubsUpload> create(const std::string& contextId,
const std::string& title,
const FilePath& originalRmd,
const FilePath& htmlFile,
const std::string& uploadId,
bool allowUpdate)
{
boost::shared_ptr<RPubsUpload> pUpload(new RPubsUpload(contextId));
pUpload->start(title, originalRmd, htmlFile, uploadId, allowUpdate);
return pUpload;
}
virtual ~RPubsUpload()
{
}
bool isRunning() const { return isRunning_; }
void terminate()
{
terminationRequested_ = true;
}
private:
explicit RPubsUpload(const std::string& contextId)
: contextId_(contextId), terminationRequested_(false), isRunning_(false)
{
}
void start(const std::string& title, const FilePath& originalRmd,
const FilePath& htmlFile, const std::string& uploadId,
bool allowUpdate)
{
using namespace rstudio::core::string_utils;
using namespace module_context;
htmlFile_ = htmlFile;
csvOutputFile_ = module_context::tempFile("rpubsupload", "csv");
isRunning_ = true;
// if we don't already have an ID for this file, and updates are allowed,
// check for a previous upload ID
std::string id = allowUpdate && uploadId.empty() ?
previousRpubsUploadId(htmlFile_) : uploadId;
boost::algorithm::trim(id);
// R binary
FilePath rProgramPath;
Error error = rScriptPath(&rProgramPath);
if (error)
{
terminateWithError(error);
return;
}
// args
std::vector<std::string> args;
args.push_back("--slave");
args.push_back("--no-save");
args.push_back("--no-restore");
args.push_back("-e");
boost::format fmt(
"result <- rsconnect::rpubsUpload('%1%', '%2%', '%3%', %4%); "
"utils::write.csv(as.data.frame(result), "
" file='%5%', "
" row.names=FALSE);");
std::string htmlPath = utf8ToSystem(htmlFile.absolutePath());
std::string outputPath = utf8ToSystem(csvOutputFile_.absolutePath());
// we may not have an original R Markdown document for this publish
// event (and that's fine)
std::string rmdPath = originalRmd == FilePath() ? "" :
utf8ToSystem(originalRmd.absolutePath());
std::string escapedTitle = string_utils::jsLiteralEscape(title);
std::string escapedHtmlPath = string_utils::jsLiteralEscape(htmlPath);
std::string escapedRmdPath = string_utils::jsLiteralEscape(rmdPath);
std::string escapedId = string_utils::jsLiteralEscape(id);
std::string escapedOutputPath = string_utils::jsLiteralEscape(outputPath);
std::string cmd = boost::str(fmt %
escapedTitle % escapedHtmlPath % escapedRmdPath %
(!escapedId.empty() ? "'" + escapedId + "'" : "NULL") %
escapedOutputPath);
args.push_back(cmd);
// options
core::system::ProcessOptions options;
options.terminateChildren = true;
options.workingDir = htmlFile.parent();
// callbacks
core::system::ProcessCallbacks cb;
cb.onContinue = boost::bind(&RPubsUpload::onContinue,
RPubsUpload::shared_from_this());
cb.onStdout = boost::bind(&RPubsUpload::onStdOut,
RPubsUpload::shared_from_this(), _2);
cb.onStderr = boost::bind(&RPubsUpload::onStdErr,
RPubsUpload::shared_from_this(), _2);
cb.onExit = boost::bind(&RPubsUpload::onCompleted,
RPubsUpload::shared_from_this(), _1);
// execute
processSupervisor().runProgram(rProgramPath.absolutePath(),
args,
options,
cb);
}
bool onContinue()
{
return !terminationRequested_;
}
void onStdOut(const std::string& output)
{
output_.append(output);
}
void onStdErr(const std::string& error)
{
error_.append(error);
}
void onCompleted(int exitStatus)
{
if (exitStatus == EXIT_SUCCESS)
{
if(csvOutputFile_.exists())
{
std::string csvOutput;
Error error = core::readStringFromFile(
csvOutputFile_,
&csvOutput,
string_utils::LineEndingPosix);
if (error)
{
terminateWithError(error);
}
else
{
// parse output
Result result = parseOutput(csvOutput);
if (!result.empty())
terminateWithResult(result);
else
terminateWithError(
"Unexpected output from upload: " + csvOutput);
}
}
else
{
terminateWithError("Unexpected output from upload: " + output_);
}
}
else
{
terminateWithError(error_);
}
}
void terminateWithError(const Error& error)
{
terminateWithError(error.summary());
}
void terminateWithError(const std::string& error)
{
terminateWithResult(Result(error));
}
struct Result
{
Result()
{
}
Result(const std::string& error)
: error(error)
{
}
Result(const std::string& id, const std::string& continueUrl)
: id(id), continueUrl(continueUrl)
{
}
bool empty() const { return id.empty() && error.empty(); }
std::string id;
std::string continueUrl;
std::string error;
};
void terminateWithResult(const Result& result)
{
isRunning_ = false;
if (!result.id.empty())
saveUploadId(htmlFile_, result.id);
json::Object statusJson;
statusJson["contextId"] = contextId_;
statusJson["id"] = result.id;
statusJson["continueUrl"] = result.continueUrl;
statusJson["error"] = result.error;
ClientEvent event(client_events::kRPubsUploadStatus, statusJson);
module_context::enqueClientEvent(event);
}
Result parseOutput(const std::string& output)
{
std::pair<std::vector<std::string>, std::string::const_iterator>
line = text::parseCsvLine(output.begin(), output.end());
if (!line.first.empty())
{
std::vector<std::string> headers = line.first;
line = text::parseCsvLine(line.second, output.end());
if (!line.first.empty())
{
std::vector<std::string> data = line.first;
if (headers.size() == 1 &&
data.size() == 1 &&
headers[0] == "error")
{
return Result(data[0]);
}
else if (headers.size() == 2 &&
data.size() == 2 &&
headers[0] == "id" &&
headers[1] == "continueUrl")
{
return Result(data[0], data[1]);
}
}
}
return Result();
}
private:
std::string contextId_;
FilePath htmlFile_;
bool terminationRequested_;
bool isRunning_;
std::string output_;
std::string error_;
FilePath csvOutputFile_;
};
std::map<std::string, boost::shared_ptr<RPubsUpload> > s_pCurrentUploads;
bool isUploadRunning(const std::string& contextId)
{
boost::shared_ptr<RPubsUpload> pCurrentUpload = s_pCurrentUploads[contextId];
return pCurrentUpload && pCurrentUpload->isRunning();
}
Error rpubsIsPublished(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
std::string htmlFile;
Error error = json::readParams(request.params, &htmlFile);
if (error)
return error;
FilePath filePath = module_context::resolveAliasedPath(htmlFile);
pResponse->setResult(
!module_context::previousRpubsUploadId(filePath).empty());
return Success();
}
Error rpubsUpload(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
std::string contextId, title, originalRmd, htmlFile, uploadId;
bool isUpdate;
Error error = json::readParams(request.params,
&contextId,
&title,
&originalRmd,
&htmlFile,
&uploadId,
&isUpdate);
if (error)
return error;
if (isUploadRunning(contextId))
{
pResponse->setResult(false);
}
else
{
// provide a default title if necessary
if (title.empty())
title = "Untitled";
FilePath filePath = module_context::resolveAliasedPath(htmlFile);
FilePath rmdPath = originalRmd.empty() ? FilePath() :
module_context::resolveAliasedPath(originalRmd);
s_pCurrentUploads[contextId] = RPubsUpload::create(contextId,
title,
rmdPath,
filePath,
uploadId,
isUpdate);
pResponse->setResult(true);
}
return Success();
}
Error terminateRpubsUpload(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
std::string contextId;
Error error = json::readParam(request.params, 0, &contextId);
if (error)
return error;
if (isUploadRunning(contextId))
s_pCurrentUploads[contextId]->terminate();
return Success();
}
} // anonymous namespace
Error initialize()
{
using boost::bind;
using namespace module_context;
ExecBlock initBlock ;
initBlock.addFunctions()
(bind(registerRpcMethod, "rpubs_is_published", rpubsIsPublished))
(bind(registerRpcMethod, "rpubs_upload", rpubsUpload))
(bind(registerRpcMethod, "terminate_rpubs_upload", terminateRpubsUpload))
;
return initBlock.execute();
}
} // namespace rpubs
} // namespace modules
namespace module_context {
std::string previousRpubsUploadId(const FilePath& filePath)
{
Settings settings;
getUploadIdSettings(&settings);
return settings.get(pathIdentifier(filePath));
}
} // namespace module_context
} // namesapce session
} // namespace rstudio
<commit_msg>excise code saving rpubs upload ID to old location<commit_after>/*
* SessionRPubs.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionRPubs.hpp"
#include <boost/bind.hpp>
#include <boost/utility.hpp>
#include <boost/format.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <core/Error.hpp>
#include <core/Exec.hpp>
#include <core/Log.hpp>
#include <core/Settings.hpp>
#include <core/FileSerializer.hpp>
#include <core/text/CsvParser.hpp>
#include <core/http/Util.hpp>
#include <core/system/Process.hpp>
#include <r/RSexp.hpp>
#include <r/RRoutines.hpp>
#include <session/SessionUserSettings.hpp>
#include <session/SessionModuleContext.hpp>
#include <session/projects/SessionProjects.hpp>
using namespace rstudio::core ;
namespace rstudio {
namespace session {
namespace {
// we get a fresh settings object for each read or write so multiple
// processes can all read and write without cache issues
void getUploadIdSettings(Settings* pSettings)
{
FilePath rpubsUploadIds =
module_context::scopedScratchPath().complete("rpubs_upload_ids");
Error error = pSettings->initialize(rpubsUploadIds);
if (error)
LOG_ERROR(error);
}
std::string pathIdentifier(const FilePath& filePath)
{
// use a relative path if we are in a project
std::string path;
projects::ProjectContext& projectContext = projects::projectContext();
if (projectContext.hasProject() &&
filePath.isWithin(projectContext.directory()))
{
path = filePath.relativePath(projectContext.directory());
}
else
{
path = filePath.absolutePath();
}
// urlencode so we can use it as a key
return http::util::urlEncode(path);
}
} // anonymous namespace
namespace modules {
namespace rpubs {
namespace {
class RPubsUpload : boost::noncopyable,
public boost::enable_shared_from_this<RPubsUpload>
{
public:
static boost::shared_ptr<RPubsUpload> create(const std::string& contextId,
const std::string& title,
const FilePath& originalRmd,
const FilePath& htmlFile,
const std::string& uploadId,
bool allowUpdate)
{
boost::shared_ptr<RPubsUpload> pUpload(new RPubsUpload(contextId));
pUpload->start(title, originalRmd, htmlFile, uploadId, allowUpdate);
return pUpload;
}
virtual ~RPubsUpload()
{
}
bool isRunning() const { return isRunning_; }
void terminate()
{
terminationRequested_ = true;
}
private:
explicit RPubsUpload(const std::string& contextId)
: contextId_(contextId), terminationRequested_(false), isRunning_(false)
{
}
void start(const std::string& title, const FilePath& originalRmd,
const FilePath& htmlFile, const std::string& uploadId,
bool allowUpdate)
{
using namespace rstudio::core::string_utils;
using namespace module_context;
htmlFile_ = htmlFile;
csvOutputFile_ = module_context::tempFile("rpubsupload", "csv");
isRunning_ = true;
// if we don't already have an ID for this file, and updates are allowed,
// check for a previous upload ID
std::string id = allowUpdate && uploadId.empty() ?
previousRpubsUploadId(htmlFile_) : uploadId;
boost::algorithm::trim(id);
// R binary
FilePath rProgramPath;
Error error = rScriptPath(&rProgramPath);
if (error)
{
terminateWithError(error);
return;
}
// args
std::vector<std::string> args;
args.push_back("--slave");
args.push_back("--no-save");
args.push_back("--no-restore");
args.push_back("-e");
boost::format fmt(
"result <- rsconnect::rpubsUpload('%1%', '%2%', '%3%', %4%); "
"utils::write.csv(as.data.frame(result), "
" file='%5%', "
" row.names=FALSE);");
std::string htmlPath = utf8ToSystem(htmlFile.absolutePath());
std::string outputPath = utf8ToSystem(csvOutputFile_.absolutePath());
// we may not have an original R Markdown document for this publish
// event (and that's fine)
std::string rmdPath = originalRmd == FilePath() ? "" :
utf8ToSystem(originalRmd.absolutePath());
std::string escapedTitle = string_utils::jsLiteralEscape(title);
std::string escapedHtmlPath = string_utils::jsLiteralEscape(htmlPath);
std::string escapedRmdPath = string_utils::jsLiteralEscape(rmdPath);
std::string escapedId = string_utils::jsLiteralEscape(id);
std::string escapedOutputPath = string_utils::jsLiteralEscape(outputPath);
std::string cmd = boost::str(fmt %
escapedTitle % escapedHtmlPath % escapedRmdPath %
(!escapedId.empty() ? "'" + escapedId + "'" : "NULL") %
escapedOutputPath);
args.push_back(cmd);
// options
core::system::ProcessOptions options;
options.terminateChildren = true;
options.workingDir = htmlFile.parent();
// callbacks
core::system::ProcessCallbacks cb;
cb.onContinue = boost::bind(&RPubsUpload::onContinue,
RPubsUpload::shared_from_this());
cb.onStdout = boost::bind(&RPubsUpload::onStdOut,
RPubsUpload::shared_from_this(), _2);
cb.onStderr = boost::bind(&RPubsUpload::onStdErr,
RPubsUpload::shared_from_this(), _2);
cb.onExit = boost::bind(&RPubsUpload::onCompleted,
RPubsUpload::shared_from_this(), _1);
// execute
processSupervisor().runProgram(rProgramPath.absolutePath(),
args,
options,
cb);
}
bool onContinue()
{
return !terminationRequested_;
}
void onStdOut(const std::string& output)
{
output_.append(output);
}
void onStdErr(const std::string& error)
{
error_.append(error);
}
void onCompleted(int exitStatus)
{
if (exitStatus == EXIT_SUCCESS)
{
if(csvOutputFile_.exists())
{
std::string csvOutput;
Error error = core::readStringFromFile(
csvOutputFile_,
&csvOutput,
string_utils::LineEndingPosix);
if (error)
{
terminateWithError(error);
}
else
{
// parse output
Result result = parseOutput(csvOutput);
if (!result.empty())
terminateWithResult(result);
else
terminateWithError(
"Unexpected output from upload: " + csvOutput);
}
}
else
{
terminateWithError("Unexpected output from upload: " + output_);
}
}
else
{
terminateWithError(error_);
}
}
void terminateWithError(const Error& error)
{
terminateWithError(error.summary());
}
void terminateWithError(const std::string& error)
{
terminateWithResult(Result(error));
}
struct Result
{
Result()
{
}
Result(const std::string& error)
: error(error)
{
}
Result(const std::string& id, const std::string& continueUrl)
: id(id), continueUrl(continueUrl)
{
}
bool empty() const { return id.empty() && error.empty(); }
std::string id;
std::string continueUrl;
std::string error;
};
void terminateWithResult(const Result& result)
{
isRunning_ = false;
json::Object statusJson;
statusJson["contextId"] = contextId_;
statusJson["id"] = result.id;
statusJson["continueUrl"] = result.continueUrl;
statusJson["error"] = result.error;
ClientEvent event(client_events::kRPubsUploadStatus, statusJson);
module_context::enqueClientEvent(event);
}
Result parseOutput(const std::string& output)
{
std::pair<std::vector<std::string>, std::string::const_iterator>
line = text::parseCsvLine(output.begin(), output.end());
if (!line.first.empty())
{
std::vector<std::string> headers = line.first;
line = text::parseCsvLine(line.second, output.end());
if (!line.first.empty())
{
std::vector<std::string> data = line.first;
if (headers.size() == 1 &&
data.size() == 1 &&
headers[0] == "error")
{
return Result(data[0]);
}
else if (headers.size() == 2 &&
data.size() == 2 &&
headers[0] == "id" &&
headers[1] == "continueUrl")
{
return Result(data[0], data[1]);
}
}
}
return Result();
}
private:
std::string contextId_;
FilePath htmlFile_;
bool terminationRequested_;
bool isRunning_;
std::string output_;
std::string error_;
FilePath csvOutputFile_;
};
std::map<std::string, boost::shared_ptr<RPubsUpload> > s_pCurrentUploads;
bool isUploadRunning(const std::string& contextId)
{
boost::shared_ptr<RPubsUpload> pCurrentUpload = s_pCurrentUploads[contextId];
return pCurrentUpload && pCurrentUpload->isRunning();
}
Error rpubsIsPublished(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
std::string htmlFile;
Error error = json::readParams(request.params, &htmlFile);
if (error)
return error;
FilePath filePath = module_context::resolveAliasedPath(htmlFile);
pResponse->setResult(
!module_context::previousRpubsUploadId(filePath).empty());
return Success();
}
Error rpubsUpload(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
std::string contextId, title, originalRmd, htmlFile, uploadId;
bool isUpdate;
Error error = json::readParams(request.params,
&contextId,
&title,
&originalRmd,
&htmlFile,
&uploadId,
&isUpdate);
if (error)
return error;
if (isUploadRunning(contextId))
{
pResponse->setResult(false);
}
else
{
// provide a default title if necessary
if (title.empty())
title = "Untitled";
FilePath filePath = module_context::resolveAliasedPath(htmlFile);
FilePath rmdPath = originalRmd.empty() ? FilePath() :
module_context::resolveAliasedPath(originalRmd);
s_pCurrentUploads[contextId] = RPubsUpload::create(contextId,
title,
rmdPath,
filePath,
uploadId,
isUpdate);
pResponse->setResult(true);
}
return Success();
}
Error terminateRpubsUpload(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
std::string contextId;
Error error = json::readParam(request.params, 0, &contextId);
if (error)
return error;
if (isUploadRunning(contextId))
s_pCurrentUploads[contextId]->terminate();
return Success();
}
} // anonymous namespace
Error initialize()
{
using boost::bind;
using namespace module_context;
ExecBlock initBlock ;
initBlock.addFunctions()
(bind(registerRpcMethod, "rpubs_is_published", rpubsIsPublished))
(bind(registerRpcMethod, "rpubs_upload", rpubsUpload))
(bind(registerRpcMethod, "terminate_rpubs_upload", terminateRpubsUpload))
;
return initBlock.execute();
}
} // namespace rpubs
} // namespace modules
namespace module_context {
std::string previousRpubsUploadId(const FilePath& filePath)
{
Settings settings;
getUploadIdSettings(&settings);
return settings.get(pathIdentifier(filePath));
}
} // namespace module_context
} // namesapce session
} // namespace rstudio
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* This file is part of the libetonyek project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "IWORKFormula.h"
#include <sstream>
#include <utility>
#include <vector>
#include <boost/fusion/adapted/std_pair.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/variant/recursive_variant.hpp>
namespace libetonyek
{
using boost::apply_visitor;
using boost::optional;
using boost::recursive_wrapper;
using boost::variant;
using std::string;
using std::vector;
struct Coord
{
unsigned m_coord;
bool m_absolute;
};
struct Address
{
Coord m_column;
Coord m_row;
optional<string> m_table;
optional<string> m_worksheet;
};
typedef std::pair<Address, Address> AddressRange;
struct Function;
struct UnaryOp;
struct BinaryOp;
typedef variant<double, string, Address, AddressRange, recursive_wrapper<UnaryOp>, recursive_wrapper<BinaryOp>, recursive_wrapper<Function> > Expression;
struct UnaryOp
{
char m_op;
Expression m_expr;
};
struct BinaryOp
{
char m_op;
Expression m_left;
Expression m_right;
};
struct Function
{
string m_name;
vector<Expression> m_args;
};
}
BOOST_FUSION_ADAPT_STRUCT(
libetonyek::Coord,
(bool, m_absolute)
(unsigned, m_coord)
)
BOOST_FUSION_ADAPT_STRUCT(
libetonyek::Address,
(optional<std::string>, m_worksheet)
(optional<std::string>, m_table)
(libetonyek::Coord, m_column)
(libetonyek::Coord, m_row)
)
BOOST_FUSION_ADAPT_STRUCT(
libetonyek::UnaryOp,
(char, m_op)
(libetonyek::Expression, m_expr)
)
BOOST_FUSION_ADAPT_STRUCT(
libetonyek::BinaryOp,
(libetonyek::Expression, m_left)
(char, m_op)
(libetonyek::Expression, m_right)
)
BOOST_FUSION_ADAPT_STRUCT(
libetonyek::Function,
(std::string, m_name)
(std::vector<libetonyek::Expression>, m_args)
)
namespace libetonyek
{
namespace
{
namespace ascii = boost::spirit::ascii;
namespace fusion = boost::fusion;
namespace phoenix = boost::phoenix;
namespace qi = boost::spirit::qi;
unsigned parseRowName(const vector<char> &)
{
// TODO: implement
return 0;
}
template<typename Iterator>
struct FormulaGrammar : public qi::grammar<Iterator, Expression()>
{
FormulaGrammar()
: FormulaGrammar::base_type(formula)
{
using ascii::char_;
using boost::none;
using phoenix::bind;
using qi::_1;
using qi::_val;
using qi::alpha;
using qi::attr;
using qi::double_;
using qi::lit;
using qi::uint_;
number %= double_;
str %= lit('\'') >> +(char_ - '\'') >> '\'';
unaryLit %= char_('+') | char_('-');
binaryLit %= char_('+') | char_('-') | char_('*') | char_('/') | char_('%');
row %=
lit('$') >> attr(true) >> uint_
| attr(false) >> uint_
;
column %=
lit('$') >> attr(true) >> columnName
| attr(false) >> columnName
;
columnName = (+alpha)[_val = bind(parseRowName, _1)];
worksheet = table.alias();
// TODO: improve
table %= +(char_ - '.');
address %=
worksheet >> '.' >> table >> '.' >> column >> row
| attr(none) >> table >> '.' >> column >> row
| attr(none) >> attr(none) >> column >> row
;
range %= address >> ':' >> address;
unaryOp %= unaryLit >> term;
binaryOp %= term >> binaryLit >> expression;
function %= +alpha >> '(' >> -(expression % ';') >> ')';
term %=
number
| str
| address
| range
| unaryOp
| function
;
expression %= term
| binaryOp
;
formula %= lit('=') >> expression;
number.name("number");
str.name("string");
unaryOp.name("unary operator");
binaryOp.name("binary operator");
row.name("row");
column.name("column");
columnName.name("column name");
table.name("table name");
worksheet.name("worksheet name");
address.name("address");
range.name("address range");
function.name("function");
expression.name("expression");
term.name("term");
formula.name("formula");
}
qi::rule<Iterator, Function()> function;
qi::rule<Iterator, Expression()> expression, formula, term;
qi::rule<Iterator, Address()> address;
qi::rule<Iterator, AddressRange()> range;
qi::rule<Iterator, unsigned()> columnName;
qi::rule<Iterator, Coord()> column, row;
qi::rule<Iterator, double()> number;
qi::rule<Iterator, string()> str, table, worksheet;
qi::rule<Iterator, UnaryOp()> unaryOp;
qi::rule<Iterator, BinaryOp()> binaryOp;
qi::rule<Iterator, char()> unaryLit, binaryLit;
};
}
namespace
{
struct printer : public boost::static_visitor<string>
{
string operator()(double val) const
{
return boost::lexical_cast<string>(val);
}
string operator()(const std::string &val) const
{
return val;
}
string operator()(const Address &val) const
{
std::ostringstream out;
if (val.m_worksheet)
out << get(val.m_worksheet) << '.';
if (val.m_table)
out << get(val.m_table) << '.';
if (val.m_column.m_absolute)
out << '$';
out << val.m_column.m_coord;
if (val.m_row.m_absolute)
out << '$';
out << val.m_row.m_coord;
return out.str();
}
string operator()(const AddressRange &val) const
{
return operator()(val.first) + ':' + operator()(val.second);
}
string operator()(const recursive_wrapper<UnaryOp> &val) const
{
return val.get().m_op + apply_visitor(printer(), val.get().m_expr);
}
string operator()(const recursive_wrapper<BinaryOp> &val) const
{
return apply_visitor(printer(), val.get().m_left) + val.get().m_op + apply_visitor(printer(), val.get().m_right);
}
string operator()(const recursive_wrapper<Function> &val) const
{
std::ostringstream out;
out << val.get().m_name << '(';
for (vector<Expression>::const_iterator it = val.get().m_args.begin(); it != val.get().m_args.end(); ++it)
out << apply_visitor(printer(), *it);
out << ')';
return out.str();
}
};
}
struct IWORKFormula::Impl
{
Expression m_formula;
};
IWORKFormula::IWORKFormula()
: m_impl(new Impl())
{
}
bool IWORKFormula::parse(const std::string &formula)
{
FormulaGrammar<string::const_iterator> grammar;
string::const_iterator it = formula.begin();
string::const_iterator end = formula.end();
const bool r = qi::phrase_parse(it, end, grammar, ascii::space, m_impl->m_formula);
return r && (it == end);
}
const std::string IWORKFormula::toString() const
{
return '=' + apply_visitor(printer(), m_impl->m_formula);
}
} // namespace libetonyek
/* vim:set shiftwidth=2 softtabstop=2 expandtab: */
<commit_msg>reformat<commit_after>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* This file is part of the libetonyek project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "IWORKFormula.h"
#include <sstream>
#include <utility>
#include <vector>
#include <boost/fusion/adapted/std_pair.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/variant/recursive_variant.hpp>
namespace libetonyek
{
using boost::apply_visitor;
using boost::optional;
using boost::recursive_wrapper;
using boost::variant;
using std::string;
using std::vector;
struct Coord
{
unsigned m_coord;
bool m_absolute;
};
struct Address
{
Coord m_column;
Coord m_row;
optional<string> m_table;
optional<string> m_worksheet;
};
typedef std::pair<Address, Address> AddressRange;
struct Function;
struct UnaryOp;
struct BinaryOp;
typedef variant<double, string, Address, AddressRange, recursive_wrapper<UnaryOp>, recursive_wrapper<BinaryOp>, recursive_wrapper<Function> > Expression;
struct UnaryOp
{
char m_op;
Expression m_expr;
};
struct BinaryOp
{
char m_op;
Expression m_left;
Expression m_right;
};
struct Function
{
string m_name;
vector<Expression> m_args;
};
}
BOOST_FUSION_ADAPT_STRUCT(
libetonyek::Coord,
(bool, m_absolute)
(unsigned, m_coord)
)
BOOST_FUSION_ADAPT_STRUCT(
libetonyek::Address,
(optional<std::string>, m_worksheet)
(optional<std::string>, m_table)
(libetonyek::Coord, m_column)
(libetonyek::Coord, m_row)
)
BOOST_FUSION_ADAPT_STRUCT(
libetonyek::UnaryOp,
(char, m_op)
(libetonyek::Expression, m_expr)
)
BOOST_FUSION_ADAPT_STRUCT(
libetonyek::BinaryOp,
(libetonyek::Expression, m_left)
(char, m_op)
(libetonyek::Expression, m_right)
)
BOOST_FUSION_ADAPT_STRUCT(
libetonyek::Function,
(std::string, m_name)
(std::vector<libetonyek::Expression>, m_args)
)
namespace libetonyek
{
namespace
{
namespace ascii = boost::spirit::ascii;
namespace fusion = boost::fusion;
namespace phoenix = boost::phoenix;
namespace qi = boost::spirit::qi;
unsigned parseRowName(const vector<char> &)
{
// TODO: implement
return 0;
}
template<typename Iterator>
struct FormulaGrammar : public qi::grammar<Iterator, Expression()>
{
FormulaGrammar()
: FormulaGrammar::base_type(formula)
{
using ascii::char_;
using boost::none;
using phoenix::bind;
using qi::_1;
using qi::_val;
using qi::alpha;
using qi::attr;
using qi::double_;
using qi::lit;
using qi::uint_;
number %= double_;
str %= lit('\'') >> +(char_ - '\'') >> '\'';
unaryLit %= char_('+') | char_('-');
binaryLit %= char_('+') | char_('-') | char_('*') | char_('/') | char_('%');
row %=
lit('$') >> attr(true) >> uint_
| attr(false) >> uint_
;
column %=
lit('$') >> attr(true) >> columnName
| attr(false) >> columnName
;
columnName = (+alpha)[_val = bind(parseRowName, _1)];
worksheet = table.alias();
// TODO: improve
table %= +(char_ - '.');
address %=
worksheet >> '.' >> table >> '.' >> column >> row
| attr(none) >> table >> '.' >> column >> row
| attr(none) >> attr(none) >> column >> row
;
range %= address >> ':' >> address;
unaryOp %= unaryLit >> term;
binaryOp %= term >> binaryLit >> expression;
function %= +alpha >> '(' >> -(expression % ';') >> ')';
term %=
number
| str
| address
| range
| unaryOp
| function
;
expression %=
term
| binaryOp
;
formula %= lit('=') >> expression;
number.name("number");
str.name("string");
unaryOp.name("unary operator");
binaryOp.name("binary operator");
row.name("row");
column.name("column");
columnName.name("column name");
table.name("table name");
worksheet.name("worksheet name");
address.name("address");
range.name("address range");
function.name("function");
expression.name("expression");
term.name("term");
formula.name("formula");
}
qi::rule<Iterator, Function()> function;
qi::rule<Iterator, Expression()> expression, formula, term;
qi::rule<Iterator, Address()> address;
qi::rule<Iterator, AddressRange()> range;
qi::rule<Iterator, unsigned()> columnName;
qi::rule<Iterator, Coord()> column, row;
qi::rule<Iterator, double()> number;
qi::rule<Iterator, string()> str, table, worksheet;
qi::rule<Iterator, UnaryOp()> unaryOp;
qi::rule<Iterator, BinaryOp()> binaryOp;
qi::rule<Iterator, char()> unaryLit, binaryLit;
};
}
namespace
{
struct printer : public boost::static_visitor<string>
{
string operator()(double val) const
{
return boost::lexical_cast<string>(val);
}
string operator()(const std::string &val) const
{
return val;
}
string operator()(const Address &val) const
{
std::ostringstream out;
if (val.m_worksheet)
out << get(val.m_worksheet) << '.';
if (val.m_table)
out << get(val.m_table) << '.';
if (val.m_column.m_absolute)
out << '$';
out << val.m_column.m_coord;
if (val.m_row.m_absolute)
out << '$';
out << val.m_row.m_coord;
return out.str();
}
string operator()(const AddressRange &val) const
{
return operator()(val.first) + ':' + operator()(val.second);
}
string operator()(const recursive_wrapper<UnaryOp> &val) const
{
return val.get().m_op + apply_visitor(printer(), val.get().m_expr);
}
string operator()(const recursive_wrapper<BinaryOp> &val) const
{
return apply_visitor(printer(), val.get().m_left) + val.get().m_op + apply_visitor(printer(), val.get().m_right);
}
string operator()(const recursive_wrapper<Function> &val) const
{
std::ostringstream out;
out << val.get().m_name << '(';
for (vector<Expression>::const_iterator it = val.get().m_args.begin(); it != val.get().m_args.end(); ++it)
out << apply_visitor(printer(), *it);
out << ')';
return out.str();
}
};
}
struct IWORKFormula::Impl
{
Expression m_formula;
};
IWORKFormula::IWORKFormula()
: m_impl(new Impl())
{
}
bool IWORKFormula::parse(const std::string &formula)
{
FormulaGrammar<string::const_iterator> grammar;
string::const_iterator it = formula.begin();
string::const_iterator end = formula.end();
const bool r = qi::phrase_parse(it, end, grammar, ascii::space, m_impl->m_formula);
return r && (it == end);
}
const std::string IWORKFormula::toString() const
{
return '=' + apply_visitor(printer(), m_impl->m_formula);
}
} // namespace libetonyek
/* vim:set shiftwidth=2 softtabstop=2 expandtab: */
<|endoftext|>
|
<commit_before>//
// Created by valdemar on 14.10.17.
//
#include "UIController.h"
#include <imgui_impl/imgui_widgets.h>
#include <imgui_impl/imgui_impl_glfw_gl3.h>
#include <imgui_impl/style.h>
#include <fontawesome.h>
#include <glm/gtc/type_ptr.hpp>
struct UIController::wnd_t {
bool show_style_editor = false;
bool show_fps_overlay = true;
bool show_info = true;
bool show_playback_control = true;
bool show_ui_help = false;
bool show_shortcuts_help = false;
bool show_metrics = false;
};
UIController::UIController(Camera *camera)
: camera_(camera) {
// Setup ImGui binding
ImGui_ImplGlfwGL3_Init(glfwGetCurrentContext(), true);
wnd_ = std::make_unique<wnd_t>();
setup_custom_style(false);
auto &io = ImGui::GetIO();
io.IniFilename = "rewindviewer.ini";
//Load and merge fontawesome to current font
io.Fonts->AddFontDefault();
const ImWchar icons_range[] = {ICON_MIN_FA, ICON_MAX_FA, 0};
ImFontConfig icons_config;
icons_config.MergeMode = true;
icons_config.PixelSnapH = true;
io.Fonts->AddFontFromFileTTF("resources/fonts/fontawesome-webfont.ttf", 14.0f, &icons_config, icons_range);
}
UIController::~UIController() {
// Cleanup imgui
ImGui_ImplGlfwGL3_Shutdown();
}
void UIController::next_frame(Scene *scene) {
// Start new frame
ImGui_ImplGlfwGL3_NewFrame();
//Update windows status
main_menu_bar();
if (ImGui::BeginMainMenuBar()) {
ImGui::EndMainMenuBar();
}
if (wnd_->show_fps_overlay) {
fps_overlay_widget();
}
if (wnd_->show_info) {
info_widget(scene);
}
if (wnd_->show_playback_control) {
playback_control_widget(scene);
}
if (wnd_->show_style_editor) {
ImGui::Begin("Style editor", &wnd_->show_style_editor);
ImGui::ShowStyleEditor();
ImGui::End();
}
if (wnd_->show_metrics) {
ImGui::ShowMetricsWindow(&wnd_->show_metrics);
}
if (wnd_->show_ui_help) {
ImGui::Begin(ICON_FA_INFO_CIRCLE " UI guide", &wnd_->show_ui_help, ImGuiWindowFlags_AlwaysAutoResize);
ImGui::ShowUserGuide();
ImGui::End();
}
if (wnd_->show_shortcuts_help) {
ImGui::Begin(ICON_FA_KEYBOARD_O " Controls help", &wnd_->show_shortcuts_help, ImGuiWindowFlags_AlwaysAutoResize);
ImGui::BulletText("Mouse drag on map to move camera");
ImGui::BulletText("Mouse wheel to zoom");
ImGui::BulletText("Space to play/stop frame playback");
ImGui::BulletText("Left, right arrow to manually change frames");
ImGui::BulletText("Esc to close application");
ImGui::End();
}
//Checking hotkeys
check_hotkeys();
//Hittest for detailed unit info
if (!ImGui::GetIO().WantCaptureMouse) {
scene->show_detailed_info(camera_->screen2world(ImGui::GetIO().MousePos));
}
//Background color
glClearColor(clear_color_.r, clear_color_.g, clear_color_.b, 1.0f);
}
void UIController::frame_end() {
ImGui::Render();
}
bool UIController::close_requested() {
return request_exit_;
}
void UIController::check_hotkeys() {
const auto &io = ImGui::GetIO();
if (!io.WantTextInput) {
if (io.KeysDown[GLFW_KEY_SPACE]) {
if (!space_pressed_) {
space_pressed_ = true;
autoplay_scene_ = !autoplay_scene_;
}
} else {
space_pressed_ = false;
}
if (io.KeysDown[GLFW_KEY_D] && io.KeyCtrl) {
developer_mode_ = true;
}
}
request_exit_ = io.KeysDown[GLFW_KEY_ESCAPE];
}
void UIController::main_menu_bar() {
if (ImGui::BeginMainMenuBar()) {
if (ImGui::BeginMenu(ICON_FA_EYE " View", true)) {
ImGui::Checkbox("FPS overlay", &wnd_->show_fps_overlay);
ImGui::Checkbox("Utility window", &wnd_->show_info);
if (developer_mode_) {
ImGui::Separator();
ImGui::Checkbox("Style editor", &wnd_->show_style_editor);
ImGui::Checkbox("Metrics", &wnd_->show_metrics);
}
ImGui::EndMenu();
}
if (ImGui::BeginMenu(ICON_FA_QUESTION_CIRCLE_O " Help", true)) {
ImGui::MenuItem(ICON_FA_INFO_CIRCLE " UI guide", nullptr, &wnd_->show_ui_help);
ImGui::MenuItem(ICON_FA_KEYBOARD_O " Controls", nullptr, &wnd_->show_shortcuts_help);
ImGui::EndMenu();
}
ImGui::EndMainMenuBar();
}
}
void UIController::fps_overlay_widget() {
ImGui::SetNextWindowPos(ImVec2(10, 20));
const auto flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize
| ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings;
if (ImGui::Begin("FPS Overlay", &wnd_->show_fps_overlay, ImVec2{0, 0}, 0.3, flags)) {
ImGui::BeginGroup();
ImGui::TextColored({1.0, 1.0, 0.0, 1.0}, "FPS %.1f", ImGui::GetIO().Framerate);
ImGui::SameLine();
ImGui::Text("[%.1f ms]", 1000.0f / ImGui::GetIO().Framerate);
ImGui::EndGroup();
ImGui::End();
}
}
void UIController::info_widget(Scene *scene) {
int width, height;
glfwGetWindowSize(glfwGetCurrentContext(), &width, &height);
const float desired_width = 300;
ImGui::SetNextWindowPos({width - desired_width, 20}, ImGuiCond_Always);
ImGui::SetNextWindowSize({desired_width, static_cast<float>(height - 20 - 30)}, ImGuiCond_Always);
ImGui::Begin("Info", &wnd_->show_info, ImGuiWindowFlags_NoTitleBar);
const auto flags = ImGuiTreeNodeFlags_DefaultOpen;
if (ImGui::CollapsingHeader(ICON_FA_COGS " Settings")) {
if (ImGui::CollapsingHeader(ICON_FA_VIDEO_CAMERA " Camera", flags)) {
ImGui::PushItemWidth(150);
ImGui::InputFloat2("Position", glm::value_ptr(camera_->pos_), 1);
ImGui::InputFloat("Viewport size", &camera_->opt_.viewport_size, 50.0, 1000.0, 0);
ImGui::PopItemWidth();
}
if (ImGui::CollapsingHeader(ICON_FA_EYEDROPPER " Colors", flags)) {
ImGui::SetColorEditOptions(ImGuiColorEditFlags_NoInputs);
ImGui::ColorEdit3("Background", glm::value_ptr(clear_color_));
ImGui::ColorEdit3("Grid", glm::value_ptr(scene->opt_.grid_color));
}
if (ImGui::CollapsingHeader(ICON_FA_MAP_O " Options", flags)) {
ImGui::Checkbox("Show full life bars", &scene->opt_.show_full_hp_bars);
ImGui::Checkbox("Show detailed unit info on hover", &scene->opt_.show_detailed_info_on_hover);
}
}
if (ImGui::CollapsingHeader(ICON_FA_COMMENT_O " Frame message", flags)) {
ImGui::BeginChild("FrameMsg", {0, 0}, true);
ImGui::TextWrapped("%s", scene->get_frame_user_message());
ImGui::EndChild();
}
ImGui::End();
}
void UIController::playback_control_widget(Scene *scene) {
static const auto button_size = ImVec2{0, 0};
static const float buttons_spacing = 5.0f;
auto &io = ImGui::GetIO();
auto width = io.DisplaySize.x;
ImGui::SetNextWindowPos({0, io.DisplaySize.y - 20 - 2 * ImGui::GetStyle().WindowPadding.y});
ImGui::SetNextWindowSize({width, 30});
static const auto flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize
| ImGuiWindowFlags_NoMove
| ImGuiWindowFlags_NoSavedSettings;
if (ImGui::Begin("Playback control", &wnd_->show_playback_control, flags)) {
ImGui::BeginGroup();
int tick = scene->get_frame_index();
if (!io.WantTextInput) {
if (io.KeysDown[GLFW_KEY_LEFT] || io.KeysDown[GLFW_KEY_RIGHT]) {
tick += io.KeysDown[GLFW_KEY_RIGHT] ? 1 : -1;
}
}
ImGui::Button(ICON_FA_FAST_BACKWARD "##fastprev", button_size);
if (ImGui::IsItemActive()) {
tick -= fast_skip_speed_;
}
ImGui::SameLine(0.0f, buttons_spacing);
if (ImGui::Button(ICON_FA_BACKWARD "##prev", button_size)) {
--tick;
}
ImGui::SameLine(0.0f, buttons_spacing);
if (autoplay_scene_) {
autoplay_scene_ = !ImGui::Button(ICON_FA_PAUSE "##pause", button_size);
} else {
autoplay_scene_ = ImGui::Button(ICON_FA_PLAY "##play", button_size);
}
ImGui::SameLine(0.0f, buttons_spacing);
if (ImGui::Button(ICON_FA_FORWARD "##next", button_size)) {
++tick;
}
ImGui::SameLine(0.0f, buttons_spacing);
ImGui::Button(ICON_FA_FAST_FORWARD "##fastnext", button_size);
if (ImGui::IsItemActive()) {
tick += fast_skip_speed_;
}
ImGui::SameLine();
tick += autoplay_scene_;
//Make tick 1-indexed to better user view
const auto frames_cnt = scene->get_frames_count();
tick = std::min(tick + 1, frames_cnt);
float ftick = tick;
ImGui::PushItemWidth(-1);
if (ImGui::TickBar("##empty", &ftick, 1, frames_cnt, {0.0f, 0.0f})) {
tick = static_cast<int>(ftick);
}
ImGui::PopItemWidth();
scene->set_frame_index(tick - 1);
ImGui::EndGroup();
ImGui::End();
}
}
<commit_msg>Build font atlas right after initialization<commit_after>//
// Created by valdemar on 14.10.17.
//
#include "UIController.h"
#include <imgui_impl/imgui_widgets.h>
#include <imgui_impl/imgui_impl_glfw_gl3.h>
#include <imgui_impl/style.h>
#include <fontawesome.h>
#include <glm/gtc/type_ptr.hpp>
struct UIController::wnd_t {
bool show_style_editor = false;
bool show_fps_overlay = true;
bool show_info = true;
bool show_playback_control = true;
bool show_ui_help = false;
bool show_shortcuts_help = false;
bool show_metrics = false;
};
UIController::UIController(Camera *camera)
: camera_(camera) {
// Setup ImGui binding
ImGui_ImplGlfwGL3_Init(glfwGetCurrentContext(), true);
wnd_ = std::make_unique<wnd_t>();
setup_custom_style(false);
auto &io = ImGui::GetIO();
io.IniFilename = "rewindviewer.ini";
//Load and merge fontawesome to current font
io.Fonts->AddFontDefault();
const ImWchar icons_range[] = {ICON_MIN_FA, ICON_MAX_FA, 0};
ImFontConfig icons_config;
icons_config.MergeMode = true;
icons_config.PixelSnapH = true;
io.Fonts->AddFontFromFileTTF("resources/fonts/fontawesome-webfont.ttf", 14.0f, &icons_config, icons_range);
//Need to call it here, otherwise fontawesome glyph ranges would be corrupted on Windows
ImGui_ImplGlfwGL3_CreateDeviceObjects();
}
UIController::~UIController() {
// Cleanup imgui
ImGui_ImplGlfwGL3_Shutdown();
}
void UIController::next_frame(Scene *scene) {
// Start new frame
ImGui_ImplGlfwGL3_NewFrame();
//Update windows status
main_menu_bar();
if (ImGui::BeginMainMenuBar()) {
ImGui::EndMainMenuBar();
}
if (wnd_->show_fps_overlay) {
fps_overlay_widget();
}
if (wnd_->show_info) {
info_widget(scene);
}
if (wnd_->show_playback_control) {
playback_control_widget(scene);
}
if (wnd_->show_style_editor) {
ImGui::Begin("Style editor", &wnd_->show_style_editor);
ImGui::ShowStyleEditor();
ImGui::End();
}
if (wnd_->show_metrics) {
ImGui::ShowMetricsWindow(&wnd_->show_metrics);
}
if (wnd_->show_ui_help) {
ImGui::Begin(ICON_FA_INFO_CIRCLE " UI guide", &wnd_->show_ui_help, ImGuiWindowFlags_AlwaysAutoResize);
ImGui::ShowUserGuide();
ImGui::End();
}
if (wnd_->show_shortcuts_help) {
ImGui::Begin(ICON_FA_KEYBOARD_O " Controls help", &wnd_->show_shortcuts_help, ImGuiWindowFlags_AlwaysAutoResize);
ImGui::BulletText("Mouse drag on map to move camera");
ImGui::BulletText("Mouse wheel to zoom");
ImGui::BulletText("Space to play/stop frame playback");
ImGui::BulletText("Left, right arrow to manually change frames");
ImGui::BulletText("Esc to close application");
ImGui::End();
}
//Checking hotkeys
check_hotkeys();
//Hittest for detailed unit info
if (!ImGui::GetIO().WantCaptureMouse) {
scene->show_detailed_info(camera_->screen2world(ImGui::GetIO().MousePos));
}
//Background color
glClearColor(clear_color_.r, clear_color_.g, clear_color_.b, 1.0f);
}
void UIController::frame_end() {
ImGui::Render();
}
bool UIController::close_requested() {
return request_exit_;
}
void UIController::check_hotkeys() {
const auto &io = ImGui::GetIO();
if (!io.WantTextInput) {
if (io.KeysDown[GLFW_KEY_SPACE]) {
if (!space_pressed_) {
space_pressed_ = true;
autoplay_scene_ = !autoplay_scene_;
}
} else {
space_pressed_ = false;
}
if (io.KeysDown[GLFW_KEY_D] && io.KeyCtrl) {
developer_mode_ = true;
}
}
request_exit_ = io.KeysDown[GLFW_KEY_ESCAPE];
}
void UIController::main_menu_bar() {
if (ImGui::BeginMainMenuBar()) {
if (ImGui::BeginMenu(ICON_FA_EYE " View", true)) {
ImGui::Checkbox("FPS overlay", &wnd_->show_fps_overlay);
ImGui::Checkbox("Utility window", &wnd_->show_info);
if (developer_mode_) {
ImGui::Separator();
ImGui::Checkbox("Style editor", &wnd_->show_style_editor);
ImGui::Checkbox("Metrics", &wnd_->show_metrics);
}
ImGui::EndMenu();
}
if (ImGui::BeginMenu(ICON_FA_QUESTION_CIRCLE_O " Help", true)) {
ImGui::MenuItem(ICON_FA_INFO_CIRCLE " UI guide", nullptr, &wnd_->show_ui_help);
ImGui::MenuItem(ICON_FA_KEYBOARD_O " Controls", nullptr, &wnd_->show_shortcuts_help);
ImGui::EndMenu();
}
ImGui::EndMainMenuBar();
}
}
void UIController::fps_overlay_widget() {
ImGui::SetNextWindowPos(ImVec2(10, 20));
const auto flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize
| ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings;
if (ImGui::Begin("FPS Overlay", &wnd_->show_fps_overlay, ImVec2{0, 0}, 0.3, flags)) {
ImGui::BeginGroup();
ImGui::TextColored({1.0, 1.0, 0.0, 1.0}, "FPS %.1f", ImGui::GetIO().Framerate);
ImGui::SameLine();
ImGui::Text("[%.1f ms]", 1000.0f / ImGui::GetIO().Framerate);
ImGui::EndGroup();
ImGui::End();
}
}
void UIController::info_widget(Scene *scene) {
int width, height;
glfwGetWindowSize(glfwGetCurrentContext(), &width, &height);
const float desired_width = 300;
ImGui::SetNextWindowPos({width - desired_width, 20}, ImGuiCond_Always);
ImGui::SetNextWindowSize({desired_width, static_cast<float>(height - 20 - 30)}, ImGuiCond_Always);
ImGui::Begin("Info", &wnd_->show_info, ImGuiWindowFlags_NoTitleBar);
const auto flags = ImGuiTreeNodeFlags_DefaultOpen;
if (ImGui::CollapsingHeader(ICON_FA_COGS " Settings")) {
if (ImGui::CollapsingHeader(ICON_FA_VIDEO_CAMERA " Camera", flags)) {
ImGui::PushItemWidth(150);
ImGui::InputFloat2("Position", glm::value_ptr(camera_->pos_), 1);
ImGui::InputFloat("Viewport size", &camera_->opt_.viewport_size, 50.0, 1000.0, 0);
ImGui::PopItemWidth();
}
if (ImGui::CollapsingHeader(ICON_FA_EYEDROPPER " Colors", flags)) {
ImGui::SetColorEditOptions(ImGuiColorEditFlags_NoInputs);
ImGui::ColorEdit3("Background", glm::value_ptr(clear_color_));
ImGui::ColorEdit3("Grid", glm::value_ptr(scene->opt_.grid_color));
}
if (ImGui::CollapsingHeader(ICON_FA_MAP_O " Options", flags)) {
ImGui::Checkbox("Show full life bars", &scene->opt_.show_full_hp_bars);
ImGui::Checkbox("Show detailed unit info on hover", &scene->opt_.show_detailed_info_on_hover);
}
}
if (ImGui::CollapsingHeader(ICON_FA_COMMENT_O " Frame message", flags)) {
ImGui::BeginChild("FrameMsg", {0, 0}, true);
ImGui::TextWrapped("%s", scene->get_frame_user_message());
ImGui::EndChild();
}
ImGui::End();
}
void UIController::playback_control_widget(Scene *scene) {
static const auto button_size = ImVec2{0, 0};
static const float buttons_spacing = 5.0f;
auto &io = ImGui::GetIO();
auto width = io.DisplaySize.x;
ImGui::SetNextWindowPos({0, io.DisplaySize.y - 20 - 2 * ImGui::GetStyle().WindowPadding.y});
ImGui::SetNextWindowSize({width, 30});
static const auto flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize
| ImGuiWindowFlags_NoMove
| ImGuiWindowFlags_NoSavedSettings;
if (ImGui::Begin("Playback control", &wnd_->show_playback_control, flags)) {
ImGui::BeginGroup();
int tick = scene->get_frame_index();
if (!io.WantTextInput) {
if (io.KeysDown[GLFW_KEY_LEFT] || io.KeysDown[GLFW_KEY_RIGHT]) {
tick += io.KeysDown[GLFW_KEY_RIGHT] ? 1 : -1;
}
}
ImGui::Button(ICON_FA_FAST_BACKWARD "##fastprev", button_size);
if (ImGui::IsItemActive()) {
tick -= fast_skip_speed_;
}
ImGui::SameLine(0.0f, buttons_spacing);
if (ImGui::Button(ICON_FA_BACKWARD "##prev", button_size)) {
--tick;
}
ImGui::SameLine(0.0f, buttons_spacing);
if (autoplay_scene_) {
autoplay_scene_ = !ImGui::Button(ICON_FA_PAUSE "##pause", button_size);
} else {
autoplay_scene_ = ImGui::Button(ICON_FA_PLAY "##play", button_size);
}
ImGui::SameLine(0.0f, buttons_spacing);
if (ImGui::Button(ICON_FA_FORWARD "##next", button_size)) {
++tick;
}
ImGui::SameLine(0.0f, buttons_spacing);
ImGui::Button(ICON_FA_FAST_FORWARD "##fastnext", button_size);
if (ImGui::IsItemActive()) {
tick += fast_skip_speed_;
}
ImGui::SameLine();
tick += autoplay_scene_;
//Make tick 1-indexed to better user view
const auto frames_cnt = scene->get_frames_count();
tick = std::min(tick + 1, frames_cnt);
float ftick = tick;
ImGui::PushItemWidth(-1);
if (ImGui::TickBar("##empty", &ftick, 1, frames_cnt, {0.0f, 0.0f})) {
tick = static_cast<int>(ftick);
}
ImGui::PopItemWidth();
scene->set_frame_index(tick - 1);
ImGui::EndGroup();
ImGui::End();
}
}
<|endoftext|>
|
<commit_before>#include "image_properties.h"
#include "opencv_utils.h"
#include <ros/ros.h>
/** \brief Parameter constructor. Sets the parameter struct to default values.
*/
template_pose::ImageProperties::Params::Params() :
desc_type("SIFT"),
bucket_width(DEFAULT_BUCKET_WIDTH),
bucket_height(DEFAULT_BUCKET_HEIGHT),
max_bucket_features(DEFAULT_MAX_BUCKET_FEATURES),
px_meter_x(DEFAULT_PX_METER_X),
px_meter_y(DEFAULT_PX_METER_Y)
{}
/** \brief ImageProperties constructor
*/
template_pose::ImageProperties::ImageProperties() {}
/** \brief Sets the parameters
* \param parameter struct.
*/
void template_pose::ImageProperties::setParams(const Params& params)
{
params_ = params;
}
/** \brief Return the image
* @return image
*/
Mat template_pose::ImageProperties::getImg() { return img_; }
/** \brief Return the keypoints of the image
* @return image keypoints
*/
vector<KeyPoint> template_pose::ImageProperties::getKp() { return kp_; }
/** \brief Return the descriptors of the image
* @return image descriptors
*/
Mat template_pose::ImageProperties::getDesc() { return desc_; }
/** \brief Return the 3D points of the image
* @return 3D points
*/
vector<Point3f> template_pose::ImageProperties::get3Dpoints() { return points_3d_; }
/** \brief Compute the properties for the images
* \param image reference image.
*/
void template_pose::ImageProperties::setImg(const Mat& img)
{
img_ = img;
// Extract keypoints and descriptors of reference image
desc_ = Mat_< vector<float> >();
template_pose::OpencvUtils::keypointDetector(img_, kp_, params_.desc_type);
// Bucket keypoints
kp_ = template_pose::OpencvUtils::bucketKeypoints(kp_,
params_.bucket_width,
params_.bucket_height,
params_.max_bucket_features);
template_pose::OpencvUtils::descriptorExtraction(img_, kp_, desc_, params_.desc_type);
}
/** \brief Compute the 3D coordinates
*/
void template_pose::ImageProperties::compute3D()
{
// Reset the 3D points
points_3d_.clear();
// Extract the image size
float origin_x = (float)img_.cols * 0.5;
float origin_y = (float)img_.rows * 0.5;
// Compute the 3D coordinates (image center as origin)
for (size_t i=0; i<kp_.size(); i++)
{
Point3f world_point;
world_point.x = (float)kp_[i].pt.x/params_.px_meter_x - origin_x;
world_point.y = (float)kp_[i].pt.y/params_.px_meter_y - origin_y;
world_point.z = 0.0;
points_3d_.push_back(world_point);
}
}<commit_msg>Fixed: the way to calculate the origin on the center of the image<commit_after>#include "image_properties.h"
#include "opencv_utils.h"
#include <ros/ros.h>
/** \brief Parameter constructor. Sets the parameter struct to default values.
*/
template_pose::ImageProperties::Params::Params() :
desc_type("SIFT"),
bucket_width(DEFAULT_BUCKET_WIDTH),
bucket_height(DEFAULT_BUCKET_HEIGHT),
max_bucket_features(DEFAULT_MAX_BUCKET_FEATURES),
px_meter_x(DEFAULT_PX_METER_X),
px_meter_y(DEFAULT_PX_METER_Y)
{}
/** \brief ImageProperties constructor
*/
template_pose::ImageProperties::ImageProperties() {}
/** \brief Sets the parameters
* \param parameter struct.
*/
void template_pose::ImageProperties::setParams(const Params& params)
{
params_ = params;
}
/** \brief Return the image
* @return image
*/
Mat template_pose::ImageProperties::getImg() { return img_; }
/** \brief Return the keypoints of the image
* @return image keypoints
*/
vector<KeyPoint> template_pose::ImageProperties::getKp() { return kp_; }
/** \brief Return the descriptors of the image
* @return image descriptors
*/
Mat template_pose::ImageProperties::getDesc() { return desc_; }
/** \brief Return the 3D points of the image
* @return 3D points
*/
vector<Point3f> template_pose::ImageProperties::get3Dpoints() { return points_3d_; }
/** \brief Compute the properties for the images
* \param image reference image.
*/
void template_pose::ImageProperties::setImg(const Mat& img)
{
img_ = img;
// Extract keypoints and descriptors of reference image
desc_ = Mat_< vector<float> >();
template_pose::OpencvUtils::keypointDetector(img_, kp_, params_.desc_type);
// Bucket keypoints
kp_ = template_pose::OpencvUtils::bucketKeypoints(kp_,
params_.bucket_width,
params_.bucket_height,
params_.max_bucket_features);
template_pose::OpencvUtils::descriptorExtraction(img_, kp_, desc_, params_.desc_type);
}
/** \brief Compute the 3D coordinates
*/
void template_pose::ImageProperties::compute3D()
{
// Reset the 3D points
points_3d_.clear();
// Extract the image size
float origin_x = (float)img_.cols * 0.5;
float origin_y = (float)img_.rows * 0.5;
// Compute the 3D coordinates (image center as origin)
for (size_t i=0; i<kp_.size(); i++)
{
Point3f world_point;
world_point.x = ((float)kp_[i].pt.x - origin_x) / params_.px_meter_x;
world_point.y = ((float)kp_[i].pt.y - origin_y) / params_.px_meter_y;
world_point.z = 0.0;
points_3d_.push_back(world_point);
}
}<|endoftext|>
|
<commit_before>#include "kernel.h"
#include "storage.h"
#include "arch/dev/Display.h"
#include "sampling.h"
#include <cassert>
#include <algorithm>
#include <cstdarg>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <set>
#include <map>
#include <cstdio>
using namespace std;
namespace Simulator
{
//
// Process class
//
std::string Process::GetName() const
{
return GetObject()->GetFQN() + ":" + m_name;
}
void Process::Deactivate()
{
// A process can be sensitive to multiple objects, so we only remove it from the list
// if the count becomes zero
if (--m_activations == 0)
{
// Remove the handle node from the list
*m_pPrev = m_next;
if (m_next != NULL) {
m_next->m_pPrev = m_pPrev;
}
m_state = STATE_IDLE;
}
}
//
// Object class
//
Object::Object(const std::string& name, Clock& clock)
: m_parent(NULL), m_name(name), m_fqn(name), m_clock(clock), m_kernel(clock.GetKernel())
{
}
Object::Object(const std::string& name, Object& parent)
: m_parent(&parent),
m_name(name),
m_fqn(parent.GetFQN() + '.' + name),
m_clock(parent.m_clock),
m_kernel(m_clock.GetKernel())
{
// Add ourself to the parent's children array
parent.m_children.push_back(this);
}
Object::Object(const std::string& name, Object& parent, Clock& clock)
: m_parent(&parent),
m_name(name),
m_fqn(parent.GetFQN() + '.' + name),
m_clock(clock),
m_kernel(clock.GetKernel())
{
// Add ourself to the parent's children array
parent.m_children.push_back(this);
}
Object::~Object()
{
if (m_parent != NULL)
{
// Remove ourself from the parent's children array
for (vector<Object*>::iterator p = m_parent->m_children.begin(); p != m_parent->m_children.end(); ++p)
{
if (*p == this)
{
m_parent->m_children.erase(p);
break;
}
}
}
}
void Object::OutputWrite_(const char* msg, ...) const
{
va_list args;
string name = GetFQN();
cerr << "[" << right << dec << setfill('0') << setw(8) << m_kernel.GetCycleNo() << ":" << name << "] ";
va_start(args, msg);
vfprintf(stderr, msg, args);
va_end(args);
cerr << endl;
}
void Object::DeadlockWrite_(const char* msg, ...) const
{
va_list args;
if (!m_kernel.m_debugging) {
const Process* process = m_kernel.GetActiveProcess();
cerr << endl << process->GetName() << ":" << endl;
m_kernel.m_debugging = true;
}
string name = GetFQN();
cerr << "[" << right << dec << setfill('0') << setw(8) << m_kernel.GetCycleNo() << ":" << name << "] ";
va_start(args, msg);
vfprintf(stderr, msg, args);
va_end(args);
cerr << endl;
}
void Object::DebugSimWrite_(const char* msg, ...) const
{
va_list args;
string name = GetFQN();
cerr << "[" << right << dec << setfill('0') << setw(8) << m_kernel.GetCycleNo() << ":" << name << "] ";
va_start(args, msg);
vfprintf(stderr, msg, args);
va_end(args);
cerr << endl;
}
//
// Kernel class
//
void Kernel::Abort()
{
m_aborted = true;
}
// Returns the Greatest Common Denominator of a and b.
static unsigned long long gcd(unsigned long long a, unsigned long long b)
{
// Euclid's algorithm
while (b != 0){
unsigned long long t = b;
b = a % b;
a = t;
}
return a;
}
// Returns the Lowest Common Multiple of a and b.
unsigned long long lcm(unsigned long long a, unsigned long long b)
{
return (a * b / gcd(a,b));
}
Clock& Kernel::CreateClock(unsigned long frequency)
{
// We only allow creating clocks before the simulation starts
assert(m_cycle == 0);
// Gotta be at least 1 MHz
assert(frequency > 0);
frequency = std::max(1UL, frequency);
/*
Calculate new master frequency:
If we have clocks of frequency [f_1, ..., f_n], we want a frequency
that allows every cycle time to be an integer multiple of the master
cycle time (e.g., a 300 MHz and 400 MHz clock would create a master
clock of 1200 MHz, where the 300 MHz clock ticks once every 4 cycles
and the 400 MHz clock ticks once every 3 cycles).
This is simply equalizing fractions. e.g., 1/300 and 1/400 becomes
4/1200 and 3/1200.
Also, see if we already have this clock.
*/
unsigned long long master_freq = 1;
for (std::vector<Clock*>::const_iterator p = m_clocks.begin(); p != m_clocks.end(); ++p)
{
if ((*p)->m_frequency == frequency)
{
// We already have this clock, no need to calculate anything.
return **p;
}
// Find Least Common Multiplier of master_freq and this clock's frequency.
master_freq = lcm(master_freq, (*p)->m_frequency);
}
master_freq = lcm(master_freq, frequency);
if (m_master_freq != master_freq)
{
// The master frequency changed, update the clock periods
m_master_freq = master_freq;
for (std::vector<Clock*>::const_iterator p = m_clocks.begin(); p != m_clocks.end(); ++p)
{
assert(m_master_freq % (*p)->m_frequency == 0);
(*p)->m_period = m_master_freq / (*p)->m_frequency;
}
}
assert(m_master_freq % frequency == 0);
m_clocks.push_back(new Clock(*this, frequency, m_master_freq / frequency));
return *m_clocks.back();
}
RunState Kernel::Step(CycleNo cycles)
{
try
{
// Time to simulate until
const CycleNo endcycle = (cycles == INFINITE_CYCLES) ? cycles : m_cycle + cycles;
if (m_cycle == 0)
{
// Update any changed storages.
// This is just to effect the initialization writes,
// in order to activate the initial processes.
UpdateStorages();
}
// Advance time to the first clock to run.
if (m_activeClocks != NULL)
{
assert(m_activeClocks->m_cycle >= m_cycle);
m_cycle = m_activeClocks->m_cycle;
}
m_aborted = false;
bool idle = false;
while (!m_aborted && !idle && (endcycle == INFINITE_CYCLES || m_cycle < endcycle))
{
// We start each cycle being idle, and see if we did something this cycle
idle = true;
//
// Acquire phase
//
m_phase = PHASE_ACQUIRE;
for (Clock* clock = m_activeClocks; clock != NULL && m_cycle == clock->m_cycle; clock = clock->m_next)
{
for (Process* process = clock->m_activeProcesses; process != NULL; process = process->m_next)
{
m_process = process;
m_debugging = false; // Will be used by DeadlockWrite() for process-seperating newlines
// If we fail in the acquire stage, don't bother with the check and commit stages
process->m_state = (process->m_delegate() == FAILED)
? STATE_DEADLOCK
: STATE_RUNNING;
}
}
//
// Arbitrate phase
//
for (Clock* clock = m_activeClocks; clock != NULL && m_cycle == clock->m_cycle; clock = clock->m_next)
{
for (Arbitrator* arbitrator = clock->m_activeArbitrators; arbitrator != NULL; arbitrator = arbitrator->m_next)
{
arbitrator->OnArbitrate();
arbitrator->m_activated = false;
}
clock->m_activeArbitrators = NULL;
}
//
// Commit phase
//
for (Clock* clock = m_activeClocks; clock != NULL && m_cycle == clock->m_cycle; clock = clock->m_next)
{
for (Process* process = clock->m_activeProcesses; process != NULL; process = process->m_next)
{
if (process->m_state != STATE_DEADLOCK)
{
m_process = process;
m_phase = PHASE_CHECK;
m_debugging = false; // Will be used by DeadlockWrite() for process-seperating newlines
Result result;
if ((result = process->m_delegate()) == SUCCESS)
{
m_phase = PHASE_COMMIT;
result = process->m_delegate();
// If the CHECK succeeded, the COMMIT cannot fail
assert(result == SUCCESS);
process->m_state = STATE_RUNNING;
// We've done something -- we're not idle
idle = false;
}
else
{
// If a process has nothing to do (DELAYED) it shouldn't have been
// called in the first place.
assert(result == FAILED);
process->m_state = STATE_DEADLOCK;
}
}
}
}
// Process the requested storage updates
// This can activate or deactivate processes due to changes in storages
// made by processes run in this cycle.
if (UpdateStorages())
{
// We've update at least one storage
idle = false;
}
if (idle)
{
// We haven't done anything this cycle. Check if there are clocks scheduled
// for cycles in the future. If so, we want to still advance the simulation.
for (Clock* clock = m_activeClocks; clock != NULL; clock = clock->m_next)
{
if (clock->m_cycle > m_cycle)
{
idle = false;
break;
}
}
}
if (Display::GetDisplay())
Display::GetDisplay()->OnCycle(m_cycle);
if (!idle)
{
// Advance the simulation
// Update the clocks
for (Clock *next, *clock = m_activeClocks; clock != NULL && m_cycle == clock->m_cycle; clock = next)
{
next = clock->m_next;
// We ran this clock, remove it from the queue
m_activeClocks = clock->m_next;
clock->m_activated = false;
assert(clock->m_activeArbitrators == NULL);
if (clock->m_activeProcesses != NULL || clock->m_activeStorages != NULL)
{
// This clock still has active components, reschedule it
ActivateClock(*clock);
}
}
// Advance time to first clock to run
if (m_activeClocks != NULL)
{
assert(m_activeClocks->m_cycle > m_cycle);
m_cycle = m_activeClocks->m_cycle;
}
}
}
// In case we overshot the end with the last update
m_cycle = std::min(m_cycle, endcycle);
return (m_aborted)
? STATE_ABORTED
: idle ? STATE_IDLE : STATE_RUNNING;
}
catch (SimulationException& e)
{
// Add information about what component/state we were executing
stringstream details;
details << "While executing process " << m_process->GetName() << endl;
e.AddDetails(details.str());
throw;
}
}
void Kernel::ActivateClock(Clock& clock)
{
if (!clock.m_activated)
{
// Calculate new activation time for clock
clock.m_cycle = (m_cycle / clock.m_period) * clock.m_period + clock.m_period;
// Insert clock into list based on activation time (earliest in front)
Clock **before = &m_activeClocks, *after = m_activeClocks;
while (after != NULL && after->m_cycle < clock.m_cycle)
{
before = &after->m_next;
after = after->m_next;
}
*before = &clock;
clock.m_next = after;
clock.m_activated = true;
}
}
bool Kernel::UpdateStorages()
{
bool updated = false;
for (Clock* clock = m_activeClocks; clock != NULL && m_cycle == clock->m_cycle; clock = clock->m_next)
{
for (Storage *s = clock->m_activeStorages; s != NULL; s = s->m_next)
{
s->Update();
s->m_activated = false;
updated = true;
}
clock->m_activeStorages = NULL;
}
return updated;
}
void Clock::ActivateProcess(Process& process)
{
if (++process.m_activations == 1)
{
// First time this process has been activated, queue it
process.m_next = m_activeProcesses;
process.m_pPrev = &m_activeProcesses;
if (process.m_next != NULL) {
process.m_next->m_pPrev = &process.m_next;
}
m_activeProcesses = &process;
process.m_state = STATE_ACTIVE;
m_kernel.ActivateClock(*this);
}
}
void Kernel::SetDebugMode(int flags)
{
m_debugMode = flags;
}
void Kernel::ToggleDebugMode(int flags)
{
m_debugMode ^= flags;
}
Kernel::Kernel(SymbolTable& symtable, BreakPoints& breakpoints)
: m_debugMode(0),
m_cycle(0),
m_symtable(symtable),
m_breakpoints(breakpoints),
m_phase(PHASE_COMMIT),
m_master_freq(0),
m_process(NULL),
m_activeClocks(NULL)
{
RegisterSampleVariable(m_cycle, "kernel.cycle", SVC_CUMULATIVE);
RegisterSampleVariable(m_phase, "kernel.phase", SVC_STATE);
}
Kernel::~Kernel()
{
for (size_t i = 0; i < m_clocks.size(); ++i)
{
delete m_clocks[i];
}
}
}
<commit_msg>[mgsim-refactor] Embed the current master cycle counter in exception reports.<commit_after>#include "kernel.h"
#include "storage.h"
#include "arch/dev/Display.h"
#include "sampling.h"
#include <cassert>
#include <algorithm>
#include <cstdarg>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <set>
#include <map>
#include <cstdio>
using namespace std;
namespace Simulator
{
//
// Process class
//
std::string Process::GetName() const
{
return GetObject()->GetFQN() + ":" + m_name;
}
void Process::Deactivate()
{
// A process can be sensitive to multiple objects, so we only remove it from the list
// if the count becomes zero
if (--m_activations == 0)
{
// Remove the handle node from the list
*m_pPrev = m_next;
if (m_next != NULL) {
m_next->m_pPrev = m_pPrev;
}
m_state = STATE_IDLE;
}
}
//
// Object class
//
Object::Object(const std::string& name, Clock& clock)
: m_parent(NULL), m_name(name), m_fqn(name), m_clock(clock), m_kernel(clock.GetKernel())
{
}
Object::Object(const std::string& name, Object& parent)
: m_parent(&parent),
m_name(name),
m_fqn(parent.GetFQN() + '.' + name),
m_clock(parent.m_clock),
m_kernel(m_clock.GetKernel())
{
// Add ourself to the parent's children array
parent.m_children.push_back(this);
}
Object::Object(const std::string& name, Object& parent, Clock& clock)
: m_parent(&parent),
m_name(name),
m_fqn(parent.GetFQN() + '.' + name),
m_clock(clock),
m_kernel(clock.GetKernel())
{
// Add ourself to the parent's children array
parent.m_children.push_back(this);
}
Object::~Object()
{
if (m_parent != NULL)
{
// Remove ourself from the parent's children array
for (vector<Object*>::iterator p = m_parent->m_children.begin(); p != m_parent->m_children.end(); ++p)
{
if (*p == this)
{
m_parent->m_children.erase(p);
break;
}
}
}
}
void Object::OutputWrite_(const char* msg, ...) const
{
va_list args;
string name = GetFQN();
cerr << "[" << right << dec << setfill('0') << setw(8) << m_kernel.GetCycleNo() << ":" << name << "] ";
va_start(args, msg);
vfprintf(stderr, msg, args);
va_end(args);
cerr << endl;
}
void Object::DeadlockWrite_(const char* msg, ...) const
{
va_list args;
if (!m_kernel.m_debugging) {
const Process* process = m_kernel.GetActiveProcess();
cerr << endl << process->GetName() << ":" << endl;
m_kernel.m_debugging = true;
}
string name = GetFQN();
cerr << "[" << right << dec << setfill('0') << setw(8) << m_kernel.GetCycleNo() << ":" << name << "] ";
va_start(args, msg);
vfprintf(stderr, msg, args);
va_end(args);
cerr << endl;
}
void Object::DebugSimWrite_(const char* msg, ...) const
{
va_list args;
string name = GetFQN();
cerr << "[" << right << dec << setfill('0') << setw(8) << m_kernel.GetCycleNo() << ":" << name << "] ";
va_start(args, msg);
vfprintf(stderr, msg, args);
va_end(args);
cerr << endl;
}
//
// Kernel class
//
void Kernel::Abort()
{
m_aborted = true;
}
// Returns the Greatest Common Denominator of a and b.
static unsigned long long gcd(unsigned long long a, unsigned long long b)
{
// Euclid's algorithm
while (b != 0){
unsigned long long t = b;
b = a % b;
a = t;
}
return a;
}
// Returns the Lowest Common Multiple of a and b.
unsigned long long lcm(unsigned long long a, unsigned long long b)
{
return (a * b / gcd(a,b));
}
Clock& Kernel::CreateClock(unsigned long frequency)
{
// We only allow creating clocks before the simulation starts
assert(m_cycle == 0);
// Gotta be at least 1 MHz
assert(frequency > 0);
frequency = std::max(1UL, frequency);
/*
Calculate new master frequency:
If we have clocks of frequency [f_1, ..., f_n], we want a frequency
that allows every cycle time to be an integer multiple of the master
cycle time (e.g., a 300 MHz and 400 MHz clock would create a master
clock of 1200 MHz, where the 300 MHz clock ticks once every 4 cycles
and the 400 MHz clock ticks once every 3 cycles).
This is simply equalizing fractions. e.g., 1/300 and 1/400 becomes
4/1200 and 3/1200.
Also, see if we already have this clock.
*/
unsigned long long master_freq = 1;
for (std::vector<Clock*>::const_iterator p = m_clocks.begin(); p != m_clocks.end(); ++p)
{
if ((*p)->m_frequency == frequency)
{
// We already have this clock, no need to calculate anything.
return **p;
}
// Find Least Common Multiplier of master_freq and this clock's frequency.
master_freq = lcm(master_freq, (*p)->m_frequency);
}
master_freq = lcm(master_freq, frequency);
if (m_master_freq != master_freq)
{
// The master frequency changed, update the clock periods
m_master_freq = master_freq;
for (std::vector<Clock*>::const_iterator p = m_clocks.begin(); p != m_clocks.end(); ++p)
{
assert(m_master_freq % (*p)->m_frequency == 0);
(*p)->m_period = m_master_freq / (*p)->m_frequency;
}
}
assert(m_master_freq % frequency == 0);
m_clocks.push_back(new Clock(*this, frequency, m_master_freq / frequency));
return *m_clocks.back();
}
RunState Kernel::Step(CycleNo cycles)
{
try
{
// Time to simulate until
const CycleNo endcycle = (cycles == INFINITE_CYCLES) ? cycles : m_cycle + cycles;
if (m_cycle == 0)
{
// Update any changed storages.
// This is just to effect the initialization writes,
// in order to activate the initial processes.
UpdateStorages();
}
// Advance time to the first clock to run.
if (m_activeClocks != NULL)
{
assert(m_activeClocks->m_cycle >= m_cycle);
m_cycle = m_activeClocks->m_cycle;
}
m_aborted = false;
bool idle = false;
while (!m_aborted && !idle && (endcycle == INFINITE_CYCLES || m_cycle < endcycle))
{
// We start each cycle being idle, and see if we did something this cycle
idle = true;
//
// Acquire phase
//
m_phase = PHASE_ACQUIRE;
for (Clock* clock = m_activeClocks; clock != NULL && m_cycle == clock->m_cycle; clock = clock->m_next)
{
for (Process* process = clock->m_activeProcesses; process != NULL; process = process->m_next)
{
m_process = process;
m_debugging = false; // Will be used by DeadlockWrite() for process-seperating newlines
// If we fail in the acquire stage, don't bother with the check and commit stages
process->m_state = (process->m_delegate() == FAILED)
? STATE_DEADLOCK
: STATE_RUNNING;
}
}
//
// Arbitrate phase
//
for (Clock* clock = m_activeClocks; clock != NULL && m_cycle == clock->m_cycle; clock = clock->m_next)
{
for (Arbitrator* arbitrator = clock->m_activeArbitrators; arbitrator != NULL; arbitrator = arbitrator->m_next)
{
arbitrator->OnArbitrate();
arbitrator->m_activated = false;
}
clock->m_activeArbitrators = NULL;
}
//
// Commit phase
//
for (Clock* clock = m_activeClocks; clock != NULL && m_cycle == clock->m_cycle; clock = clock->m_next)
{
for (Process* process = clock->m_activeProcesses; process != NULL; process = process->m_next)
{
if (process->m_state != STATE_DEADLOCK)
{
m_process = process;
m_phase = PHASE_CHECK;
m_debugging = false; // Will be used by DeadlockWrite() for process-seperating newlines
Result result;
if ((result = process->m_delegate()) == SUCCESS)
{
m_phase = PHASE_COMMIT;
result = process->m_delegate();
// If the CHECK succeeded, the COMMIT cannot fail
assert(result == SUCCESS);
process->m_state = STATE_RUNNING;
// We've done something -- we're not idle
idle = false;
}
else
{
// If a process has nothing to do (DELAYED) it shouldn't have been
// called in the first place.
assert(result == FAILED);
process->m_state = STATE_DEADLOCK;
}
}
}
}
// Process the requested storage updates
// This can activate or deactivate processes due to changes in storages
// made by processes run in this cycle.
if (UpdateStorages())
{
// We've update at least one storage
idle = false;
}
if (idle)
{
// We haven't done anything this cycle. Check if there are clocks scheduled
// for cycles in the future. If so, we want to still advance the simulation.
for (Clock* clock = m_activeClocks; clock != NULL; clock = clock->m_next)
{
if (clock->m_cycle > m_cycle)
{
idle = false;
break;
}
}
}
if (Display::GetDisplay())
Display::GetDisplay()->OnCycle(m_cycle);
if (!idle)
{
// Advance the simulation
// Update the clocks
for (Clock *next, *clock = m_activeClocks; clock != NULL && m_cycle == clock->m_cycle; clock = next)
{
next = clock->m_next;
// We ran this clock, remove it from the queue
m_activeClocks = clock->m_next;
clock->m_activated = false;
assert(clock->m_activeArbitrators == NULL);
if (clock->m_activeProcesses != NULL || clock->m_activeStorages != NULL)
{
// This clock still has active components, reschedule it
ActivateClock(*clock);
}
}
// Advance time to first clock to run
if (m_activeClocks != NULL)
{
assert(m_activeClocks->m_cycle > m_cycle);
m_cycle = m_activeClocks->m_cycle;
}
}
}
// In case we overshot the end with the last update
m_cycle = std::min(m_cycle, endcycle);
return (m_aborted)
? STATE_ABORTED
: idle ? STATE_IDLE : STATE_RUNNING;
}
catch (SimulationException& e)
{
// Add information about what component/state we were executing
stringstream details;
details << "While executing process " << m_process->GetName() << endl
<< "At master cycle " << m_cycle << endl;
e.AddDetails(details.str());
throw;
}
}
void Kernel::ActivateClock(Clock& clock)
{
if (!clock.m_activated)
{
// Calculate new activation time for clock
clock.m_cycle = (m_cycle / clock.m_period) * clock.m_period + clock.m_period;
// Insert clock into list based on activation time (earliest in front)
Clock **before = &m_activeClocks, *after = m_activeClocks;
while (after != NULL && after->m_cycle < clock.m_cycle)
{
before = &after->m_next;
after = after->m_next;
}
*before = &clock;
clock.m_next = after;
clock.m_activated = true;
}
}
bool Kernel::UpdateStorages()
{
bool updated = false;
for (Clock* clock = m_activeClocks; clock != NULL && m_cycle == clock->m_cycle; clock = clock->m_next)
{
for (Storage *s = clock->m_activeStorages; s != NULL; s = s->m_next)
{
s->Update();
s->m_activated = false;
updated = true;
}
clock->m_activeStorages = NULL;
}
return updated;
}
void Clock::ActivateProcess(Process& process)
{
if (++process.m_activations == 1)
{
// First time this process has been activated, queue it
process.m_next = m_activeProcesses;
process.m_pPrev = &m_activeProcesses;
if (process.m_next != NULL) {
process.m_next->m_pPrev = &process.m_next;
}
m_activeProcesses = &process;
process.m_state = STATE_ACTIVE;
m_kernel.ActivateClock(*this);
}
}
void Kernel::SetDebugMode(int flags)
{
m_debugMode = flags;
}
void Kernel::ToggleDebugMode(int flags)
{
m_debugMode ^= flags;
}
Kernel::Kernel(SymbolTable& symtable, BreakPoints& breakpoints)
: m_debugMode(0),
m_cycle(0),
m_symtable(symtable),
m_breakpoints(breakpoints),
m_phase(PHASE_COMMIT),
m_master_freq(0),
m_process(NULL),
m_activeClocks(NULL)
{
RegisterSampleVariable(m_cycle, "kernel.cycle", SVC_CUMULATIVE);
RegisterSampleVariable(m_phase, "kernel.phase", SVC_STATE);
}
Kernel::~Kernel()
{
for (size_t i = 0; i < m_clocks.size(); ++i)
{
delete m_clocks[i];
}
}
}
<|endoftext|>
|
<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <gtest/gtest.h>
#include "SurgSim/Collision/ContactCalculation.h"
#include "SurgSim/Collision/ShapeCollisionRepresentation.h"
#include "SurgSim/Collision/SpherePlaneDcdContact.h"
#include "SurgSim/Math/SphereShape.h"
#include "SurgSim/Math/PlaneShape.h"
#include "SurgSim/Math/Vector.h"
#include "SurgSim/Math/Quaternion.h"
#include "SurgSim/Math/RigidTransform.h"
using SurgSim::Math::Vector3d;
using SurgSim::Math::Quaterniond;
using SurgSim::Math::RigidTransform3d;
using SurgSim::Math::PlaneShape;
using SurgSim::Math::SphereShape;
namespace SurgSim
{
namespace Collision
{
TEST(RepresentationTest, ZeroContactTest)
{
std::shared_ptr<PlaneShape> plane = std::make_shared<PlaneShape>();
std::shared_ptr<SphereShape> sphere = std::make_shared<SphereShape>(1.0);
std::shared_ptr<Representation> planeRep = std::make_shared<ShapeCollisionRepresentation>(
"Plane Shape", plane, SurgSim::Math::makeRigidTransform(Quaterniond::Identity(), Vector3d::Zero()));
std::shared_ptr<Representation> sphereRep = std::make_shared<ShapeCollisionRepresentation>(
"Sphere Shape",sphere, SurgSim::Math::makeRigidTransform(Quaterniond::Identity(), Vector3d(0.0, 2.0, 0.0)));
std::shared_ptr<CollisionPair> pairSP = std::make_shared<CollisionPair>(sphereRep, planeRep);
std::shared_ptr<SpherePlaneDcdContact> calContact = std::make_shared<SpherePlaneDcdContact>();
calContact->calculateContact(pairSP);
auto contactReps = planeRep->getContacts();
// Expect the plane has one contact in the contact list
EXPECT_EQ(1u, contactReps.size());
// Expect the plane is in contact with the sphere
auto
EXPECT_EQ();
}
}
TEST(ContactCalculation, DidContactTest)
{
}
}; // namespace Collision
}; // namespace SurgSim
<commit_msg>Remove unit test for SurgSim::Collision::Representation<commit_after><|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Designer of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "mainwindow.h"
#include "qdesigner.h"
#include "qdesigner_actions.h"
#include "qdesigner_workbench.h"
#include "qdesigner_formwindow.h"
#include "qdesigner_toolwindow.h"
#include "qdesigner_settings.h"
#include "qttoolbardialog.h"
#include <QtDesigner/QDesignerFormWindowInterface>
#include <QtWidgets/QAction>
#include <QtGui/QCloseEvent>
#include <QtWidgets/QToolBar>
#include <QtWidgets/QMdiSubWindow>
#include <QtWidgets/QStatusBar>
#include <QtWidgets/QMenu>
#include <QtWidgets/QLayout>
#include <QtWidgets/QDockWidget>
#include <QtCore/QUrl>
#include <QtCore/QDebug>
#include <QtCore/QMimeData>
static const char *uriListMimeFormatC = "text/uri-list";
QT_BEGIN_NAMESPACE
typedef QList<QAction *> ActionList;
// Helpers for creating toolbars and menu
static void addActionsToToolBar(const ActionList &actions, QToolBar *t)
{
const ActionList::const_iterator cend = actions.constEnd();
for (ActionList::const_iterator it = actions.constBegin(); it != cend; ++it) {
QAction *action = *it;
if (action->property(QDesignerActions::defaultToolbarPropertyName).toBool())
t->addAction(action);
}
}
static QToolBar *createToolBar(const QString &title, const QString &objectName, const ActionList &actions)
{
QToolBar *rc = new QToolBar;
rc->setObjectName(objectName);
rc->setWindowTitle(title);
addActionsToToolBar(actions, rc);
return rc;
}
// ---------------- MainWindowBase
MainWindowBase::MainWindowBase(QWidget *parent, Qt::WindowFlags flags) :
QMainWindow(parent, flags),
m_policy(AcceptCloseEvents)
{
#ifndef Q_OS_MAC
setWindowIcon(qDesigner->windowIcon());
#endif
}
void MainWindowBase::closeEvent(QCloseEvent *e)
{
switch (m_policy) {
case AcceptCloseEvents:
QMainWindow::closeEvent(e);
break;
case EmitCloseEventSignal:
emit closeEventReceived(e);
break;
}
}
QList<QToolBar *> MainWindowBase::createToolBars(const QDesignerActions *actions, bool singleToolBar)
{
// Note that whenever you want to add a new tool bar here, you also have to update the default
// action groups added to the toolbar manager in the mainwindow constructor
QList<QToolBar *> rc;
if (singleToolBar) {
//: Not currently used (main tool bar)
QToolBar *main = createToolBar(tr("Main"), QStringLiteral("mainToolBar"), actions->fileActions()->actions());
addActionsToToolBar(actions->editActions()->actions(), main);
addActionsToToolBar(actions->toolActions()->actions(), main);
addActionsToToolBar(actions->formActions()->actions(), main);
rc.push_back(main);
} else {
rc.push_back(createToolBar(tr("File"), QStringLiteral("fileToolBar"), actions->fileActions()->actions()));
rc.push_back(createToolBar(tr("Edit"), QStringLiteral("editToolBar"), actions->editActions()->actions()));
rc.push_back(createToolBar(tr("Tools"), QStringLiteral("toolsToolBar"), actions->toolActions()->actions()));
rc.push_back(createToolBar(tr("Form"), QStringLiteral("formToolBar"), actions->formActions()->actions()));
}
return rc;
}
QString MainWindowBase::mainWindowTitle()
{
return tr("Qt Designer");
}
// Use the minor Qt version as settings versions to avoid conflicts
int MainWindowBase::settingsVersion()
{
const int version = QT_VERSION;
return (version & 0x00FF00) >> 8;
}
// ----------------- DockedMdiArea
DockedMdiArea::DockedMdiArea(const QString &extension, QWidget *parent) :
QMdiArea(parent),
m_extension(extension)
{
setAcceptDrops(true);
setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
}
QStringList DockedMdiArea::uiFiles(const QMimeData *d) const
{
// Extract dropped UI files from Mime data.
QStringList rc;
if (!d->hasFormat(QLatin1String(uriListMimeFormatC)))
return rc;
const QList<QUrl> urls = d->urls();
if (urls.empty())
return rc;
const QList<QUrl>::const_iterator cend = urls.constEnd();
for (QList<QUrl>::const_iterator it = urls.constBegin(); it != cend; ++it) {
const QString fileName = it->toLocalFile();
if (!fileName.isEmpty() && fileName.endsWith(m_extension))
rc.push_back(fileName);
}
return rc;
}
bool DockedMdiArea::event(QEvent *event)
{
// Listen for desktop file manager drop and emit a signal once a file is
// dropped.
switch (event->type()) {
case QEvent::DragEnter: {
QDragEnterEvent *e = static_cast<QDragEnterEvent*>(event);
if (!uiFiles(e->mimeData()).empty()) {
e->acceptProposedAction();
return true;
}
}
break;
case QEvent::Drop: {
QDropEvent *e = static_cast<QDropEvent*>(event);
const QStringList files = uiFiles(e->mimeData());
const QStringList::const_iterator cend = files.constEnd();
for (QStringList::const_iterator it = files.constBegin(); it != cend; ++it) {
emit fileDropped(*it);
}
e->acceptProposedAction();
return true;
}
break;
default:
break;
}
return QMdiArea::event(event);
}
// ------------- ToolBarManager:
static void addActionsToToolBarManager(const ActionList &al, const QString &title, QtToolBarManager *tbm)
{
const ActionList::const_iterator cend = al.constEnd();
for (ActionList::const_iterator it = al.constBegin(); it != cend; ++it)
tbm->addAction(*it, title);
}
ToolBarManager::ToolBarManager(QMainWindow *configureableMainWindow,
QWidget *parent,
QMenu *toolBarMenu,
const QDesignerActions *actions,
const QList<QToolBar *> &toolbars,
const QList<QDesignerToolWindow*> &toolWindows) :
QObject(parent),
m_configureableMainWindow(configureableMainWindow),
m_parent(parent),
m_toolBarMenu(toolBarMenu),
m_manager(new QtToolBarManager(this)),
m_configureAction(new QAction(tr("Configure Toolbars..."), this)),
m_toolbars(toolbars)
{
m_configureAction->setMenuRole(QAction::NoRole);
m_configureAction->setObjectName(QStringLiteral("__qt_configure_tool_bars_action"));
connect(m_configureAction, SIGNAL(triggered()), this, SLOT(configureToolBars()));
m_manager->setMainWindow(configureableMainWindow);
foreach(QToolBar *tb, m_toolbars) {
const QString title = tb->windowTitle();
m_manager->addToolBar(tb, title);
addActionsToToolBarManager(tb->actions(), title, m_manager);
}
addActionsToToolBarManager(actions->windowActions()->actions(), tr("Window"), m_manager);
addActionsToToolBarManager(actions->helpActions()->actions(), tr("Help"), m_manager);
// Filter out the device profile preview actions which have int data().
ActionList previewActions = actions->styleActions()->actions();
ActionList::iterator it = previewActions.begin();
for ( ; (*it)->isSeparator() || (*it)->data().type() == QVariant::Int; ++it) ;
previewActions.erase(previewActions.begin(), it);
addActionsToToolBarManager(previewActions, tr("Style"), m_manager);
const QString dockTitle = tr("Dock views");
foreach (QDesignerToolWindow *tw, toolWindows) {
if (QAction *action = tw->action())
m_manager->addAction(action, dockTitle);
}
QString category(tr("File"));
foreach(QAction *action, actions->fileActions()->actions())
m_manager->addAction(action, category);
category = tr("Edit");
foreach(QAction *action, actions->editActions()->actions())
m_manager->addAction(action, category);
category = tr("Tools");
foreach(QAction *action, actions->toolActions()->actions())
m_manager->addAction(action, category);
category = tr("Form");
foreach(QAction *action, actions->formActions()->actions())
m_manager->addAction(action, category);
m_manager->addAction(m_configureAction, tr("Toolbars"));
updateToolBarMenu();
}
// sort function for sorting tool bars alphabetically by title [non-static since called from template]
bool toolBarTitleLessThan(const QToolBar *t1, const QToolBar *t2)
{
return t1->windowTitle() < t2->windowTitle();
}
void ToolBarManager::updateToolBarMenu()
{
// Sort tool bars alphabetically by title
qStableSort(m_toolbars.begin(), m_toolbars.end(), toolBarTitleLessThan);
// add to menu
m_toolBarMenu->clear();
foreach (QToolBar *tb, m_toolbars)
m_toolBarMenu->addAction(tb->toggleViewAction());
m_toolBarMenu->addAction(m_configureAction);
}
void ToolBarManager::configureToolBars()
{
QtToolBarDialog dlg(m_parent);
dlg.setWindowFlags(dlg.windowFlags() & ~Qt::WindowContextHelpButtonHint);
dlg.setToolBarManager(m_manager);
dlg.exec();
updateToolBarMenu();
}
QByteArray ToolBarManager::saveState(int version) const
{
return m_manager->saveState(version);
}
bool ToolBarManager::restoreState(const QByteArray &state, int version)
{
return m_manager->restoreState(state, version);
}
// ---------- DockedMainWindow
DockedMainWindow::DockedMainWindow(QDesignerWorkbench *wb,
QMenu *toolBarMenu,
const QList<QDesignerToolWindow*> &toolWindows) :
m_toolBarManager(0)
{
setObjectName(QStringLiteral("MDIWindow"));
setWindowTitle(mainWindowTitle());
const QList<QToolBar *> toolbars = createToolBars(wb->actionManager(), false);
foreach (QToolBar *tb, toolbars)
addToolBar(tb);
DockedMdiArea *dma = new DockedMdiArea(wb->actionManager()->uiExtension());
connect(dma, SIGNAL(fileDropped(QString)),
this, SIGNAL(fileDropped(QString)));
connect(dma, SIGNAL(subWindowActivated(QMdiSubWindow*)),
this, SLOT(slotSubWindowActivated(QMdiSubWindow*)));
setCentralWidget(dma);
QStatusBar *sb = statusBar();
Q_UNUSED(sb)
m_toolBarManager = new ToolBarManager(this, this, toolBarMenu, wb->actionManager(), toolbars, toolWindows);
}
QMdiArea *DockedMainWindow::mdiArea() const
{
return static_cast<QMdiArea *>(centralWidget());
}
void DockedMainWindow::slotSubWindowActivated(QMdiSubWindow* subWindow)
{
if (subWindow) {
QWidget *widget = subWindow->widget();
if (QDesignerFormWindow *fw = qobject_cast<QDesignerFormWindow*>(widget)) {
emit formWindowActivated(fw);
mdiArea()->setActiveSubWindow(subWindow);
}
}
}
// Create a MDI subwindow for the form.
QMdiSubWindow *DockedMainWindow::createMdiSubWindow(QWidget *fw, Qt::WindowFlags f, const QKeySequence &designerCloseActionShortCut)
{
QMdiSubWindow *rc = mdiArea()->addSubWindow(fw, f);
// Make action shortcuts respond only if focused to avoid conflicts with
// designer menu actions
if (designerCloseActionShortCut == QKeySequence(QKeySequence::Close)) {
const ActionList systemMenuActions = rc->systemMenu()->actions();
if (!systemMenuActions.empty()) {
const ActionList::const_iterator cend = systemMenuActions.constEnd();
for (ActionList::const_iterator it = systemMenuActions.constBegin(); it != cend; ++it) {
if ( (*it)->shortcut() == designerCloseActionShortCut) {
(*it)->setShortcutContext(Qt::WidgetShortcut);
break;
}
}
}
}
return rc;
}
DockedMainWindow::DockWidgetList DockedMainWindow::addToolWindows(const DesignerToolWindowList &tls)
{
DockWidgetList rc;
foreach (QDesignerToolWindow *tw, tls) {
QDockWidget *dockWidget = new QDockWidget;
dockWidget->setObjectName(tw->objectName() + QStringLiteral("_dock"));
dockWidget->setWindowTitle(tw->windowTitle());
addDockWidget(tw->dockWidgetAreaHint(), dockWidget);
dockWidget->setWidget(tw);
rc.push_back(dockWidget);
}
return rc;
}
// Settings consist of MainWindow state and tool bar manager state
void DockedMainWindow::restoreSettings(const QDesignerSettings &s, const DockWidgetList &dws, const QRect &desktopArea)
{
const int version = settingsVersion();
m_toolBarManager->restoreState(s.toolBarsState(DockedMode), version);
// If there are no old geometry settings, show the window maximized
s.restoreGeometry(this, QRect(desktopArea.topLeft(), QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX)));
const QByteArray mainWindowState = s.mainWindowState(DockedMode);
const bool restored = !mainWindowState.isEmpty() && restoreState(mainWindowState, version);
if (!restored) {
// Default: Tabify less relevant windows bottom/right.
tabifyDockWidget(dws.at(QDesignerToolWindow::SignalSlotEditor),
dws.at(QDesignerToolWindow::ActionEditor));
tabifyDockWidget(dws.at(QDesignerToolWindow::ActionEditor),
dws.at(QDesignerToolWindow::ResourceEditor));
}
}
void DockedMainWindow::saveSettings(QDesignerSettings &s) const
{
const int version = settingsVersion();
s.setToolBarsState(DockedMode, m_toolBarManager->saveState(version));
s.saveGeometryFor(this);
s.setMainWindowState(DockedMode, saveState(version));
}
QT_END_NAMESPACE
<commit_msg>Add missing border to the central widget in Designer.<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Designer of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "mainwindow.h"
#include "qdesigner.h"
#include "qdesigner_actions.h"
#include "qdesigner_workbench.h"
#include "qdesigner_formwindow.h"
#include "qdesigner_toolwindow.h"
#include "qdesigner_settings.h"
#include "qttoolbardialog.h"
#include <QtDesigner/QDesignerFormWindowInterface>
#include <QtWidgets/QAction>
#include <QtGui/QCloseEvent>
#include <QtWidgets/QToolBar>
#include <QtWidgets/QMdiSubWindow>
#include <QtWidgets/QStatusBar>
#include <QtWidgets/QMenu>
#include <QtWidgets/QLayout>
#include <QtWidgets/QDockWidget>
#include <QtCore/QUrl>
#include <QtCore/QDebug>
#include <QtCore/QMimeData>
static const char *uriListMimeFormatC = "text/uri-list";
QT_BEGIN_NAMESPACE
typedef QList<QAction *> ActionList;
// Helpers for creating toolbars and menu
static void addActionsToToolBar(const ActionList &actions, QToolBar *t)
{
const ActionList::const_iterator cend = actions.constEnd();
for (ActionList::const_iterator it = actions.constBegin(); it != cend; ++it) {
QAction *action = *it;
if (action->property(QDesignerActions::defaultToolbarPropertyName).toBool())
t->addAction(action);
}
}
static QToolBar *createToolBar(const QString &title, const QString &objectName, const ActionList &actions)
{
QToolBar *rc = new QToolBar;
rc->setObjectName(objectName);
rc->setWindowTitle(title);
addActionsToToolBar(actions, rc);
return rc;
}
// ---------------- MainWindowBase
MainWindowBase::MainWindowBase(QWidget *parent, Qt::WindowFlags flags) :
QMainWindow(parent, flags),
m_policy(AcceptCloseEvents)
{
#ifndef Q_OS_MAC
setWindowIcon(qDesigner->windowIcon());
#endif
}
void MainWindowBase::closeEvent(QCloseEvent *e)
{
switch (m_policy) {
case AcceptCloseEvents:
QMainWindow::closeEvent(e);
break;
case EmitCloseEventSignal:
emit closeEventReceived(e);
break;
}
}
QList<QToolBar *> MainWindowBase::createToolBars(const QDesignerActions *actions, bool singleToolBar)
{
// Note that whenever you want to add a new tool bar here, you also have to update the default
// action groups added to the toolbar manager in the mainwindow constructor
QList<QToolBar *> rc;
if (singleToolBar) {
//: Not currently used (main tool bar)
QToolBar *main = createToolBar(tr("Main"), QStringLiteral("mainToolBar"), actions->fileActions()->actions());
addActionsToToolBar(actions->editActions()->actions(), main);
addActionsToToolBar(actions->toolActions()->actions(), main);
addActionsToToolBar(actions->formActions()->actions(), main);
rc.push_back(main);
} else {
rc.push_back(createToolBar(tr("File"), QStringLiteral("fileToolBar"), actions->fileActions()->actions()));
rc.push_back(createToolBar(tr("Edit"), QStringLiteral("editToolBar"), actions->editActions()->actions()));
rc.push_back(createToolBar(tr("Tools"), QStringLiteral("toolsToolBar"), actions->toolActions()->actions()));
rc.push_back(createToolBar(tr("Form"), QStringLiteral("formToolBar"), actions->formActions()->actions()));
}
return rc;
}
QString MainWindowBase::mainWindowTitle()
{
return tr("Qt Designer");
}
// Use the minor Qt version as settings versions to avoid conflicts
int MainWindowBase::settingsVersion()
{
const int version = QT_VERSION;
return (version & 0x00FF00) >> 8;
}
// ----------------- DockedMdiArea
DockedMdiArea::DockedMdiArea(const QString &extension, QWidget *parent) :
QMdiArea(parent),
m_extension(extension)
{
setFrameStyle(QFrame::StyledPanel | QFrame::Sunken);
setLineWidth(1);
setAcceptDrops(true);
setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
}
QStringList DockedMdiArea::uiFiles(const QMimeData *d) const
{
// Extract dropped UI files from Mime data.
QStringList rc;
if (!d->hasFormat(QLatin1String(uriListMimeFormatC)))
return rc;
const QList<QUrl> urls = d->urls();
if (urls.empty())
return rc;
const QList<QUrl>::const_iterator cend = urls.constEnd();
for (QList<QUrl>::const_iterator it = urls.constBegin(); it != cend; ++it) {
const QString fileName = it->toLocalFile();
if (!fileName.isEmpty() && fileName.endsWith(m_extension))
rc.push_back(fileName);
}
return rc;
}
bool DockedMdiArea::event(QEvent *event)
{
// Listen for desktop file manager drop and emit a signal once a file is
// dropped.
switch (event->type()) {
case QEvent::DragEnter: {
QDragEnterEvent *e = static_cast<QDragEnterEvent*>(event);
if (!uiFiles(e->mimeData()).empty()) {
e->acceptProposedAction();
return true;
}
}
break;
case QEvent::Drop: {
QDropEvent *e = static_cast<QDropEvent*>(event);
const QStringList files = uiFiles(e->mimeData());
const QStringList::const_iterator cend = files.constEnd();
for (QStringList::const_iterator it = files.constBegin(); it != cend; ++it) {
emit fileDropped(*it);
}
e->acceptProposedAction();
return true;
}
break;
default:
break;
}
return QMdiArea::event(event);
}
// ------------- ToolBarManager:
static void addActionsToToolBarManager(const ActionList &al, const QString &title, QtToolBarManager *tbm)
{
const ActionList::const_iterator cend = al.constEnd();
for (ActionList::const_iterator it = al.constBegin(); it != cend; ++it)
tbm->addAction(*it, title);
}
ToolBarManager::ToolBarManager(QMainWindow *configureableMainWindow,
QWidget *parent,
QMenu *toolBarMenu,
const QDesignerActions *actions,
const QList<QToolBar *> &toolbars,
const QList<QDesignerToolWindow*> &toolWindows) :
QObject(parent),
m_configureableMainWindow(configureableMainWindow),
m_parent(parent),
m_toolBarMenu(toolBarMenu),
m_manager(new QtToolBarManager(this)),
m_configureAction(new QAction(tr("Configure Toolbars..."), this)),
m_toolbars(toolbars)
{
m_configureAction->setMenuRole(QAction::NoRole);
m_configureAction->setObjectName(QStringLiteral("__qt_configure_tool_bars_action"));
connect(m_configureAction, SIGNAL(triggered()), this, SLOT(configureToolBars()));
m_manager->setMainWindow(configureableMainWindow);
foreach(QToolBar *tb, m_toolbars) {
const QString title = tb->windowTitle();
m_manager->addToolBar(tb, title);
addActionsToToolBarManager(tb->actions(), title, m_manager);
}
addActionsToToolBarManager(actions->windowActions()->actions(), tr("Window"), m_manager);
addActionsToToolBarManager(actions->helpActions()->actions(), tr("Help"), m_manager);
// Filter out the device profile preview actions which have int data().
ActionList previewActions = actions->styleActions()->actions();
ActionList::iterator it = previewActions.begin();
for ( ; (*it)->isSeparator() || (*it)->data().type() == QVariant::Int; ++it) ;
previewActions.erase(previewActions.begin(), it);
addActionsToToolBarManager(previewActions, tr("Style"), m_manager);
const QString dockTitle = tr("Dock views");
foreach (QDesignerToolWindow *tw, toolWindows) {
if (QAction *action = tw->action())
m_manager->addAction(action, dockTitle);
}
QString category(tr("File"));
foreach(QAction *action, actions->fileActions()->actions())
m_manager->addAction(action, category);
category = tr("Edit");
foreach(QAction *action, actions->editActions()->actions())
m_manager->addAction(action, category);
category = tr("Tools");
foreach(QAction *action, actions->toolActions()->actions())
m_manager->addAction(action, category);
category = tr("Form");
foreach(QAction *action, actions->formActions()->actions())
m_manager->addAction(action, category);
m_manager->addAction(m_configureAction, tr("Toolbars"));
updateToolBarMenu();
}
// sort function for sorting tool bars alphabetically by title [non-static since called from template]
bool toolBarTitleLessThan(const QToolBar *t1, const QToolBar *t2)
{
return t1->windowTitle() < t2->windowTitle();
}
void ToolBarManager::updateToolBarMenu()
{
// Sort tool bars alphabetically by title
qStableSort(m_toolbars.begin(), m_toolbars.end(), toolBarTitleLessThan);
// add to menu
m_toolBarMenu->clear();
foreach (QToolBar *tb, m_toolbars)
m_toolBarMenu->addAction(tb->toggleViewAction());
m_toolBarMenu->addAction(m_configureAction);
}
void ToolBarManager::configureToolBars()
{
QtToolBarDialog dlg(m_parent);
dlg.setWindowFlags(dlg.windowFlags() & ~Qt::WindowContextHelpButtonHint);
dlg.setToolBarManager(m_manager);
dlg.exec();
updateToolBarMenu();
}
QByteArray ToolBarManager::saveState(int version) const
{
return m_manager->saveState(version);
}
bool ToolBarManager::restoreState(const QByteArray &state, int version)
{
return m_manager->restoreState(state, version);
}
// ---------- DockedMainWindow
DockedMainWindow::DockedMainWindow(QDesignerWorkbench *wb,
QMenu *toolBarMenu,
const QList<QDesignerToolWindow*> &toolWindows) :
m_toolBarManager(0)
{
setObjectName(QStringLiteral("MDIWindow"));
setWindowTitle(mainWindowTitle());
const QList<QToolBar *> toolbars = createToolBars(wb->actionManager(), false);
foreach (QToolBar *tb, toolbars)
addToolBar(tb);
DockedMdiArea *dma = new DockedMdiArea(wb->actionManager()->uiExtension());
connect(dma, SIGNAL(fileDropped(QString)),
this, SIGNAL(fileDropped(QString)));
connect(dma, SIGNAL(subWindowActivated(QMdiSubWindow*)),
this, SLOT(slotSubWindowActivated(QMdiSubWindow*)));
setCentralWidget(dma);
QStatusBar *sb = statusBar();
Q_UNUSED(sb)
m_toolBarManager = new ToolBarManager(this, this, toolBarMenu, wb->actionManager(), toolbars, toolWindows);
}
QMdiArea *DockedMainWindow::mdiArea() const
{
return static_cast<QMdiArea *>(centralWidget());
}
void DockedMainWindow::slotSubWindowActivated(QMdiSubWindow* subWindow)
{
if (subWindow) {
QWidget *widget = subWindow->widget();
if (QDesignerFormWindow *fw = qobject_cast<QDesignerFormWindow*>(widget)) {
emit formWindowActivated(fw);
mdiArea()->setActiveSubWindow(subWindow);
}
}
}
// Create a MDI subwindow for the form.
QMdiSubWindow *DockedMainWindow::createMdiSubWindow(QWidget *fw, Qt::WindowFlags f, const QKeySequence &designerCloseActionShortCut)
{
QMdiSubWindow *rc = mdiArea()->addSubWindow(fw, f);
// Make action shortcuts respond only if focused to avoid conflicts with
// designer menu actions
if (designerCloseActionShortCut == QKeySequence(QKeySequence::Close)) {
const ActionList systemMenuActions = rc->systemMenu()->actions();
if (!systemMenuActions.empty()) {
const ActionList::const_iterator cend = systemMenuActions.constEnd();
for (ActionList::const_iterator it = systemMenuActions.constBegin(); it != cend; ++it) {
if ( (*it)->shortcut() == designerCloseActionShortCut) {
(*it)->setShortcutContext(Qt::WidgetShortcut);
break;
}
}
}
}
return rc;
}
DockedMainWindow::DockWidgetList DockedMainWindow::addToolWindows(const DesignerToolWindowList &tls)
{
DockWidgetList rc;
foreach (QDesignerToolWindow *tw, tls) {
QDockWidget *dockWidget = new QDockWidget;
dockWidget->setObjectName(tw->objectName() + QStringLiteral("_dock"));
dockWidget->setWindowTitle(tw->windowTitle());
addDockWidget(tw->dockWidgetAreaHint(), dockWidget);
dockWidget->setWidget(tw);
rc.push_back(dockWidget);
}
return rc;
}
// Settings consist of MainWindow state and tool bar manager state
void DockedMainWindow::restoreSettings(const QDesignerSettings &s, const DockWidgetList &dws, const QRect &desktopArea)
{
const int version = settingsVersion();
m_toolBarManager->restoreState(s.toolBarsState(DockedMode), version);
// If there are no old geometry settings, show the window maximized
s.restoreGeometry(this, QRect(desktopArea.topLeft(), QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX)));
const QByteArray mainWindowState = s.mainWindowState(DockedMode);
const bool restored = !mainWindowState.isEmpty() && restoreState(mainWindowState, version);
if (!restored) {
// Default: Tabify less relevant windows bottom/right.
tabifyDockWidget(dws.at(QDesignerToolWindow::SignalSlotEditor),
dws.at(QDesignerToolWindow::ActionEditor));
tabifyDockWidget(dws.at(QDesignerToolWindow::ActionEditor),
dws.at(QDesignerToolWindow::ResourceEditor));
}
}
void DockedMainWindow::saveSettings(QDesignerSettings &s) const
{
const int version = settingsVersion();
s.setToolBarsState(DockedMode, m_toolBarManager->saveState(version));
s.saveGeometryFor(this);
s.setMainWindowState(DockedMode, saveState(version));
}
QT_END_NAMESPACE
<|endoftext|>
|
<commit_before>namespace mant {
namespace bbob2009 {
class SchwefelFunction : public BlackBoxOptimisationBenchmark2009 {
public:
inline explicit SchwefelFunction(
const unsigned int& numberOfDimensions) noexcept;
inline std::string toString() const noexcept override;
protected:
const arma::Col<double> parameterConditioning_;
inline double getObjectiveValueImplementation(
const arma::Col<double>& parameter) const noexcept override;
#if defined(MANTELLA_USE_PARALLEL)
friend class cereal::access;
template <typename Archive>
void serialize(
Archive& archive) noexcept {
archive(cereal::make_nvp("BlackBoxOptimisationBenchmark2009", cereal::base_class<BlackBoxOptimisationBenchmark2009>(this)));
archive(cereal::make_nvp("numberOfDimensions", numberOfDimensions_));
archive(cereal::make_nvp("parameterReflection", parameterReflection_));
}
template <typename Archive>
static void load_and_construct(
Archive& archive,
cereal::construct<SchwefelFunction>& construct) noexcept {
unsigned int numberOfDimensions;
archive(cereal::make_nvp("numberOfDimensions", numberOfDimensions));
construct(numberOfDimensions);
archive(cereal::make_nvp("BlackBoxOptimisationBenchmark2009", cereal::base_class<BlackBoxOptimisationBenchmark2009>(construct.ptr())));
archive(cereal::make_nvp("parameterReflection", construct->parameterReflection_));
}
#endif
};
//
// Implementation
//
inline SchwefelFunction::SchwefelFunction(
const unsigned int& numberOfDimensions) noexcept
: BlackBoxOptimisationBenchmark2009(numberOfDimensions),
parameterConditioning_(getParameterConditioning(std::sqrt(10.0))) {
// A vector with all elements randomly and uniformly set to either 2 or -2.
setParameterScaling(arma::zeros<arma::Col<double>>(numberOfDimensions_) + (std::bernoulli_distribution(0.5)(Rng::getGenerator()) ? 2.0 : -2.0));
}
inline double SchwefelFunction::getObjectiveValueImplementation(
const arma::Col<double>& parameter) const noexcept {
arma::Col<double> s = parameter;
s.tail(s.n_elem - 1) += 0.25 * (parameter.head(parameter.n_elem - 1) - parameterReflection_.head(parameterReflection_.n_elem - 1));
const arma::Col<double>& z = 100.0 * (parameterConditioning_ % (s - parameterReflection_) + parameterReflection_);
return 0.01 * (418.9828872724339 - arma::mean(z % arma::sin(arma::sqrt(arma::abs(z))))) + 100.0 * getBoundConstraintsValue(z / 100.0);
}
inline std::string SchwefelFunction::toString() const noexcept {
return "schwefel-function";
}
}
}
#if defined(MANTELLA_USE_PARALLEL)
CEREAL_REGISTER_TYPE(mant::bbob2009::SchwefelFunction);
#endif
<commit_msg>Fixed some calculation errors<commit_after>namespace mant {
namespace bbob2009 {
class SchwefelFunction : public BlackBoxOptimisationBenchmark2009 {
public:
inline explicit SchwefelFunction(
const unsigned int& numberOfDimensions) noexcept;
inline std::string toString() const noexcept override;
protected:
const arma::Col<double> parameterConditioning_;
inline double getObjectiveValueImplementation(
const arma::Col<double>& parameter) const noexcept override;
#if defined(MANTELLA_USE_PARALLEL)
friend class cereal::access;
template <typename Archive>
void serialize(
Archive& archive) noexcept {
archive(cereal::make_nvp("BlackBoxOptimisationBenchmark2009", cereal::base_class<BlackBoxOptimisationBenchmark2009>(this)));
archive(cereal::make_nvp("numberOfDimensions", numberOfDimensions_));
archive(cereal::make_nvp("parameterReflection", parameterReflection_));
}
template <typename Archive>
static void load_and_construct(
Archive& archive,
cereal::construct<SchwefelFunction>& construct) noexcept {
unsigned int numberOfDimensions;
archive(cereal::make_nvp("numberOfDimensions", numberOfDimensions));
construct(numberOfDimensions);
archive(cereal::make_nvp("BlackBoxOptimisationBenchmark2009", cereal::base_class<BlackBoxOptimisationBenchmark2009>(construct.ptr())));
archive(cereal::make_nvp("parameterReflection", construct->parameterReflection_));
}
#endif
};
//
// Implementation
//
inline SchwefelFunction::SchwefelFunction(
const unsigned int& numberOfDimensions) noexcept
: BlackBoxOptimisationBenchmark2009(numberOfDimensions),
parameterConditioning_(getParameterConditioning(std::sqrt(10.0))) {
// A vector with all elements randomly and uniformly set to either 2 or -2.
setParameterScaling(arma::zeros<arma::Col<double>>(numberOfDimensions_) + (std::bernoulli_distribution(0.5)(Rng::getGenerator()) ? 2.0 : -2.0));
}
inline double SchwefelFunction::getObjectiveValueImplementation(
const arma::Col<double>& parameter) const noexcept {
arma::Col<double> s = parameter;
s.tail(s.n_elem - 1) += 0.25 * (s.head(s.n_elem - 1) - 4.2096874633);
const arma::Col<double>& z = 100.0 * (parameterConditioning_ % (s - 4.2096874633) + 4.2096874633);
return 0.01 * (418.9828872724339 - arma::mean(z % arma::sin(arma::sqrt(arma::abs(z))))) + 100.0 * getBoundConstraintsValue(z / 100.0);
}
inline std::string SchwefelFunction::toString() const noexcept {
return "schwefel-function";
}
}
}
#if defined(MANTELLA_USE_PARALLEL)
CEREAL_REGISTER_TYPE(mant::bbob2009::SchwefelFunction);
#endif
<|endoftext|>
|
<commit_before>/*
* PBKDF/EMSA/EME/KDF/MGF Retrieval
* (C) 1999-2007 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/
#include <botan/lookup.h>
#include <botan/libstate.h>
#include <botan/scan_name.h>
#if defined(BOTAN_HAS_MGF1)
#include <botan/mgf1.h>
#endif
#if defined(BOTAN_HAS_EMSA1)
#include <botan/emsa1.h>
#endif
#if defined(BOTAN_HAS_EMSA1_BSI)
#include <botan/emsa1_bsi.h>
#endif
#if defined(BOTAN_HAS_EMSA2)
#include <botan/emsa2.h>
#endif
#if defined(BOTAN_HAS_EMSA3)
#include <botan/emsa3.h>
#endif
#if defined(BOTAN_HAS_EMSA4)
#include <botan/emsa4.h>
#endif
#if defined(BOTAN_HAS_EMSA_RAW)
#include <botan/emsa_raw.h>
#endif
#if defined(BOTAN_HAS_EME1)
#include <botan/eme1.h>
#endif
#if defined(BOTAN_HAS_EME_PKCS1v15)
#include <botan/eme_pkcs.h>
#endif
#if defined(BOTAN_HAS_KDF1)
#include <botan/kdf1.h>
#endif
#if defined(BOTAN_HAS_KDF2)
#include <botan/kdf2.h>
#endif
#if defined(BOTAN_HAS_X942_PRF)
#include <botan/prf_x942.h>
#endif
#if defined(BOTAN_HAS_SSL_V3_PRF)
#include <botan/prf_ssl3.h>
#endif
#if defined(BOTAN_HAS_TLS_V10_PRF)
#include <botan/prf_tls.h>
#endif
namespace Botan {
/*
* Get a PBKDF algorithm by name
*/
PBKDF* get_pbkdf(const std::string& algo_spec)
{
Algorithm_Factory& af = global_state().algorithm_factory();
if(PBKDF* pbkdf = af.make_pbkdf(algo_spec))
return pbkdf;
throw Algorithm_Not_Found(algo_spec);
}
/*
* Get an EMSA by name
*/
EMSA* get_emsa(const std::string& algo_spec)
{
SCAN_Name request(algo_spec);
Algorithm_Factory& af = global_state().algorithm_factory();
#if defined(BOTAN_HAS_EMSA_RAW)
if(request.algo_name() == "Raw" && request.arg_count() == 0)
return new EMSA_Raw;
#endif
#if defined(BOTAN_HAS_EMSA1)
if(request.algo_name() == "EMSA1" && request.arg_count() == 1)
{
if(request.arg(0) == "Raw")
return new EMSA_Raw;
return new EMSA1(af.make_hash_function(request.arg(0)));
}
#endif
#if defined(BOTAN_HAS_EMSA1_BSI)
if(request.algo_name() == "EMSA1_BSI" && request.arg_count() == 1)
return new EMSA1_BSI(af.make_hash_function(request.arg(0)));
#endif
#if defined(BOTAN_HAS_EMSA2)
if(request.algo_name() == "EMSA2" && request.arg_count() == 1)
return new EMSA2(af.make_hash_function(request.arg(0)));
#endif
#if defined(BOTAN_HAS_EMSA3)
if(request.algo_name() == "EMSA3" && request.arg_count() == 1)
{
if(request.arg(0) == "Raw")
return new EMSA3_Raw;
return new EMSA3(af.make_hash_function(request.arg(0)));
}
#endif
#if defined(BOTAN_HAS_EMSA4)
if(request.algo_name() == "EMSA4" && request.arg_count_between(1, 3))
{
// 3 args: Hash, MGF, salt size (MGF is hardcoded MGF1 in Botan)
if(request.arg_count() == 1)
return new EMSA4(af.make_hash_function(request.arg(0)));
if(request.arg_count() == 2 && request.arg(1) != "MGF1")
return new EMSA4(af.make_hash_function(request.arg(0)));
if(request.arg_count() == 3)
return new EMSA4(af.make_hash_function(request.arg(0)),
request.arg_as_integer(2, 0));
}
#endif
throw Algorithm_Not_Found(algo_spec);
}
/*
* Get an EME by name
*/
EME* get_eme(const std::string& algo_spec)
{
SCAN_Name request(algo_spec);
Algorithm_Factory& af = global_state().algorithm_factory();
if(request.algo_name() == "Raw")
return 0; // No padding
#if defined(BOTAN_HAS_EME_PKCS1v15)
if(request.algo_name() == "PKCS1v15" && request.arg_count() == 0)
return new EME_PKCS1v15;
#endif
#if defined(BOTAN_HAS_EME1)
if(request.algo_name() == "EME1" && request.arg_count_between(1, 2))
{
if(request.arg_count() == 1 ||
(request.arg_count() == 2 && request.arg(1) == "MGF1"))
{
return new EME1(af.make_hash_function(request.arg(0)));
}
}
#endif
throw Algorithm_Not_Found(algo_spec);
}
/*
* Get an KDF by name
*/
KDF* get_kdf(const std::string& algo_spec)
{
SCAN_Name request(algo_spec);
Algorithm_Factory& af = global_state().algorithm_factory();
if(request.algo_name() == "Raw")
return 0; // No KDF
#if defined(BOTAN_HAS_KDF1)
if(request.algo_name() == "KDF1" && request.arg_count() == 1)
return new KDF1(af.make_hash_function(request.arg(0)));
#endif
#if defined(BOTAN_HAS_KDF2)
if(request.algo_name() == "KDF2" && request.arg_count() == 1)
return new KDF2(af.make_hash_function(request.arg(0)));
#endif
#if defined(BOTAN_HAS_X942_PRF)
if(request.algo_name() == "X9.42-PRF" && request.arg_count() == 1)
return new X942_PRF(request.arg(0)); // OID
#endif
#if defined(BOTAN_HAS_TLS_V10_PRF)
if(request.algo_name() == "TLS-PRF" && request.arg_count() == 0)
return new TLS_PRF;
#endif
#if defined(BOTAN_HAS_TLS_V10_PRF)
if(request.algo_name() == "TLS-PRF" && request.arg_count() == 0)
return new TLS_PRF;
#endif
#if defined(BOTAN_HAS_TLS_V12_PRF)
if(request.algo_name() == "TLS-12-PRF" && request.arg_count() == 1)
return new TLS_12_PRF(af.make_mac("HMAC(" + request.arg(0) + ")"));
#endif
throw Algorithm_Not_Found(algo_spec);
}
}
<commit_msg>Support lookup of the SSLv3 PRF<commit_after>/*
* PBKDF/EMSA/EME/KDF/MGF Retrieval
* (C) 1999-2007 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/
#include <botan/lookup.h>
#include <botan/libstate.h>
#include <botan/scan_name.h>
#if defined(BOTAN_HAS_MGF1)
#include <botan/mgf1.h>
#endif
#if defined(BOTAN_HAS_EMSA1)
#include <botan/emsa1.h>
#endif
#if defined(BOTAN_HAS_EMSA1_BSI)
#include <botan/emsa1_bsi.h>
#endif
#if defined(BOTAN_HAS_EMSA2)
#include <botan/emsa2.h>
#endif
#if defined(BOTAN_HAS_EMSA3)
#include <botan/emsa3.h>
#endif
#if defined(BOTAN_HAS_EMSA4)
#include <botan/emsa4.h>
#endif
#if defined(BOTAN_HAS_EMSA_RAW)
#include <botan/emsa_raw.h>
#endif
#if defined(BOTAN_HAS_EME1)
#include <botan/eme1.h>
#endif
#if defined(BOTAN_HAS_EME_PKCS1v15)
#include <botan/eme_pkcs.h>
#endif
#if defined(BOTAN_HAS_KDF1)
#include <botan/kdf1.h>
#endif
#if defined(BOTAN_HAS_KDF2)
#include <botan/kdf2.h>
#endif
#if defined(BOTAN_HAS_X942_PRF)
#include <botan/prf_x942.h>
#endif
#if defined(BOTAN_HAS_SSL_V3_PRF)
#include <botan/prf_ssl3.h>
#endif
#if defined(BOTAN_HAS_TLS_V10_PRF)
#include <botan/prf_tls.h>
#endif
namespace Botan {
/*
* Get a PBKDF algorithm by name
*/
PBKDF* get_pbkdf(const std::string& algo_spec)
{
Algorithm_Factory& af = global_state().algorithm_factory();
if(PBKDF* pbkdf = af.make_pbkdf(algo_spec))
return pbkdf;
throw Algorithm_Not_Found(algo_spec);
}
/*
* Get an EMSA by name
*/
EMSA* get_emsa(const std::string& algo_spec)
{
SCAN_Name request(algo_spec);
Algorithm_Factory& af = global_state().algorithm_factory();
#if defined(BOTAN_HAS_EMSA_RAW)
if(request.algo_name() == "Raw" && request.arg_count() == 0)
return new EMSA_Raw;
#endif
#if defined(BOTAN_HAS_EMSA1)
if(request.algo_name() == "EMSA1" && request.arg_count() == 1)
{
if(request.arg(0) == "Raw")
return new EMSA_Raw;
return new EMSA1(af.make_hash_function(request.arg(0)));
}
#endif
#if defined(BOTAN_HAS_EMSA1_BSI)
if(request.algo_name() == "EMSA1_BSI" && request.arg_count() == 1)
return new EMSA1_BSI(af.make_hash_function(request.arg(0)));
#endif
#if defined(BOTAN_HAS_EMSA2)
if(request.algo_name() == "EMSA2" && request.arg_count() == 1)
return new EMSA2(af.make_hash_function(request.arg(0)));
#endif
#if defined(BOTAN_HAS_EMSA3)
if(request.algo_name() == "EMSA3" && request.arg_count() == 1)
{
if(request.arg(0) == "Raw")
return new EMSA3_Raw;
return new EMSA3(af.make_hash_function(request.arg(0)));
}
#endif
#if defined(BOTAN_HAS_EMSA4)
if(request.algo_name() == "EMSA4" && request.arg_count_between(1, 3))
{
// 3 args: Hash, MGF, salt size (MGF is hardcoded MGF1 in Botan)
if(request.arg_count() == 1)
return new EMSA4(af.make_hash_function(request.arg(0)));
if(request.arg_count() == 2 && request.arg(1) != "MGF1")
return new EMSA4(af.make_hash_function(request.arg(0)));
if(request.arg_count() == 3)
return new EMSA4(af.make_hash_function(request.arg(0)),
request.arg_as_integer(2, 0));
}
#endif
throw Algorithm_Not_Found(algo_spec);
}
/*
* Get an EME by name
*/
EME* get_eme(const std::string& algo_spec)
{
SCAN_Name request(algo_spec);
Algorithm_Factory& af = global_state().algorithm_factory();
if(request.algo_name() == "Raw")
return 0; // No padding
#if defined(BOTAN_HAS_EME_PKCS1v15)
if(request.algo_name() == "PKCS1v15" && request.arg_count() == 0)
return new EME_PKCS1v15;
#endif
#if defined(BOTAN_HAS_EME1)
if(request.algo_name() == "EME1" && request.arg_count_between(1, 2))
{
if(request.arg_count() == 1 ||
(request.arg_count() == 2 && request.arg(1) == "MGF1"))
{
return new EME1(af.make_hash_function(request.arg(0)));
}
}
#endif
throw Algorithm_Not_Found(algo_spec);
}
/*
* Get an KDF by name
*/
KDF* get_kdf(const std::string& algo_spec)
{
SCAN_Name request(algo_spec);
Algorithm_Factory& af = global_state().algorithm_factory();
if(request.algo_name() == "Raw")
return 0; // No KDF
#if defined(BOTAN_HAS_KDF1)
if(request.algo_name() == "KDF1" && request.arg_count() == 1)
return new KDF1(af.make_hash_function(request.arg(0)));
#endif
#if defined(BOTAN_HAS_KDF2)
if(request.algo_name() == "KDF2" && request.arg_count() == 1)
return new KDF2(af.make_hash_function(request.arg(0)));
#endif
#if defined(BOTAN_HAS_X942_PRF)
if(request.algo_name() == "X9.42-PRF" && request.arg_count() == 1)
return new X942_PRF(request.arg(0)); // OID
#endif
#if defined(BOTAN_HAS_SSL_V3_PRF)
if(request.algo_name() == "SSL3-PRF" && request.arg_count() == 0)
return new TLS_PRF;
#endif
#if defined(BOTAN_HAS_TLS_V10_PRF)
if(request.algo_name() == "TLS-PRF" && request.arg_count() == 0)
return new TLS_PRF;
#endif
#if defined(BOTAN_HAS_TLS_V10_PRF)
if(request.algo_name() == "TLS-PRF" && request.arg_count() == 0)
return new TLS_PRF;
#endif
#if defined(BOTAN_HAS_TLS_V12_PRF)
if(request.algo_name() == "TLS-12-PRF" && request.arg_count() == 1)
return new TLS_12_PRF(af.make_mac("HMAC(" + request.arg(0) + ")"));
#endif
throw Algorithm_Not_Found(algo_spec);
}
}
<|endoftext|>
|
<commit_before>#include "Frontend.h"
#include "CudaRt.h"
/*
Routines not found in the cuda's header files.
KEEP THEM WITH CARE
*/
extern void** __cudaRegisterFatBinary(void *fatCubin) {
/* Fake host pointer */
void ** handler = (void **) & fatCubin;
Buffer * input_buffer = new Buffer();
input_buffer->AddString(CudaUtil::MarshalHostPointer(handler));
input_buffer = CudaUtil::MarshalFatCudaBinary(
(__cudaFatCudaBinary *) fatCubin, input_buffer);
Frontend *f = Frontend::GetFrontend();
f->Execute("cudaRegisterFatBinary", input_buffer);
if (f->Success())
return handler;
return NULL;
}
extern void __cudaUnregisterFatBinary(void **fatCubinHandle) {
Frontend *f = Frontend::GetFrontend();
f->AddStringForArguments(CudaUtil::MarshalHostPointer(fatCubinHandle));
f->Execute("cudaUnregisterFatBinary");
}
extern void __cudaRegisterFunction(void **fatCubinHandle, const char *hostFun,
char *deviceFun, const char *deviceName, int thread_limit, uint3 *tid,
uint3 *bid, dim3 *bDim, dim3 *gDim, int *wSize) {
Frontend *f = Frontend::GetFrontend();
f->AddStringForArguments(CudaUtil::MarshalHostPointer(fatCubinHandle));
f->AddStringForArguments(CudaUtil::MarshalHostPointer(hostFun));
f->AddStringForArguments(deviceFun);
f->AddStringForArguments(deviceName);
f->AddVariableForArguments(thread_limit);
f->AddHostPointerForArguments(tid);
f->AddHostPointerForArguments(bid);
f->AddHostPointerForArguments(bDim);
f->AddHostPointerForArguments(gDim);
f->AddHostPointerForArguments(wSize);
f->Execute("cudaRegisterFunction");
deviceFun = f->GetOutputString();
tid = f->GetOutputHostPointer<uint3 > ();
bid = f->GetOutputHostPointer<uint3 > ();
bDim = f->GetOutputHostPointer<dim3 > ();
gDim = f->GetOutputHostPointer<dim3 > ();
wSize = f->GetOutputHostPointer<int>();
}
extern void __cudaRegisterVar(void **fatCubinHandle, char *hostVar,
char *deviceAddress, const char *deviceName, int ext, int size,
int constant, int global) {
Frontend *f = Frontend::GetFrontend();
f->AddStringForArguments(CudaUtil::MarshalHostPointer(fatCubinHandle));
f->AddStringForArguments(CudaUtil::MarshalHostPointer(hostVar));
f->AddStringForArguments(deviceAddress);
f->AddStringForArguments(deviceName);
f->AddVariableForArguments(ext);
f->AddVariableForArguments(size);
f->AddVariableForArguments(constant);
f->AddVariableForArguments(global);
f->Execute("cudaRegisterVar");
}
extern void __cudaRegisterShared(void **fatCubinHandle, void **devicePtr) {
Frontend *f = Frontend::GetFrontend();
f->AddStringForArguments(CudaUtil::MarshalHostPointer(fatCubinHandle));
f->AddStringForArguments((char *) devicePtr);
f->Execute("cudaRegisterShared");
}
extern void __cudaRegisterSharedVar(void **fatCubinHandle, void **devicePtr,
size_t size, size_t alignment, int storage) {
// FIXME: implement
cerr << "*** Error: __cudaRegisterSharedVar() not yet implemented!" << endl;
}
extern void __cudaRegisterTexture(void **fatCubinHandle,
const textureReference *hostVar, void **deviceAddress, char *deviceName,
int dim, int norm, int ext) {
cerr << "*** Error: __cudaRegisterTexture() not yet implemented!" << endl;
}
/* */
extern int __cudaSynchronizeThreads(void** x, void* y) {
// FIXME: implement
cerr << "*** Error: __cudaSynchronizeThreads() not yet implemented!"
<< endl;
return 0;
}
extern void __cudaTextureFetch(const void *tex, void *index, int integer,
void *val) {
// FIXME: implement
cerr << "*** Error: __cudaTextureFetch() not yet implemented!" << endl;
}
<commit_msg>fixed fat binary registration<commit_after>#include "Frontend.h"
#include "CudaRt.h"
/*
Routines not found in the cuda's header files.
KEEP THEM WITH CARE
*/
extern void** __cudaRegisterFatBinary(void *fatCubin) {
/* Fake host pointer */
Buffer * input_buffer = new Buffer();
input_buffer->AddString(CudaUtil::MarshalHostPointer((void **) fatCubin));
input_buffer = CudaUtil::MarshalFatCudaBinary(
(__cudaFatCudaBinary *) fatCubin, input_buffer);
Frontend *f = Frontend::GetFrontend();
f->Execute("cudaRegisterFatBinary", input_buffer);
if (f->Success())
return (void **) fatCubin;
return NULL;
}
extern void __cudaUnregisterFatBinary(void **fatCubinHandle) {
Frontend *f = Frontend::GetFrontend();
f->AddStringForArguments(CudaUtil::MarshalHostPointer(fatCubinHandle));
f->Execute("cudaUnregisterFatBinary");
}
extern void __cudaRegisterFunction(void **fatCubinHandle, const char *hostFun,
char *deviceFun, const char *deviceName, int thread_limit, uint3 *tid,
uint3 *bid, dim3 *bDim, dim3 *gDim, int *wSize) {
Frontend *f = Frontend::GetFrontend();
f->AddStringForArguments(CudaUtil::MarshalHostPointer(fatCubinHandle));
f->AddStringForArguments(CudaUtil::MarshalHostPointer(hostFun));
f->AddStringForArguments(deviceFun);
f->AddStringForArguments(deviceName);
f->AddVariableForArguments(thread_limit);
f->AddHostPointerForArguments(tid);
f->AddHostPointerForArguments(bid);
f->AddHostPointerForArguments(bDim);
f->AddHostPointerForArguments(gDim);
f->AddHostPointerForArguments(wSize);
f->Execute("cudaRegisterFunction");
deviceFun = f->GetOutputString();
tid = f->GetOutputHostPointer<uint3 > ();
bid = f->GetOutputHostPointer<uint3 > ();
bDim = f->GetOutputHostPointer<dim3 > ();
gDim = f->GetOutputHostPointer<dim3 > ();
wSize = f->GetOutputHostPointer<int>();
}
extern void __cudaRegisterVar(void **fatCubinHandle, char *hostVar,
char *deviceAddress, const char *deviceName, int ext, int size,
int constant, int global) {
Frontend *f = Frontend::GetFrontend();
f->AddStringForArguments(CudaUtil::MarshalHostPointer(fatCubinHandle));
f->AddStringForArguments(CudaUtil::MarshalHostPointer(hostVar));
f->AddStringForArguments(deviceAddress);
f->AddStringForArguments(deviceName);
f->AddVariableForArguments(ext);
f->AddVariableForArguments(size);
f->AddVariableForArguments(constant);
f->AddVariableForArguments(global);
f->Execute("cudaRegisterVar");
}
extern void __cudaRegisterShared(void **fatCubinHandle, void **devicePtr) {
Frontend *f = Frontend::GetFrontend();
f->AddStringForArguments(CudaUtil::MarshalHostPointer(fatCubinHandle));
f->AddStringForArguments((char *) devicePtr);
f->Execute("cudaRegisterShared");
}
extern void __cudaRegisterSharedVar(void **fatCubinHandle, void **devicePtr,
size_t size, size_t alignment, int storage) {
// FIXME: implement
cerr << "*** Error: __cudaRegisterSharedVar() not yet implemented!" << endl;
}
extern void __cudaRegisterTexture(void **fatCubinHandle,
const textureReference *hostVar, void **deviceAddress, char *deviceName,
int dim, int norm, int ext) {
cerr << "*** Error: __cudaRegisterTexture() not yet implemented!" << endl;
}
/* */
extern int __cudaSynchronizeThreads(void** x, void* y) {
// FIXME: implement
cerr << "*** Error: __cudaSynchronizeThreads() not yet implemented!"
<< endl;
return 0;
}
extern void __cudaTextureFetch(const void *tex, void *index, int integer,
void *val) {
// FIXME: implement
cerr << "*** Error: __cudaTextureFetch() not yet implemented!" << endl;
}
<|endoftext|>
|
<commit_before>#ifndef INCLUDE_AL_SINGLE_READER_WRITER_RING_BUFFER_HPP
#define INCLUDE_AL_SINGLE_READER_WRITER_RING_BUFFER_HPP
/* Allocore --
Multimedia / virtual environment application class library
Copyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB.
Copyright (C) 2006-2008. The Regents of the University of California (REGENTS).
All Rights Reserved.
Permission to use, copy, modify, distribute, and distribute modified versions
of this software and its documentation without fee and without a signed
licensing agreement, is hereby granted, provided that the above copyright
notice, the list of contributors, this paragraph and the following two paragraphs
appear in all copies, modifications, and distributions.
IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING
OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED
HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
File description:
Passing data between a pair of threads without locking
File author(s):
Graham Wakefield, 2010, grrrwaaa@gmail.com
*/
namespace al {
class SingleRWRingBuffer {
public:
/*
Allocate ringbuffer.
Actual size rounded up to next power of 2.
*/
SingleRWRingBuffer(size_t sz=256);
~SingleRWRingBuffer();
/*
The number of bytes available for writing.
*/
size_t writeSpace() const;
/*
The number of bytes available for reading.
*/
size_t readSpace() const;
/*
Copy sz bytes into the ringbuffer
Returns bytes actually copied
*/
size_t write(const char * src, size_t sz);
/*
Read data and advance the read pointer
Returns bytes actually copied
*/
size_t read(char * dst, size_t sz);
/*
Read data without advancing the read pointer
Returns bytes actually copied
*/
size_t peek(char * dst, size_t sz);
protected:
size_t mSize, mWrap;
size_t mRead, mWrite;
char * mData;
};
inline unsigned long next_power_of_two(unsigned long v) {
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v |= v >> 32;
v++;
return v;
}
/*
Allocate ringbuffer.
Actual size rounded up to next power of 2.
*/
inline SingleRWRingBuffer :: SingleRWRingBuffer(size_t sz)
: mSize(next_power_of_two(sz)),
mWrap(mSize-1),
mRead(0),
mWrite(0)
{
mData = new char[mSize];
}
inline SingleRWRingBuffer :: ~SingleRWRingBuffer() {
delete[] mData;
}
/*
The number of bytes available for writing.
*/
inline size_t SingleRWRingBuffer :: writeSpace() const {
const size_t r = mRead;
const size_t w = mWrite;
if (r==w) return mWrap;
return ((mSize + (r - w)) & mWrap) - 1;
}
/*
The number of bytes available for reading.
*/
inline size_t SingleRWRingBuffer :: readSpace() const {
const size_t r = mRead;
const size_t w = mWrite;
return (mSize + (w - r)) & mWrap;
}
/*
Copy sz bytes into the ringbuffer
Returns bytes actually copied
*/
inline size_t SingleRWRingBuffer :: write(const char * src, size_t sz) {
size_t space = writeSpace();
sz = sz > space ? space : sz;
if (sz == 0) return 0;
size_t w = mWrite;
size_t end = w + sz;
if (end < mSize) {
memcpy(mData+w, src, sz);
} else {
size_t split = mSize-w;
end &= mWrap;
memcpy(mData+w, src, split);
memcpy(mData, src+split, end);
}
mWrite = end;
return sz;
}
/*
Read data and advance the read pointer
Returns bytes actually copied
*/
inline size_t SingleRWRingBuffer :: read(char * dst, size_t sz) {
size_t space = readSpace();
sz = sz > space ? space : sz;
if (sz == 0) return 0;
size_t r = mRead;
size_t end = r + sz;
if (end < mSize) {
memcpy(dst, mData+r, sz);
} else {
size_t split = mSize-r;
end &= mWrap;
memcpy(dst, mData+r, split);
memcpy(dst+split, mData, end);
}
mRead = end;
return sz;
}
/*
Read data without advancing the read pointer
Returns bytes actually copied
*/
inline size_t SingleRWRingBuffer :: peek(char * dst, size_t sz) {
size_t space = readSpace();
sz = sz > space ? space : sz;
if (sz == 0) return 0;
size_t r = mRead;
size_t end = r + sz;
if (end < mSize) {
memcpy(dst, mData+r, sz);
} else {
size_t split = mSize-r;
end &= mWrap;
memcpy(dst, mData+r, split);
memcpy(dst+split, mData, end);
}
return sz;
}
} // al::
#endif /* include guard */
<commit_msg>make next_power_of_two for 32 or 64-bit unsigned long<commit_after>#ifndef INCLUDE_AL_SINGLE_READER_WRITER_RING_BUFFER_HPP
#define INCLUDE_AL_SINGLE_READER_WRITER_RING_BUFFER_HPP
/* Allocore --
Multimedia / virtual environment application class library
Copyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB.
Copyright (C) 2006-2008. The Regents of the University of California (REGENTS).
All Rights Reserved.
Permission to use, copy, modify, distribute, and distribute modified versions
of this software and its documentation without fee and without a signed
licensing agreement, is hereby granted, provided that the above copyright
notice, the list of contributors, this paragraph and the following two paragraphs
appear in all copies, modifications, and distributions.
IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING
OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED
HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
File description:
Passing data between a pair of threads without locking
File author(s):
Graham Wakefield, 2010, grrrwaaa@gmail.com
*/
namespace al {
class SingleRWRingBuffer {
public:
/*
Allocate ringbuffer.
Actual size rounded up to next power of 2.
*/
SingleRWRingBuffer(size_t sz=256);
~SingleRWRingBuffer();
/*
The number of bytes available for writing.
*/
size_t writeSpace() const;
/*
The number of bytes available for reading.
*/
size_t readSpace() const;
/*
Copy sz bytes into the ringbuffer
Returns bytes actually copied
*/
size_t write(const char * src, size_t sz);
/*
Read data and advance the read pointer
Returns bytes actually copied
*/
size_t read(char * dst, size_t sz);
/*
Read data without advancing the read pointer
Returns bytes actually copied
*/
size_t peek(char * dst, size_t sz);
protected:
size_t mSize, mWrap;
size_t mRead, mWrite;
char * mData;
};
//inline unsigned long next_power_of_two(unsigned long v){
// --v;
// v |= v >> 1;
// v |= v >> 2;
// v |= v >> 4;
// v |= v >> 8;
// v |= v >>16;
// v |= v >>32; // FIXME: this throws warnings if sizeof(unsigned long) == 4
// return v+1;
//}
template <class T>
inline T next_power_of_two(T n){
T k=1;
--n;
do{
n |= n >> k;
k <<= 1;
} while (n & (n+1));
return n+1;
}
/*
Allocate ringbuffer.
Actual size rounded up to next power of 2.
*/
inline SingleRWRingBuffer :: SingleRWRingBuffer(size_t sz)
: mSize(next_power_of_two(sz)),
mWrap(mSize-1),
mRead(0),
mWrite(0)
{
mData = new char[mSize];
}
inline SingleRWRingBuffer :: ~SingleRWRingBuffer() {
delete[] mData;
}
/*
The number of bytes available for writing.
*/
inline size_t SingleRWRingBuffer :: writeSpace() const {
const size_t r = mRead;
const size_t w = mWrite;
if (r==w) return mWrap;
return ((mSize + (r - w)) & mWrap) - 1;
}
/*
The number of bytes available for reading.
*/
inline size_t SingleRWRingBuffer :: readSpace() const {
const size_t r = mRead;
const size_t w = mWrite;
return (mSize + (w - r)) & mWrap;
}
/*
Copy sz bytes into the ringbuffer
Returns bytes actually copied
*/
inline size_t SingleRWRingBuffer :: write(const char * src, size_t sz) {
size_t space = writeSpace();
sz = sz > space ? space : sz;
if (sz == 0) return 0;
size_t w = mWrite;
size_t end = w + sz;
if (end < mSize) {
memcpy(mData+w, src, sz);
} else {
size_t split = mSize-w;
end &= mWrap;
memcpy(mData+w, src, split);
memcpy(mData, src+split, end);
}
mWrite = end;
return sz;
}
/*
Read data and advance the read pointer
Returns bytes actually copied
*/
inline size_t SingleRWRingBuffer :: read(char * dst, size_t sz) {
size_t space = readSpace();
sz = sz > space ? space : sz;
if (sz == 0) return 0;
size_t r = mRead;
size_t end = r + sz;
if (end < mSize) {
memcpy(dst, mData+r, sz);
} else {
size_t split = mSize-r;
end &= mWrap;
memcpy(dst, mData+r, split);
memcpy(dst+split, mData, end);
}
mRead = end;
return sz;
}
/*
Read data without advancing the read pointer
Returns bytes actually copied
*/
inline size_t SingleRWRingBuffer :: peek(char * dst, size_t sz) {
size_t space = readSpace();
sz = sz > space ? space : sz;
if (sz == 0) return 0;
size_t r = mRead;
size_t end = r + sz;
if (end < mSize) {
memcpy(dst, mData+r, sz);
} else {
size_t split = mSize-r;
end &= mWrap;
memcpy(dst, mData+r, split);
memcpy(dst+split, mData, end);
}
return sz;
}
} // al::
#endif /* include guard */
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2013, Randolph Voorhies, Shane Grant
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of cereal 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 <COPYRIGHT HOLDER> 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.
*/
#ifndef CEREAL_BINARY_ARCHIVE_BINARY_ARCHIVE_HPP_
#define CEREAL_BINARY_ARCHIVE_BINARY_ARCHIVE_HPP_
#include <cereal/cereal.hpp>
#include <stack>
#include <sstream>
namespace cereal
{
// ######################################################################
class BinaryOutputArchive : public OutputArchive<BinaryOutputArchive, AllowEmptyClassElision>
{
public:
BinaryOutputArchive(std::ostream & stream) :
OutputArchive<BinaryOutputArchive, AllowEmptyClassElision>(this),
itsStream(stream)
{ }
//! Writes size bytes of data to the output stream
void saveBinary( const void * data, size_t size )
{
auto const writtenSize = itsStream.rdbuf()->sputn( reinterpret_cast<const char*>( data ), size );
if(writtenSize != size)
throw Exception("Failed to write " + std::to_string(size) + " bytes to output stream! Wrote " + std::to_string(writtenSize));
}
//! Pushes a placeholder for data onto the archive and saves its position
void pushPosition( size_t size )
{
itsPositionStack.push( itsStream.tellp() );
for(size_t i = 0; i < size; ++i)
itsStream.rdbuf()->sputc('\0'); // char doesn't matter, but null-term is zero
}
//! Pops the most recently pushed position onto the archive, going to the end
//! of the archive if the stack is empty
/*! @return true if the stack is empty and we are at the end of the archive */
bool popPosition()
{
if( itsPositionStack.empty() ) // seek to end of stream
{
itsStream.seekp( 0, std::ios_base::end );
return true;
}
else
{
itsStream.seekp( itsPositionStack.top() );
itsPositionStack.pop();
return false;
}
}
//! Resets the position stack and seeks to the end of the archive
void resetPosition()
{
while( !popPosition() );
}
private:
std::ostream & itsStream;
std::stack<std::ostream::pos_type> itsPositionStack;
};
// ######################################################################
class BinaryInputArchive : public InputArchive<BinaryInputArchive, AllowEmptyClassElision>
{
public:
BinaryInputArchive(std::istream & stream) :
InputArchive<BinaryInputArchive, AllowEmptyClassElision>(this),
itsStream(stream)
{ }
//! Reads size bytes of data from the input stream
void loadBinary( void * const data, size_t size )
{
auto const readSize = itsStream.rdbuf()->sgetn( reinterpret_cast<char*>( data ), size );
if(readSize != size)
throw Exception("Failed to read " + std::to_string(size) + " bytes from input stream! Read " + std::to_string(readSize));
}
private:
std::istream & itsStream;
};
//! Saving for POD types to binary
template<class T> inline
typename std::enable_if<std::is_arithmetic<T>::value, void>::type
save(BinaryOutputArchive & ar, T const & t)
{
ar.saveBinary(std::addressof(t), sizeof(t));
}
//! Loading for POD types from binary
template<class T> inline
typename std::enable_if<std::is_arithmetic<T>::value, void>::type
load(BinaryInputArchive & ar, T & t)
{
ar.loadBinary(std::addressof(t), sizeof(t));
}
//! Serializing NVP types to binary
template <class Archive, class T> inline
CEREAL_ARCHIVE_RESTRICT_SERIALIZE(BinaryInputArchive, BinaryOutputArchive)
serialize( Archive & ar, NameValuePair<T> & t )
{
ar( t.value );
}
template <class T> inline
typename std::enable_if<std::is_array<T>::value, void>::type
save(BinaryOutputArchive & ar, T const & array)
{
ar.saveBinary(array, traits::sizeof_array<T>() * sizeof(typename std::remove_all_extents<T>::type));
}
template <class T> inline
typename std::enable_if<std::is_array<T>::value, void>::type
load(BinaryInputArchive & ar, T & array)
{
ar.loadBinary(array, traits::sizeof_array<T>() * sizeof(typename std::remove_all_extents<T>::type));
}
template <class T> inline
void save(BinaryOutputArchive & ar, BinaryData<T> const & bd)
{
ar.saveBinary(bd.data, bd.size);
}
template <class T> inline
void load(BinaryInputArchive & ar, BinaryData<T> & bd)
{
ar.loadBinary(bd.data, bd.size);
}
template <class Archive, class T> inline
CEREAL_ARCHIVE_RESTRICT_SERIALIZE(BinaryInputArchive, BinaryOutputArchive)
serialize( Archive & ar, T * & t )
{
static_assert(!sizeof(T), "Cereal does not support serializing raw pointers - please use a smart pointer");
}
} // namespace cereal
#endif // CEREAL_BINARY_ARCHIVE_BINARY_ARCHIVE_HPP_
<commit_msg>Making sure we're using size_t in load/saveBinary<commit_after>/*
Copyright (c) 2013, Randolph Voorhies, Shane Grant
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of cereal 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 <COPYRIGHT HOLDER> 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.
*/
#ifndef CEREAL_BINARY_ARCHIVE_BINARY_ARCHIVE_HPP_
#define CEREAL_BINARY_ARCHIVE_BINARY_ARCHIVE_HPP_
#include <cereal/cereal.hpp>
#include <stack>
#include <sstream>
namespace cereal
{
// ######################################################################
class BinaryOutputArchive : public OutputArchive<BinaryOutputArchive, AllowEmptyClassElision>
{
public:
BinaryOutputArchive(std::ostream & stream) :
OutputArchive<BinaryOutputArchive, AllowEmptyClassElision>(this),
itsStream(stream)
{ }
//! Writes size bytes of data to the output stream
void saveBinary( const void * data, size_t size )
{
size_t const writtenSize = itsStream.rdbuf()->sputn( reinterpret_cast<const char*>( data ), size );
if(writtenSize != size)
throw Exception("Failed to write " + std::to_string(size) + " bytes to output stream! Wrote " + std::to_string(writtenSize));
}
//! Pushes a placeholder for data onto the archive and saves its position
void pushPosition( size_t size )
{
itsPositionStack.push( itsStream.tellp() );
for(size_t i = 0; i < size; ++i)
itsStream.rdbuf()->sputc('\0'); // char doesn't matter, but null-term is zero
}
//! Pops the most recently pushed position onto the archive, going to the end
//! of the archive if the stack is empty
/*! @return true if the stack is empty and we are at the end of the archive */
bool popPosition()
{
if( itsPositionStack.empty() ) // seek to end of stream
{
itsStream.seekp( 0, std::ios_base::end );
return true;
}
else
{
itsStream.seekp( itsPositionStack.top() );
itsPositionStack.pop();
return false;
}
}
//! Resets the position stack and seeks to the end of the archive
void resetPosition()
{
while( !popPosition() );
}
private:
std::ostream & itsStream;
std::stack<std::ostream::pos_type> itsPositionStack;
};
// ######################################################################
class BinaryInputArchive : public InputArchive<BinaryInputArchive, AllowEmptyClassElision>
{
public:
BinaryInputArchive(std::istream & stream) :
InputArchive<BinaryInputArchive, AllowEmptyClassElision>(this),
itsStream(stream)
{ }
//! Reads size bytes of data from the input stream
void loadBinary( void * const data, size_t size )
{
size_t const readSize = itsStream.rdbuf()->sgetn( reinterpret_cast<char*>( data ), size );
if(readSize != size)
throw Exception("Failed to read " + std::to_string(size) + " bytes from input stream! Read " + std::to_string(readSize));
}
private:
std::istream & itsStream;
};
//! Saving for POD types to binary
template<class T> inline
typename std::enable_if<std::is_arithmetic<T>::value, void>::type
save(BinaryOutputArchive & ar, T const & t)
{
ar.saveBinary(std::addressof(t), sizeof(t));
}
//! Loading for POD types from binary
template<class T> inline
typename std::enable_if<std::is_arithmetic<T>::value, void>::type
load(BinaryInputArchive & ar, T & t)
{
ar.loadBinary(std::addressof(t), sizeof(t));
}
//! Serializing NVP types to binary
template <class Archive, class T> inline
CEREAL_ARCHIVE_RESTRICT_SERIALIZE(BinaryInputArchive, BinaryOutputArchive)
serialize( Archive & ar, NameValuePair<T> & t )
{
ar( t.value );
}
template <class T> inline
typename std::enable_if<std::is_array<T>::value, void>::type
save(BinaryOutputArchive & ar, T const & array)
{
ar.saveBinary(array, traits::sizeof_array<T>() * sizeof(typename std::remove_all_extents<T>::type));
}
template <class T> inline
typename std::enable_if<std::is_array<T>::value, void>::type
load(BinaryInputArchive & ar, T & array)
{
ar.loadBinary(array, traits::sizeof_array<T>() * sizeof(typename std::remove_all_extents<T>::type));
}
template <class T> inline
void save(BinaryOutputArchive & ar, BinaryData<T> const & bd)
{
ar.saveBinary(bd.data, bd.size);
}
template <class T> inline
void load(BinaryInputArchive & ar, BinaryData<T> & bd)
{
ar.loadBinary(bd.data, bd.size);
}
template <class Archive, class T> inline
CEREAL_ARCHIVE_RESTRICT_SERIALIZE(BinaryInputArchive, BinaryOutputArchive)
serialize( Archive & ar, T * & t )
{
static_assert(!sizeof(T), "Cereal does not support serializing raw pointers - please use a smart pointer");
}
} // namespace cereal
#endif // CEREAL_BINARY_ARCHIVE_BINARY_ARCHIVE_HPP_
<|endoftext|>
|
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2016-2017 Davide Faconti
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. 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.
* *******************************************************************/
#ifndef VARIANT_H
#define VARIANT_H
#include <type_traits>
#include <limits>
#include "ros_type_introspection/builtin_types.hpp"
#include "ros_type_introspection/details/exceptions.hpp"
#include "ros_type_introspection/details/conversion_impl.hpp"
#include "absl/strings/string_view.h"
namespace RosIntrospection
{
class Variant
{
public:
Variant() {
_type = OTHER;
_storage.raw_string = nullptr;
}
~Variant();
Variant(const Variant& other): _type(OTHER)
{
if( other._type == STRING)
{
const char* raw = other._storage.raw_string;
const uint32_t size = *(reinterpret_cast<const uint32_t*>( &raw[0] ));
const char* data = (&raw[4]);
assign( data, size );
}
else{
_type = other._type;
_storage.raw_data = other._storage.raw_data;
}
}
Variant(Variant&& other): _type(OTHER)
{
if( other._type == STRING)
{
_storage.raw_string = nullptr;
std::swap( _storage.raw_string, other._storage.raw_string);
std::swap( _type, other._type);
}
else{
_type = other._type;
_storage.raw_data = other._storage.raw_data;
}
}
Variant& operator = (const Variant& other)
{
if( other._type == STRING)
{
const char* raw = other._storage.raw_string;
const uint32_t size = *(reinterpret_cast<const uint32_t*>( &raw[0] ));
const char* data = (&raw[4]);
assign( data, size );
}
else{
_type = other._type;
_storage.raw_data = other._storage.raw_data;
}
return *this;
}
template<typename T> Variant(const T& value);
// specialization for raw string
Variant(const char* buffer, size_t length);
BuiltinType getTypeID() const;
template<typename T> T convert( ) const;
template<typename T> T extract( ) const;
template <typename T> void assign(const T& value);
void assign(const char* buffer, size_t length);
private:
union {
std::array<uint8_t,8> raw_data;
char* raw_string;
}_storage;
void clearStringIfNecessary();
BuiltinType _type;
};
//----------------------- Implementation ----------------------------------------------
template<typename T>
inline Variant::Variant(const T& value):
_type(OTHER)
{
static_assert (std::numeric_limits<T>::is_specialized ||
std::is_same<T, ros::Time>::value ||
std::is_same<T, absl::string_view>::value ||
std::is_same<T, std::string>::value ||
std::is_same<T, ros::Duration>::value
, "not a valid type");
_storage.raw_string = (nullptr);
assign(value);
}
inline Variant::Variant(const char* buffer, size_t length):_type(OTHER)
{
_storage.raw_string = (nullptr);
assign(buffer,length);
}
inline Variant::~Variant()
{
clearStringIfNecessary();
}
//-------------------------------------
inline BuiltinType Variant::getTypeID() const {
return _type;
}
template<typename T> inline T Variant::extract( ) const
{
static_assert (std::numeric_limits<T>::is_specialized ||
std::is_same<T, ros::Time>::value ||
std::is_same<T, ros::Duration>::value
, "not a valid type");
if( _type != RosIntrospection::getType<T>() )
{
throw TypeException("Variant::extract -> wrong type");
}
return * reinterpret_cast<const T*>( &_storage.raw_data[0] );
}
template<> inline absl::string_view Variant::extract( ) const
{
if( _type != STRING )
{
throw TypeException("Variant::extract -> wrong type");
}
const uint32_t size = *(reinterpret_cast<const uint32_t*>( &_storage.raw_string[0] ));
char* data = static_cast<char*>(&_storage.raw_string[4]);
return absl::string_view(data, size);
}
template<> inline std::string Variant::extract( ) const
{
if( _type != STRING )
{
throw TypeException("Variant::extract -> wrong type");
}
const uint32_t size = *(reinterpret_cast<const uint32_t*>( &_storage.raw_string[0] ));
char* data = static_cast<char*>(&_storage.raw_string[4]);
return std::string(data, size);
}
//-------------------------------------
template <typename T> inline void Variant::assign(const T& value)
{
static_assert (std::numeric_limits<T>::is_specialized ||
std::is_same<T, ros::Time>::value ||
std::is_same<T, ros::Duration>::value
, "not a valid type");
clearStringIfNecessary();
_type = RosIntrospection::getType<T>() ;
*reinterpret_cast<T *>( &_storage.raw_data[0] ) = value;
}
inline void Variant::clearStringIfNecessary()
{
if( _storage.raw_string && _type == STRING)
{
delete [] _storage.raw_string;
_storage.raw_string = nullptr;
}
}
inline void Variant::assign(const char* buffer, size_t size)
{
clearStringIfNecessary();
_type = STRING;
_storage.raw_string = new char[size+5];
*reinterpret_cast<uint32_t *>( &_storage.raw_string[0] ) = size;
memcpy(&_storage.raw_string[4] , buffer, size );
_storage.raw_string[size+4] = '\0';
}
template <> inline void Variant::assign(const absl::string_view& value)
{
assign( value.data(), value.size() );
}
template <> inline void Variant::assign(const std::string& value)
{
assign( value.data(), value.size() );
}
//-------------------------------------
template<typename DST> inline DST Variant::convert() const
{
static_assert (std::numeric_limits<DST>::is_specialized ||
std::is_same<DST, ros::Time>::value ||
std::is_same<DST, ros::Duration>::value
, "not a valid type");
using namespace RosIntrospection::details;
DST target;
const auto& raw_data = &_storage.raw_data[0];
//----------
switch( _type )
{
case CHAR:
case INT8: convert_impl<int8_t, DST>(*reinterpret_cast<const int8_t*>( raw_data), target ); break;
case INT16: convert_impl<int16_t, DST>(*reinterpret_cast<const int16_t*>( raw_data), target ); break;
case INT32: convert_impl<int32_t, DST>(*reinterpret_cast<const int32_t*>( raw_data), target ); break;
case INT64: convert_impl<int64_t, DST>(*reinterpret_cast<const int64_t*>( raw_data), target ); break;
case BOOL:
case BYTE:
case UINT8: convert_impl<uint8_t, DST>(*reinterpret_cast<const uint8_t*>( raw_data), target ); break;
case UINT16: convert_impl<uint16_t, DST>(*reinterpret_cast<const uint16_t*>( raw_data), target ); break;
case UINT32: convert_impl<uint32_t, DST>(*reinterpret_cast<const uint32_t*>( raw_data), target ); break;
case UINT64: convert_impl<uint64_t, DST>(*reinterpret_cast<const uint64_t*>( raw_data), target ); break;
case FLOAT32: convert_impl<float, DST>(*reinterpret_cast<const float*>( raw_data), target ); break;
case FLOAT64: convert_impl<double, DST>(*reinterpret_cast<const double*>( raw_data), target ); break;
case STRING: {
throw TypeException("String will not be converted to a numerical value implicitly");
} break;
case DURATION:
case TIME: {
throw TypeException("ros::Duration and ros::Time can be converted only to double (will be seconds)");
} break;
case OTHER: throw TypeException("Variant::convert -> cannot convert type" + std::to_string(_type)); break;
}
return target;
}
template<> inline double Variant::convert() const
{
using namespace RosIntrospection::details;
double target = 0;
const auto& raw_data = &_storage.raw_data[0];
//----------
switch( _type )
{
case CHAR:
case INT8: convert_impl<int8_t, double>(*reinterpret_cast<const int8_t*>( raw_data), target ); break;
case INT16: convert_impl<int16_t, double>(*reinterpret_cast<const int16_t*>( raw_data), target ); break;
case INT32: convert_impl<int32_t, double>(*reinterpret_cast<const int32_t*>( raw_data), target ); break;
case INT64: convert_impl<int64_t, double>(*reinterpret_cast<const int64_t*>( raw_data), target ); break;
case BOOL:
case BYTE:
case UINT8: convert_impl<uint8_t, double>(*reinterpret_cast<const uint8_t*>( raw_data), target ); break;
case UINT16: convert_impl<uint16_t, double>(*reinterpret_cast<const uint16_t*>( raw_data), target ); break;
case UINT32: convert_impl<uint32_t, double>(*reinterpret_cast<const uint32_t*>( raw_data), target ); break;
case UINT64: convert_impl<uint64_t, double>(*reinterpret_cast<const uint64_t*>( raw_data), target ); break;
case FLOAT32: convert_impl<float, double>(*reinterpret_cast<const float*>( raw_data), target ); break;
case FLOAT64: return extract<double>();
case STRING: {
throw TypeException("String will not be converted to a double implicitly");
}break;
case DURATION: {
ros::Duration tmp = extract<ros::Duration>();
target = tmp.toSec();
}break;
case TIME: {
ros::Time tmp = extract<ros::Time>();
target = tmp.toSec();
}break;
case OTHER: throw TypeException("Variant::convert -> cannot convert type" + std::to_string(_type));
}
return target;
}
template<> inline ros::Time Variant::convert() const
{
if( _type != TIME )
{
throw TypeException("Variant::convert -> cannot convert ros::Time");
}
return extract<ros::Time>();
}
template<> inline ros::Duration Variant::convert() const
{
if( _type != DURATION )
{
throw TypeException("Variant::convert -> cannot convert ros::Duration");
}
return extract<ros::Duration>();
}
template<> inline std::string Variant::convert() const
{
if( _type != STRING )
{
throw TypeException("Variant::convert -> cannot convert to std::string");
}
return extract<std::string>();
}
} //end namespace
#endif // VARIANT_H
<commit_msg>Fix issue #38<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2016-2017 Davide Faconti
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. 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.
* *******************************************************************/
#ifndef VARIANT_H
#define VARIANT_H
#include <type_traits>
#include <limits>
#include "ros_type_introspection/builtin_types.hpp"
#include "ros_type_introspection/details/exceptions.hpp"
#include "ros_type_introspection/details/conversion_impl.hpp"
#include "absl/strings/string_view.h"
namespace RosIntrospection
{
class Variant
{
public:
Variant() {
_type = OTHER;
_storage.raw_string = nullptr;
}
~Variant();
Variant(const Variant& other): _type(OTHER)
{
if( other._type == STRING)
{
const char* raw = other._storage.raw_string;
const uint32_t size = *(reinterpret_cast<const uint32_t*>( &raw[0] ));
const char* data = (&raw[4]);
assign( data, size );
}
else{
_type = other._type;
_storage.raw_data = other._storage.raw_data;
}
}
Variant(Variant&& other): _type(OTHER)
{
if( other._type == STRING)
{
_storage.raw_string = nullptr;
std::swap( _storage.raw_string, other._storage.raw_string);
std::swap( _type, other._type);
}
else{
_type = other._type;
_storage.raw_data = other._storage.raw_data;
}
}
Variant& operator = (const Variant& other)
{
if( other._type == STRING)
{
const char* raw = other._storage.raw_string;
const uint32_t size = *(reinterpret_cast<const uint32_t*>( &raw[0] ));
const char* data = (&raw[4]);
assign( data, size );
}
else{
_type = other._type;
_storage.raw_data = other._storage.raw_data;
}
return *this;
}
template<typename T> Variant(const T& value);
// specialization for raw string
Variant(const char* buffer, size_t length);
BuiltinType getTypeID() const;
template<typename T> T convert( ) const;
template<typename T> T extract( ) const;
template <typename T> void assign(const T& value);
void assign(const char* buffer, size_t length);
private:
union {
std::array<uint8_t,8> raw_data;
char* raw_string;
}_storage;
void clearStringIfNecessary();
BuiltinType _type;
};
//----------------------- Implementation ----------------------------------------------
template<typename T>
inline Variant::Variant(const T& value):
_type(OTHER)
{
static_assert (std::numeric_limits<T>::is_specialized ||
std::is_same<T, ros::Time>::value ||
std::is_same<T, absl::string_view>::value ||
std::is_same<T, std::string>::value ||
std::is_same<T, ros::Duration>::value
, "not a valid type");
_storage.raw_string = (nullptr);
assign(value);
}
inline Variant::Variant(const char* buffer, size_t length):_type(OTHER)
{
_storage.raw_string = (nullptr);
assign(buffer,length);
}
inline Variant::~Variant()
{
clearStringIfNecessary();
}
//-------------------------------------
inline BuiltinType Variant::getTypeID() const {
return _type;
}
template<typename T> inline T Variant::extract( ) const
{
static_assert (std::numeric_limits<T>::is_specialized ||
std::is_same<T, ros::Time>::value ||
std::is_same<T, ros::Duration>::value
, "not a valid type");
if( _type != RosIntrospection::getType<T>() )
{
throw TypeException("Variant::extract -> wrong type");
}
return * reinterpret_cast<const T*>( &_storage.raw_data[0] );
}
template<> inline absl::string_view Variant::extract( ) const
{
if( _type != STRING )
{
throw TypeException("Variant::extract -> wrong type");
}
const uint32_t size = *(reinterpret_cast<const uint32_t*>( &_storage.raw_string[0] ));
char* data = static_cast<char*>(&_storage.raw_string[4]);
return absl::string_view(data, size);
}
template<> inline std::string Variant::extract( ) const
{
if( _type != STRING )
{
throw TypeException("Variant::extract -> wrong type");
}
const uint32_t size = *(reinterpret_cast<const uint32_t*>( &_storage.raw_string[0] ));
char* data = static_cast<char*>(&_storage.raw_string[4]);
return std::string(data, size);
}
//-------------------------------------
template <typename T> inline void Variant::assign(const T& value)
{
static_assert (std::numeric_limits<T>::is_specialized ||
std::is_same<T, ros::Time>::value ||
std::is_same<T, ros::Duration>::value
, "not a valid type");
clearStringIfNecessary();
_type = RosIntrospection::getType<T>() ;
*reinterpret_cast<T *>( &_storage.raw_data[0] ) = value;
}
inline void Variant::clearStringIfNecessary()
{
if( _storage.raw_string && _type == STRING)
{
delete [] _storage.raw_string;
_storage.raw_string = nullptr;
}
}
inline void Variant::assign(const char* buffer, size_t size)
{
clearStringIfNecessary();
_type = STRING;
_storage.raw_string = new char[size+5];
*reinterpret_cast<uint32_t *>( &_storage.raw_string[0] ) = size;
memcpy(&_storage.raw_string[4] , buffer, size );
_storage.raw_string[size+4] = '\0';
}
template <> inline void Variant::assign(const absl::string_view& value)
{
assign( value.data(), value.size() );
}
template <> inline void Variant::assign(const std::string& value)
{
assign( value.data(), value.size() );
}
//-------------------------------------
template<typename DST> inline DST Variant::convert() const
{
static_assert (std::numeric_limits<DST>::is_specialized ||
std::is_same<DST, ros::Time>::value ||
std::is_same<DST, ros::Duration>::value
, "not a valid type");
using namespace RosIntrospection::details;
DST target;
const auto& raw_data = &_storage.raw_data[0];
//----------
switch( _type )
{
case CHAR:
case INT8: convert_impl<int8_t, DST>(*reinterpret_cast<const int8_t*>( raw_data), target ); break;
case INT16: convert_impl<int16_t, DST>(*reinterpret_cast<const int16_t*>( raw_data), target ); break;
case INT32: convert_impl<int32_t, DST>(*reinterpret_cast<const int32_t*>( raw_data), target ); break;
case INT64: convert_impl<int64_t, DST>(*reinterpret_cast<const int64_t*>( raw_data), target ); break;
case BOOL:
case BYTE:
case UINT8: convert_impl<uint8_t, DST>(*reinterpret_cast<const uint8_t*>( raw_data), target ); break;
case UINT16: convert_impl<uint16_t, DST>(*reinterpret_cast<const uint16_t*>( raw_data), target ); break;
case UINT32: convert_impl<uint32_t, DST>(*reinterpret_cast<const uint32_t*>( raw_data), target ); break;
case UINT64: convert_impl<uint64_t, DST>(*reinterpret_cast<const uint64_t*>( raw_data), target ); break;
case FLOAT32: convert_impl<float, DST>(*reinterpret_cast<const float*>( raw_data), target ); break;
case FLOAT64: convert_impl<double, DST>(*reinterpret_cast<const double*>( raw_data), target ); break;
case STRING: {
throw TypeException("String will not be converted to a numerical value implicitly");
} break;
case DURATION:
case TIME: {
throw TypeException("ros::Duration and ros::Time can be converted only to double (will be seconds)");
} break;
default: throw TypeException("Variant::convert -> cannot convert type" + std::to_string(_type)); break;
}
return target;
}
template<> inline double Variant::convert() const
{
using namespace RosIntrospection::details;
double target = 0;
const auto& raw_data = &_storage.raw_data[0];
//----------
switch( _type )
{
case CHAR:
case INT8: convert_impl<int8_t, double>(*reinterpret_cast<const int8_t*>( raw_data), target ); break;
case INT16: convert_impl<int16_t, double>(*reinterpret_cast<const int16_t*>( raw_data), target ); break;
case INT32: convert_impl<int32_t, double>(*reinterpret_cast<const int32_t*>( raw_data), target ); break;
case INT64: convert_impl<int64_t, double>(*reinterpret_cast<const int64_t*>( raw_data), target ); break;
case BOOL:
case BYTE:
case UINT8: convert_impl<uint8_t, double>(*reinterpret_cast<const uint8_t*>( raw_data), target ); break;
case UINT16: convert_impl<uint16_t, double>(*reinterpret_cast<const uint16_t*>( raw_data), target ); break;
case UINT32: convert_impl<uint32_t, double>(*reinterpret_cast<const uint32_t*>( raw_data), target ); break;
case UINT64: convert_impl<uint64_t, double>(*reinterpret_cast<const uint64_t*>( raw_data), target ); break;
case FLOAT32: convert_impl<float, double>(*reinterpret_cast<const float*>( raw_data), target ); break;
case FLOAT64: return extract<double>();
case STRING: {
throw TypeException("String will not be converted to a double implicitly");
}break;
case DURATION: {
ros::Duration tmp = extract<ros::Duration>();
target = tmp.toSec();
}break;
case TIME: {
ros::Time tmp = extract<ros::Time>();
target = tmp.toSec();
}break;
default: throw TypeException("Variant::convert -> cannot convert type" + std::to_string(_type));
}
return target;
}
template<> inline ros::Time Variant::convert() const
{
if( _type != TIME )
{
throw TypeException("Variant::convert -> cannot convert ros::Time");
}
return extract<ros::Time>();
}
template<> inline ros::Duration Variant::convert() const
{
if( _type != DURATION )
{
throw TypeException("Variant::convert -> cannot convert ros::Duration");
}
return extract<ros::Duration>();
}
template<> inline std::string Variant::convert() const
{
if( _type != STRING )
{
throw TypeException("Variant::convert -> cannot convert to std::string");
}
return extract<std::string>();
}
} //end namespace
#endif // VARIANT_H
<|endoftext|>
|
<commit_before>// Development utility to confirm the width of various Win32 objects.
// Compile with cl constants.cpp
#include <stdlib.h>
#include <windows.h>
#include <stdio.h>
void main()
{
printf("On this platform:\n");
printf("sizeof(int) is %zu\n", sizeof(int));
printf("sizeof(LPCSTR) is %zu\n", sizeof(LPCSTR));
printf("sizeof(LPCWSTR) is %zu\n", sizeof(LPCWSTR));
printf("sizeof(HANDLE) is %zu\n", sizeof(HANDLE));
printf("sizeof(HINSTANCE) is %zu\n", sizeof(HINSTANCE));
printf("sizeof(HWND) is %zu\n", sizeof(HWND));
printf("sizeof(HDC) is %zu\n", sizeof(HDC));
printf("sizeof(HBRUSH) is %zu\n", sizeof(HBRUSH));
printf("sizeof(ATOM) is %zu\n", sizeof(ATOM));
printf("sizeof(WPARAM) is %zu\n", sizeof(WPARAM));
printf("sizeof(LPARAM) is %zu\n", sizeof(LPARAM));
printf("sizeof(LRESULT) is %zu\n", sizeof(LRESULT));
printf("sizeof(WNDCLASS) is %zu\n", sizeof(WNDCLASS));
printf("sizeof(WNDPROC) is %zu\n", sizeof(WNDPROC));
printf("sizeof(POINT) is %zu\n", sizeof(POINT));
printf("sizeof(RECT) is %zu\n", sizeof(RECT));
printf("sizeof(MSG) is %zu\n", sizeof(MSG));
printf("sizeof(TCHAR) is %zu\n", sizeof(TCHAR));
printf("sizeof(UINT) is %zu\n", sizeof(UINT));
printf("sizeof(DWORD) is %zu\n", sizeof(DWORD));
printf("sizeof(WORD) is %zu\n", sizeof(WORD));
printf("sizeof(SHORT) is %zu\n", sizeof(SHORT));
printf("sizeof(LONG) is %zu\n", sizeof(LONG));
printf("sizeof(BYTE) is %zu\n", sizeof(BYTE));
printf("sizeof(BOOL) is %zu\n", sizeof(BOOL));
printf("sizeof(COORD) is %zu\n", sizeof(COORD));
printf("sizeof(SMALL_RECT) is %zu\n", sizeof(SMALL_RECT));
}<commit_msg>Update constants.cpp<commit_after>// Development utility to confirm the width of various Win32 objects.
// This is the only C++ code in the repo, and is not used by the
// package itself.
// Compile with cl constants.cpp
#include <stdlib.h>
#include <windows.h>
#include <stdio.h>
void main()
{
printf("On this platform:\n");
printf("sizeof(int) is %zu\n", sizeof(int));
printf("sizeof(LPCSTR) is %zu\n", sizeof(LPCSTR));
printf("sizeof(LPCWSTR) is %zu\n", sizeof(LPCWSTR));
printf("sizeof(HANDLE) is %zu\n", sizeof(HANDLE));
printf("sizeof(HINSTANCE) is %zu\n", sizeof(HINSTANCE));
printf("sizeof(HWND) is %zu\n", sizeof(HWND));
printf("sizeof(HDC) is %zu\n", sizeof(HDC));
printf("sizeof(HBRUSH) is %zu\n", sizeof(HBRUSH));
printf("sizeof(ATOM) is %zu\n", sizeof(ATOM));
printf("sizeof(WPARAM) is %zu\n", sizeof(WPARAM));
printf("sizeof(LPARAM) is %zu\n", sizeof(LPARAM));
printf("sizeof(LRESULT) is %zu\n", sizeof(LRESULT));
printf("sizeof(WNDCLASS) is %zu\n", sizeof(WNDCLASS));
printf("sizeof(WNDPROC) is %zu\n", sizeof(WNDPROC));
printf("sizeof(POINT) is %zu\n", sizeof(POINT));
printf("sizeof(RECT) is %zu\n", sizeof(RECT));
printf("sizeof(MSG) is %zu\n", sizeof(MSG));
printf("sizeof(TCHAR) is %zu\n", sizeof(TCHAR));
printf("sizeof(UINT) is %zu\n", sizeof(UINT));
printf("sizeof(DWORD) is %zu\n", sizeof(DWORD));
printf("sizeof(WORD) is %zu\n", sizeof(WORD));
printf("sizeof(SHORT) is %zu\n", sizeof(SHORT));
printf("sizeof(LONG) is %zu\n", sizeof(LONG));
printf("sizeof(BYTE) is %zu\n", sizeof(BYTE));
printf("sizeof(BOOL) is %zu\n", sizeof(BOOL));
printf("sizeof(COORD) is %zu\n", sizeof(COORD));
printf("sizeof(SMALL_RECT) is %zu\n", sizeof(SMALL_RECT));
}
<|endoftext|>
|
<commit_before>/*
* PointLIFProbe.hpp
*
* Created on: Mar 10, 2009
* Author: rasmussn
*/
#ifndef POINTPROBE_HPP_
#define POINTPROBE_HPP_
#include "LayerProbe.hpp"
namespace PV {
class PointLIFProbe: public PV::LayerProbe {
public:
PointLIFProbe(const char * filename, int xLoc, int yLoc, int fLoc, const char * msg);
PointLIFProbe(int xLoc, int yLoc, int fLoc, const char * msg);
virtual ~PointLIFProbe();
virtual int outputState(float time, HyPerLayer * l);
void setSparseOutput(bool flag) {sparseOutput = flag;}
protected:
int xLoc;
int yLoc;
int fLoc;
char * msg;
bool sparseOutput;
};
}
#endif /* POINTPROBE_HPP_ */
<commit_msg>fixed pointprobe to pointlifprob<commit_after>/*
* PointLIFProbe.hpp
*
* Created on: Mar 10, 2009
* Author: rasmussn
*/
#ifndef POINTLIFPROBE_HPP_
#define POINTLIFPROBE_HPP_
#include "LayerProbe.hpp"
namespace PV {
class PointLIFProbe: public PV::LayerProbe {
public:
PointLIFProbe(const char * filename, int xLoc, int yLoc, int fLoc, const char * msg);
PointLIFProbe(int xLoc, int yLoc, int fLoc, const char * msg);
virtual ~PointLIFProbe();
virtual int outputState(float time, HyPerLayer * l);
void setSparseOutput(bool flag) {sparseOutput = flag;}
protected:
int xLoc;
int yLoc;
int fLoc;
char * msg;
bool sparseOutput;
};
}
#endif /* POINTPROBE_HPP_ */
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2008-2013 The Communi Project
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*/
#include "irccommandparser.h"
#include <climits>
/*!
\file irccommandparser.h
\brief #include <IrcCommandParser>
*/
/*!
\class IrcCommandParser irccommandparser.h <IrcCommandParser>
\ingroup utility
\brief Parses commands from user input.
\section syntax Syntax
Since the list of supported commands and the exact syntax for each
command is application specific, IrcCommandParser does not provide
any built-in command syntaxes. It is left up to the applications
to introduce the supported commands and syntaxes.
IrcCommandParser supports the following command syntax markup:
Syntax | Example | Description
-------------------|----------------------|------------
<param> | <target> | A required parameter.
(<param>) | (<key>) | An optional parameter.
<param...> | <message...> | A required parameter, multiple words accepted. (1)
(<param...>) | (<message...>) | An optional parameter, multiple words accepted. (1)
(<#param>) | (<#channel>) | An optional channel parameter. (2)
[param] | [target] | Inject the current target.
-# Multi-word parameters are only supported in the last parameter position.
-# An optional channel parameter is filled up with the current channel when absent.
\note The parameter names are insignificant, but descriptive
parameter names are recommended for the sake of readability.
\section context Context
Notice that commands are often context sensitive. While some command
may accept an optional parameter that is filled up with the current
target (channel/query) name when absent, another command may always
inject the current target name as a certain parameter. Therefore
IrcCommandParser must be kept up-to-date with the \ref currentTarget
"current target" and the \ref channels "list of channels".
\section example Example
\code
IrcCommandParser* parser = new IrcCommandParser(this);
parser->addCommand(IrcCommand::Join, "JOIN <#channel> (<key>)");
parser->addCommand(IrcCommand::Part, "PART (<#channel>) (<message...>)");
parser->addCommand(IrcCommand::Kick, "KICK (<#channel>) <nick> (<reason...>)");
parser->addCommand(IrcCommand::CtcpAction, "ME [target] <message...>");
parser->addCommand(IrcCommand::CtcpAction, "ACTION <target> <message...>");
// currently in a query, and also present on some channels
parser->setCurrentTarget("jpnurmi");
parser->setChannels(QStringList() << "#communi" << "#freenode");
\endcode
*/
struct IrcCommandInfo
{
IrcCommand::Type type;
QString command;
QString syntax;
};
class IrcCommandParserPrivate
{
public:
IrcCommandParserPrivate() : prefix(QLatin1Char('/')) { }
QList<IrcCommandInfo> find(const QString& command) const;
IrcCommand* parse(const IrcCommandInfo& command, QStringList params) const;
QString prefix;
QString current;
QStringList channels;
QList<IrcCommandInfo> commands;
};
QList<IrcCommandInfo> IrcCommandParserPrivate::find(const QString& command) const
{
QList<IrcCommandInfo> result;
foreach (const IrcCommandInfo& cmd, commands) {
if (cmd.command == command)
result += cmd;
}
return result;
}
static inline bool isOptional(const QString& token)
{
return token.startsWith(QLatin1Char('(')) && token.endsWith(QLatin1Char(')'));
}
static inline bool isMultiWord(const QString& token)
{
return token.contains(QLatin1String("..."));
}
static inline bool isChannel(const QString& token)
{
return token.contains(QLatin1Char('#'));
}
static inline bool isCurrent(const QString& token)
{
return token.startsWith(QLatin1Char('[')) && token.endsWith(QLatin1Char(']'));
}
IrcCommand* IrcCommandParserPrivate::parse(const IrcCommandInfo& command, QStringList params) const
{
const QStringList tokens = command.syntax.split(QLatin1Char(' '), QString::SkipEmptyParts);
const bool onChannel = channels.contains(current, Qt::CaseInsensitive);
int min = 0;
int max = tokens.count();
for (int i = 0; i < tokens.count(); ++i) {
const QString token = tokens.at(i);
if (!isOptional(token))
++min;
const bool last = (i == tokens.count() - 1);
if (last && isMultiWord(token))
max = INT_MAX;
if (isOptional(token) && isChannel(token)) {
if (onChannel) {
const QString param = params.value(i);
if (param.isNull() || !channels.contains(param, Qt::CaseInsensitive))
params.insert(i, current);
} else if (!channels.contains(params.value(i))) {
return 0;
}
++min;
} else if (isCurrent(token)) {
params.insert(i, current);
}
}
if (params.count() >= min && params.count() <= max) {
IrcCommand* cmd = new IrcCommand;
cmd->setType(command.type);
cmd->setParameters(params);
return cmd;
}
return 0;
}
/*!
Clears the list of commands.
\sa reset()
*/
void IrcCommandParser::clear()
{
Q_D(IrcCommandParser);
d->commands.clear();
emit commandsChanged(QStringList());
}
/*!
Resets the channels and the current target.
\sa clear()
*/
void IrcCommandParser::reset()
{
setChannels(QStringList());
setCurrentTarget(QString());
}
/*!
Constructs a command parser with \a parent.
*/
IrcCommandParser::IrcCommandParser(QObject* parent) : QObject(parent), d_ptr(new IrcCommandParserPrivate)
{
}
/*!
Destructs the command parser.
*/
IrcCommandParser::~IrcCommandParser()
{
}
/*!
This property holds the known commands.
\par Access function:
\li QStringList <b>commands</b>() const
\par Notifier signal:
\li void <b>commandsChanged</b>(const QStringList& commands)
\sa addCommand(), removeCommand()
*/
QStringList IrcCommandParser::commands() const
{
Q_D(const IrcCommandParser);
QStringList result;
foreach (const IrcCommandInfo& cmd, d->commands)
result += cmd.command;
return result;
}
/*!
Returns the syntax for the given \a command.
*/
QString IrcCommandParser::syntax(const QString& command) const
{
Q_D(const IrcCommandParser);
IrcCommandInfo info = d->find(command.toUpper()).value(0);
if (!info.command.isEmpty())
return info.command + QLatin1Char(' ') + info.syntax;
return QString();
}
/*!
Adds a command with \a type and \a syntax.
*/
void IrcCommandParser::addCommand(IrcCommand::Type type, const QString& syntax)
{
Q_D(IrcCommandParser);
QStringList words = syntax.split(QLatin1Char(' '), QString::SkipEmptyParts);
if (!words.isEmpty()) {
IrcCommandInfo cmd;
cmd.type = type;
cmd.command = words.takeFirst().toUpper();
cmd.syntax = words.join(QLatin1String(" "));
d->commands += cmd;
emit commandsChanged(commands());
}
}
/*!
Removes the command with \a type and \a syntax.
*/
void IrcCommandParser::removeCommand(IrcCommand::Type type, const QString& syntax)
{
Q_D(IrcCommandParser);
int count = d->commands.count();
QMutableListIterator<IrcCommandInfo> it(d->commands);
while (it.hasNext()) {
IrcCommandInfo cmd = it.next();
if (cmd.type == type && (syntax.isEmpty() || !syntax.compare(cmd.syntax, Qt::CaseInsensitive)))
it.remove();
}
if (d->commands.count() != count)
emit commandsChanged(commands());
}
/*!
This property holds the available channels.
\par Access function:
\li QStringList <b>channels</b>() const
\li void <b>setChannels</b>(const QStringList& channels)
\par Notifier signal:
\li void <b>channelsChanged</b>(const QStringList& channels)
*/
QStringList IrcCommandParser::channels() const
{
Q_D(const IrcCommandParser);
return d->channels;
}
void IrcCommandParser::setChannels(const QStringList& channels)
{
Q_D(IrcCommandParser);
if (d->channels != channels) {
d->channels = channels;
emit channelsChanged(channels);
}
}
/*!
This property holds the current target.
\par Access function:
\li QString <b>currentTarget</b>() const
\li void <b>setCurrentTarget</b>(const QString& target)
\par Notifier signal:
\li void <b>currentTargetChanged</b>(const QString& target)
*/
QString IrcCommandParser::currentTarget() const
{
Q_D(const IrcCommandParser);
return d->current;
}
void IrcCommandParser::setCurrentTarget(const QString& target)
{
Q_D(IrcCommandParser);
if (d->current != target) {
d->current = target;
emit currentTargetChanged(target);
}
}
/*!
This property holds the command prefix.
The default value is "/".
\par Access function:
\li QString <b>prefix</b>() const
\li void <b>setPrefix</b>(const QString& prefix)
\par Notifier signal:
\li void <b>prefixChanged</b>(const QString& prefix)
*/
QString IrcCommandParser::prefix() const
{
Q_D(const IrcCommandParser);
return d->prefix;
}
void IrcCommandParser::setPrefix(const QString& prefix)
{
Q_D(IrcCommandParser);
if (d->prefix != prefix) {
d->prefix = prefix;
emit prefixChanged(prefix);
}
}
static bool isMessage(const QString& input, const QString& prefix)
{
if (prefix.isEmpty())
return false;
return !input.startsWith(prefix) || input.startsWith(prefix.repeated(2)) || input.startsWith(prefix + QLatin1Char(' '));
}
/*!
Parses and returns the command for \a input, or \c 0 if the input is not valid.
*/
IrcCommand* IrcCommandParser::parse(const QString& input) const
{
Q_D(const IrcCommandParser);
if (isMessage(input, d->prefix)) {
QString message = input;
if (message.startsWith(d->prefix))
message.remove(0, 1);
return IrcCommand::createMessage(d->current, message.trimmed());
} else {
QStringList params = input.mid(d->prefix.length()).split(QLatin1Char(' '), QString::SkipEmptyParts);
if (!params.isEmpty()) {
const QString& command = params.takeFirst().toUpper();
foreach (const IrcCommandInfo& c, d->find(command)) {
IrcCommand* cmd = d->parse(c, params);
if (cmd)
return cmd;
}
}
}
return 0;
}
<commit_msg>IrcCommandParser: support custom commands<commit_after>/*
* Copyright (C) 2008-2013 The Communi Project
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*/
#include "irccommandparser.h"
#include <climits>
/*!
\file irccommandparser.h
\brief #include <IrcCommandParser>
*/
/*!
\class IrcCommandParser irccommandparser.h <IrcCommandParser>
\ingroup utility
\brief Parses commands from user input.
\section syntax Syntax
Since the list of supported commands and the exact syntax for each
command is application specific, IrcCommandParser does not provide
any built-in command syntaxes. It is left up to the applications
to introduce the supported commands and syntaxes.
IrcCommandParser supports the following command syntax markup:
Syntax | Example | Description
-------------------|----------------------|------------
<param> | <target> | A required parameter.
(<param>) | (<key>) | An optional parameter.
<param...> | <message...> | A required parameter, multiple words accepted. (1)
(<param...>) | (<message...>) | An optional parameter, multiple words accepted. (1)
(<#param>) | (<#channel>) | An optional channel parameter. (2)
[param] | [target] | Inject the current target.
-# Multi-word parameters are only supported in the last parameter position.
-# An optional channel parameter is filled up with the current channel when absent.
\note The parameter names are insignificant, but descriptive
parameter names are recommended for the sake of readability.
\section context Context
Notice that commands are often context sensitive. While some command
may accept an optional parameter that is filled up with the current
target (channel/query) name when absent, another command may always
inject the current target name as a certain parameter. Therefore
IrcCommandParser must be kept up-to-date with the \ref currentTarget
"current target" and the \ref channels "list of channels".
\section example Example
\code
IrcCommandParser* parser = new IrcCommandParser(this);
parser->addCommand(IrcCommand::Join, "JOIN <#channel> (<key>)");
parser->addCommand(IrcCommand::Part, "PART (<#channel>) (<message...>)");
parser->addCommand(IrcCommand::Kick, "KICK (<#channel>) <nick> (<reason...>)");
parser->addCommand(IrcCommand::CtcpAction, "ME [target] <message...>");
parser->addCommand(IrcCommand::CtcpAction, "ACTION <target> <message...>");
// currently in a query, and also present on some channels
parser->setCurrentTarget("jpnurmi");
parser->setChannels(QStringList() << "#communi" << "#freenode");
\endcode
\section custom Custom commands
The parser also supports such custom client specific commands that
are not sent to the server. Since IrcCommand does not know how to
handle custom commands, the parser treats them as a special case
injecting the command as a first parameter.
\code
IrcParser parser;
parser.addCommand(IrcCommand::Custom, "QUERY <user>");
IrcCommand* command = parser.parse("/query jpnurmi");
Q_ASSERT(command->type() == IrcCommand::Custom);
qDebug() << command->parameters; // ("QUERY", "jpnurmi")
\endcode
*/
struct IrcCommandInfo
{
IrcCommand::Type type;
QString command;
QString syntax;
};
class IrcCommandParserPrivate
{
public:
IrcCommandParserPrivate() : prefix(QLatin1Char('/')) { }
QList<IrcCommandInfo> find(const QString& command) const;
IrcCommand* parse(const IrcCommandInfo& command, QStringList params) const;
QString prefix;
QString current;
QStringList channels;
QList<IrcCommandInfo> commands;
};
QList<IrcCommandInfo> IrcCommandParserPrivate::find(const QString& command) const
{
QList<IrcCommandInfo> result;
foreach (const IrcCommandInfo& cmd, commands) {
if (cmd.command == command)
result += cmd;
}
return result;
}
static inline bool isOptional(const QString& token)
{
return token.startsWith(QLatin1Char('(')) && token.endsWith(QLatin1Char(')'));
}
static inline bool isMultiWord(const QString& token)
{
return token.contains(QLatin1String("..."));
}
static inline bool isChannel(const QString& token)
{
return token.contains(QLatin1Char('#'));
}
static inline bool isCurrent(const QString& token)
{
return token.startsWith(QLatin1Char('[')) && token.endsWith(QLatin1Char(']'));
}
IrcCommand* IrcCommandParserPrivate::parse(const IrcCommandInfo& command, QStringList params) const
{
const QStringList tokens = command.syntax.split(QLatin1Char(' '), QString::SkipEmptyParts);
const bool onChannel = channels.contains(current, Qt::CaseInsensitive);
int min = 0;
int max = tokens.count();
for (int i = 0; i < tokens.count(); ++i) {
const QString token = tokens.at(i);
if (!isOptional(token))
++min;
const bool last = (i == tokens.count() - 1);
if (last && isMultiWord(token))
max = INT_MAX;
if (isOptional(token) && isChannel(token)) {
if (onChannel) {
const QString param = params.value(i);
if (param.isNull() || !channels.contains(param, Qt::CaseInsensitive))
params.insert(i, current);
} else if (!channels.contains(params.value(i))) {
return 0;
}
++min;
} else if (isCurrent(token)) {
params.insert(i, current);
}
}
if (params.count() >= min && params.count() <= max) {
IrcCommand* cmd = new IrcCommand;
cmd->setType(command.type);
if (command.type == IrcCommand::Custom)
params.prepend(command.command);
cmd->setParameters(params);
return cmd;
}
return 0;
}
/*!
Clears the list of commands.
\sa reset()
*/
void IrcCommandParser::clear()
{
Q_D(IrcCommandParser);
d->commands.clear();
emit commandsChanged(QStringList());
}
/*!
Resets the channels and the current target.
\sa clear()
*/
void IrcCommandParser::reset()
{
setChannels(QStringList());
setCurrentTarget(QString());
}
/*!
Constructs a command parser with \a parent.
*/
IrcCommandParser::IrcCommandParser(QObject* parent) : QObject(parent), d_ptr(new IrcCommandParserPrivate)
{
}
/*!
Destructs the command parser.
*/
IrcCommandParser::~IrcCommandParser()
{
}
/*!
This property holds the known commands.
\par Access function:
\li QStringList <b>commands</b>() const
\par Notifier signal:
\li void <b>commandsChanged</b>(const QStringList& commands)
\sa addCommand(), removeCommand()
*/
QStringList IrcCommandParser::commands() const
{
Q_D(const IrcCommandParser);
QStringList result;
foreach (const IrcCommandInfo& cmd, d->commands)
result += cmd.command;
return result;
}
/*!
Returns the syntax for the given \a command.
*/
QString IrcCommandParser::syntax(const QString& command) const
{
Q_D(const IrcCommandParser);
IrcCommandInfo info = d->find(command.toUpper()).value(0);
if (!info.command.isEmpty())
return info.command + QLatin1Char(' ') + info.syntax;
return QString();
}
/*!
Adds a command with \a type and \a syntax.
*/
void IrcCommandParser::addCommand(IrcCommand::Type type, const QString& syntax)
{
Q_D(IrcCommandParser);
QStringList words = syntax.split(QLatin1Char(' '), QString::SkipEmptyParts);
if (!words.isEmpty()) {
IrcCommandInfo cmd;
cmd.type = type;
cmd.command = words.takeFirst().toUpper();
cmd.syntax = words.join(QLatin1String(" "));
d->commands += cmd;
emit commandsChanged(commands());
}
}
/*!
Removes the command with \a type and \a syntax.
*/
void IrcCommandParser::removeCommand(IrcCommand::Type type, const QString& syntax)
{
Q_D(IrcCommandParser);
int count = d->commands.count();
QMutableListIterator<IrcCommandInfo> it(d->commands);
while (it.hasNext()) {
IrcCommandInfo cmd = it.next();
if (cmd.type == type && (syntax.isEmpty() || !syntax.compare(cmd.syntax, Qt::CaseInsensitive)))
it.remove();
}
if (d->commands.count() != count)
emit commandsChanged(commands());
}
/*!
This property holds the available channels.
\par Access function:
\li QStringList <b>channels</b>() const
\li void <b>setChannels</b>(const QStringList& channels)
\par Notifier signal:
\li void <b>channelsChanged</b>(const QStringList& channels)
*/
QStringList IrcCommandParser::channels() const
{
Q_D(const IrcCommandParser);
return d->channels;
}
void IrcCommandParser::setChannels(const QStringList& channels)
{
Q_D(IrcCommandParser);
if (d->channels != channels) {
d->channels = channels;
emit channelsChanged(channels);
}
}
/*!
This property holds the current target.
\par Access function:
\li QString <b>currentTarget</b>() const
\li void <b>setCurrentTarget</b>(const QString& target)
\par Notifier signal:
\li void <b>currentTargetChanged</b>(const QString& target)
*/
QString IrcCommandParser::currentTarget() const
{
Q_D(const IrcCommandParser);
return d->current;
}
void IrcCommandParser::setCurrentTarget(const QString& target)
{
Q_D(IrcCommandParser);
if (d->current != target) {
d->current = target;
emit currentTargetChanged(target);
}
}
/*!
This property holds the command prefix.
The default value is "/".
\par Access function:
\li QString <b>prefix</b>() const
\li void <b>setPrefix</b>(const QString& prefix)
\par Notifier signal:
\li void <b>prefixChanged</b>(const QString& prefix)
*/
QString IrcCommandParser::prefix() const
{
Q_D(const IrcCommandParser);
return d->prefix;
}
void IrcCommandParser::setPrefix(const QString& prefix)
{
Q_D(IrcCommandParser);
if (d->prefix != prefix) {
d->prefix = prefix;
emit prefixChanged(prefix);
}
}
static bool isMessage(const QString& input, const QString& prefix)
{
if (prefix.isEmpty())
return false;
return !input.startsWith(prefix) || input.startsWith(prefix.repeated(2)) || input.startsWith(prefix + QLatin1Char(' '));
}
/*!
Parses and returns the command for \a input, or \c 0 if the input is not valid.
*/
IrcCommand* IrcCommandParser::parse(const QString& input) const
{
Q_D(const IrcCommandParser);
if (isMessage(input, d->prefix)) {
QString message = input;
if (message.startsWith(d->prefix))
message.remove(0, 1);
return IrcCommand::createMessage(d->current, message.trimmed());
} else {
QStringList params = input.mid(d->prefix.length()).split(QLatin1Char(' '), QString::SkipEmptyParts);
if (!params.isEmpty()) {
const QString& command = params.takeFirst().toUpper();
foreach (const IrcCommandInfo& c, d->find(command)) {
IrcCommand* cmd = d->parse(c, params);
if (cmd)
return cmd;
}
}
}
return 0;
}
<|endoftext|>
|
<commit_before>/****************************************************************************
* Copyright (C) 2014 by Savoir-Faire Linux *
* Author : Emmanuel Lepage Vallee <emmanuel.lepage@savoirfairelinux.com> *
* *
* 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 General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
***************************************************************************/
#include "itembackendmodel.h"
#include "commonbackendmanagerinterface.h"
#include "visitors/itemmodelstateserializationvisitor.h"
CommonItemBackendModel::CommonItemBackendModel(QObject* parent) : QAbstractItemModel(parent)
{
connect(ContactModel::instance(),SIGNAL(newBackendAdded(AbstractContactBackend*)),this,SLOT(slotUpdate()));
load();
}
CommonItemBackendModel::~CommonItemBackendModel()
{
while (m_lTopLevelBackends.size()) {
ProxyItem* item = m_lTopLevelBackends[0];
m_lTopLevelBackends.remove(0);
while (item->m_Children.size()) {
//FIXME I don't think it can currently happen, but there may be
//more than 2 levels.
ProxyItem* item2 = item->m_Children[0];
item->m_Children.remove(0);
delete item2;
}
delete item;
}
}
QVariant CommonItemBackendModel::data (const QModelIndex& idx, int role) const
{
if (idx.isValid()) {
ProxyItem* item = static_cast<ProxyItem*>(idx.internalPointer());
switch(role) {
case Qt::DisplayRole:
return item->backend->name();
break;
case Qt::DecorationRole:
return item->backend->icon();
break;
// case Qt::CheckStateRole:
// return item->backend->isEnabled()?Qt::Checked:Qt::Unchecked;
case Qt::CheckStateRole: {
if (ItemModelStateSerializationVisitor::instance())
return ItemModelStateSerializationVisitor::instance()->isChecked(item->backend)?Qt::Checked:Qt::Unchecked;
}
};
}
//else {
// ProxyItem* item = static_cast<ProxyItem*>(idx.internalPointer());
// return item->model->data(item->model->index(item->row,item->col));
//}
return QVariant();
}
int CommonItemBackendModel::rowCount (const QModelIndex& parent) const
{
if (!parent.isValid()) {
static bool init = false; //FIXME this doesn't allow dynamic backends
static int result = 0;
if (!init) {
for(int i=0;i<ContactModel::instance()->backends().size();i++)
result += ContactModel::instance()->backends()[i]->parentBackend()==nullptr?1:0;
init = true;
}
return result;
}
else {
ProxyItem* item = static_cast<ProxyItem*>(parent.internalPointer());
return item->backend->childrenBackends().size();
}
}
int CommonItemBackendModel::columnCount (const QModelIndex& parent) const
{
Q_UNUSED(parent)
return 1;
}
Qt::ItemFlags CommonItemBackendModel::flags(const QModelIndex& idx) const
{
if (!idx.isValid())
return 0;
ProxyItem* item = static_cast<ProxyItem*>(idx.internalPointer());
bool checkable = item->backend->supportedFeatures() & (AbstractContactBackend::SupportedFeatures::ENABLEABLE |
AbstractContactBackend::SupportedFeatures::DISABLEABLE | AbstractContactBackend::SupportedFeatures::MANAGEABLE );
return Qt::ItemIsEnabled | Qt::ItemIsSelectable | (checkable?Qt::ItemIsUserCheckable:Qt::NoItemFlags);
}
bool CommonItemBackendModel::setData (const QModelIndex& index, const QVariant &value, int role )
{
Q_UNUSED(index)
Q_UNUSED(value)
Q_UNUSED(role)
if (role == Qt::CheckStateRole) {
ProxyItem* item = static_cast<ProxyItem*>(index.internalPointer());
if (item) {
const bool old = item->backend->isEnabled();
ItemModelStateSerializationVisitor::instance()->setChecked(item->backend,value==Qt::Checked);
if (old != (value==Qt::Checked))
emit checkStateChanged();
return true;
}
}
return false;
}
QModelIndex CommonItemBackendModel::parent( const QModelIndex& idx ) const
{
if (idx.isValid()) {
ProxyItem* item = static_cast<ProxyItem*>(idx.internalPointer());
if (!item->parent)
return QModelIndex();
return createIndex(item->row,item->col,item->parent);
}
return QModelIndex();
}
QModelIndex CommonItemBackendModel::index( int row, int column, const QModelIndex& parent ) const
{
if (parent.isValid()) {
ProxyItem* parentItem = static_cast<ProxyItem*>(parent.internalPointer());
ProxyItem* item = nullptr;
if (row < parentItem->m_Children.size())
item = parentItem->m_Children[row];
else {
item = new ProxyItem();
item->parent = parentItem;
item->backend = static_cast<AbstractContactBackend*>(parentItem->backend->childrenBackends()[row]);
parentItem->m_Children << item;
}
item->row = row;
item->col = column;
return createIndex(row,column,item);
}
else { //Top level
ProxyItem* item = nullptr;
if (row < m_lTopLevelBackends.size())
item = m_lTopLevelBackends[row];
else {
item = new ProxyItem();
item->backend = ContactModel::instance()->backends()[row];
const_cast<CommonItemBackendModel*>(this)->m_lTopLevelBackends << item;
}
item->row = row;
item->col = column;
return createIndex(item->row,item->col,item);
}
}
void CommonItemBackendModel::slotUpdate()
{
emit layoutChanged();
}
QVariant CommonItemBackendModel::headerData(int section, Qt::Orientation orientation, int role) const
{
Q_UNUSED(section)
if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
return QVariant(tr("Name"));
return QVariant();
}
bool CommonItemBackendModel::save()
{
if (ItemModelStateSerializationVisitor::instance()) {
return ItemModelStateSerializationVisitor::instance()->save();
}
return false;
}
bool CommonItemBackendModel::load()
{
if (ItemModelStateSerializationVisitor::instance()) {
return ItemModelStateSerializationVisitor::instance()->load();
}
return false;
}
<commit_msg>[ #47726 ] Add support for loading new contact backends at runtime<commit_after>/****************************************************************************
* Copyright (C) 2014 by Savoir-Faire Linux *
* Author : Emmanuel Lepage Vallee <emmanuel.lepage@savoirfairelinux.com> *
* *
* 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 General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
***************************************************************************/
#include "itembackendmodel.h"
#include "commonbackendmanagerinterface.h"
#include "visitors/itemmodelstateserializationvisitor.h"
CommonItemBackendModel::CommonItemBackendModel(QObject* parent) : QAbstractItemModel(parent)
{
connect(ContactModel::instance(),SIGNAL(newBackendAdded(AbstractContactBackend*)),this,SLOT(slotUpdate()));
load();
}
CommonItemBackendModel::~CommonItemBackendModel()
{
while (m_lTopLevelBackends.size()) {
ProxyItem* item = m_lTopLevelBackends[0];
m_lTopLevelBackends.remove(0);
while (item->m_Children.size()) {
//FIXME I don't think it can currently happen, but there may be
//more than 2 levels.
ProxyItem* item2 = item->m_Children[0];
item->m_Children.remove(0);
delete item2;
}
delete item;
}
}
QVariant CommonItemBackendModel::data (const QModelIndex& idx, int role) const
{
if (idx.isValid()) {
ProxyItem* item = static_cast<ProxyItem*>(idx.internalPointer());
switch(role) {
case Qt::DisplayRole:
return item->backend->name();
break;
case Qt::DecorationRole:
return item->backend->icon();
break;
// case Qt::CheckStateRole:
// return item->backend->isEnabled()?Qt::Checked:Qt::Unchecked;
case Qt::CheckStateRole: {
if (ItemModelStateSerializationVisitor::instance())
return ItemModelStateSerializationVisitor::instance()->isChecked(item->backend)?Qt::Checked:Qt::Unchecked;
}
};
}
//else {
// ProxyItem* item = static_cast<ProxyItem*>(idx.internalPointer());
// return item->model->data(item->model->index(item->row,item->col));
//}
return QVariant();
}
int CommonItemBackendModel::rowCount (const QModelIndex& parent) const
{
if (!parent.isValid()) {
static bool init = false; //FIXME this doesn't allow dynamic backends
static int result = 0;
if (!init) {
for(int i=0;i<ContactModel::instance()->backends().size();i++)
result += ContactModel::instance()->backends()[i]->parentBackend()==nullptr?1:0;
init = true;
}
return result;
}
else {
ProxyItem* item = static_cast<ProxyItem*>(parent.internalPointer());
return item->backend->childrenBackends().size();
}
}
int CommonItemBackendModel::columnCount (const QModelIndex& parent) const
{
Q_UNUSED(parent)
return 1;
}
Qt::ItemFlags CommonItemBackendModel::flags(const QModelIndex& idx) const
{
if (!idx.isValid())
return 0;
ProxyItem* item = static_cast<ProxyItem*>(idx.internalPointer());
bool checkable = item->backend->supportedFeatures() & (AbstractContactBackend::SupportedFeatures::ENABLEABLE |
AbstractContactBackend::SupportedFeatures::DISABLEABLE | AbstractContactBackend::SupportedFeatures::MANAGEABLE );
return Qt::ItemIsEnabled | Qt::ItemIsSelectable | (checkable?Qt::ItemIsUserCheckable:Qt::NoItemFlags);
}
bool CommonItemBackendModel::setData (const QModelIndex& index, const QVariant &value, int role )
{
Q_UNUSED(index)
Q_UNUSED(value)
Q_UNUSED(role)
if (role == Qt::CheckStateRole) {
ProxyItem* item = static_cast<ProxyItem*>(index.internalPointer());
if (item) {
const bool old = item->backend->isEnabled();
ItemModelStateSerializationVisitor::instance()->setChecked(item->backend,value==Qt::Checked);
if (old != (value==Qt::Checked))
emit checkStateChanged();
return true;
}
}
return false;
}
QModelIndex CommonItemBackendModel::parent( const QModelIndex& idx ) const
{
if (idx.isValid()) {
ProxyItem* item = static_cast<ProxyItem*>(idx.internalPointer());
if (!item->parent)
return QModelIndex();
return createIndex(item->row,item->col,item->parent);
}
return QModelIndex();
}
QModelIndex CommonItemBackendModel::index( int row, int column, const QModelIndex& parent ) const
{
if (parent.isValid()) {
ProxyItem* parentItem = static_cast<ProxyItem*>(parent.internalPointer());
ProxyItem* item = nullptr;
if (row < parentItem->m_Children.size())
item = parentItem->m_Children[row];
else {
item = new ProxyItem();
item->parent = parentItem;
item->backend = static_cast<AbstractContactBackend*>(parentItem->backend->childrenBackends()[row]);
parentItem->m_Children << item;
}
item->row = row;
item->col = column;
return createIndex(row,column,item);
}
else { //Top level
ProxyItem* item = nullptr;
if (row < m_lTopLevelBackends.size())
item = m_lTopLevelBackends[row];
else {
item = new ProxyItem();
item->backend = ContactModel::instance()->backends()[row];
const_cast<CommonItemBackendModel*>(this)->m_lTopLevelBackends << item;
}
item->row = row;
item->col = column;
return createIndex(item->row,item->col,item);
}
}
void CommonItemBackendModel::slotUpdate()
{
emit layoutChanged();
}
QVariant CommonItemBackendModel::headerData(int section, Qt::Orientation orientation, int role) const
{
Q_UNUSED(section)
if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
return QVariant(tr("Name"));
return QVariant();
}
bool CommonItemBackendModel::save()
{
if (ItemModelStateSerializationVisitor::instance()) {
//Load newly enabled backends
foreach(ProxyItem* top ,m_lTopLevelBackends) {
AbstractContactBackend* current = top->backend;
if (ItemModelStateSerializationVisitor::instance()->isChecked(current) && !current->isEnabled())
current->load();
//TODO implement real tree digging
foreach(ProxyItem* leaf ,top->m_Children) {
current = leaf->backend;
if (ItemModelStateSerializationVisitor::instance()->isChecked(current) && !current->isEnabled())
current->load();
}
}
return ItemModelStateSerializationVisitor::instance()->save();
}
return false;
}
bool CommonItemBackendModel::load()
{
if (ItemModelStateSerializationVisitor::instance()) {
return ItemModelStateSerializationVisitor::instance()->load();
}
return false;
}
<|endoftext|>
|
<commit_before>/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
#ifndef __PROCESS_GMOCK_HPP__
#define __PROCESS_GMOCK_HPP__
#include <gmock/gmock.h>
#include <process/dispatch.hpp>
#include <process/event.hpp>
#include <process/filter.hpp>
#include <process/pid.hpp>
#include <stout/exit.hpp>
#include <stout/nothing.hpp>
#include <stout/synchronized.hpp>
// NOTE: The gmock library relies on std::tr1::tuple. The gmock
// library provides multiple possible 'tuple' implementations but it
// still uses std::tr1::tuple as the "type" name, hence our use of it
// in this file.
#define FUTURE_MESSAGE(name, from, to) \
process::FutureMessage(name, from, to)
#define DROP_MESSAGE(name, from, to) \
process::FutureMessage(name, from, to, true)
// The mechanism of how we match method dispatches is done by
// comparing std::type_info of the member function pointers. Because
// of this, the method function pointer passed to either
// FUTURE_DISPATCH or DROP_DISPATCH must match exactly the member
// function that is passed to the dispatch method.
// TODO(tnachen): In a situation where a base class has a virtual
// function and that a derived class overrides, and if in unit tests
// we want to verify it calls the exact derived member function, we
// need to change how dispatch matching works. One possible way is to
// move the dispatch matching logic at event dequeue time, as we then
// have the actual Process the dispatch event is calling to.
#define FUTURE_DISPATCH(pid, method) \
process::FutureDispatch(pid, method)
#define DROP_DISPATCH(pid, method) \
process::FutureDispatch(pid, method, true)
#define DROP_MESSAGES(name, from, to) \
process::DropMessages(name, from, to)
#define EXPECT_NO_FUTURE_MESSAGES(name, from, to) \
process::ExpectNoFutureMessages(name, from, to)
#define DROP_DISPATCHES(pid, method) \
process::DropDispatches(pid, method)
ACTION_TEMPLATE(PromiseArg,
HAS_1_TEMPLATE_PARAMS(int, k),
AND_1_VALUE_PARAMS(promise))
{
// TODO(benh): Use a shared_ptr for promise to defend against this
// action getting invoked more than once (e.g., used via
// WillRepeatedly). We won't be able to set it a second time but at
// least we won't get a segmentation fault. We could also consider
// warning users if they attempted to set it more than once.
promise->set(std::tr1::get<k>(args));
delete promise;
}
template <int index, typename T>
PromiseArgActionP<index, process::Promise<T>*> FutureArg(
process::Future<T>* future)
{
process::Promise<T>* promise = new process::Promise<T>();
*future = promise->future();
return PromiseArg<index>(promise);
}
ACTION_TEMPLATE(PromiseArgField,
HAS_1_TEMPLATE_PARAMS(int, k),
AND_2_VALUE_PARAMS(field, promise))
{
// TODO(benh): Use a shared_ptr for promise to defend against this
// action getting invoked more than once (e.g., used via
// WillRepeatedly). We won't be able to set it a second time but at
// least we won't get a segmentation fault. We could also consider
// warning users if they attempted to set it more than once.
promise->set(*(std::tr1::get<k>(args).*field));
delete promise;
}
template <int index, typename Field, typename T>
PromiseArgFieldActionP2<index, Field, process::Promise<T>*> FutureArgField(
Field field,
process::Future<T>* future)
{
process::Promise<T>* promise = new process::Promise<T>();
*future = promise->future();
return PromiseArgField<index>(field, promise);
}
ACTION_P2(PromiseSatisfy, promise, value)
{
promise->set(value);
delete promise;
}
template <typename T>
PromiseSatisfyActionP2<process::Promise<T>*, T> FutureSatisfy(
process::Future<T>* future,
T t)
{
process::Promise<T>* promise = new process::Promise<T>();
*future = promise->future();
return PromiseSatisfy(promise, t);
}
inline PromiseSatisfyActionP2<process::Promise<Nothing>*, Nothing>
FutureSatisfy(process::Future<Nothing>* future)
{
process::Promise<Nothing>* promise = new process::Promise<Nothing>();
*future = promise->future();
return PromiseSatisfy(promise, Nothing());
}
// This action invokes an "inner" action but captures the result and
// stores a copy of it in a future. Note that this is implemented
// similarly to the IgnoreResult action, which relies on the cast
// operator to Action<F> which must occur (implicitly) before the
// expression has completed, hence we can pass the Future<R>* all the
// way through to our action "implementation".
template <typename R, typename A>
class FutureResultAction
{
public:
explicit FutureResultAction(process::Future<R>* future, const A& action)
: future(future),
action(action) {}
template <typename F>
operator ::testing::Action<F>() const
{
return ::testing::Action<F>(new Implementation<F>(future, action));
}
private:
template <typename F>
class Implementation : public ::testing::ActionInterface<F>
{
public:
explicit Implementation(process::Future<R>* future, const A& action)
: action(action)
{
*future = promise.future();
}
virtual typename ::testing::ActionInterface<F>::Result Perform(
const typename ::testing::ActionInterface<F>::ArgumentTuple& args)
{
const typename ::testing::ActionInterface<F>::Result result =
action.Perform(args);
promise.set(result);
return result;
}
private:
// Not copyable, not assignable.
Implementation(const Implementation&);
Implementation& operator = (const Implementation&);
process::Promise<R> promise;
const ::testing::Action<F> action;
};
process::Future<R>* future;
const A action;
};
template <typename R, typename A>
FutureResultAction<R, A> FutureResult(
process::Future<R>* future,
const A& action)
{
return FutureResultAction<R, A>(future, action);
}
namespace process {
class MockFilter : public Filter
{
public:
MockFilter()
{
EXPECT_CALL(*this, filter(testing::A<const MessageEvent&>()))
.WillRepeatedly(testing::Return(false));
EXPECT_CALL(*this, filter(testing::A<const DispatchEvent&>()))
.WillRepeatedly(testing::Return(false));
EXPECT_CALL(*this, filter(testing::A<const HttpEvent&>()))
.WillRepeatedly(testing::Return(false));
EXPECT_CALL(*this, filter(testing::A<const ExitedEvent&>()))
.WillRepeatedly(testing::Return(false));
}
MOCK_METHOD1(filter, bool(const MessageEvent&));
MOCK_METHOD1(filter, bool(const DispatchEvent&));
MOCK_METHOD1(filter, bool(const HttpEvent&));
MOCK_METHOD1(filter, bool(const ExitedEvent&));
};
// A definition of a libprocess filter to enable waiting for events
// (such as messages or dispatches) via in tests. This is not meant to
// be used directly by tests; tests should use macros like
// FUTURE_MESSAGE and FUTURE_DISPATCH instead.
class TestsFilter : public Filter
{
public:
TestsFilter() = default;
virtual bool filter(const MessageEvent& event) { return handle(event); }
virtual bool filter(const DispatchEvent& event) { return handle(event); }
virtual bool filter(const HttpEvent& event) { return handle(event); }
virtual bool filter(const ExitedEvent& event) { return handle(event); }
template <typename T>
bool handle(const T& t)
{
synchronized (mutex) {
return mock.filter(t);
}
}
MockFilter mock;
// We use a recursive mutex here in the event that satisfying the
// future created in FutureMessage or FutureDispatch via the
// FutureArgField or FutureSatisfy actions invokes callbacks (from
// Future::then or Future::onAny, etc) that themselves invoke
// FutureDispatch or FutureMessage.
std::recursive_mutex mutex;
};
class FilterTestEventListener : public ::testing::EmptyTestEventListener
{
public:
// Returns the singleton instance of the listener.
static FilterTestEventListener* instance()
{
static FilterTestEventListener* listener = new FilterTestEventListener();
return listener;
}
// Installs and returns the filter, creating it if necessary.
TestsFilter* install()
{
if (!started) {
EXIT(1)
<< "To use FUTURE/DROP_MESSAGE/DISPATCH, etc. you need to do the "
<< "following before you invoke RUN_ALL_TESTS():\n\n"
<< "\t::testing::TestEventListeners& listeners =\n"
<< "\t ::testing::UnitTest::GetInstance()->listeners();\n"
<< "\tlisteners.Append(process::FilterTestEventListener::instance());";
}
if (filter != NULL) {
return filter;
}
filter = new TestsFilter();
// Set the filter in libprocess.
process::filter(filter);
return filter;
}
virtual void OnTestProgramStart(const ::testing::UnitTest&)
{
started = true;
}
virtual void OnTestEnd(const ::testing::TestInfo&)
{
if (filter != NULL) {
// Remove the filter in libprocess _before_ deleting.
process::filter(NULL);
delete filter;
filter = NULL;
}
}
private:
FilterTestEventListener() : filter(NULL), started(false) {}
TestsFilter* filter;
// Indicates if we got the OnTestProgramStart callback in order to
// detect if we have been properly added as a listener.
bool started;
};
MATCHER_P3(MessageMatcher, name, from, to, "")
{
const MessageEvent& event = ::std::tr1::get<0>(arg);
return (testing::Matcher<std::string>(name).Matches(event.message->name) &&
testing::Matcher<UPID>(from).Matches(event.message->from) &&
testing::Matcher<UPID>(to).Matches(event.message->to));
}
MATCHER_P2(DispatchMatcher, pid, method, "")
{
const DispatchEvent& event = ::std::tr1::get<0>(arg);
return (testing::Matcher<UPID>(pid).Matches(event.pid) &&
event.functionType.isSome() &&
*event.functionType.get() == typeid(method));
}
template <typename Name, typename From, typename To>
Future<Message> FutureMessage(Name name, From from, To to, bool drop = false)
{
TestsFilter* filter = FilterTestEventListener::instance()->install();
Future<Message> future;
synchronized (filter->mutex) {
EXPECT_CALL(filter->mock, filter(testing::A<const MessageEvent&>()))
.With(MessageMatcher(name, from, to))
.WillOnce(testing::DoAll(FutureArgField<0>(
&MessageEvent::message,
&future),
testing::Return(drop)))
.RetiresOnSaturation(); // Don't impose any subsequent expectations.
}
return future;
}
template <typename PID, typename Method>
Future<Nothing> FutureDispatch(PID pid, Method method, bool drop = false)
{
TestsFilter* filter = FilterTestEventListener::instance()->install();
Future<Nothing> future;
synchronized (filter->mutex) {
EXPECT_CALL(filter->mock, filter(testing::A<const DispatchEvent&>()))
.With(DispatchMatcher(pid, method))
.WillOnce(testing::DoAll(FutureSatisfy(&future),
testing::Return(drop)))
.RetiresOnSaturation(); // Don't impose any subsequent expectations.
}
return future;
}
template <typename Name, typename From, typename To>
void DropMessages(Name name, From from, To to)
{
TestsFilter* filter = FilterTestEventListener::instance()->install();
synchronized (filter->mutex) {
EXPECT_CALL(filter->mock, filter(testing::A<const MessageEvent&>()))
.With(MessageMatcher(name, from, to))
.WillRepeatedly(testing::Return(true));
}
}
template <typename Name, typename From, typename To>
void ExpectNoFutureMessages(Name name, From from, To to)
{
TestsFilter* filter = FilterTestEventListener::instance()->install();
synchronized (filter->mutex) {
EXPECT_CALL(filter->mock, filter(testing::A<const MessageEvent&>()))
.With(MessageMatcher(name, from, to))
.Times(0);
}
}
template <typename PID, typename Method>
void DropDispatches(PID pid, Method method)
{
TestsFilter* filter = FilterTestEventListener::instance()->install();
synchronized (filter->mutex) {
EXPECT_CALL(filter->mock, filter(testing::A<const DispatchEvent&>()))
.With(DispatchMatcher(pid, method))
.WillRepeatedly(testing::Return(true));
}
}
} // namespace process {
#endif // __PROCESS_GMOCK_HPP__
<commit_msg>Added FutureUnionMessage, DropUnionMessages and ExpectNoFutureUnionMessages.<commit_after>/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
#ifndef __PROCESS_GMOCK_HPP__
#define __PROCESS_GMOCK_HPP__
#include <gmock/gmock.h>
#include <process/dispatch.hpp>
#include <process/event.hpp>
#include <process/filter.hpp>
#include <process/pid.hpp>
#include <stout/exit.hpp>
#include <stout/nothing.hpp>
#include <stout/synchronized.hpp>
// NOTE: The gmock library relies on std::tr1::tuple. The gmock
// library provides multiple possible 'tuple' implementations but it
// still uses std::tr1::tuple as the "type" name, hence our use of it
// in this file.
#define FUTURE_MESSAGE(name, from, to) \
process::FutureMessage(name, from, to)
#define DROP_MESSAGE(name, from, to) \
process::FutureMessage(name, from, to, true)
// The mechanism of how we match method dispatches is done by
// comparing std::type_info of the member function pointers. Because
// of this, the method function pointer passed to either
// FUTURE_DISPATCH or DROP_DISPATCH must match exactly the member
// function that is passed to the dispatch method.
// TODO(tnachen): In a situation where a base class has a virtual
// function and that a derived class overrides, and if in unit tests
// we want to verify it calls the exact derived member function, we
// need to change how dispatch matching works. One possible way is to
// move the dispatch matching logic at event dequeue time, as we then
// have the actual Process the dispatch event is calling to.
#define FUTURE_DISPATCH(pid, method) \
process::FutureDispatch(pid, method)
#define DROP_DISPATCH(pid, method) \
process::FutureDispatch(pid, method, true)
#define DROP_MESSAGES(name, from, to) \
process::DropMessages(name, from, to)
#define EXPECT_NO_FUTURE_MESSAGES(name, from, to) \
process::ExpectNoFutureMessages(name, from, to)
#define DROP_DISPATCHES(pid, method) \
process::DropDispatches(pid, method)
ACTION_TEMPLATE(PromiseArg,
HAS_1_TEMPLATE_PARAMS(int, k),
AND_1_VALUE_PARAMS(promise))
{
// TODO(benh): Use a shared_ptr for promise to defend against this
// action getting invoked more than once (e.g., used via
// WillRepeatedly). We won't be able to set it a second time but at
// least we won't get a segmentation fault. We could also consider
// warning users if they attempted to set it more than once.
promise->set(std::tr1::get<k>(args));
delete promise;
}
template <int index, typename T>
PromiseArgActionP<index, process::Promise<T>*> FutureArg(
process::Future<T>* future)
{
process::Promise<T>* promise = new process::Promise<T>();
*future = promise->future();
return PromiseArg<index>(promise);
}
ACTION_TEMPLATE(PromiseArgField,
HAS_1_TEMPLATE_PARAMS(int, k),
AND_2_VALUE_PARAMS(field, promise))
{
// TODO(benh): Use a shared_ptr for promise to defend against this
// action getting invoked more than once (e.g., used via
// WillRepeatedly). We won't be able to set it a second time but at
// least we won't get a segmentation fault. We could also consider
// warning users if they attempted to set it more than once.
promise->set(*(std::tr1::get<k>(args).*field));
delete promise;
}
template <int index, typename Field, typename T>
PromiseArgFieldActionP2<index, Field, process::Promise<T>*> FutureArgField(
Field field,
process::Future<T>* future)
{
process::Promise<T>* promise = new process::Promise<T>();
*future = promise->future();
return PromiseArgField<index>(field, promise);
}
ACTION_P2(PromiseSatisfy, promise, value)
{
promise->set(value);
delete promise;
}
template <typename T>
PromiseSatisfyActionP2<process::Promise<T>*, T> FutureSatisfy(
process::Future<T>* future,
T t)
{
process::Promise<T>* promise = new process::Promise<T>();
*future = promise->future();
return PromiseSatisfy(promise, t);
}
inline PromiseSatisfyActionP2<process::Promise<Nothing>*, Nothing>
FutureSatisfy(process::Future<Nothing>* future)
{
process::Promise<Nothing>* promise = new process::Promise<Nothing>();
*future = promise->future();
return PromiseSatisfy(promise, Nothing());
}
// This action invokes an "inner" action but captures the result and
// stores a copy of it in a future. Note that this is implemented
// similarly to the IgnoreResult action, which relies on the cast
// operator to Action<F> which must occur (implicitly) before the
// expression has completed, hence we can pass the Future<R>* all the
// way through to our action "implementation".
template <typename R, typename A>
class FutureResultAction
{
public:
explicit FutureResultAction(process::Future<R>* future, const A& action)
: future(future),
action(action) {}
template <typename F>
operator ::testing::Action<F>() const
{
return ::testing::Action<F>(new Implementation<F>(future, action));
}
private:
template <typename F>
class Implementation : public ::testing::ActionInterface<F>
{
public:
explicit Implementation(process::Future<R>* future, const A& action)
: action(action)
{
*future = promise.future();
}
virtual typename ::testing::ActionInterface<F>::Result Perform(
const typename ::testing::ActionInterface<F>::ArgumentTuple& args)
{
const typename ::testing::ActionInterface<F>::Result result =
action.Perform(args);
promise.set(result);
return result;
}
private:
// Not copyable, not assignable.
Implementation(const Implementation&);
Implementation& operator = (const Implementation&);
process::Promise<R> promise;
const ::testing::Action<F> action;
};
process::Future<R>* future;
const A action;
};
template <typename R, typename A>
FutureResultAction<R, A> FutureResult(
process::Future<R>* future,
const A& action)
{
return FutureResultAction<R, A>(future, action);
}
namespace process {
class MockFilter : public Filter
{
public:
MockFilter()
{
EXPECT_CALL(*this, filter(testing::A<const MessageEvent&>()))
.WillRepeatedly(testing::Return(false));
EXPECT_CALL(*this, filter(testing::A<const DispatchEvent&>()))
.WillRepeatedly(testing::Return(false));
EXPECT_CALL(*this, filter(testing::A<const HttpEvent&>()))
.WillRepeatedly(testing::Return(false));
EXPECT_CALL(*this, filter(testing::A<const ExitedEvent&>()))
.WillRepeatedly(testing::Return(false));
}
MOCK_METHOD1(filter, bool(const MessageEvent&));
MOCK_METHOD1(filter, bool(const DispatchEvent&));
MOCK_METHOD1(filter, bool(const HttpEvent&));
MOCK_METHOD1(filter, bool(const ExitedEvent&));
};
// A definition of a libprocess filter to enable waiting for events
// (such as messages or dispatches) via in tests. This is not meant to
// be used directly by tests; tests should use macros like
// FUTURE_MESSAGE and FUTURE_DISPATCH instead.
class TestsFilter : public Filter
{
public:
TestsFilter() = default;
virtual bool filter(const MessageEvent& event) { return handle(event); }
virtual bool filter(const DispatchEvent& event) { return handle(event); }
virtual bool filter(const HttpEvent& event) { return handle(event); }
virtual bool filter(const ExitedEvent& event) { return handle(event); }
template <typename T>
bool handle(const T& t)
{
synchronized (mutex) {
return mock.filter(t);
}
}
MockFilter mock;
// We use a recursive mutex here in the event that satisfying the
// future created in FutureMessage or FutureDispatch via the
// FutureArgField or FutureSatisfy actions invokes callbacks (from
// Future::then or Future::onAny, etc) that themselves invoke
// FutureDispatch or FutureMessage.
std::recursive_mutex mutex;
};
class FilterTestEventListener : public ::testing::EmptyTestEventListener
{
public:
// Returns the singleton instance of the listener.
static FilterTestEventListener* instance()
{
static FilterTestEventListener* listener = new FilterTestEventListener();
return listener;
}
// Installs and returns the filter, creating it if necessary.
TestsFilter* install()
{
if (!started) {
EXIT(1)
<< "To use FUTURE/DROP_MESSAGE/DISPATCH, etc. you need to do the "
<< "following before you invoke RUN_ALL_TESTS():\n\n"
<< "\t::testing::TestEventListeners& listeners =\n"
<< "\t ::testing::UnitTest::GetInstance()->listeners();\n"
<< "\tlisteners.Append(process::FilterTestEventListener::instance());";
}
if (filter != NULL) {
return filter;
}
filter = new TestsFilter();
// Set the filter in libprocess.
process::filter(filter);
return filter;
}
virtual void OnTestProgramStart(const ::testing::UnitTest&)
{
started = true;
}
virtual void OnTestEnd(const ::testing::TestInfo&)
{
if (filter != NULL) {
// Remove the filter in libprocess _before_ deleting.
process::filter(NULL);
delete filter;
filter = NULL;
}
}
private:
FilterTestEventListener() : filter(NULL), started(false) {}
TestsFilter* filter;
// Indicates if we got the OnTestProgramStart callback in order to
// detect if we have been properly added as a listener.
bool started;
};
MATCHER_P3(MessageMatcher, name, from, to, "")
{
const MessageEvent& event = ::std::tr1::get<0>(arg);
return (testing::Matcher<std::string>(name).Matches(event.message->name) &&
testing::Matcher<UPID>(from).Matches(event.message->from) &&
testing::Matcher<UPID>(to).Matches(event.message->to));
}
// This matches protobuf messages that are described using the
// standard protocol buffer "union" trick, see:
// https://developers.google.com/protocol-buffers/docs/techniques#union.
MATCHER_P4(UnionMessageMatcher, message, unionType, from, to, "")
{
const process::MessageEvent& event = ::std::tr1::get<0>(arg);
message_type message;
return (testing::Matcher<std::string>(message.GetTypeName()).Matches(
event.message->name) &&
message.ParseFromString(event.message->body) &&
testing::Matcher<unionType_type>(unionType).Matches(message.type()) &&
testing::Matcher<process::UPID>(from).Matches(event.message->from) &&
testing::Matcher<process::UPID>(to).Matches(event.message->to));
}
MATCHER_P2(DispatchMatcher, pid, method, "")
{
const DispatchEvent& event = ::std::tr1::get<0>(arg);
return (testing::Matcher<UPID>(pid).Matches(event.pid) &&
event.functionType.isSome() &&
*event.functionType.get() == typeid(method));
}
template <typename Name, typename From, typename To>
Future<Message> FutureMessage(Name name, From from, To to, bool drop = false)
{
TestsFilter* filter = FilterTestEventListener::instance()->install();
Future<Message> future;
synchronized (filter->mutex) {
EXPECT_CALL(filter->mock, filter(testing::A<const MessageEvent&>()))
.With(MessageMatcher(name, from, to))
.WillOnce(testing::DoAll(FutureArgField<0>(
&MessageEvent::message,
&future),
testing::Return(drop)))
.RetiresOnSaturation(); // Don't impose any subsequent expectations.
}
return future;
}
template <typename Message, typename UnionType, typename From, typename To>
Future<process::Message> FutureUnionMessage(
Message message, UnionType unionType, From from, To to, bool drop = false)
{
TestsFilter* filter =
FilterTestEventListener::instance()->install();
Future<process::Message> future;
synchronized (filter->mutex) {
EXPECT_CALL(filter->mock, filter(testing::A<const MessageEvent&>()))
.With(UnionMessageMatcher(message, unionType, from, to))
.WillOnce(testing::DoAll(FutureArgField<0>(
&MessageEvent::message,
&future),
testing::Return(drop)))
.RetiresOnSaturation(); // Don't impose any subsequent expectations.
}
return future;
}
template <typename PID, typename Method>
Future<Nothing> FutureDispatch(PID pid, Method method, bool drop = false)
{
TestsFilter* filter = FilterTestEventListener::instance()->install();
Future<Nothing> future;
synchronized (filter->mutex) {
EXPECT_CALL(filter->mock, filter(testing::A<const DispatchEvent&>()))
.With(DispatchMatcher(pid, method))
.WillOnce(testing::DoAll(FutureSatisfy(&future),
testing::Return(drop)))
.RetiresOnSaturation(); // Don't impose any subsequent expectations.
}
return future;
}
template <typename Name, typename From, typename To>
void DropMessages(Name name, From from, To to)
{
TestsFilter* filter = FilterTestEventListener::instance()->install();
synchronized (filter->mutex) {
EXPECT_CALL(filter->mock, filter(testing::A<const MessageEvent&>()))
.With(MessageMatcher(name, from, to))
.WillRepeatedly(testing::Return(true));
}
}
template <typename Message, typename UnionType, typename From, typename To>
void DropUnionMessages(Message message, UnionType unionType, From from, To to)
{
TestsFilter* filter = FilterTestEventListener::instance()->install();
synchronized (filter->mutex) {
EXPECT_CALL(filter->mock, filter(testing::A<const MessageEvent&>()))
.With(UnionMessageMatcher(message, unionType, from, to))
.WillRepeatedly(testing::Return(true));
}
}
template <typename Name, typename From, typename To>
void ExpectNoFutureMessages(Name name, From from, To to)
{
TestsFilter* filter = FilterTestEventListener::instance()->install();
synchronized (filter->mutex) {
EXPECT_CALL(filter->mock, filter(testing::A<const MessageEvent&>()))
.With(MessageMatcher(name, from, to))
.Times(0);
}
}
template <typename Message, typename UnionType, typename From, typename To>
void ExpectNoFutureUnionMessages(
Message message, UnionType unionType, From from, To to)
{
TestsFilter* filter = FilterTestEventListener::instance()->install();
synchronized (filter->mutex) {
EXPECT_CALL(filter->mock, filter(testing::A<const MessageEvent&>()))
.With(UnionMessageMatcher(message, unionType, from, to))
.Times(0);
}
}
template <typename PID, typename Method>
void DropDispatches(PID pid, Method method)
{
TestsFilter* filter = FilterTestEventListener::instance()->install();
synchronized (filter->mutex) {
EXPECT_CALL(filter->mock, filter(testing::A<const DispatchEvent&>()))
.With(DispatchMatcher(pid, method))
.WillRepeatedly(testing::Return(true));
}
}
} // namespace process {
#endif // __PROCESS_GMOCK_HPP__
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2017 Trail of Bits, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <memory>
#include <unordered_map>
#include <llvm/ADT/SmallVector.h>
#include <llvm/IR/BasicBlock.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/IntrinsicInst.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Metadata.h>
#include <llvm/IR/Module.h>
#include "remill/Arch/Arch.h"
#include "remill/Arch/Name.h"
#include "remill/BC/ABI.h"
#include "remill/BC/Compat/Attributes.h"
#include "remill/BC/Compat/DebugInfo.h"
#include "remill/BC/Compat/GlobalValue.h"
#include "remill/BC/Util.h"
#include "remill/BC/Version.h"
#include "remill/OS/OS.h"
DEFINE_string(arch, "",
"Architecture of the code being translated. "
"Valid architectures: x86, amd64 (with or without "
"`_avx` or `_avx512` appended), aarch64, "
"mips32, mips64");
DECLARE_string(os);
namespace remill {
namespace {
static unsigned AddressSize(ArchName arch_name) {
switch (arch_name) {
case kArchInvalid:
LOG(FATAL) << "Cannot get address size for invalid arch.";
return 0;
case kArchX86:
case kArchX86_AVX:
case kArchX86_AVX512:
case kArchMips32:
return 32;
case kArchAMD64:
case kArchAMD64_AVX:
case kArchAMD64_AVX512:
case kArchMips64:
case kArchAArch64LittleEndian:
return 64;
}
return 0;
}
// Used for static storage duration caches of `Arch` specializations. The
// `std::unique_ptr` makes sure that the `Arch` objects are freed on `exit`
// from the program.
using ArchPtr = std::unique_ptr<const Arch>;
using ArchCache = std::unordered_map<uint32_t, ArchPtr>;
} // namespace
Arch::Arch(OSName os_name_, ArchName arch_name_)
: os_name(os_name_),
arch_name(arch_name_),
address_size(AddressSize(arch_name_)) {}
Arch::~Arch(void) {}
bool Arch::LazyDecodeInstruction(
uint64_t address, const std::string &instr_bytes,
Instruction &inst) const {
return DecodeInstruction(address, instr_bytes, inst);
}
llvm::Triple Arch::BasicTriple(void) const {
llvm::Triple triple;
switch (os_name) {
case kOSInvalid:
LOG(FATAL) << "Cannot get triple OS.";
break;
case kOSLinux:
case kOSVxWorks:
triple.setOS(llvm::Triple::Linux);
triple.setEnvironment(llvm::Triple::GNU);
triple.setVendor(llvm::Triple::PC);
triple.setObjectFormat(llvm::Triple::ELF);
break;
case kOSmacOS:
triple.setOS(llvm::Triple::MacOSX);
triple.setEnvironment(llvm::Triple::UnknownEnvironment);
triple.setVendor(llvm::Triple::Apple);
triple.setObjectFormat(llvm::Triple::MachO);
break;
case kOSWindows:
triple.setOS(llvm::Triple::Win32);
triple.setEnvironment(llvm::Triple::MSVC);
triple.setVendor(llvm::Triple::UnknownVendor);
triple.setObjectFormat(llvm::Triple::COFF);
break;
}
return triple;
}
const Arch *Arch::Get(OSName os_name_, ArchName arch_name_) {
switch (arch_name_) {
case kArchInvalid:
LOG(FATAL) << "Unrecognized architecture.";
return nullptr;
case kArchAArch64LittleEndian: {
static ArchCache gArchAArch64LE;
auto &arch = gArchAArch64LE[os_name_];
if (!arch) {
DLOG(INFO) << "Using architecture: AArch64, feature set: Little Endian";
arch = ArchPtr(GetAArch64(os_name_, arch_name_));
}
return arch.get();
}
case kArchX86: {
static ArchCache gArchX86;
auto &arch = gArchX86[os_name_];
if (!arch) {
DLOG(INFO) << "Using architecture: X86";
arch = ArchPtr(GetX86(os_name_, arch_name_));
}
return arch.get();
}
case kArchMips32: {
static ArchCache gArchMips;
auto &arch = gArchMips[os_name_];
if (!arch) {
DLOG(INFO) << "Using architecture: 32-bit MIPS";
arch = ArchPtr(GetMips(os_name_, arch_name_));
}
return arch.get();
}
case kArchMips64: {
static ArchCache gArchMips64;
auto &arch = gArchMips64[os_name_];
if (!arch) {
DLOG(INFO) << "Using architecture: 64-bit MIPS";
arch = ArchPtr(GetMips(os_name_, arch_name_));
}
return arch.get();
}
case kArchX86_AVX: {
static ArchCache gArchX86_AVX;
auto &arch = gArchX86_AVX[os_name_];
if (!arch) {
DLOG(INFO) << "Using architecture: X86, feature set: AVX";
arch = ArchPtr(GetX86(os_name_, arch_name_));
}
return arch.get();
}
case kArchX86_AVX512: {
static ArchCache gArchX86_AVX512;
auto &arch = gArchX86_AVX512[os_name_];
if (!arch) {
DLOG(INFO) << "Using architecture: X86, feature set: AVX512";
arch = ArchPtr(GetX86(os_name_, arch_name_));
}
return arch.get();
}
case kArchAMD64: {
static ArchCache gArchAMD64;
auto &arch = gArchAMD64[os_name_];
if (!arch) {
DLOG(INFO) << "Using architecture: AMD64";
arch = ArchPtr(GetX86(os_name_, arch_name_));
}
return arch.get();
}
case kArchAMD64_AVX: {
static ArchCache gArchAMD64_AVX;
auto &arch = gArchAMD64_AVX[os_name_];
if (!arch) {
DLOG(INFO) << "Using architecture: AMD64, feature set: AVX";
arch = ArchPtr(GetX86(os_name_, arch_name_));
}
return arch.get();
}
case kArchAMD64_AVX512: {
static ArchCache gArchAMD64_AVX512;
auto &arch = gArchAMD64_AVX512[os_name_];
if (!arch) {
DLOG(INFO) << "Using architecture: AMD64, feature set: AVX512";
arch = ArchPtr(GetX86(os_name_, arch_name_));
}
return arch.get();
}
}
return nullptr;
}
const Arch *Arch::GetMips(OSName, ArchName) {
return nullptr;
}
const Arch *GetHostArch(void) {
static const Arch *gHostArch = nullptr;
if (!gHostArch) {
gHostArch = Arch::Get(GetOSName(REMILL_OS), GetArchName(REMILL_ARCH));
}
return gHostArch;
}
const Arch *GetTargetArch(void) {
static const Arch *gTargetArch = nullptr;
if (!gTargetArch) {
gTargetArch = Arch::Get(GetOSName(FLAGS_os), GetArchName(FLAGS_arch));
}
return gTargetArch;
}
bool Arch::IsX86(void) const {
switch (arch_name) {
case remill::kArchX86:
case remill::kArchX86_AVX:
case remill::kArchX86_AVX512:
return true;
default:
return false;
}
}
bool Arch::IsAMD64(void) const {
switch (arch_name) {
case remill::kArchAMD64:
case remill::kArchAMD64_AVX:
case remill::kArchAMD64_AVX512:
return true;
default:
return false;
}
}
bool Arch::IsAArch64(void) const {
return remill::kArchAArch64LittleEndian == arch_name;
}
namespace {
// These variables must always be defined within `__remill_basic_block`.
static bool BlockHasSpecialVars(llvm::Function *basic_block) {
return FindVarInFunction(basic_block, "STATE", true) &&
FindVarInFunction(basic_block, "MEMORY", true) &&
FindVarInFunction(basic_block, "PC", true) &&
FindVarInFunction(basic_block, "BRANCH_TAKEN", true);
}
// Clang isn't guaranteed to play nice and name the LLVM values within the
// `__remill_basic_block` intrinsic with the same names as we find in the
// C++ definition of that function. However, we compile that function with
// debug information, and so we will try to recover the variables names for
// later lookup.
static void FixupBasicBlockVariables(llvm::Function *basic_block) {
if (BlockHasSpecialVars(basic_block)) {
return;
}
for (auto &block : *basic_block) {
for (auto &inst : block) {
if (auto decl_inst = llvm::dyn_cast<llvm::DbgDeclareInst>(&inst)) {
auto addr = decl_inst->getAddress();
#if LLVM_VERSION_NUMBER >= LLVM_VERSION(3, 7)
addr->setName(decl_inst->getVariable()->getName());
#else
llvm::DIVariable var(decl_inst->getVariable());
addr->setName(var.getName());
#endif
}
}
}
CHECK(BlockHasSpecialVars(basic_block))
<< "Unable to locate required variables in `__remill_basic_block`.";
}
// Initialize some attributes that are common to all newly created block
// functions. Also, give pretty names to the arguments of block functions.
static void InitBlockFunctionAttributes(llvm::Function *block_func) {
block_func->setLinkage(llvm::GlobalValue::ExternalLinkage);
block_func->setVisibility(llvm::GlobalValue::DefaultVisibility);
remill::NthArgument(block_func, kMemoryPointerArgNum)->setName("memory");
remill::NthArgument(block_func, kStatePointerArgNum)->setName("state");
remill::NthArgument(block_func, kPCArgNum)->setName("pc");
}
} // namespace
// Add attributes to llvm::Argument in a way portable across LLVMs
static void AddNoAliasToArgument(llvm::Argument *Arg) {
IF_LLVM_LT_39(
Arg->addAttr(
llvm::AttributeSet::get(
Arg->getContext(),
Arg->getArgNo() + 1,
llvm::Attribute::NoAlias)
);
);
IF_LLVM_GTE_39(
Arg->addAttr(llvm::Attribute::NoAlias);
);
}
// ensures that mandatory remill functions have the correct
// type signature and variable names
static void PrepareModuleRemillFunctions(llvm::Module *mod) {
auto basic_block = BasicBlockFunction(mod);
InitFunctionAttributes(basic_block);
FixupBasicBlockVariables(basic_block);
InitBlockFunctionAttributes(basic_block);
basic_block->addFnAttr(llvm::Attribute::OptimizeNone);
basic_block->removeFnAttr(llvm::Attribute::AlwaysInline);
basic_block->removeFnAttr(llvm::Attribute::InlineHint);
basic_block->addFnAttr(llvm::Attribute::NoInline);
basic_block->setVisibility(llvm::GlobalValue::DefaultVisibility);
AddNoAliasToArgument(remill::NthArgument(basic_block, kStatePointerArgNum));
AddNoAliasToArgument(remill::NthArgument(basic_block, kMemoryPointerArgNum));
}
// Converts an LLVM module object to have the right triple / data layout
// information for the target architecture.
//
void Arch::PrepareModuleDataLayout(llvm::Module *mod) const {
mod->setDataLayout(DataLayout().getStringRepresentation());
mod->setTargetTriple(Triple().str());
// Go and remove compile-time attributes added into the semantics. These
// can screw up later compilation. We purposefully compile semantics with
// things like auto-vectorization disabled so that it keeps the bitcode
// to a simpler subset of the available LLVM instuction set. If/when we
// compile this bitcode back into machine code, we may want to use those
// features, and clang will complain if we try to do so if these metadata
// remain present.
auto &context = mod->getContext();
llvm::AttributeSet target_attribs;
target_attribs = target_attribs.addAttribute(
context,
IF_LLVM_LT_50_(llvm::AttributeSet::FunctionIndex)
"target-features");
target_attribs = target_attribs.addAttribute(
context,
IF_LLVM_LT_50_(llvm::AttributeSet::FunctionIndex)
"target-cpu");
for (llvm::Function &func : *mod) {
auto attribs = func.getAttributes();
attribs = attribs.removeAttributes(
context,
llvm::AttributeLoc::FunctionIndex,
target_attribs);
func.setAttributes(attribs);
}
}
void Arch::PrepareModule(llvm::Module *mod) const {
PrepareModuleRemillFunctions(mod);
PrepareModuleDataLayout(mod);
}
} // namespace remill
<commit_msg>Follow remill coding style<commit_after>/*
* Copyright (c) 2017 Trail of Bits, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <memory>
#include <unordered_map>
#include <llvm/ADT/SmallVector.h>
#include <llvm/IR/BasicBlock.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/IntrinsicInst.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Metadata.h>
#include <llvm/IR/Module.h>
#include "remill/Arch/Arch.h"
#include "remill/Arch/Name.h"
#include "remill/BC/ABI.h"
#include "remill/BC/Compat/Attributes.h"
#include "remill/BC/Compat/DebugInfo.h"
#include "remill/BC/Compat/GlobalValue.h"
#include "remill/BC/Util.h"
#include "remill/BC/Version.h"
#include "remill/OS/OS.h"
DEFINE_string(arch, "",
"Architecture of the code being translated. "
"Valid architectures: x86, amd64 (with or without "
"`_avx` or `_avx512` appended), aarch64, "
"mips32, mips64");
DECLARE_string(os);
namespace remill {
namespace {
static unsigned AddressSize(ArchName arch_name) {
switch (arch_name) {
case kArchInvalid:
LOG(FATAL) << "Cannot get address size for invalid arch.";
return 0;
case kArchX86:
case kArchX86_AVX:
case kArchX86_AVX512:
case kArchMips32:
return 32;
case kArchAMD64:
case kArchAMD64_AVX:
case kArchAMD64_AVX512:
case kArchMips64:
case kArchAArch64LittleEndian:
return 64;
}
return 0;
}
// Used for static storage duration caches of `Arch` specializations. The
// `std::unique_ptr` makes sure that the `Arch` objects are freed on `exit`
// from the program.
using ArchPtr = std::unique_ptr<const Arch>;
using ArchCache = std::unordered_map<uint32_t, ArchPtr>;
} // namespace
Arch::Arch(OSName os_name_, ArchName arch_name_)
: os_name(os_name_),
arch_name(arch_name_),
address_size(AddressSize(arch_name_)) {}
Arch::~Arch(void) {}
bool Arch::LazyDecodeInstruction(
uint64_t address, const std::string &instr_bytes,
Instruction &inst) const {
return DecodeInstruction(address, instr_bytes, inst);
}
llvm::Triple Arch::BasicTriple(void) const {
llvm::Triple triple;
switch (os_name) {
case kOSInvalid:
LOG(FATAL) << "Cannot get triple OS.";
break;
case kOSLinux:
case kOSVxWorks:
triple.setOS(llvm::Triple::Linux);
triple.setEnvironment(llvm::Triple::GNU);
triple.setVendor(llvm::Triple::PC);
triple.setObjectFormat(llvm::Triple::ELF);
break;
case kOSmacOS:
triple.setOS(llvm::Triple::MacOSX);
triple.setEnvironment(llvm::Triple::UnknownEnvironment);
triple.setVendor(llvm::Triple::Apple);
triple.setObjectFormat(llvm::Triple::MachO);
break;
case kOSWindows:
triple.setOS(llvm::Triple::Win32);
triple.setEnvironment(llvm::Triple::MSVC);
triple.setVendor(llvm::Triple::UnknownVendor);
triple.setObjectFormat(llvm::Triple::COFF);
break;
}
return triple;
}
const Arch *Arch::Get(OSName os_name_, ArchName arch_name_) {
switch (arch_name_) {
case kArchInvalid:
LOG(FATAL) << "Unrecognized architecture.";
return nullptr;
case kArchAArch64LittleEndian: {
static ArchCache gArchAArch64LE;
auto &arch = gArchAArch64LE[os_name_];
if (!arch) {
DLOG(INFO) << "Using architecture: AArch64, feature set: Little Endian";
arch = ArchPtr(GetAArch64(os_name_, arch_name_));
}
return arch.get();
}
case kArchX86: {
static ArchCache gArchX86;
auto &arch = gArchX86[os_name_];
if (!arch) {
DLOG(INFO) << "Using architecture: X86";
arch = ArchPtr(GetX86(os_name_, arch_name_));
}
return arch.get();
}
case kArchMips32: {
static ArchCache gArchMips;
auto &arch = gArchMips[os_name_];
if (!arch) {
DLOG(INFO) << "Using architecture: 32-bit MIPS";
arch = ArchPtr(GetMips(os_name_, arch_name_));
}
return arch.get();
}
case kArchMips64: {
static ArchCache gArchMips64;
auto &arch = gArchMips64[os_name_];
if (!arch) {
DLOG(INFO) << "Using architecture: 64-bit MIPS";
arch = ArchPtr(GetMips(os_name_, arch_name_));
}
return arch.get();
}
case kArchX86_AVX: {
static ArchCache gArchX86_AVX;
auto &arch = gArchX86_AVX[os_name_];
if (!arch) {
DLOG(INFO) << "Using architecture: X86, feature set: AVX";
arch = ArchPtr(GetX86(os_name_, arch_name_));
}
return arch.get();
}
case kArchX86_AVX512: {
static ArchCache gArchX86_AVX512;
auto &arch = gArchX86_AVX512[os_name_];
if (!arch) {
DLOG(INFO) << "Using architecture: X86, feature set: AVX512";
arch = ArchPtr(GetX86(os_name_, arch_name_));
}
return arch.get();
}
case kArchAMD64: {
static ArchCache gArchAMD64;
auto &arch = gArchAMD64[os_name_];
if (!arch) {
DLOG(INFO) << "Using architecture: AMD64";
arch = ArchPtr(GetX86(os_name_, arch_name_));
}
return arch.get();
}
case kArchAMD64_AVX: {
static ArchCache gArchAMD64_AVX;
auto &arch = gArchAMD64_AVX[os_name_];
if (!arch) {
DLOG(INFO) << "Using architecture: AMD64, feature set: AVX";
arch = ArchPtr(GetX86(os_name_, arch_name_));
}
return arch.get();
}
case kArchAMD64_AVX512: {
static ArchCache gArchAMD64_AVX512;
auto &arch = gArchAMD64_AVX512[os_name_];
if (!arch) {
DLOG(INFO) << "Using architecture: AMD64, feature set: AVX512";
arch = ArchPtr(GetX86(os_name_, arch_name_));
}
return arch.get();
}
}
return nullptr;
}
const Arch *Arch::GetMips(OSName, ArchName) {
return nullptr;
}
const Arch *GetHostArch(void) {
static const Arch *gHostArch = nullptr;
if (!gHostArch) {
gHostArch = Arch::Get(GetOSName(REMILL_OS), GetArchName(REMILL_ARCH));
}
return gHostArch;
}
const Arch *GetTargetArch(void) {
static const Arch *gTargetArch = nullptr;
if (!gTargetArch) {
gTargetArch = Arch::Get(GetOSName(FLAGS_os), GetArchName(FLAGS_arch));
}
return gTargetArch;
}
bool Arch::IsX86(void) const {
switch (arch_name) {
case remill::kArchX86:
case remill::kArchX86_AVX:
case remill::kArchX86_AVX512:
return true;
default:
return false;
}
}
bool Arch::IsAMD64(void) const {
switch (arch_name) {
case remill::kArchAMD64:
case remill::kArchAMD64_AVX:
case remill::kArchAMD64_AVX512:
return true;
default:
return false;
}
}
bool Arch::IsAArch64(void) const {
return remill::kArchAArch64LittleEndian == arch_name;
}
namespace {
// These variables must always be defined within `__remill_basic_block`.
static bool BlockHasSpecialVars(llvm::Function *basic_block) {
return FindVarInFunction(basic_block, "STATE", true) &&
FindVarInFunction(basic_block, "MEMORY", true) &&
FindVarInFunction(basic_block, "PC", true) &&
FindVarInFunction(basic_block, "BRANCH_TAKEN", true);
}
// Clang isn't guaranteed to play nice and name the LLVM values within the
// `__remill_basic_block` intrinsic with the same names as we find in the
// C++ definition of that function. However, we compile that function with
// debug information, and so we will try to recover the variables names for
// later lookup.
static void FixupBasicBlockVariables(llvm::Function *basic_block) {
if (BlockHasSpecialVars(basic_block)) {
return;
}
for (auto &block : *basic_block) {
for (auto &inst : block) {
if (auto decl_inst = llvm::dyn_cast<llvm::DbgDeclareInst>(&inst)) {
auto addr = decl_inst->getAddress();
#if LLVM_VERSION_NUMBER >= LLVM_VERSION(3, 7)
addr->setName(decl_inst->getVariable()->getName());
#else
llvm::DIVariable var(decl_inst->getVariable());
addr->setName(var.getName());
#endif
}
}
}
CHECK(BlockHasSpecialVars(basic_block))
<< "Unable to locate required variables in `__remill_basic_block`.";
}
// Initialize some attributes that are common to all newly created block
// functions. Also, give pretty names to the arguments of block functions.
static void InitBlockFunctionAttributes(llvm::Function *block_func) {
block_func->setLinkage(llvm::GlobalValue::ExternalLinkage);
block_func->setVisibility(llvm::GlobalValue::DefaultVisibility);
remill::NthArgument(block_func, kMemoryPointerArgNum)->setName("memory");
remill::NthArgument(block_func, kStatePointerArgNum)->setName("state");
remill::NthArgument(block_func, kPCArgNum)->setName("pc");
}
} // namespace
// Add attributes to llvm::Argument in a way portable across LLVMs
static void AddNoAliasToArgument(llvm::Argument *arg) {
IF_LLVM_LT_39(
arg->addAttr(
llvm::AttributeSet::get(
arg->getContext(),
arg->getArgNo() + 1,
llvm::Attribute::NoAlias)
);
);
IF_LLVM_GTE_39(
arg->addAttr(llvm::Attribute::NoAlias);
);
}
// ensures that mandatory remill functions have the correct
// type signature and variable names
static void PrepareModuleRemillFunctions(llvm::Module *mod) {
auto basic_block = BasicBlockFunction(mod);
InitFunctionAttributes(basic_block);
FixupBasicBlockVariables(basic_block);
InitBlockFunctionAttributes(basic_block);
basic_block->addFnAttr(llvm::Attribute::OptimizeNone);
basic_block->removeFnAttr(llvm::Attribute::AlwaysInline);
basic_block->removeFnAttr(llvm::Attribute::InlineHint);
basic_block->addFnAttr(llvm::Attribute::NoInline);
basic_block->setVisibility(llvm::GlobalValue::DefaultVisibility);
AddNoAliasToArgument(remill::NthArgument(basic_block, kStatePointerArgNum));
AddNoAliasToArgument(remill::NthArgument(basic_block, kMemoryPointerArgNum));
}
// Converts an LLVM module object to have the right triple / data layout
// information for the target architecture.
//
void Arch::PrepareModuleDataLayout(llvm::Module *mod) const {
mod->setDataLayout(DataLayout().getStringRepresentation());
mod->setTargetTriple(Triple().str());
// Go and remove compile-time attributes added into the semantics. These
// can screw up later compilation. We purposefully compile semantics with
// things like auto-vectorization disabled so that it keeps the bitcode
// to a simpler subset of the available LLVM instuction set. If/when we
// compile this bitcode back into machine code, we may want to use those
// features, and clang will complain if we try to do so if these metadata
// remain present.
auto &context = mod->getContext();
llvm::AttributeSet target_attribs;
target_attribs = target_attribs.addAttribute(
context,
IF_LLVM_LT_50_(llvm::AttributeSet::FunctionIndex)
"target-features");
target_attribs = target_attribs.addAttribute(
context,
IF_LLVM_LT_50_(llvm::AttributeSet::FunctionIndex)
"target-cpu");
for (llvm::Function &func : *mod) {
auto attribs = func.getAttributes();
attribs = attribs.removeAttributes(
context,
llvm::AttributeLoc::FunctionIndex,
target_attribs);
func.setAttributes(attribs);
}
}
void Arch::PrepareModule(llvm::Module *mod) const {
PrepareModuleRemillFunctions(mod);
PrepareModuleDataLayout(mod);
}
} // namespace remill
<|endoftext|>
|
<commit_before>/*
* Copyright 2016 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/io/async/AsyncUDPSocket.h>
#include <folly/io/async/EventBase.h>
#include <folly/Likely.h>
#include <folly/portability/Fcntl.h>
#include <folly/portability/Sockets.h>
#include <folly/portability/Unistd.h>
#include <errno.h>
// Due to the way kernel headers are included, this may or may not be defined.
// Number pulled from 3.10 kernel headers.
#ifndef SO_REUSEPORT
#define SO_REUSEPORT 15
#endif
namespace fsp = folly::portability::sockets;
namespace folly {
AsyncUDPSocket::AsyncUDPSocket(EventBase* evb)
: EventHandler(CHECK_NOTNULL(evb)),
eventBase_(evb),
fd_(-1),
readCallback_(nullptr) {
DCHECK(evb->isInEventBaseThread());
}
AsyncUDPSocket::~AsyncUDPSocket() {
if (fd_ != -1) {
close();
}
}
void AsyncUDPSocket::bind(const folly::SocketAddress& address) {
int socket = fsp::socket(address.getFamily(), SOCK_DGRAM, IPPROTO_UDP);
if (socket == -1) {
throw AsyncSocketException(AsyncSocketException::NOT_OPEN,
"error creating async udp socket",
errno);
}
auto g = folly::makeGuard([&] { ::close(socket); });
// put the socket in non-blocking mode
int ret = fcntl(socket, F_SETFL, O_NONBLOCK);
if (ret != 0) {
throw AsyncSocketException(AsyncSocketException::NOT_OPEN,
"failed to put socket in non-blocking mode",
errno);
}
if (reuseAddr_) {
// put the socket in reuse mode
int value = 1;
if (setsockopt(socket,
SOL_SOCKET,
SO_REUSEADDR,
&value,
sizeof(value)) != 0) {
throw AsyncSocketException(AsyncSocketException::NOT_OPEN,
"failed to put socket in reuse mode",
errno);
}
}
if (reusePort_) {
// put the socket in port reuse mode
int value = 1;
if (setsockopt(socket,
SOL_SOCKET,
SO_REUSEPORT,
&value,
sizeof(value)) != 0) {
::close(socket);
throw AsyncSocketException(AsyncSocketException::NOT_OPEN,
"failed to put socket in reuse_port mode",
errno);
}
}
// If we're using IPv6, make sure we don't accept V4-mapped connections
if (address.getFamily() == AF_INET6) {
int flag = 1;
if (setsockopt(socket, IPPROTO_IPV6, IPV6_V6ONLY, &flag, sizeof(flag))) {
throw AsyncSocketException(
AsyncSocketException::NOT_OPEN,
"Failed to set IPV6_V6ONLY",
errno);
}
}
// bind to the address
sockaddr_storage addrStorage;
address.getAddress(&addrStorage);
sockaddr* saddr = reinterpret_cast<sockaddr*>(&addrStorage);
if (fsp::bind(socket, saddr, address.getActualSize()) != 0) {
throw AsyncSocketException(
AsyncSocketException::NOT_OPEN,
"failed to bind the async udp socket for:" + address.describe(),
errno);
}
// success
g.dismiss();
fd_ = socket;
ownership_ = FDOwnership::OWNS;
// attach to EventHandler
EventHandler::changeHandlerFD(fd_);
if (address.getPort() != 0) {
localAddress_ = address;
} else {
localAddress_.setFromLocalAddress(fd_);
}
}
void AsyncUDPSocket::setFD(int fd, FDOwnership ownership) {
CHECK_EQ(-1, fd_) << "Already bound to another FD";
fd_ = fd;
ownership_ = ownership;
EventHandler::changeHandlerFD(fd_);
localAddress_.setFromLocalAddress(fd_);
}
ssize_t AsyncUDPSocket::write(const folly::SocketAddress& address,
const std::unique_ptr<folly::IOBuf>& buf) {
// UDP's typical MTU size is 1500, so high number of buffers
// really do not make sense. Optimze for buffer chains with
// buffers less than 16, which is the highest I can think of
// for a real use case.
iovec vec[16];
size_t iovec_len = buf->fillIov(vec, sizeof(vec)/sizeof(vec[0]));
if (UNLIKELY(iovec_len == 0)) {
buf->coalesce();
vec[0].iov_base = const_cast<uint8_t*>(buf->data());
vec[0].iov_len = buf->length();
iovec_len = 1;
}
return writev(address, vec, iovec_len);
}
ssize_t AsyncUDPSocket::writev(const folly::SocketAddress& address,
const struct iovec* vec, size_t iovec_len) {
CHECK_NE(-1, fd_) << "Socket not yet bound";
sockaddr_storage addrStorage;
address.getAddress(&addrStorage);
struct msghdr msg;
msg.msg_name = reinterpret_cast<void*>(&addrStorage);
msg.msg_namelen = address.getActualSize();
msg.msg_iov = const_cast<struct iovec*>(vec);
msg.msg_iovlen = iovec_len;
msg.msg_control = nullptr;
msg.msg_controllen = 0;
msg.msg_flags = 0;
return ::sendmsg(fd_, &msg, 0);
}
void AsyncUDPSocket::resumeRead(ReadCallback* cob) {
CHECK(!readCallback_) << "Another read callback already installed";
CHECK_NE(-1, fd_) << "UDP server socket not yet bind to an address";
readCallback_ = CHECK_NOTNULL(cob);
if (!updateRegistration()) {
AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
"failed to register for accept events");
readCallback_ = nullptr;
cob->onReadError(ex);
return;
}
}
void AsyncUDPSocket::pauseRead() {
// It is ok to pause an already paused socket
readCallback_ = nullptr;
updateRegistration();
}
void AsyncUDPSocket::close() {
DCHECK(eventBase_->isInEventBaseThread());
if (readCallback_) {
auto cob = readCallback_;
readCallback_ = nullptr;
cob->onReadClosed();
}
// Unregister any events we are registered for
unregisterHandler();
if (fd_ != -1 && ownership_ == FDOwnership::OWNS) {
::close(fd_);
}
fd_ = -1;
}
void AsyncUDPSocket::handlerReady(uint16_t events) noexcept {
if (events & EventHandler::READ) {
DCHECK(readCallback_);
handleRead();
}
}
void AsyncUDPSocket::handleRead() noexcept {
void* buf{nullptr};
size_t len{0};
readCallback_->getReadBuffer(&buf, &len);
if (buf == nullptr || len == 0) {
AsyncSocketException ex(
AsyncSocketException::BAD_ARGS,
"AsyncUDPSocket::getReadBuffer() returned empty buffer");
auto cob = readCallback_;
readCallback_ = nullptr;
cob->onReadError(ex);
updateRegistration();
return;
}
struct sockaddr_storage addrStorage;
socklen_t addrLen = sizeof(addrStorage);
memset(&addrStorage, 0, addrLen);
struct sockaddr* rawAddr = reinterpret_cast<sockaddr*>(&addrStorage);
rawAddr->sa_family = localAddress_.getFamily();
ssize_t bytesRead = recvfrom(fd_, buf, len, MSG_TRUNC, rawAddr, &addrLen);
if (bytesRead >= 0) {
clientAddress_.setFromSockaddr(rawAddr, addrLen);
if (bytesRead > 0) {
bool truncated = false;
if ((size_t)bytesRead > len) {
truncated = true;
bytesRead = len;
}
readCallback_->onDataAvailable(clientAddress_, bytesRead, truncated);
}
} else {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
// No data could be read without blocking the socket
return;
}
AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
"::recvfrom() failed",
errno);
// In case of UDP we can continue reading from the socket
// even if the current request fails. We notify the user
// so that he can do some logging/stats collection if he wants.
auto cob = readCallback_;
readCallback_ = nullptr;
cob->onReadError(ex);
updateRegistration();
}
}
bool AsyncUDPSocket::updateRegistration() noexcept {
uint16_t flags = NONE;
if (readCallback_) {
flags |= READ;
}
return registerHandler(flags | PERSIST);
}
} // Namespace
<commit_msg>Fix potential double close() on exception<commit_after>/*
* Copyright 2016 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/io/async/AsyncUDPSocket.h>
#include <folly/io/async/EventBase.h>
#include <folly/Likely.h>
#include <folly/portability/Fcntl.h>
#include <folly/portability/Sockets.h>
#include <folly/portability/Unistd.h>
#include <errno.h>
// Due to the way kernel headers are included, this may or may not be defined.
// Number pulled from 3.10 kernel headers.
#ifndef SO_REUSEPORT
#define SO_REUSEPORT 15
#endif
namespace fsp = folly::portability::sockets;
namespace folly {
AsyncUDPSocket::AsyncUDPSocket(EventBase* evb)
: EventHandler(CHECK_NOTNULL(evb)),
eventBase_(evb),
fd_(-1),
readCallback_(nullptr) {
DCHECK(evb->isInEventBaseThread());
}
AsyncUDPSocket::~AsyncUDPSocket() {
if (fd_ != -1) {
close();
}
}
void AsyncUDPSocket::bind(const folly::SocketAddress& address) {
int socket = fsp::socket(address.getFamily(), SOCK_DGRAM, IPPROTO_UDP);
if (socket == -1) {
throw AsyncSocketException(AsyncSocketException::NOT_OPEN,
"error creating async udp socket",
errno);
}
auto g = folly::makeGuard([&] { ::close(socket); });
// put the socket in non-blocking mode
int ret = fcntl(socket, F_SETFL, O_NONBLOCK);
if (ret != 0) {
throw AsyncSocketException(AsyncSocketException::NOT_OPEN,
"failed to put socket in non-blocking mode",
errno);
}
if (reuseAddr_) {
// put the socket in reuse mode
int value = 1;
if (setsockopt(socket,
SOL_SOCKET,
SO_REUSEADDR,
&value,
sizeof(value)) != 0) {
throw AsyncSocketException(AsyncSocketException::NOT_OPEN,
"failed to put socket in reuse mode",
errno);
}
}
if (reusePort_) {
// put the socket in port reuse mode
int value = 1;
if (setsockopt(socket,
SOL_SOCKET,
SO_REUSEPORT,
&value,
sizeof(value)) != 0) {
throw AsyncSocketException(AsyncSocketException::NOT_OPEN,
"failed to put socket in reuse_port mode",
errno);
}
}
// If we're using IPv6, make sure we don't accept V4-mapped connections
if (address.getFamily() == AF_INET6) {
int flag = 1;
if (setsockopt(socket, IPPROTO_IPV6, IPV6_V6ONLY, &flag, sizeof(flag))) {
throw AsyncSocketException(
AsyncSocketException::NOT_OPEN,
"Failed to set IPV6_V6ONLY",
errno);
}
}
// bind to the address
sockaddr_storage addrStorage;
address.getAddress(&addrStorage);
sockaddr* saddr = reinterpret_cast<sockaddr*>(&addrStorage);
if (fsp::bind(socket, saddr, address.getActualSize()) != 0) {
throw AsyncSocketException(
AsyncSocketException::NOT_OPEN,
"failed to bind the async udp socket for:" + address.describe(),
errno);
}
// success
g.dismiss();
fd_ = socket;
ownership_ = FDOwnership::OWNS;
// attach to EventHandler
EventHandler::changeHandlerFD(fd_);
if (address.getPort() != 0) {
localAddress_ = address;
} else {
localAddress_.setFromLocalAddress(fd_);
}
}
void AsyncUDPSocket::setFD(int fd, FDOwnership ownership) {
CHECK_EQ(-1, fd_) << "Already bound to another FD";
fd_ = fd;
ownership_ = ownership;
EventHandler::changeHandlerFD(fd_);
localAddress_.setFromLocalAddress(fd_);
}
ssize_t AsyncUDPSocket::write(const folly::SocketAddress& address,
const std::unique_ptr<folly::IOBuf>& buf) {
// UDP's typical MTU size is 1500, so high number of buffers
// really do not make sense. Optimze for buffer chains with
// buffers less than 16, which is the highest I can think of
// for a real use case.
iovec vec[16];
size_t iovec_len = buf->fillIov(vec, sizeof(vec)/sizeof(vec[0]));
if (UNLIKELY(iovec_len == 0)) {
buf->coalesce();
vec[0].iov_base = const_cast<uint8_t*>(buf->data());
vec[0].iov_len = buf->length();
iovec_len = 1;
}
return writev(address, vec, iovec_len);
}
ssize_t AsyncUDPSocket::writev(const folly::SocketAddress& address,
const struct iovec* vec, size_t iovec_len) {
CHECK_NE(-1, fd_) << "Socket not yet bound";
sockaddr_storage addrStorage;
address.getAddress(&addrStorage);
struct msghdr msg;
msg.msg_name = reinterpret_cast<void*>(&addrStorage);
msg.msg_namelen = address.getActualSize();
msg.msg_iov = const_cast<struct iovec*>(vec);
msg.msg_iovlen = iovec_len;
msg.msg_control = nullptr;
msg.msg_controllen = 0;
msg.msg_flags = 0;
return ::sendmsg(fd_, &msg, 0);
}
void AsyncUDPSocket::resumeRead(ReadCallback* cob) {
CHECK(!readCallback_) << "Another read callback already installed";
CHECK_NE(-1, fd_) << "UDP server socket not yet bind to an address";
readCallback_ = CHECK_NOTNULL(cob);
if (!updateRegistration()) {
AsyncSocketException ex(AsyncSocketException::NOT_OPEN,
"failed to register for accept events");
readCallback_ = nullptr;
cob->onReadError(ex);
return;
}
}
void AsyncUDPSocket::pauseRead() {
// It is ok to pause an already paused socket
readCallback_ = nullptr;
updateRegistration();
}
void AsyncUDPSocket::close() {
DCHECK(eventBase_->isInEventBaseThread());
if (readCallback_) {
auto cob = readCallback_;
readCallback_ = nullptr;
cob->onReadClosed();
}
// Unregister any events we are registered for
unregisterHandler();
if (fd_ != -1 && ownership_ == FDOwnership::OWNS) {
::close(fd_);
}
fd_ = -1;
}
void AsyncUDPSocket::handlerReady(uint16_t events) noexcept {
if (events & EventHandler::READ) {
DCHECK(readCallback_);
handleRead();
}
}
void AsyncUDPSocket::handleRead() noexcept {
void* buf{nullptr};
size_t len{0};
readCallback_->getReadBuffer(&buf, &len);
if (buf == nullptr || len == 0) {
AsyncSocketException ex(
AsyncSocketException::BAD_ARGS,
"AsyncUDPSocket::getReadBuffer() returned empty buffer");
auto cob = readCallback_;
readCallback_ = nullptr;
cob->onReadError(ex);
updateRegistration();
return;
}
struct sockaddr_storage addrStorage;
socklen_t addrLen = sizeof(addrStorage);
memset(&addrStorage, 0, addrLen);
struct sockaddr* rawAddr = reinterpret_cast<sockaddr*>(&addrStorage);
rawAddr->sa_family = localAddress_.getFamily();
ssize_t bytesRead = recvfrom(fd_, buf, len, MSG_TRUNC, rawAddr, &addrLen);
if (bytesRead >= 0) {
clientAddress_.setFromSockaddr(rawAddr, addrLen);
if (bytesRead > 0) {
bool truncated = false;
if ((size_t)bytesRead > len) {
truncated = true;
bytesRead = len;
}
readCallback_->onDataAvailable(clientAddress_, bytesRead, truncated);
}
} else {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
// No data could be read without blocking the socket
return;
}
AsyncSocketException ex(AsyncSocketException::INTERNAL_ERROR,
"::recvfrom() failed",
errno);
// In case of UDP we can continue reading from the socket
// even if the current request fails. We notify the user
// so that he can do some logging/stats collection if he wants.
auto cob = readCallback_;
readCallback_ = nullptr;
cob->onReadError(ex);
updateRegistration();
}
}
bool AsyncUDPSocket::updateRegistration() noexcept {
uint16_t flags = NONE;
if (readCallback_) {
flags |= READ;
}
return registerHandler(flags | PERSIST);
}
} // Namespace
<|endoftext|>
|
<commit_before>#pragma once
#include <functional>
#include <map>
#include <memory>
#include "base/not_null.hpp"
#include "integrators/ordinary_differential_equations.hpp"
#include "physics/continuous_trajectory.hpp"
#include "physics/massive_body.hpp"
#include "physics/trajectory.hpp"
namespace principia {
using integrators::AdaptiveStepSizeIntegrator;
using integrators::FixedStepSizeIntegrator;
using integrators::SpecialSecondOrderDifferentialEquation;
namespace physics {
template<typename Frame>
class Ephemeris {
static_assert(Frame::is_inertial, "Frame must be inertial");
public:
// The equation describing the motion of the |bodies_|.
using PlanetaryMotion =
SpecialSecondOrderDifferentialEquation<Position<Frame>>;
PlanetaryMotion::SystemState last_state_;
// We don't specify non-autonomy in PlanetaryMotion since there isn't a type
// for that at this time, so time-dependent intrinsic acceleration yields the
// same type of map.
using TimedBurnMotion = PlanetaryMotion;
// Constructs an Ephemeris that owns the |bodies|.
Ephemeris(
std::vector<not_null<std::unique_ptr<MassiveBody>>> bodies,
std::vector<DegreesOfFreedom<Frame>> initial_state,
Instant const& initial_time,
FixedStepSizeIntegrator<PlanetaryMotion> const& planetary_integrator,
Time const& step_size);
ContinuousTrajectory<Frame> const& trajectory(
not_null<MassiveBody const*>) const;
// The common |t_min| of the trajectories.
Instant t_min() const;
// The common |t_max| of the trajectories.
Instant t_max() const;
// Calls |ForgetBefore| on all trajectories.
void ForgetBefore(Instant const& t);
// Prolongs the ephemeris up to at least |t|. After the call, |t_max() >= t|.
void Prolong(Instant const& t);
// Computes the trajectory of a massless body in the gravitational potential
// described by |this| and subject to the given |intrinsic_acceleration| up to
// exactly |t|.
// TODO(egg): overloads for state-dependent intrinsic acceleration, either
// dependent on the positions (yielding special second-order ODE) or on the
// positions and velocities (yielding a general second-order ODE).
void Advance(
not_null<Trajectory<Frame>*> const trajectory,
std::function<
Vector<Acceleration, Frame>(
Instant const&)> intrinsic_acceleration,
RelativeDegreesOfFreedom const& tolerance,
AdaptiveStepSizeIntegrator<TimedBurnMotion> integrator,
Instant const& t);
private:
std::vector<not_null<std::unique_ptr<MassiveBody>>> bodies_;
std::map<not_null<MassiveBody const*>,
ContinuousTrajectory<Frame>> trajectories_;
FixedStepSizeIntegrator<PlanetaryMotion> const& planetary_integrator_;
};
} // namespace physics
} // namespace principia
<commit_msg>comment<commit_after>#pragma once
#include <functional>
#include <map>
#include <memory>
#include "base/not_null.hpp"
#include "integrators/ordinary_differential_equations.hpp"
#include "physics/continuous_trajectory.hpp"
#include "physics/massive_body.hpp"
#include "physics/trajectory.hpp"
namespace principia {
using integrators::AdaptiveStepSizeIntegrator;
using integrators::FixedStepSizeIntegrator;
using integrators::SpecialSecondOrderDifferentialEquation;
namespace physics {
template<typename Frame>
class Ephemeris {
static_assert(Frame::is_inertial, "Frame must be inertial");
public:
// The equation describing the motion of the |bodies_|.
using PlanetaryMotion =
SpecialSecondOrderDifferentialEquation<Position<Frame>>;
PlanetaryMotion::SystemState last_state_;
// We don't specify non-autonomy in PlanetaryMotion since there isn't a type
// for that at this time, so time-dependent intrinsic acceleration yields the
// same type of map.
using TimedBurnMotion = PlanetaryMotion;
// Constructs an Ephemeris that owns the |bodies|.
Ephemeris(
std::vector<not_null<std::unique_ptr<MassiveBody>>> bodies,
std::vector<DegreesOfFreedom<Frame>> initial_state,
Instant const& initial_time,
FixedStepSizeIntegrator<PlanetaryMotion> const& planetary_integrator,
Time const& step_size);
ContinuousTrajectory<Frame> const& trajectory(
not_null<MassiveBody const*>) const;
// The common |t_min| of the trajectories.
Instant t_min() const;
// The common |t_max| of the trajectories.
Instant t_max() const;
// Calls |ForgetBefore| on all trajectories.
void ForgetBefore(Instant const& t);
// Prolongs the ephemeris up to at least |t|. After the call, |t_max() >= t|.
void Prolong(Instant const& t);
// Computes the trajectory of a massless body in the gravitational potential
// described by |this| and subject to the given |intrinsic_acceleration| up to
// exactly |t|.
// If |t > t_max()|, calls |Prolong(t)| beforehand.
void Advance(
not_null<Trajectory<Frame>*> const trajectory,
std::function<
Vector<Acceleration, Frame>(
Instant const&)> intrinsic_acceleration,
RelativeDegreesOfFreedom const& tolerance,
AdaptiveStepSizeIntegrator<TimedBurnMotion> integrator,
Instant const& t);
private:
std::vector<not_null<std::unique_ptr<MassiveBody>>> bodies_;
std::map<not_null<MassiveBody const*>,
ContinuousTrajectory<Frame>> trajectories_;
FixedStepSizeIntegrator<PlanetaryMotion> const& planetary_integrator_;
};
} // namespace physics
} // namespace principia
<|endoftext|>
|
<commit_before>#include "connection.h"
#include "sim.h"
#include <arpa/inet.h>
#include <chrono>
#include <csignal>
#include <pthread.h>
#include <simlib/config_file.h>
#include <simlib/debug.h>
#include <simlib/filesystem.h>
#include <simlib/process.h>
using std::string;
static int socket_fd;
namespace server {
static void* worker(void*) {
try {
sockaddr_in name;
socklen_t client_name_len = sizeof(name);
char ip[INET_ADDRSTRLEN];
Connection conn(-1);
Sim sim_worker;
for (;;) {
// accept the connection
int client_socket_fd = accept4(socket_fd, (sockaddr*)&name,
&client_name_len, SOCK_CLOEXEC);
FileDescriptorCloser closer(client_socket_fd);
if (client_socket_fd == -1)
continue;
// extract IP
inet_ntop(AF_INET, &name.sin_addr, ip, INET_ADDRSTRLEN);
stdlog("Connection accepted: ", pthread_self(), " form ", ip);
conn.assign(client_socket_fd);
HttpRequest req = conn.getRequest();
if (conn.state() == Connection::OK) {
using namespace std::chrono;
auto beg = steady_clock::now();
HttpResponse resp = sim_worker.handle(ip, std::move(req));
auto microdur =
duration_cast<microseconds>(steady_clock::now() - beg);
stdlog("Response generated in ", toString(microdur * 1000),
" ms.");
conn.sendResponse(std::move(resp));
}
stdlog("Closing...");
closer.close();
stdlog("Closed");
}
} catch (const std::exception& e) {
ERRLOG_CATCH(e);
} catch (...) {
ERRLOG_CATCH();
}
return nullptr;
}
} // namespace server
int main() {
// Init server
// Change directory to process executable directory
string cwd;
try {
cwd = chdirToExecDir();
} catch (const std::exception& e) {
errlog("Failed to change working directory: ", e.what());
}
// Terminate older instances
kill_processes_by_exec({getExec(getpid())}, std::chrono::seconds(4), true);
// Loggers
// stdlog (like everything) writes to stderr, so redirect stdout and stderr
// to the log file
if (freopen(SERVER_LOG, "a", stdout) == nullptr ||
dup3(STDOUT_FILENO, STDERR_FILENO, O_CLOEXEC) == -1) {
errlog("Failed to open `", SERVER_LOG, '`', errmsg());
}
try {
errlog.open(SERVER_ERROR_LOG);
} catch (const std::exception& e) {
errlog("Failed to open `", SERVER_ERROR_LOG, "`: ", e.what());
}
// Signal control
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = &exit;
(void)sigaction(SIGINT, &sa, nullptr);
(void)sigaction(SIGTERM, &sa, nullptr);
(void)sigaction(SIGQUIT, &sa, nullptr);
ConfigFile config;
try {
config.add_vars("address", "workers");
config.load_config_from_file("sim.conf");
} catch (const std::exception& e) {
errlog("Failed to load sim.config: ", e.what());
return 5;
}
string address = config["address"].as_string();
int workers = config["workers"].as_int();
if (workers < 1) {
errlog("sim.conf: Number of workers cannot be lower than 1");
return 6;
}
sockaddr_in name;
name.sin_family = AF_INET;
memset(name.sin_zero, 0, sizeof(name.sin_zero));
// Extract port from address
unsigned port = 80; // server port
size_t colon_pos = address.find(':');
// Colon has been found
if (colon_pos < address.size()) {
if (strtou(address, port, colon_pos + 1) !=
static_cast<int>(address.size() - colon_pos - 1)) {
errlog("sim.config: incorrect port number");
return 7;
}
address[colon_pos] = '\0'; // need to extract IPv4 address
} else
address += '\0'; // need to extract IPv4 address
// Set server port
name.sin_port = htons(port);
// Extract IPv4 address
if (0 == strcmp(address.data(), "*")) // strcmp because of '\0' in address
name.sin_addr.s_addr = htonl(INADDR_ANY); // server address
else if (address.empty() ||
inet_aton(address.data(), &name.sin_addr) == 0) {
errlog("sim.config: incorrect IPv4 address");
return 8;
}
// clang-format off
stdlog("\n=================== Server launched ==================="
"\nPID: ", getpid(),
"\nworkers: ", workers,
"\naddress: ", address.data(), ':', port);
// clang-format on
if ((socket_fd = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, IPPROTO_TCP)) <
0) {
errlog("Failed to create socket", errmsg());
return 1;
}
int true_ = 1;
if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &true_, sizeof(int))) {
errlog("Failed to setopt", errmsg());
return 2;
}
// Bind
constexpr int TRIES = 8;
for (int try_no = 1; bind(socket_fd, (sockaddr*)&name, sizeof(name));) {
errlog("Failed to bind (try ", try_no, ')', errmsg());
if (++try_no > TRIES)
return 3;
usleep(800000);
}
if (listen(socket_fd, 10)) {
errlog("Failed to listen", errmsg());
return 4;
}
// Alter default thread stack size
pthread_attr_t attr;
constexpr size_t THREAD_STACK_SIZE = 4 << 20; // 4 MiB
if (pthread_attr_init(&attr) ||
pthread_attr_setstacksize(&attr, THREAD_STACK_SIZE)) {
errlog("Failed to set new thread stack size");
return 4;
}
std::vector<pthread_t> threads(workers);
for (int i = 1; i < workers; ++i) {
pthread_create(&threads[i], &attr, server::worker,
nullptr); // TODO: errors...
}
threads[0] = pthread_self();
server::worker(nullptr);
close(socket_fd);
return 0;
}
<commit_msg>Fixed failed bind() message in server-error log after rerunning the sim-server<commit_after>#include "connection.h"
#include "sim.h"
#include <arpa/inet.h>
#include <chrono>
#include <csignal>
#include <pthread.h>
#include <simlib/config_file.h>
#include <simlib/debug.h>
#include <simlib/filesystem.h>
#include <simlib/process.h>
#include <thread>
using std::string;
static int socket_fd;
namespace server {
static void* worker(void*) {
try {
sockaddr_in name;
socklen_t client_name_len = sizeof(name);
char ip[INET_ADDRSTRLEN];
Connection conn(-1);
Sim sim_worker;
for (;;) {
// accept the connection
int client_socket_fd = accept4(socket_fd, (sockaddr*)&name,
&client_name_len, SOCK_CLOEXEC);
FileDescriptorCloser closer(client_socket_fd);
if (client_socket_fd == -1)
continue;
// extract IP
inet_ntop(AF_INET, &name.sin_addr, ip, INET_ADDRSTRLEN);
stdlog("Connection accepted: ", pthread_self(), " form ", ip);
conn.assign(client_socket_fd);
HttpRequest req = conn.getRequest();
if (conn.state() == Connection::OK) {
using namespace std::chrono;
auto beg = steady_clock::now();
HttpResponse resp = sim_worker.handle(ip, std::move(req));
auto microdur =
duration_cast<microseconds>(steady_clock::now() - beg);
stdlog("Response generated in ", toString(microdur * 1000),
" ms.");
conn.sendResponse(std::move(resp));
}
stdlog("Closing...");
closer.close();
stdlog("Closed");
}
} catch (const std::exception& e) {
ERRLOG_CATCH(e);
} catch (...) {
ERRLOG_CATCH();
}
return nullptr;
}
} // namespace server
int main() {
// Init server
// Change directory to process executable directory
string cwd;
try {
cwd = chdirToExecDir();
} catch (const std::exception& e) {
errlog("Failed to change working directory: ", e.what());
}
// Terminate older instances
kill_processes_by_exec({getExec(getpid())}, std::chrono::seconds(4), true);
// Loggers
// stdlog (like everything) writes to stderr, so redirect stdout and stderr
// to the log file
if (freopen(SERVER_LOG, "a", stdout) == nullptr ||
dup3(STDOUT_FILENO, STDERR_FILENO, O_CLOEXEC) == -1) {
errlog("Failed to open `", SERVER_LOG, '`', errmsg());
}
try {
errlog.open(SERVER_ERROR_LOG);
} catch (const std::exception& e) {
errlog("Failed to open `", SERVER_ERROR_LOG, "`: ", e.what());
}
// Signal control
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = &exit;
(void)sigaction(SIGINT, &sa, nullptr);
(void)sigaction(SIGTERM, &sa, nullptr);
(void)sigaction(SIGQUIT, &sa, nullptr);
ConfigFile config;
try {
config.add_vars("address", "workers");
config.load_config_from_file("sim.conf");
} catch (const std::exception& e) {
errlog("Failed to load sim.config: ", e.what());
return 5;
}
string address = config["address"].as_string();
int workers = config["workers"].as_int();
if (workers < 1) {
errlog("sim.conf: Number of workers cannot be lower than 1");
return 6;
}
sockaddr_in name;
name.sin_family = AF_INET;
memset(name.sin_zero, 0, sizeof(name.sin_zero));
// Extract port from address
unsigned port = 80; // server port
size_t colon_pos = address.find(':');
// Colon has been found
if (colon_pos < address.size()) {
if (strtou(address, port, colon_pos + 1) !=
static_cast<int>(address.size() - colon_pos - 1)) {
errlog("sim.config: incorrect port number");
return 7;
}
address[colon_pos] = '\0'; // need to extract IPv4 address
} else
address += '\0'; // need to extract IPv4 address
// Set server port
name.sin_port = htons(port);
// Extract IPv4 address
if (0 == strcmp(address.data(), "*")) // strcmp because of '\0' in address
name.sin_addr.s_addr = htonl(INADDR_ANY); // server address
else if (address.empty() ||
inet_aton(address.data(), &name.sin_addr) == 0) {
errlog("sim.config: incorrect IPv4 address");
return 8;
}
// clang-format off
stdlog("\n=================== Server launched ==================="
"\nPID: ", getpid(),
"\nworkers: ", workers,
"\naddress: ", address.data(), ':', port);
// clang-format on
if ((socket_fd = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, IPPROTO_TCP)) <
0) {
errlog("Failed to create socket", errmsg());
return 1;
}
int true_ = 1;
if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &true_, sizeof(int))) {
errlog("Failed to setopt", errmsg());
return 2;
}
// Bind
constexpr int FAST_SILENT_TRIES = 40;
constexpr int SLOW_TRIES = 8;
int bound = [&] {
auto call_bind = [&] {
return bind(socket_fd, (sockaddr*)&name, sizeof(name));
};
for (int try_no = 1; try_no <= FAST_SILENT_TRIES; ++try_no) {
if (try_no > 1) {
std::this_thread::sleep_for(
std::chrono::milliseconds(1000 / FAST_SILENT_TRIES));
}
if (call_bind() == 0)
return true;
}
for (int try_no = 1; try_no <= SLOW_TRIES; ++try_no) {
std::this_thread::sleep_for(std::chrono::milliseconds(800));
if (call_bind() == 0)
return true;
errlog("Failed to bind (try ", try_no, ')', errmsg());
}
return false;
}();
if (not bound) {
errlog("Giving up");
return 3;
}
if (listen(socket_fd, 10)) {
errlog("Failed to listen", errmsg());
return 4;
}
// Alter default thread stack size
pthread_attr_t attr;
constexpr size_t THREAD_STACK_SIZE = 4 << 20; // 4 MiB
if (pthread_attr_init(&attr) ||
pthread_attr_setstacksize(&attr, THREAD_STACK_SIZE)) {
errlog("Failed to set new thread stack size");
return 4;
}
std::vector<pthread_t> threads(workers);
for (int i = 1; i < workers; ++i) {
pthread_create(&threads[i], &attr, server::worker,
nullptr); // TODO: errors...
}
threads[0] = pthread_self();
server::worker(nullptr);
close(socket_fd);
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. 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.
*
*
*/
/** \author Julius Kammerl (julius@kammerl.de)*/
#include <gtest/gtest.h>
#include <vector>
#include <stdio.h>
using namespace std;
#include <pcl/common/time.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
using namespace pcl;
#include "pcl/kdtree/organized_neighbor_search.h"
#include "pcl/kdtree/impl/organized_neighbor_search.hpp"
// helper class for priority queue
class prioPointQueueEntry
{
public:
prioPointQueueEntry ()
{
}
prioPointQueueEntry (PointXYZ& point_arg, double pointDistance_arg, int pointIdx_arg)
{
point_ = point_arg;
pointDistance_ = pointDistance_arg;
pointIdx_ = pointIdx_arg;
}
bool
operator< (const prioPointQueueEntry& rhs_arg) const
{
return (this->pointDistance_ < rhs_arg.pointDistance_);
}
PointXYZ point_;
double pointDistance_;int pointIdx_;
};
TEST (PCL, Organized_Neighbor_Search_Pointcloud_Nearest_K_Neighbour_Search)
{
const unsigned int test_runs = 5;
unsigned int test_id;
// instantiate point cloud
PointCloud<PointXYZ>::Ptr cloudIn (new PointCloud<PointXYZ> ());
size_t i;
srand (time (NULL));
unsigned int K;
// create organized search
OrganizedNeighborSearch<PointXYZ> organizedNeighborSearch;
std::vector<int> k_indices;
std::vector<float> k_sqr_distances;
std::vector<int> k_indices_bruteforce;
std::vector<float> k_sqr_distances_bruteforce;
// typical focal length from kinect
const double oneOverFocalLength = 0.0018;
double x,y,z;
int xpos, ypos, centerX, centerY, idx;
for (test_id = 0; test_id < test_runs; test_id++)
{
// define a random search point
K = (rand () % 10)+1;
// generate point cloud
cloudIn->width = 640;
cloudIn->height = 480;
cloudIn->points.clear();
cloudIn->points.reserve (cloudIn->width * cloudIn->height);
centerX = cloudIn->width>>1;
centerY = cloudIn->height>>1;
idx = 0;
for (ypos = -centerY; ypos < centerY; ypos++)
for (xpos = -centerX; xpos < centerX; xpos++)
{
z = 15.0 * ((double)rand () / (double)(RAND_MAX+1.0))+20;
y = (double)ypos*oneOverFocalLength*(double)z;
x = (double)xpos*oneOverFocalLength*(double)z;
cloudIn->points.push_back(PointXYZ (x, y, z));
}
unsigned int searchIdx = rand()%(cloudIn->width * cloudIn->height);
const PointXYZ& searchPoint = cloudIn->points[searchIdx];
k_indices.clear();
k_sqr_distances.clear();
// organized nearest neighbor search
organizedNeighborSearch.setInputCloud (cloudIn);
organizedNeighborSearch.nearestKSearch (searchPoint, (int)K, k_indices, k_sqr_distances);
double pointDist;
k_indices_bruteforce.clear();
k_sqr_distances_bruteforce.clear();
std::priority_queue<prioPointQueueEntry> pointCandidates;
// push all points and their distance to the search point into a priority queue - bruteforce approach.
for (i = 0; i < cloudIn->points.size (); i++)
{
pointDist = ((cloudIn->points[i].x - searchPoint.x) * (cloudIn->points[i].x - searchPoint.x) +
/*+*/ (cloudIn->points[i].y - searchPoint.y) * (cloudIn->points[i].y - searchPoint.y) +
(cloudIn->points[i].z - searchPoint.z) * (cloudIn->points[i].z - searchPoint.z));
prioPointQueueEntry pointEntry (cloudIn->points[i], pointDist, i);
pointCandidates.push (pointEntry);
}
// pop priority queue until we have the nearest K elements
while (pointCandidates.size () > K)
pointCandidates.pop ();
// copy results into vectors
while (pointCandidates.size ())
{
k_indices_bruteforce.push_back (pointCandidates.top ().pointIdx_);
k_sqr_distances_bruteforce.push_back (pointCandidates.top ().pointDistance_);
pointCandidates.pop ();
}
ASSERT_EQ ( k_indices.size() , k_indices_bruteforce.size() );
// compare nearest neighbor results of organized search with bruteforce search
for (i = 0; i < k_indices.size (); i++)
{
ASSERT_EQ ( k_indices[i] , k_indices_bruteforce.back() );
EXPECT_NEAR (k_sqr_distances[i], k_sqr_distances_bruteforce.back(), 1e-4);
k_indices_bruteforce.pop_back();
k_sqr_distances_bruteforce.pop_back();
}
}
}
TEST (PCL, Organized_Neighbor_Search_Pointcloud_Neighbours_Within_Radius_Search)
{
const unsigned int test_runs = 10;
unsigned int test_id;
size_t i,j;
srand (time (NULL));
OrganizedNeighborSearch<PointXYZ> organizedNeighborSearch;
std::vector<int> k_indices;
std::vector<float> k_sqr_distances;
std::vector<int> k_indices_bruteforce;
std::vector<float> k_sqr_distances_bruteforce;
// typical focal length from kinect
const double oneOverFocalLength = 0.0018;
double x,y,z;
int xpos, ypos, centerX, centerY, idx;
for (test_id = 0; test_id < test_runs; test_id++)
{
// generate point cloud
PointCloud<PointXYZ>::Ptr cloudIn (new PointCloud<PointXYZ> ());
cloudIn->width = 640;
cloudIn->height = 480;
cloudIn->points.clear();
cloudIn->points.resize (cloudIn->width * cloudIn->height);
centerX = cloudIn->width>>1;
centerY = cloudIn->height>>1;
idx = 0;
for (ypos = -centerY; ypos < centerY; ypos++)
for (xpos = -centerX; xpos < centerX; xpos++)
{
z = 5.0 * ( ((double)rand () / (double)RAND_MAX))+5;
y = ypos*oneOverFocalLength*z;
x = xpos*oneOverFocalLength*z;
cloudIn->points[idx++]= PointXYZ (x, y, z);
}
unsigned int randomIdx = rand()%(cloudIn->width * cloudIn->height);
const PointXYZ& searchPoint = cloudIn->points[randomIdx];
double pointDist;
double searchRadius = 1.0 * ((double)rand () / (double)RAND_MAX);
int minX = cloudIn->width;
int minY = cloudIn->height;
int maxX = 0;
int maxY = 0;
// bruteforce radius search
vector<int> cloudSearchBruteforce;
cloudSearchBruteforce.clear();
for (i = 0; i < cloudIn->points.size (); i++)
{
pointDist = sqrt (
(cloudIn->points[i].x - searchPoint.x) * (cloudIn->points[i].x - searchPoint.x)
+ (cloudIn->points[i].y - searchPoint.y) * (cloudIn->points[i].y - searchPoint.y)
+ (cloudIn->points[i].z - searchPoint.z) * (cloudIn->points[i].z - searchPoint.z));
if (pointDist <= searchRadius)
{
// add point candidates to vector list
cloudSearchBruteforce.push_back ((int)i);
minX = std::min<int>(minX, i%cloudIn->width);
minY = std::min<int>(minY, i/cloudIn->width);
maxX = std::max<int>(maxX, i%cloudIn->width);
maxY = std::max<int>(maxY, i/cloudIn->width);
}
}
vector<int> cloudNWRSearch;
vector<float> cloudNWRRadius;
// execute organized search
organizedNeighborSearch.setInputCloud (cloudIn);
organizedNeighborSearch.radiusSearch (searchPoint, searchRadius, cloudNWRSearch, cloudNWRRadius);
bool pointInBruteforceCloud;
// check if result from organized radius search can be also found in bruteforce search
std::vector<int>::const_iterator current = cloudNWRSearch.begin();
while (current != cloudNWRSearch.end())
{
pointInBruteforceCloud = false;
pointDist = sqrt (
(cloudIn->points[*current].x-searchPoint.x) * (cloudIn->points[*current].x-searchPoint.x) +
(cloudIn->points[*current].y-searchPoint.y) * (cloudIn->points[*current].y-searchPoint.y) +
(cloudIn->points[*current].z-searchPoint.z) * (cloudIn->points[*current].z-searchPoint.z)
);
ASSERT_EQ ( (pointDist<=searchRadius) , true);
++current;
}
// check if bruteforce result from organized radius search can be also found in bruteforce search
current = cloudSearchBruteforce.begin();
while (current != cloudSearchBruteforce.end())
{
pointInBruteforceCloud = false;
pointDist = sqrt (
(cloudIn->points[*current].x-searchPoint.x) * (cloudIn->points[*current].x-searchPoint.x) +
(cloudIn->points[*current].y-searchPoint.y) * (cloudIn->points[*current].y-searchPoint.y) +
(cloudIn->points[*current].z-searchPoint.z) * (cloudIn->points[*current].z-searchPoint.z)
);
ASSERT_EQ ( (pointDist<=searchRadius) , true);
++current;
}
for (i = 0; i < cloudSearchBruteforce.size (); i++) {
bool found = false;
for (j = 0; j < cloudNWRSearch.size (); j++) {
if (cloudNWRSearch[i]== cloudSearchBruteforce[j])
{
found = true;
break;
}
}
}
ASSERT_EQ ( cloudNWRRadius.size() , cloudSearchBruteforce.size());
// check if result limitation works
organizedNeighborSearch.radiusSearch(searchPoint, searchRadius, cloudNWRSearch, cloudNWRRadius, 5);
ASSERT_EQ ( cloudNWRRadius.size() <= 5, true);
}
}
/* ---[ */
int
main (int argc, char** argv)
{
testing::InitGoogleTest (&argc, argv);
return (RUN_ALL_TESTS ());
}
/* ]--- */
<commit_msg>Reduced point cloud size in test_organized_neighbor_search.cpp as test took too long on a Windows VM<commit_after>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. 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.
*
*
*/
/** \author Julius Kammerl (julius@kammerl.de)*/
#include <gtest/gtest.h>
#include <vector>
#include <stdio.h>
using namespace std;
#include <pcl/common/time.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
using namespace pcl;
#include "pcl/kdtree/organized_neighbor_search.h"
#include "pcl/kdtree/impl/organized_neighbor_search.hpp"
// helper class for priority queue
class prioPointQueueEntry
{
public:
prioPointQueueEntry ()
{
}
prioPointQueueEntry (PointXYZ& point_arg, double pointDistance_arg, int pointIdx_arg)
{
point_ = point_arg;
pointDistance_ = pointDistance_arg;
pointIdx_ = pointIdx_arg;
}
bool
operator< (const prioPointQueueEntry& rhs_arg) const
{
return (this->pointDistance_ < rhs_arg.pointDistance_);
}
PointXYZ point_;
double pointDistance_;int pointIdx_;
};
TEST (PCL, Organized_Neighbor_Search_Pointcloud_Nearest_K_Neighbour_Search)
{
const unsigned int test_runs = 2;
unsigned int test_id;
// instantiate point cloud
PointCloud<PointXYZ>::Ptr cloudIn (new PointCloud<PointXYZ> ());
size_t i;
srand (time (NULL));
unsigned int K;
// create organized search
OrganizedNeighborSearch<PointXYZ> organizedNeighborSearch;
std::vector<int> k_indices;
std::vector<float> k_sqr_distances;
std::vector<int> k_indices_bruteforce;
std::vector<float> k_sqr_distances_bruteforce;
// typical focal length from kinect
const double oneOverFocalLength = 0.0018;
double x,y,z;
int xpos, ypos, centerX, centerY, idx;
for (test_id = 0; test_id < test_runs; test_id++)
{
// define a random search point
K = (rand () % 10)+1;
// generate point cloud
cloudIn->width = 128;
cloudIn->height = 32;
cloudIn->points.clear();
cloudIn->points.reserve (cloudIn->width * cloudIn->height);
centerX = cloudIn->width>>1;
centerY = cloudIn->height>>1;
idx = 0;
for (ypos = -centerY; ypos < centerY; ypos++)
for (xpos = -centerX; xpos < centerX; xpos++)
{
z = 15.0 * ((double)rand () / (double)(RAND_MAX+1.0))+20;
y = (double)ypos*oneOverFocalLength*(double)z;
x = (double)xpos*oneOverFocalLength*(double)z;
cloudIn->points.push_back(PointXYZ (x, y, z));
}
unsigned int searchIdx = rand()%(cloudIn->width * cloudIn->height);
const PointXYZ& searchPoint = cloudIn->points[searchIdx];
k_indices.clear();
k_sqr_distances.clear();
// organized nearest neighbor search
organizedNeighborSearch.setInputCloud (cloudIn);
organizedNeighborSearch.nearestKSearch (searchPoint, (int)K, k_indices, k_sqr_distances);
double pointDist;
k_indices_bruteforce.clear();
k_sqr_distances_bruteforce.clear();
std::priority_queue<prioPointQueueEntry> pointCandidates;
// push all points and their distance to the search point into a priority queue - bruteforce approach.
for (i = 0; i < cloudIn->points.size (); i++)
{
pointDist = ((cloudIn->points[i].x - searchPoint.x) * (cloudIn->points[i].x - searchPoint.x) +
/*+*/ (cloudIn->points[i].y - searchPoint.y) * (cloudIn->points[i].y - searchPoint.y) +
(cloudIn->points[i].z - searchPoint.z) * (cloudIn->points[i].z - searchPoint.z));
prioPointQueueEntry pointEntry (cloudIn->points[i], pointDist, i);
pointCandidates.push (pointEntry);
}
// pop priority queue until we have the nearest K elements
while (pointCandidates.size () > K)
pointCandidates.pop ();
// copy results into vectors
while (pointCandidates.size ())
{
k_indices_bruteforce.push_back (pointCandidates.top ().pointIdx_);
k_sqr_distances_bruteforce.push_back (pointCandidates.top ().pointDistance_);
pointCandidates.pop ();
}
ASSERT_EQ ( k_indices.size() , k_indices_bruteforce.size() );
// compare nearest neighbor results of organized search with bruteforce search
for (i = 0; i < k_indices.size (); i++)
{
ASSERT_EQ ( k_indices[i] , k_indices_bruteforce.back() );
EXPECT_NEAR (k_sqr_distances[i], k_sqr_distances_bruteforce.back(), 1e-4);
k_indices_bruteforce.pop_back();
k_sqr_distances_bruteforce.pop_back();
}
}
}
TEST (PCL, Organized_Neighbor_Search_Pointcloud_Neighbours_Within_Radius_Search)
{
const unsigned int test_runs = 10;
unsigned int test_id;
size_t i,j;
srand (time (NULL));
OrganizedNeighborSearch<PointXYZ> organizedNeighborSearch;
std::vector<int> k_indices;
std::vector<float> k_sqr_distances;
std::vector<int> k_indices_bruteforce;
std::vector<float> k_sqr_distances_bruteforce;
// typical focal length from kinect
const double oneOverFocalLength = 0.0018;
double x,y,z;
int xpos, ypos, centerX, centerY, idx;
for (test_id = 0; test_id < test_runs; test_id++)
{
// generate point cloud
PointCloud<PointXYZ>::Ptr cloudIn (new PointCloud<PointXYZ> ());
cloudIn->width = 640;
cloudIn->height = 480;
cloudIn->points.clear();
cloudIn->points.resize (cloudIn->width * cloudIn->height);
centerX = cloudIn->width>>1;
centerY = cloudIn->height>>1;
idx = 0;
for (ypos = -centerY; ypos < centerY; ypos++)
for (xpos = -centerX; xpos < centerX; xpos++)
{
z = 5.0 * ( ((double)rand () / (double)RAND_MAX))+5;
y = ypos*oneOverFocalLength*z;
x = xpos*oneOverFocalLength*z;
cloudIn->points[idx++]= PointXYZ (x, y, z);
}
unsigned int randomIdx = rand()%(cloudIn->width * cloudIn->height);
const PointXYZ& searchPoint = cloudIn->points[randomIdx];
double pointDist;
double searchRadius = 1.0 * ((double)rand () / (double)RAND_MAX);
int minX = cloudIn->width;
int minY = cloudIn->height;
int maxX = 0;
int maxY = 0;
// bruteforce radius search
vector<int> cloudSearchBruteforce;
cloudSearchBruteforce.clear();
for (i = 0; i < cloudIn->points.size (); i++)
{
pointDist = sqrt (
(cloudIn->points[i].x - searchPoint.x) * (cloudIn->points[i].x - searchPoint.x)
+ (cloudIn->points[i].y - searchPoint.y) * (cloudIn->points[i].y - searchPoint.y)
+ (cloudIn->points[i].z - searchPoint.z) * (cloudIn->points[i].z - searchPoint.z));
if (pointDist <= searchRadius)
{
// add point candidates to vector list
cloudSearchBruteforce.push_back ((int)i);
minX = std::min<int>(minX, i%cloudIn->width);
minY = std::min<int>(minY, i/cloudIn->width);
maxX = std::max<int>(maxX, i%cloudIn->width);
maxY = std::max<int>(maxY, i/cloudIn->width);
}
}
vector<int> cloudNWRSearch;
vector<float> cloudNWRRadius;
// execute organized search
organizedNeighborSearch.setInputCloud (cloudIn);
organizedNeighborSearch.radiusSearch (searchPoint, searchRadius, cloudNWRSearch, cloudNWRRadius);
bool pointInBruteforceCloud;
// check if result from organized radius search can be also found in bruteforce search
std::vector<int>::const_iterator current = cloudNWRSearch.begin();
while (current != cloudNWRSearch.end())
{
pointInBruteforceCloud = false;
pointDist = sqrt (
(cloudIn->points[*current].x-searchPoint.x) * (cloudIn->points[*current].x-searchPoint.x) +
(cloudIn->points[*current].y-searchPoint.y) * (cloudIn->points[*current].y-searchPoint.y) +
(cloudIn->points[*current].z-searchPoint.z) * (cloudIn->points[*current].z-searchPoint.z)
);
ASSERT_EQ ( (pointDist<=searchRadius) , true);
++current;
}
// check if bruteforce result from organized radius search can be also found in bruteforce search
current = cloudSearchBruteforce.begin();
while (current != cloudSearchBruteforce.end())
{
pointInBruteforceCloud = false;
pointDist = sqrt (
(cloudIn->points[*current].x-searchPoint.x) * (cloudIn->points[*current].x-searchPoint.x) +
(cloudIn->points[*current].y-searchPoint.y) * (cloudIn->points[*current].y-searchPoint.y) +
(cloudIn->points[*current].z-searchPoint.z) * (cloudIn->points[*current].z-searchPoint.z)
);
ASSERT_EQ ( (pointDist<=searchRadius) , true);
++current;
}
for (i = 0; i < cloudSearchBruteforce.size (); i++) {
bool found = false;
for (j = 0; j < cloudNWRSearch.size (); j++) {
if (cloudNWRSearch[i]== cloudSearchBruteforce[j])
{
found = true;
break;
}
}
}
ASSERT_EQ ( cloudNWRRadius.size() , cloudSearchBruteforce.size());
// check if result limitation works
organizedNeighborSearch.radiusSearch(searchPoint, searchRadius, cloudNWRSearch, cloudNWRRadius, 5);
ASSERT_EQ ( cloudNWRRadius.size() <= 5, true);
}
}
/* ---[ */
int
main (int argc, char** argv)
{
testing::InitGoogleTest (&argc, argv);
return (RUN_ALL_TESTS ());
}
/* ]--- */
<|endoftext|>
|
<commit_before>/*!
@file
@copyright Edouard Alligand and Joel Falcou 2015-2017
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_BRIGAND_TYPES_ARGS_HPP
#define BOOST_BRIGAND_TYPES_ARGS_HPP
#include <brigand/sequences/at.hpp>
#include <brigand/sequences/list.hpp>
namespace brigand
{
// args metafunction class
template<unsigned int Index> struct args
{
};
// Predefined placeholders
struct _1 {};
struct _2 {};
using _3 = args<2>;
using _4 = args<3>;
using _5 = args<4>;
using _6 = args<5>;
using _7 = args<6>;
using _8 = args<7>;
using _9 = args<8>;
using _state = _1;
using _element = _2;
}
#endif
<commit_msg>Delete args.hpp<commit_after><|endoftext|>
|
<commit_before>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2014-2015 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <inviwo/core/util/dialogfactory.h>
#include <inviwo/core/io/rawvolumereader.h>
#include <inviwo/core/datastructures/volume/volumedisk.h>
#include <inviwo/core/datastructures/volume/volumeramprecision.h>
#include <inviwo/core/util/filesystem.h>
#include <inviwo/core/util/formatconversion.h>
namespace inviwo {
RawVolumeReader::RawVolumeReader()
: DataReaderType<Volume>(), rawFile_(""), littleEndian_(true),
dimensions_(0), spacing_(0.01f), format_(nullptr), parametersSet_(false) {
addExtension(FileExtension("raw", "Raw binary file"));
}
RawVolumeReader::RawVolumeReader(const RawVolumeReader& rhs)
: DataReaderType<Volume>(rhs)
, rawFile_(rhs.rawFile_)
, littleEndian_(true)
, dimensions_(rhs.dimensions_)
, spacing_(rhs.spacing_)
, format_(rhs.format_)
, parametersSet_(false) {}
RawVolumeReader& RawVolumeReader::operator=(const RawVolumeReader& that) {
if (this != &that) {
rawFile_ = that.rawFile_;
littleEndian_ = that.littleEndian_;
dimensions_ = that.dimensions_;
spacing_ = that.spacing_;
format_ = that.format_;
DataReaderType<Volume>::operator=(that);
}
return *this;
}
RawVolumeReader* RawVolumeReader::clone() const {
return new RawVolumeReader(*this);
}
void RawVolumeReader::setParameters(const DataFormatBase* format, ivec3 dimensions, bool littleEndian) {
parametersSet_ = true;
format_ = format;
dimensions_ = dimensions;
littleEndian_ = littleEndian;
}
Volume* RawVolumeReader::readMetaData(std::string filePath) {
if (!filesystem::fileExists(filePath)) {
std::string newPath = filesystem::addBasePath(filePath);
if (filesystem::fileExists(newPath)) {
filePath = newPath;
} else {
throw DataReaderException("Error could not find input file: " + filePath, IvwContext);
}
}
std::string fileDirectory = filesystem::getFileDirectory(filePath);
std::string fileExtension = filesystem::getFileExtension(filePath);
rawFile_ = filePath;
if (!parametersSet_) {
// TODO use uniqe ponter here. //Peter
DataReaderDialog* readerDialog =
dynamic_cast<DataReaderDialog*>(DialogFactory::getPtr()->getDialog("RawVolumeReader"));
if (!readerDialog) {
throw DataReaderException("No data reader dialog found.", IvwContext);
}
readerDialog->setFile(rawFile_);
if (readerDialog->show()) {
format_ = readerDialog->getFormat();
dimensions_ = readerDialog->getDimensions();
littleEndian_ = readerDialog->getEndianess();
spacing_ = static_cast<glm::vec3>(readerDialog->getSpacing());
delete readerDialog;
} else {
delete readerDialog;
throw DataReaderException("Raw data import terminated by user", IvwContext);
}
}
if (format_) {
glm::mat3 basis(1.0f);
glm::mat4 wtm(1.0f);
basis[0][0] = dimensions_.x * spacing_.x;
basis[1][1] = dimensions_.y * spacing_.y;
basis[2][2] = dimensions_.z * spacing_.z;
// Center the data around origo.
glm::vec3 offset(-0.5f*(basis[0]+basis[1]+basis[2]));
Volume* volume = new Volume();
volume->setBasis(basis);
volume->setOffset(offset);
volume->setWorldMatrix(wtm);
volume->setDimensions(dimensions_);
volume->setDataFormat(format_);
VolumeDisk* vd = new VolumeDisk(filePath, dimensions_, format_);
vd->setDataReader(this->clone());
volume->addRepresentation(vd);
std::string size = formatBytesToString(dimensions_.x * dimensions_.y * dimensions_.z *
(format_->getSize()));
LogInfo("Loaded volume: " << filePath << " size: " << size);
return volume;
} else {
throw DataReaderException("Raw data import could not determine format", IvwContext);
}
}
void RawVolumeReader::readDataInto(void* destination) const {
std::fstream fin(rawFile_.c_str(), std::ios::in | std::ios::binary);
if (fin.good()) {
std::size_t size = dimensions_.x*dimensions_.y*dimensions_.z*(format_->getSize());
fin.read(static_cast<char*>(destination), size);
if (!littleEndian_ && format_->getSize() > 1) {
std::size_t bytes = format_->getSize();
char* temp = new char[bytes];
for (std::size_t i = 0; i < size; i += bytes) {
for (std::size_t j = 0; j < bytes; j++)
temp[j] = static_cast<char*>(destination)[i + j];
for (std::size_t j = 0; j < bytes; j++)
static_cast<char*>(destination)[i + j] = temp[bytes - j - 1];
}
delete [] temp;
}
} else
throw DataReaderException("Error: Could not read from raw file: " + rawFile_, IvwContext);
fin.close();
}
void* RawVolumeReader::readData() const {
std::size_t size = dimensions_.x*dimensions_.y*dimensions_.z*(format_->getSize());
char* data = new char[size];
if (data)
readDataInto(data);
else
throw DataReaderException("Error: Could not allocate memory for loading raw file: " + rawFile_, IvwContext);
return data;
}
} // namespace
<commit_msg>Core: fixed typo in RAWVolumeReader<commit_after>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2014-2015 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <inviwo/core/util/dialogfactory.h>
#include <inviwo/core/io/rawvolumereader.h>
#include <inviwo/core/datastructures/volume/volumedisk.h>
#include <inviwo/core/datastructures/volume/volumeramprecision.h>
#include <inviwo/core/util/filesystem.h>
#include <inviwo/core/util/formatconversion.h>
namespace inviwo {
RawVolumeReader::RawVolumeReader()
: DataReaderType<Volume>(), rawFile_(""), littleEndian_(true),
dimensions_(0), spacing_(0.01f), format_(nullptr), parametersSet_(false) {
addExtension(FileExtension("raw", "Raw binary file"));
}
RawVolumeReader::RawVolumeReader(const RawVolumeReader& rhs)
: DataReaderType<Volume>(rhs)
, rawFile_(rhs.rawFile_)
, littleEndian_(true)
, dimensions_(rhs.dimensions_)
, spacing_(rhs.spacing_)
, format_(rhs.format_)
, parametersSet_(false) {}
RawVolumeReader& RawVolumeReader::operator=(const RawVolumeReader& that) {
if (this != &that) {
rawFile_ = that.rawFile_;
littleEndian_ = that.littleEndian_;
dimensions_ = that.dimensions_;
spacing_ = that.spacing_;
format_ = that.format_;
DataReaderType<Volume>::operator=(that);
}
return *this;
}
RawVolumeReader* RawVolumeReader::clone() const {
return new RawVolumeReader(*this);
}
void RawVolumeReader::setParameters(const DataFormatBase* format, ivec3 dimensions, bool littleEndian) {
parametersSet_ = true;
format_ = format;
dimensions_ = dimensions;
littleEndian_ = littleEndian;
}
Volume* RawVolumeReader::readMetaData(std::string filePath) {
if (!filesystem::fileExists(filePath)) {
std::string newPath = filesystem::addBasePath(filePath);
if (filesystem::fileExists(newPath)) {
filePath = newPath;
} else {
throw DataReaderException("Error could not find input file: " + filePath, IvwContext);
}
}
std::string fileDirectory = filesystem::getFileDirectory(filePath);
std::string fileExtension = filesystem::getFileExtension(filePath);
rawFile_ = filePath;
if (!parametersSet_) {
// TODO use uniqe pointer here. //Peter
DataReaderDialog* readerDialog =
dynamic_cast<DataReaderDialog*>(DialogFactory::getPtr()->getDialog("RawVolumeReader"));
if (!readerDialog) {
throw DataReaderException("No data reader dialog found.", IvwContext);
}
readerDialog->setFile(rawFile_);
if (readerDialog->show()) {
format_ = readerDialog->getFormat();
dimensions_ = readerDialog->getDimensions();
littleEndian_ = readerDialog->getEndianess();
spacing_ = static_cast<glm::vec3>(readerDialog->getSpacing());
delete readerDialog;
} else {
delete readerDialog;
throw DataReaderException("Raw data import terminated by user", IvwContext);
}
}
if (format_) {
glm::mat3 basis(1.0f);
glm::mat4 wtm(1.0f);
basis[0][0] = dimensions_.x * spacing_.x;
basis[1][1] = dimensions_.y * spacing_.y;
basis[2][2] = dimensions_.z * spacing_.z;
// Center the data around origo.
glm::vec3 offset(-0.5f*(basis[0]+basis[1]+basis[2]));
Volume* volume = new Volume();
volume->setBasis(basis);
volume->setOffset(offset);
volume->setWorldMatrix(wtm);
volume->setDimensions(dimensions_);
volume->setDataFormat(format_);
VolumeDisk* vd = new VolumeDisk(filePath, dimensions_, format_);
vd->setDataReader(this->clone());
volume->addRepresentation(vd);
std::string size = formatBytesToString(dimensions_.x * dimensions_.y * dimensions_.z *
(format_->getSize()));
LogInfo("Loaded volume: " << filePath << " size: " << size);
return volume;
} else {
throw DataReaderException("Raw data import could not determine format", IvwContext);
}
}
void RawVolumeReader::readDataInto(void* destination) const {
std::fstream fin(rawFile_.c_str(), std::ios::in | std::ios::binary);
if (fin.good()) {
std::size_t size = dimensions_.x*dimensions_.y*dimensions_.z*(format_->getSize());
fin.read(static_cast<char*>(destination), size);
if (!littleEndian_ && format_->getSize() > 1) {
std::size_t bytes = format_->getSize();
char* temp = new char[bytes];
for (std::size_t i = 0; i < size; i += bytes) {
for (std::size_t j = 0; j < bytes; j++)
temp[j] = static_cast<char*>(destination)[i + j];
for (std::size_t j = 0; j < bytes; j++)
static_cast<char*>(destination)[i + j] = temp[bytes - j - 1];
}
delete [] temp;
}
} else
throw DataReaderException("Error: Could not read from raw file: " + rawFile_, IvwContext);
fin.close();
}
void* RawVolumeReader::readData() const {
std::size_t size = dimensions_.x*dimensions_.y*dimensions_.z*(format_->getSize());
char* data = new char[size];
if (data)
readDataInto(data);
else
throw DataReaderException("Error: Could not allocate memory for loading raw file: " + rawFile_, IvwContext);
return data;
}
} // namespace
<|endoftext|>
|
<commit_before>// =-=-=-=-=-=-=-
#include "apiHeaderAll.hpp"
#include "msParam.hpp"
#include "reGlobalsExtern.hpp"
#include "irods_ms_plugin.hpp"
// =-=-=-=-=-=-=-
// STL Includes
#include <string>
#include <iostream>
// =-=-=-=-=-=-=-
// cURL Includes
#include <curl/curl.h>
#include <curl/easy.h>
typedef struct {
char objPath[MAX_NAME_LEN];
int l1descInx;
rsComm_t *rsComm;
} writeDataInp_t;
class irodsCurl {
private:
// iRODS server handle
rsComm_t *rsComm;
// cURL handle
CURL *curl;
public:
irodsCurl( rsComm_t *comm ) {
rsComm = comm;
curl = curl_easy_init();
if ( !curl ) {
rodsLog( LOG_ERROR, "irodsCurl: %s", curl_easy_strerror( CURLE_FAILED_INIT ) );
}
}
~irodsCurl() {
if ( curl ) {
curl_easy_cleanup( curl );
}
}
int get( char *url, char *objPath ) {
CURLcode res = CURLE_OK;
writeDataInp_t writeDataInp; // the "file descriptor" for our destination object
openedDataObjInp_t openedDataObjInp; // for closing iRODS object after writing
int status;
// Zero fill openedDataObjInp
memset( &openedDataObjInp, 0, sizeof( openedDataObjInp_t ) );
// Set up writeDataInp
snprintf( writeDataInp.objPath, MAX_NAME_LEN, "%s", objPath );
writeDataInp.l1descInx = 0; // the object is yet to be created
writeDataInp.rsComm = rsComm;
// Set up easy handler
curl_easy_setopt( curl, CURLOPT_WRITEFUNCTION, &irodsCurl::my_write_obj );
curl_easy_setopt( curl, CURLOPT_WRITEDATA, &writeDataInp );
curl_easy_setopt( curl, CURLOPT_URL, url );
// CURL call
res = curl_easy_perform( curl );
// Some error logging
if ( res != CURLE_OK ) {
rodsLog( LOG_ERROR, "irodsCurl::get: cURL error: %s", curl_easy_strerror( res ) );
}
// close iRODS object
if ( writeDataInp.l1descInx ) {
openedDataObjInp.l1descInx = writeDataInp.l1descInx;
status = rsDataObjClose( rsComm, &openedDataObjInp );
if ( status < 0 ) {
rodsLog( LOG_ERROR, "irodsCurl::get: rsDataObjClose failed for %s, status = %d",
writeDataInp.objPath, status );
}
}
return res;
}
// Custom callback function for the curl handler, to write to an iRODS object
static size_t my_write_obj( void *buffer, size_t size, size_t nmemb, writeDataInp_t *writeDataInp ) {
dataObjInp_t dataObjInp; // input struct for rsDataObjCreate
openedDataObjInp_t openedDataObjInp; // input struct for rsDataObjWrite
bytesBuf_t bytesBuf; // input buffer for rsDataObjWrite
size_t written; // return value
int l1descInx;
// Make sure we have something to write to
if ( !writeDataInp ) {
rodsLog( LOG_ERROR, "my_write_obj: writeDataInp is NULL, status = %d", SYS_INTERNAL_NULL_INPUT_ERR );
return SYS_INTERNAL_NULL_INPUT_ERR;
}
// Zero fill input structs
memset( &dataObjInp, 0, sizeof( dataObjInp_t ) );
memset( &openedDataObjInp, 0, sizeof( openedDataObjInp_t ) );
// If this is the first call we need to create our data object before writing to it
if ( !writeDataInp->l1descInx ) {
strncpy( dataObjInp.objPath, writeDataInp->objPath, MAX_NAME_LEN );
// Overwrite existing file (for this tutorial only, in case the example has been run before)
addKeyVal( &dataObjInp.condInput, FORCE_FLAG_KW, "" );
writeDataInp->l1descInx = rsDataObjCreate( writeDataInp->rsComm, &dataObjInp );
// No create?
if ( writeDataInp->l1descInx <= 2 ) {
rodsLog( LOG_ERROR, "my_write_obj: rsDataObjCreate failed for %s, status = %d", dataObjInp.objPath, writeDataInp->l1descInx );
return ( writeDataInp->l1descInx );
}
}
// Set up input buffer for rsDataObjWrite
bytesBuf.len = ( int )( size * nmemb );
bytesBuf.buf = buffer;
// Set up input struct for rsDataObjWrite
openedDataObjInp.l1descInx = writeDataInp->l1descInx;;
openedDataObjInp.len = bytesBuf.len;
// Write to data object
written = rsDataObjWrite( writeDataInp->rsComm, &openedDataObjInp, &bytesBuf );
return ( written );
}
}; // class irodsCurl
extern "C" {
// =-=-=-=-=-=-=-
// 1. Write a standard issue microservice
int irods_curl_get( msParam_t* url, msParam_t* dest_obj, ruleExecInfo_t* rei ) {
dataObjInp_t destObjInp, *myDestObjInp; /* for parsing input object */
// Sanity checks
if ( !rei || !rei->rsComm ) {
rodsLog( LOG_ERROR, "irods_curl_get: Input rei or rsComm is NULL." );
return ( SYS_INTERNAL_NULL_INPUT_ERR );
}
// Get path of destination object
rei->status = parseMspForDataObjInp( dest_obj, &destObjInp, &myDestObjInp, 0 );
if ( rei->status < 0 ) {
rodsLog( LOG_ERROR, "irods_curl_get: Input object error. status = %d", rei->status );
return ( rei->status );
}
// Create irodsCurl instance
irodsCurl myCurl( rei->rsComm );
// Call irodsCurl::get
rei->status = myCurl.get( parseMspForStr( url ), destObjInp.objPath );
// Done
return rei->status;
}
// =-=-=-=-=-=-=-
// 2. Create the plugin factory function which will return a microservice
// table entry
irods::ms_table_entry* plugin_factory() {
// =-=-=-=-=-=-=-
// 3. allocate a microservice plugin which takes the number of function
// params as a parameter to the constructor
irods::ms_table_entry* msvc = new irods::ms_table_entry( 2 );
// =-=-=-=-=-=-=-
// 4. add the microservice function as an operation to the plugin
// the first param is the name / key of the operation, the second
// is the name of the function which will be the microservice
msvc->add_operation( "irods_curl_get", "irods_curl_get" );
// =-=-=-=-=-=-=-
// 5. return the newly created microservice plugin
return msvc;
}
} // extern "C"
<commit_msg>changed curl function<commit_after>// =-=-=-=-=-=-=-
#include "apiHeaderAll.hpp"
#include "msParam.hpp"
#include "reGlobalsExtern.hpp"
#include "irods_ms_plugin.hpp"
// =-=-=-=-=-=-=-
// STL Includes
#include <string>
#include <iostream>
// =-=-=-=-=-=-=-
// cURL Includes
#include <curl/curl.h>
#include <curl/easy.h>
typedef struct {
char objPath[MAX_NAME_LEN];
int l1descInx;
rsComm_t *rsComm;
} writeDataInp_t;
class irodsCurl {
private:
// iRODS server handle
rsComm_t *rsComm;
// cURL handle
CURL *curl;
public:
irodsCurl( rsComm_t *comm ) {
rsComm = comm;
curl = curl_easy_init();
if ( !curl ) {
rodsLog( LOG_ERROR, "irodsCurl: %s", curl_easy_strerror( CURLE_FAILED_INIT ) );
}
}
~irodsCurl() {
if ( curl ) {
curl_easy_cleanup( curl );
}
}
int get( char *url, char *sourcePath, char *destPath ) {
CURLcode res = CURLE_OK;
writeDataInp_t writeDataInp; // the "file descriptor" for our destination object
openedDataObjInp_t openedDataObjInp; // for closing iRODS object after writing
int status;
FILE *fd;
fd = fopen(sourcePath, "rb"); /* open file to upload */
if(!fd) { return 1; /* can't continue */ }
// Zero fill openedDataObjInp
memset( &openedDataObjInp, 0, sizeof( openedDataObjInp_t ) );
// Set up writeDataInp
snprintf( writeDataInp.objPath, MAX_NAME_LEN, "%s", destPath );
writeDataInp.l1descInx = 0; // the object is yet to be created
writeDataInp.rsComm = rsComm;
// Set up easy handler
curl_easy_setopt( curl, CURLOPT_WRITEFUNCTION, &irodsCurl::my_write_obj );
curl_easy_setopt( curl, CURLOPT_WRITEDATA, &writeDataInp );
curl_easy_setopt( curl, CURLOPT_URL, url );
// CURL call
res = curl_easy_perform( curl );
// Some error logging
if ( res != CURLE_OK ) {
rodsLog( LOG_ERROR, "irodsCurl::get: cURL error: %s", curl_easy_strerror( res ) );
}
// close iRODS object
if ( writeDataInp.l1descInx ) {
openedDataObjInp.l1descInx = writeDataInp.l1descInx;
status = rsDataObjClose( rsComm, &openedDataObjInp );
if ( status < 0 ) {
rodsLog( LOG_ERROR, "irodsCurl::get: rsDataObjClose failed for %s, status = %d",
writeDataInp.objPath, status );
}
}
return res;
}
// Custom callback function for the curl handler, to write to an iRODS object
static size_t my_write_obj( void *buffer, size_t size, size_t nmemb, writeDataInp_t *writeDataInp ) {
dataObjInp_t dataObjInp; // input struct for rsDataObjCreate
openedDataObjInp_t openedDataObjInp; // input struct for rsDataObjWrite
bytesBuf_t bytesBuf; // input buffer for rsDataObjWrite
size_t written; // return value
int l1descInx;
// Make sure we have something to write to
if ( !writeDataInp ) {
rodsLog( LOG_ERROR, "my_write_obj: writeDataInp is NULL, status = %d", SYS_INTERNAL_NULL_INPUT_ERR );
return SYS_INTERNAL_NULL_INPUT_ERR;
}
// Zero fill input structs
memset( &dataObjInp, 0, sizeof( dataObjInp_t ) );
memset( &openedDataObjInp, 0, sizeof( openedDataObjInp_t ) );
// If this is the first call we need to create our data object before writing to it
if ( !writeDataInp->l1descInx ) {
strncpy( dataObjInp.objPath, writeDataInp->objPath, MAX_NAME_LEN );
// Overwrite existing file (for this tutorial only, in case the example has been run before)
addKeyVal( &dataObjInp.condInput, FORCE_FLAG_KW, "" );
writeDataInp->l1descInx = rsDataObjCreate( writeDataInp->rsComm, &dataObjInp );
// No create?
if ( writeDataInp->l1descInx <= 2 ) {
rodsLog( LOG_ERROR, "my_write_obj: rsDataObjCreate failed for %s, status = %d", dataObjInp.objPath, writeDataInp->l1descInx );
return ( writeDataInp->l1descInx );
}
}
// Set up input buffer for rsDataObjWrite
bytesBuf.len = ( int )( size * nmemb );
bytesBuf.buf = buffer;
// Set up input struct for rsDataObjWrite
openedDataObjInp.l1descInx = writeDataInp->l1descInx;;
openedDataObjInp.len = bytesBuf.len;
// Write to data object
written = rsDataObjWrite( writeDataInp->rsComm, &openedDataObjInp, &bytesBuf );
return ( written );
}
}; // class irodsCurl
extern "C" {
// =-=-=-=-=-=-=-
// 1. Write a standard issue microservice
int irods_curl_get( msParam_t* url, msParam_t* source_obj, msParam_t* dest_obj, ruleExecInfo_t* rei ) {
dataObjInp_t destObjInp, *myDestObjInp; /* for parsing input object */
// Sanity checks
if ( !rei || !rei->rsComm ) {
rodsLog( LOG_ERROR, "irods_curl_get: Input rei or rsComm is NULL." );
return ( SYS_INTERNAL_NULL_INPUT_ERR );
}
// Get path of destination object
rei->status = parseMspForDataObjInp( dest_obj, &destObjInp, &myDestObjInp, 0 );
if ( rei->status < 0 ) {
rodsLog( LOG_ERROR, "irods_curl_get: Input object error. status = %d", rei->status );
return ( rei->status );
}
// Create irodsCurl instance
irodsCurl myCurl( rei->rsComm );
// Call irodsCurl::get
char *sourceStr = parseMspForStr(source_obj);
rei->status = myCurl.get( parseMspForStr( url ), sourceStr, destObjInp.objPath );
// Done
return rei->status;
}
// =-=-=-=-=-=-=-
// 2. Create the plugin factory function which will return a microservice
// table entry
irods::ms_table_entry* plugin_factory() {
// =-=-=-=-=-=-=-
// 3. allocate a microservice plugin which takes the number of function
// params as a parameter to the constructor
irods::ms_table_entry* msvc = new irods::ms_table_entry( 3 );
// =-=-=-=-=-=-=-
// 4. add the microservice function as an operation to the plugin
// the first param is the name / key of the operation, the second
// is the name of the function which will be the microservice
msvc->add_operation( "irods_curl_get", "irods_curl_get" );
// =-=-=-=-=-=-=-
// 5. return the newly created microservice plugin
return msvc;
}
} // extern "C"
<|endoftext|>
|
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Id$
*/
#if !defined(XMLURL_HPP)
#define XMLURL_HPP
#include <xercesc/util/XercesDefs.hpp>
#include <xercesc/util/XMLException.hpp>
XERCES_CPP_NAMESPACE_BEGIN
class BinInputStream;
//
// This class supports file, http, and ftp style URLs. All others are
// rejected
//
class XMLUTIL_EXPORT XMLURL
{
public:
// -----------------------------------------------------------------------
// Class types
//
// And they must remain in this order because they are indexes into an
// array internally!
// -----------------------------------------------------------------------
enum Protocols
{
File
, HTTP
, FTP
, Protocols_Count
, Unknown
};
// -----------------------------------------------------------------------
// Public static methods
// -----------------------------------------------------------------------
Protocols lookupByName(const XMLCh* const protoName);
// -----------------------------------------------------------------------
// Constructors and Destructor
// -----------------------------------------------------------------------
XMLURL();
XMLURL
(
const XMLCh* const baseURL
, const XMLCh* const relativeURL
);
XMLURL
(
const XMLCh* const baseURL
, const char* const relativeURL
);
XMLURL
(
const XMLURL& baseURL
, const XMLCh* const relativeURL
);
XMLURL
(
const XMLURL& baseURL
, const char* const relativeURL
);
XMLURL
(
const XMLCh* const urlText
);
XMLURL
(
const char* const urlText
);
XMLURL(const XMLURL& toCopy);
virtual ~XMLURL();
// -----------------------------------------------------------------------
// Operators
// -----------------------------------------------------------------------
XMLURL& operator=(const XMLURL& toAssign);
bool operator==(const XMLURL& toCompare) const;
bool operator!=(const XMLURL& toCompare) const;
// -----------------------------------------------------------------------
// Getter methods
// -----------------------------------------------------------------------
const XMLCh* getFragment() const;
const XMLCh* getHost() const;
const XMLCh* getPassword() const;
const XMLCh* getPath() const;
unsigned int getPortNum() const;
Protocols getProtocol() const;
const XMLCh* getProtocolName() const;
const XMLCh* getQuery() const;
const XMLCh* getURLText() const;
const XMLCh* getUser() const;
// -----------------------------------------------------------------------
// Setter methods
// -----------------------------------------------------------------------
void setURL(const XMLCh* const urlText);
void setURL
(
const XMLCh* const baseURL
, const XMLCh* const relativeURL
);
void setURL
(
const XMLURL& baseURL
, const XMLCh* const relativeURL
);
// -----------------------------------------------------------------------
// Miscellaneous methods
// -----------------------------------------------------------------------
bool isRelative() const;
bool hasInvalidChar() const;
BinInputStream* makeNewStream() const;
void makeRelativeTo(const XMLCh* const baseURLText);
void makeRelativeTo(const XMLURL& baseURL);
private:
// -----------------------------------------------------------------------
// Private helper methods
// -----------------------------------------------------------------------
void buildFullText();
void cleanup();
bool conglomerateWithBase(const XMLURL& baseURL, bool useExceptions=true);
void parse
(
const XMLCh* const urlText
);
// -----------------------------------------------------------------------
// Data members
//
// fFragment
// The fragment part of the URL, if any. If none, its a null.
//
// fHost
// The host part of the URL that was parsed out. This one will often
// be null (or "localhost", which also means the current machine.)
//
// fPassword
// The password found, if any. If none then its a null.
//
// fPath
// The path part of the URL that was parsed out, if any. If none,
// then its a null.
//
// fPortNum
// The port that was indicated in the URL. If no port was provided
// explicitly, then its left zero.
//
// fProtocol
// Indicates the type of the URL's source. The text of the prefix
// can be gotten from this.
//
// fQuery
// The query part of the URL, if any. If none, then its a null.
//
// fUser
// The username found, if any. If none, then its a null.
//
// fURLText
// This is a copy of the URL text, after it has been taken apart,
// made relative if needed, canonicalized, and then put back
// together. Its only created upon demand.
//
// fHasInvalidChar
// This indicates if the URL Text contains invalid characters as per
// RFC 2396 standard.
// -----------------------------------------------------------------------
XMLCh* fFragment;
XMLCh* fHost;
XMLCh* fPassword;
XMLCh* fPath;
unsigned int fPortNum;
Protocols fProtocol;
XMLCh* fQuery;
XMLCh* fUser;
XMLCh* fURLText;
bool fHasInvalidChar;
};
// ---------------------------------------------------------------------------
// XMLURL: Public operators
// ---------------------------------------------------------------------------
inline bool XMLURL::operator!=(const XMLURL& toCompare) const
{
return !operator==(toCompare);
}
// ---------------------------------------------------------------------------
// XMLURL: Getter methods
// ---------------------------------------------------------------------------
inline const XMLCh* XMLURL::getFragment() const
{
return fFragment;
}
inline const XMLCh* XMLURL::getHost() const
{
return fHost;
}
inline const XMLCh* XMLURL::getPassword() const
{
return fPassword;
}
inline const XMLCh* XMLURL::getPath() const
{
return fPath;
}
inline XMLURL::Protocols XMLURL::getProtocol() const
{
return fProtocol;
}
inline const XMLCh* XMLURL::getQuery() const
{
return fQuery;
}
inline const XMLCh* XMLURL::getUser() const
{
return fUser;
}
inline const XMLCh* XMLURL::getURLText() const
{
//
// Fault it in if not already. Since this is a const method and we
// can't use mutable members due the compilers we have to support,
// we have to cast off the constness.
//
if (!fURLText)
((XMLURL*)this)->buildFullText();
return fURLText;
}
MakeXMLException(MalformedURLException, XMLUTIL_EXPORT)
XERCES_CPP_NAMESPACE_END
#endif
<commit_msg>[Bug 7592] XMLURL::lookupByName() should be static<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Id$
*/
#if !defined(XMLURL_HPP)
#define XMLURL_HPP
#include <xercesc/util/XercesDefs.hpp>
#include <xercesc/util/XMLException.hpp>
XERCES_CPP_NAMESPACE_BEGIN
class BinInputStream;
//
// This class supports file, http, and ftp style URLs. All others are
// rejected
//
class XMLUTIL_EXPORT XMLURL
{
public:
// -----------------------------------------------------------------------
// Class types
//
// And they must remain in this order because they are indexes into an
// array internally!
// -----------------------------------------------------------------------
enum Protocols
{
File
, HTTP
, FTP
, Protocols_Count
, Unknown
};
// -----------------------------------------------------------------------
// Public static methods
// -----------------------------------------------------------------------
static Protocols lookupByName(const XMLCh* const protoName);
// -----------------------------------------------------------------------
// Constructors and Destructor
// -----------------------------------------------------------------------
XMLURL();
XMLURL
(
const XMLCh* const baseURL
, const XMLCh* const relativeURL
);
XMLURL
(
const XMLCh* const baseURL
, const char* const relativeURL
);
XMLURL
(
const XMLURL& baseURL
, const XMLCh* const relativeURL
);
XMLURL
(
const XMLURL& baseURL
, const char* const relativeURL
);
XMLURL
(
const XMLCh* const urlText
);
XMLURL
(
const char* const urlText
);
XMLURL(const XMLURL& toCopy);
virtual ~XMLURL();
// -----------------------------------------------------------------------
// Operators
// -----------------------------------------------------------------------
XMLURL& operator=(const XMLURL& toAssign);
bool operator==(const XMLURL& toCompare) const;
bool operator!=(const XMLURL& toCompare) const;
// -----------------------------------------------------------------------
// Getter methods
// -----------------------------------------------------------------------
const XMLCh* getFragment() const;
const XMLCh* getHost() const;
const XMLCh* getPassword() const;
const XMLCh* getPath() const;
unsigned int getPortNum() const;
Protocols getProtocol() const;
const XMLCh* getProtocolName() const;
const XMLCh* getQuery() const;
const XMLCh* getURLText() const;
const XMLCh* getUser() const;
// -----------------------------------------------------------------------
// Setter methods
// -----------------------------------------------------------------------
void setURL(const XMLCh* const urlText);
void setURL
(
const XMLCh* const baseURL
, const XMLCh* const relativeURL
);
void setURL
(
const XMLURL& baseURL
, const XMLCh* const relativeURL
);
// -----------------------------------------------------------------------
// Miscellaneous methods
// -----------------------------------------------------------------------
bool isRelative() const;
bool hasInvalidChar() const;
BinInputStream* makeNewStream() const;
void makeRelativeTo(const XMLCh* const baseURLText);
void makeRelativeTo(const XMLURL& baseURL);
private:
// -----------------------------------------------------------------------
// Private helper methods
// -----------------------------------------------------------------------
void buildFullText();
void cleanup();
bool conglomerateWithBase(const XMLURL& baseURL, bool useExceptions=true);
void parse
(
const XMLCh* const urlText
);
// -----------------------------------------------------------------------
// Data members
//
// fFragment
// The fragment part of the URL, if any. If none, its a null.
//
// fHost
// The host part of the URL that was parsed out. This one will often
// be null (or "localhost", which also means the current machine.)
//
// fPassword
// The password found, if any. If none then its a null.
//
// fPath
// The path part of the URL that was parsed out, if any. If none,
// then its a null.
//
// fPortNum
// The port that was indicated in the URL. If no port was provided
// explicitly, then its left zero.
//
// fProtocol
// Indicates the type of the URL's source. The text of the prefix
// can be gotten from this.
//
// fQuery
// The query part of the URL, if any. If none, then its a null.
//
// fUser
// The username found, if any. If none, then its a null.
//
// fURLText
// This is a copy of the URL text, after it has been taken apart,
// made relative if needed, canonicalized, and then put back
// together. Its only created upon demand.
//
// fHasInvalidChar
// This indicates if the URL Text contains invalid characters as per
// RFC 2396 standard.
// -----------------------------------------------------------------------
XMLCh* fFragment;
XMLCh* fHost;
XMLCh* fPassword;
XMLCh* fPath;
unsigned int fPortNum;
Protocols fProtocol;
XMLCh* fQuery;
XMLCh* fUser;
XMLCh* fURLText;
bool fHasInvalidChar;
};
// ---------------------------------------------------------------------------
// XMLURL: Public operators
// ---------------------------------------------------------------------------
inline bool XMLURL::operator!=(const XMLURL& toCompare) const
{
return !operator==(toCompare);
}
// ---------------------------------------------------------------------------
// XMLURL: Getter methods
// ---------------------------------------------------------------------------
inline const XMLCh* XMLURL::getFragment() const
{
return fFragment;
}
inline const XMLCh* XMLURL::getHost() const
{
return fHost;
}
inline const XMLCh* XMLURL::getPassword() const
{
return fPassword;
}
inline const XMLCh* XMLURL::getPath() const
{
return fPath;
}
inline XMLURL::Protocols XMLURL::getProtocol() const
{
return fProtocol;
}
inline const XMLCh* XMLURL::getQuery() const
{
return fQuery;
}
inline const XMLCh* XMLURL::getUser() const
{
return fUser;
}
inline const XMLCh* XMLURL::getURLText() const
{
//
// Fault it in if not already. Since this is a const method and we
// can't use mutable members due the compilers we have to support,
// we have to cast off the constness.
//
if (!fURLText)
((XMLURL*)this)->buildFullText();
return fURLText;
}
MakeXMLException(MalformedURLException, XMLUTIL_EXPORT)
XERCES_CPP_NAMESPACE_END
#endif
<|endoftext|>
|
<commit_before>// This file is part of the "x0" project, http://github.com/christianparpart/x0>
// (c) 2009-2017 Christian Parpart <christian@parpart.family>
//
// Licensed under the MIT License (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of
// the License at: http://opensource.org/licenses/MIT
#include <xzero/raft/Transport.h>
#include <xzero/raft/Handler.h>
#include <xzero/raft/Listener.h>
#include <xzero/raft/Discovery.h>
#include <xzero/raft/Server.h>
#include <xzero/raft/Generator.h>
#include <xzero/raft/Parser.h>
#include <xzero/net/EndPoint.h>
#include <xzero/net/InetEndPoint.h>
#include <xzero/net/InetConnector.h>
#include <xzero/BufferUtil.h>
#include <xzero/logging.h>
namespace xzero {
namespace raft {
Transport::~Transport() {
}
/*
* - the peer that wants to say something, initiates the connection
* - the connection may be reused (pooled) for future messages
* - an incoming connection MAY be reused to send the response, too
*/
// {{{ PeerConnection
class PeerConnection
: public Connection,
public Listener {
public:
PeerConnection(Connector* connector,
EndPoint* endpoint,
Id peerId,
Handler* handler);
// Connection override (connection-endpoint hooks)
void onOpen(bool dataReady) override;
void onFillable() override;
void onFlushable() override;
// Listener overrides (parser hooks)
void receive(Id from, const VoteRequest& message) override;
void receive(Id from, const VoteResponse& message) override;
void receive(Id from, const AppendEntriesRequest& message) override;
void receive(Id from, const AppendEntriesResponse& message) override;
void receive(Id from, const InstallSnapshotResponse& message) override;
void receive(Id from, const InstallSnapshotRequest& message) override;
private:
Buffer inputBuffer_;
Buffer outputBuffer_;
size_t outputOffset_;
Handler* handler_;
Parser parser_;
};
PeerConnection::PeerConnection(Connector* connector,
EndPoint* endpoint,
Id peerId,
Handler* handler)
: Connection(endpoint, connector->executor()),
inputBuffer_(4096),
outputBuffer_(4096),
outputOffset_(0),
handler_(handler),
parser_(peerId, this) {
}
void PeerConnection::onOpen(bool dataReady) {
Connection::onOpen(dataReady);
if (dataReady) {
onFillable();
} else {
wantFill();
}
}
void PeerConnection::onFillable() {
size_t n = endpoint()->fill(&inputBuffer_);
if (n == 0) {
close();
return; // EOF
}
n = parser_.parseFragment(inputBuffer_);
inputBuffer_.clear();
if (n == 0) {
// no message passed => need more input
wantFill();
}
}
void PeerConnection::onFlushable() {
size_t n = endpoint()->flush(outputBuffer_.ref(outputOffset_));
outputOffset_ += n;
if (outputOffset_ == outputBuffer_.size()) {
outputBuffer_.clear();
outputOffset_ = 0;
wantFill();
}
}
void PeerConnection::receive(Id from, const VoteRequest& req) {
VoteResponse res = handler_->handleRequest(from, req);
Generator(BufferUtil::writer(&outputBuffer_)).generateVoteResponse(res);
wantFlush();
}
void PeerConnection::receive(Id from, const VoteResponse& res) {
handler_->handleResponse(from, res);
}
void PeerConnection::receive(Id from, const AppendEntriesRequest& req) {
AppendEntriesResponse res = handler_->handleRequest(from, req);
Generator(BufferUtil::writer(&outputBuffer_)).generateAppendEntriesResponse(res);
wantFlush();
}
void PeerConnection::receive(Id from, const AppendEntriesResponse& res) {
handler_->handleResponse(from, res);
}
void PeerConnection::receive(Id from, const InstallSnapshotRequest& req) {
InstallSnapshotResponse res = handler_->handleRequest(from, req);
Generator(BufferUtil::writer(&outputBuffer_)).generateInstallSnapshotResponse(res);
wantFlush();
}
void PeerConnection::receive(Id from, const InstallSnapshotResponse& res) {
handler_->handleResponse(from, res);
}
// }}}
// {{{ InetTransport
InetTransport::InetTransport(const Discovery* discovery,
Executor* handlerExecutor,
std::shared_ptr<Connector> connector)
: ConnectionFactory("raft"),
discovery_(discovery),
handlerExecutor_(handlerExecutor),
connector_(connector) {
}
InetTransport::~InetTransport() {
}
void InetTransport::setHandler(Handler* handler) {
handler_ = handler;
}
Connection* InetTransport::create(Connector* connector,
EndPoint* endpoint) {
Id peerId = 4242; // TODO: detect peer ID
return configure(
endpoint->setConnection<PeerConnection>(connector,
endpoint,
peerId,
handler_),
connector);
}
RefPtr<EndPoint> InetTransport::getEndPoint(Id target) {
constexpr Duration connectTimeout = 5_seconds;
constexpr Duration readTimeout = 5_seconds;
constexpr Duration writeTimeout = 5_seconds;
Result<std::string> address = discovery_->getAddress(target);
if (address.isFailure())
return nullptr;
// TODO: make ourself independant from TCP/IP here and also allow other EndPoint's.
// TODO: add endpoint pooling, to reduce resource hogging.
RefPtr<EndPoint> ep = InetEndPoint::connect(
InetAddress(*address),
connectTimeout,
readTimeout,
writeTimeout,
connector_->executor());
return ep;
}
void InetTransport::send(Id target, const VoteRequest& msg) {
if (RefPtr<EndPoint> ep = getEndPoint(target)) {
Buffer buffer;
Generator(BufferUtil::writer(&buffer)).generateVoteRequest(msg);
ep->flush(buffer);
}
}
void InetTransport::send(Id target, const AppendEntriesRequest& msg) {
if (RefPtr<EndPoint> ep = getEndPoint(target)) {
Buffer buffer;
Generator(BufferUtil::writer(&buffer)).generateAppendEntriesRequest(msg);
ep->flush(buffer);
}
}
void InetTransport::send(Id target, const InstallSnapshotRequest& msg) {
if (RefPtr<EndPoint> ep = getEndPoint(target)) {
Buffer buffer;
Generator(BufferUtil::writer(&buffer)).generateInstallSnapshotRequest(msg);
ep->flush(buffer);
}
}
// }}}
// {{{ LocalTransport
LocalTransport::LocalTransport(Id myId, Executor* executor)
: myId_(myId),
myHandler_(nullptr),
executor_(executor),
peers_() {
}
LocalTransport::LocalTransport(LocalTransport&& m)
: myId_(m.myId_),
myHandler_(m.myHandler_),
executor_(m.executor_),
peers_(std::move(m.peers_)) {
}
LocalTransport& LocalTransport::operator=(LocalTransport&& m) {
myId_ = std::move(m.myId_);
myHandler_ = std::move(m.myHandler_);
executor_ = std::move(m.executor_);
peers_ = std::move(m.peers_);
return *this;
}
void LocalTransport::setPeer(Id peerId, Handler* target) {
peers_[peerId] = target;
}
Handler* LocalTransport::getPeer(Id id) {
auto i = peers_.find(id);
if (i != peers_.end()) {
return i->second;
} else {
return nullptr;
}
}
void LocalTransport::setHandler(Handler* handler) {
myHandler_ = handler;
}
void LocalTransport::send(Id target, const VoteRequest& msg) {
assert(msg.candidateId == myId_);
// sends a VoteRequest msg to the given target.
// XXX emulate async/delayed behaviour by deferring receival via executor API.
executor_->execute([=]() {
VoteResponse result = getPeer(target)->handleRequest(myId_, msg);
executor_->execute([=]() {
getPeer(myId_)->handleResponse(target, result);
});
});
//logDebug("raft.LocalTransport", "$0 send to $1: $2", myId_, target, msg);
}
void LocalTransport::send(Id target, const AppendEntriesRequest& msg) {
assert(msg.leaderId == myId_);
executor_->execute([=]() {
logDebug("raft.LocalTransport", "AppendEntriesRequest from $0 to $1: $2", myId_, target, msg);
AppendEntriesResponse result = getPeer(target)->handleRequest(myId_, msg);
executor_->execute([=]() {
getPeer(myId_)->handleResponse(target, result);
});
});
}
void LocalTransport::send(Id target, const InstallSnapshotRequest& msg) {
assert(msg.leaderId == myId_);
executor_->execute([=]() {
InstallSnapshotResponse result = getPeer(target)->handleRequest(myId_, msg);
executor_->execute([=]() {
getPeer(myId_)->handleResponse(target, result);
});
});
}
// }}}
} // namespace raft
} // namespace xzero
<commit_msg>[xzero] raft: fixes missing field initialization<commit_after>// This file is part of the "x0" project, http://github.com/christianparpart/x0>
// (c) 2009-2017 Christian Parpart <christian@parpart.family>
//
// Licensed under the MIT License (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of
// the License at: http://opensource.org/licenses/MIT
#include <xzero/raft/Transport.h>
#include <xzero/raft/Handler.h>
#include <xzero/raft/Listener.h>
#include <xzero/raft/Discovery.h>
#include <xzero/raft/Server.h>
#include <xzero/raft/Generator.h>
#include <xzero/raft/Parser.h>
#include <xzero/net/EndPoint.h>
#include <xzero/net/InetEndPoint.h>
#include <xzero/net/InetConnector.h>
#include <xzero/BufferUtil.h>
#include <xzero/logging.h>
namespace xzero {
namespace raft {
Transport::~Transport() {
}
/*
* - the peer that wants to say something, initiates the connection
* - the connection may be reused (pooled) for future messages
* - an incoming connection MAY be reused to send the response, too
*/
// {{{ PeerConnection
class PeerConnection
: public Connection,
public Listener {
public:
PeerConnection(Connector* connector,
EndPoint* endpoint,
Id peerId,
Handler* handler);
// Connection override (connection-endpoint hooks)
void onOpen(bool dataReady) override;
void onFillable() override;
void onFlushable() override;
// Listener overrides (parser hooks)
void receive(Id from, const VoteRequest& message) override;
void receive(Id from, const VoteResponse& message) override;
void receive(Id from, const AppendEntriesRequest& message) override;
void receive(Id from, const AppendEntriesResponse& message) override;
void receive(Id from, const InstallSnapshotResponse& message) override;
void receive(Id from, const InstallSnapshotRequest& message) override;
private:
Buffer inputBuffer_;
Buffer outputBuffer_;
size_t outputOffset_;
Handler* handler_;
Parser parser_;
};
PeerConnection::PeerConnection(Connector* connector,
EndPoint* endpoint,
Id peerId,
Handler* handler)
: Connection(endpoint, connector->executor()),
inputBuffer_(4096),
outputBuffer_(4096),
outputOffset_(0),
handler_(handler),
parser_(peerId, this) {
}
void PeerConnection::onOpen(bool dataReady) {
Connection::onOpen(dataReady);
if (dataReady) {
onFillable();
} else {
wantFill();
}
}
void PeerConnection::onFillable() {
size_t n = endpoint()->fill(&inputBuffer_);
if (n == 0) {
close();
return; // EOF
}
n = parser_.parseFragment(inputBuffer_);
inputBuffer_.clear();
if (n == 0) {
// no message passed => need more input
wantFill();
}
}
void PeerConnection::onFlushable() {
size_t n = endpoint()->flush(outputBuffer_.ref(outputOffset_));
outputOffset_ += n;
if (outputOffset_ == outputBuffer_.size()) {
outputBuffer_.clear();
outputOffset_ = 0;
wantFill();
}
}
void PeerConnection::receive(Id from, const VoteRequest& req) {
VoteResponse res = handler_->handleRequest(from, req);
Generator(BufferUtil::writer(&outputBuffer_)).generateVoteResponse(res);
wantFlush();
}
void PeerConnection::receive(Id from, const VoteResponse& res) {
handler_->handleResponse(from, res);
}
void PeerConnection::receive(Id from, const AppendEntriesRequest& req) {
AppendEntriesResponse res = handler_->handleRequest(from, req);
Generator(BufferUtil::writer(&outputBuffer_)).generateAppendEntriesResponse(res);
wantFlush();
}
void PeerConnection::receive(Id from, const AppendEntriesResponse& res) {
handler_->handleResponse(from, res);
}
void PeerConnection::receive(Id from, const InstallSnapshotRequest& req) {
InstallSnapshotResponse res = handler_->handleRequest(from, req);
Generator(BufferUtil::writer(&outputBuffer_)).generateInstallSnapshotResponse(res);
wantFlush();
}
void PeerConnection::receive(Id from, const InstallSnapshotResponse& res) {
handler_->handleResponse(from, res);
}
// }}}
// {{{ InetTransport
InetTransport::InetTransport(const Discovery* discovery,
Executor* handlerExecutor,
std::shared_ptr<Connector> connector)
: ConnectionFactory("raft"),
discovery_(discovery),
handler_(nullptr),
handlerExecutor_(handlerExecutor),
connector_(connector) {
}
InetTransport::~InetTransport() {
}
void InetTransport::setHandler(Handler* handler) {
handler_ = handler;
}
Connection* InetTransport::create(Connector* connector,
EndPoint* endpoint) {
Id peerId = 4242; // TODO: detect peer ID
return configure(
endpoint->setConnection<PeerConnection>(connector,
endpoint,
peerId,
handler_),
connector);
}
RefPtr<EndPoint> InetTransport::getEndPoint(Id target) {
constexpr Duration connectTimeout = 5_seconds;
constexpr Duration readTimeout = 5_seconds;
constexpr Duration writeTimeout = 5_seconds;
Result<std::string> address = discovery_->getAddress(target);
if (address.isFailure())
return nullptr;
// TODO: make ourself independant from TCP/IP here and also allow other EndPoint's.
// TODO: add endpoint pooling, to reduce resource hogging.
RefPtr<EndPoint> ep = InetEndPoint::connect(
InetAddress(*address),
connectTimeout,
readTimeout,
writeTimeout,
connector_->executor());
return ep;
}
void InetTransport::send(Id target, const VoteRequest& msg) {
if (RefPtr<EndPoint> ep = getEndPoint(target)) {
Buffer buffer;
Generator(BufferUtil::writer(&buffer)).generateVoteRequest(msg);
ep->flush(buffer);
}
}
void InetTransport::send(Id target, const AppendEntriesRequest& msg) {
if (RefPtr<EndPoint> ep = getEndPoint(target)) {
Buffer buffer;
Generator(BufferUtil::writer(&buffer)).generateAppendEntriesRequest(msg);
ep->flush(buffer);
}
}
void InetTransport::send(Id target, const InstallSnapshotRequest& msg) {
if (RefPtr<EndPoint> ep = getEndPoint(target)) {
Buffer buffer;
Generator(BufferUtil::writer(&buffer)).generateInstallSnapshotRequest(msg);
ep->flush(buffer);
}
}
// }}}
// {{{ LocalTransport
LocalTransport::LocalTransport(Id myId, Executor* executor)
: myId_(myId),
myHandler_(nullptr),
executor_(executor),
peers_() {
}
LocalTransport::LocalTransport(LocalTransport&& m)
: myId_(m.myId_),
myHandler_(m.myHandler_),
executor_(m.executor_),
peers_(std::move(m.peers_)) {
}
LocalTransport& LocalTransport::operator=(LocalTransport&& m) {
myId_ = std::move(m.myId_);
myHandler_ = std::move(m.myHandler_);
executor_ = std::move(m.executor_);
peers_ = std::move(m.peers_);
return *this;
}
void LocalTransport::setPeer(Id peerId, Handler* target) {
peers_[peerId] = target;
}
Handler* LocalTransport::getPeer(Id id) {
auto i = peers_.find(id);
if (i != peers_.end()) {
return i->second;
} else {
return nullptr;
}
}
void LocalTransport::setHandler(Handler* handler) {
myHandler_ = handler;
}
void LocalTransport::send(Id target, const VoteRequest& msg) {
assert(msg.candidateId == myId_);
// sends a VoteRequest msg to the given target.
// XXX emulate async/delayed behaviour by deferring receival via executor API.
executor_->execute([=]() {
VoteResponse result = getPeer(target)->handleRequest(myId_, msg);
executor_->execute([=]() {
getPeer(myId_)->handleResponse(target, result);
});
});
//logDebug("raft.LocalTransport", "$0 send to $1: $2", myId_, target, msg);
}
void LocalTransport::send(Id target, const AppendEntriesRequest& msg) {
assert(msg.leaderId == myId_);
executor_->execute([=]() {
logDebug("raft.LocalTransport", "AppendEntriesRequest from $0 to $1: $2", myId_, target, msg);
AppendEntriesResponse result = getPeer(target)->handleRequest(myId_, msg);
executor_->execute([=]() {
getPeer(myId_)->handleResponse(target, result);
});
});
}
void LocalTransport::send(Id target, const InstallSnapshotRequest& msg) {
assert(msg.leaderId == myId_);
executor_->execute([=]() {
InstallSnapshotResponse result = getPeer(target)->handleRequest(myId_, msg);
executor_->execute([=]() {
getPeer(myId_)->handleResponse(target, result);
});
});
}
// }}}
} // namespace raft
} // namespace xzero
<|endoftext|>
|
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "<WebSig>" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 2001, Institute for
* Data Communications Systems, <http://www.nue.et-inf.uni-siegen.de/>.
* The development of this software was partly funded by the European
* Commission in the <WebSig> project in the ISIS Programme.
* For more information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* XSEC
*
* XSECURIResolverGenericWin32 := A URI Resolver that will work "out of
* the box" with Windows. Re-implements
* much Xerces code, but allows us to
* handle HTTP redirects as is required by
* the DSIG Standard
*
* Author(s): Berin Lautenbach
*
* $Id$
*
* $Log$
* Revision 1.1 2003/02/12 09:45:29 blautenb
* Win32 Re-implementation of Xerces URIResolver to support re-directs
*
*
*/
#include "XSECURIResolverGenericWin32.hpp"
#include <xercesc/util/XMLUniDefs.hpp>
#include <xercesc/util/XMLUri.hpp>
#include <xercesc/util/XMLUni.hpp>
#include <xercesc/util/Janitor.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/BinFileInputStream.hpp>
XSEC_USING_XERCES(XMLString);
#include <xsec/framework/XSECError.hpp>
#include <xsec/utils/winutils/XSECBinHTTPURIInputStream.hpp>
static const XMLCh gFileScheme[] = {
XERCES_CPP_NAMESPACE_QUALIFIER chLatin_f,
XERCES_CPP_NAMESPACE_QUALIFIER chLatin_i,
XERCES_CPP_NAMESPACE_QUALIFIER chLatin_l,
XERCES_CPP_NAMESPACE_QUALIFIER chLatin_e,
XERCES_CPP_NAMESPACE_QUALIFIER chNull
};
static const XMLCh gHttpScheme[] = {
XERCES_CPP_NAMESPACE_QUALIFIER chLatin_h,
XERCES_CPP_NAMESPACE_QUALIFIER chLatin_t,
XERCES_CPP_NAMESPACE_QUALIFIER chLatin_t,
XERCES_CPP_NAMESPACE_QUALIFIER chLatin_p,
XERCES_CPP_NAMESPACE_QUALIFIER chNull
};
XSECURIResolverGenericWin32::XSECURIResolverGenericWin32() :
mp_baseURI(NULL) {
};
XSECURIResolverGenericWin32::~XSECURIResolverGenericWin32() {
if (mp_baseURI != NULL)
delete[] mp_baseURI;
}
// -----------------------------------------------------------------------
// Resolve a URI that is passed in
// -----------------------------------------------------------------------
BinInputStream * XSECURIResolverGenericWin32::resolveURI(const XMLCh * uri) {
XSEC_USING_XERCES(BinInputStream);
XSEC_USING_XERCES(XMLUri);
XSEC_USING_XERCES(XMLUni);
XSEC_USING_XERCES(Janitor);
XSEC_USING_XERCES(BinFileInputStream);
XMLUri * xmluri;
// Create the appropriate XMLUri objects
if (mp_baseURI != NULL) {
XMLUri * turi;
XSECnew(turi, XMLUri(mp_baseURI));
Janitor<XMLUri> j_turi(turi);
XSECnew(xmluri, XMLUri(turi, uri));
}
else {
XSECnew(xmluri, XMLUri(uri));
}
Janitor<XMLUri> j_xmluri(xmluri);
// Determine what kind of URI this is and how to handle it.
if (!XMLString::compareIString(xmluri->getScheme(), gFileScheme)) {
// This is a file. We only really understand if this is localhost
// XMLUri has already cleaned of escape characters (%xx)
if (xmluri->getHost() == NULL ||
!XMLString::compareIString(xmluri->getHost(), XMLUni::fgLocalHostString)) {
// Localhost
BinFileInputStream* retStrm = new BinFileInputStream(xmluri->getPath());
if (!retStrm->getIsOpen())
{
delete retStrm;
return 0;
}
return retStrm;
}
else {
throw XSECException(XSECException::ErrorOpeningURI,
"XSECURIResolverGenericWin32 - unable to open non-localhost file");
}
}
// Is the scheme a HTTP?
if (!XMLString::compareIString(xmluri->getScheme(), gHttpScheme)) {
// Pass straight to our local XSECBinHTTPUriInputStream
XSECBinHTTPURIInputStream *ret;
XSECnew(ret, XSECBinHTTPURIInputStream(*xmluri));
return ret;
}
throw XSECException(XSECException::ErrorOpeningURI,
"XSECURIResolverGenericWin32 - unknown URI scheme");
}
// -----------------------------------------------------------------------
// Clone me
// -----------------------------------------------------------------------
XSECURIResolver * XSECURIResolverGenericWin32::clone(void) {
XSECURIResolverGenericWin32 * ret;
ret = new XSECURIResolverGenericWin32();
if (this->mp_baseURI != NULL)
ret->mp_baseURI = XMLString::replicate(this->mp_baseURI);
else
ret->mp_baseURI = NULL;
return ret;
}
<commit_msg>Work around for Xerces XMLUri bug<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "<WebSig>" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 2001, Institute for
* Data Communications Systems, <http://www.nue.et-inf.uni-siegen.de/>.
* The development of this software was partly funded by the European
* Commission in the <WebSig> project in the ISIS Programme.
* For more information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* XSEC
*
* XSECURIResolverGenericWin32 := A URI Resolver that will work "out of
* the box" with Windows. Re-implements
* much Xerces code, but allows us to
* handle HTTP redirects as is required by
* the DSIG Standard
*
* Author(s): Berin Lautenbach
*
* $Id$
*
* $Log$
* Revision 1.2 2003/02/17 11:21:45 blautenb
* Work around for Xerces XMLUri bug
*
* Revision 1.1 2003/02/12 09:45:29 blautenb
* Win32 Re-implementation of Xerces URIResolver to support re-directs
*
*
*/
#include "XSECURIResolverGenericWin32.hpp"
#include <xercesc/util/XMLUniDefs.hpp>
#include <xercesc/util/XMLUri.hpp>
#include <xercesc/util/XMLUni.hpp>
#include <xercesc/util/Janitor.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/BinFileInputStream.hpp>
XSEC_USING_XERCES(XMLString);
XSEC_USING_XERCES(ArrayJanitor);
#include <xsec/framework/XSECError.hpp>
#include <xsec/utils/winutils/XSECBinHTTPURIInputStream.hpp>
static const XMLCh gFileScheme[] = {
XERCES_CPP_NAMESPACE_QUALIFIER chLatin_f,
XERCES_CPP_NAMESPACE_QUALIFIER chLatin_i,
XERCES_CPP_NAMESPACE_QUALIFIER chLatin_l,
XERCES_CPP_NAMESPACE_QUALIFIER chLatin_e,
XERCES_CPP_NAMESPACE_QUALIFIER chNull
};
static const XMLCh gHttpScheme[] = {
XERCES_CPP_NAMESPACE_QUALIFIER chLatin_h,
XERCES_CPP_NAMESPACE_QUALIFIER chLatin_t,
XERCES_CPP_NAMESPACE_QUALIFIER chLatin_t,
XERCES_CPP_NAMESPACE_QUALIFIER chLatin_p,
XERCES_CPP_NAMESPACE_QUALIFIER chNull
};
#if XERCES_VERSION_MAJOR == 2 && XERCES_VERSION_MINOR < 3
static const XMLCh DOTDOT_SLASH[] = {
XERCES_CPP_NAMESPACE_QUALIFIER chPeriod,
XERCES_CPP_NAMESPACE_QUALIFIER chPeriod,
XERCES_CPP_NAMESPACE_QUALIFIER chForwardSlash,
XERCES_CPP_NAMESPACE_QUALIFIER chNull
};
#endif
XSECURIResolverGenericWin32::XSECURIResolverGenericWin32() :
mp_baseURI(NULL) {
};
XSECURIResolverGenericWin32::~XSECURIResolverGenericWin32() {
if (mp_baseURI != NULL)
delete[] mp_baseURI;
}
// -----------------------------------------------------------------------
// Resolve a URI that is passed in
// -----------------------------------------------------------------------
BinInputStream * XSECURIResolverGenericWin32::resolveURI(const XMLCh * uri) {
XSEC_USING_XERCES(BinInputStream);
XSEC_USING_XERCES(XMLUri);
XSEC_USING_XERCES(XMLUni);
XSEC_USING_XERCES(Janitor);
XSEC_USING_XERCES(BinFileInputStream);
XMLUri * xmluri;
// Create the appropriate XMLUri objects
if (mp_baseURI != NULL) {
XMLUri * turi;
#if XERCES_VERSION_MAJOR == 2 && XERCES_VERSION_MINOR < 3
// XMLUri relative paths are broken, so we need to strip out ".."
XMLCh * b = XMLString::replicate(mp_baseURI);
ArrayJanitor<XMLCh> j_b(b);
XMLCh * r = XMLString::replicate(uri);
ArrayJanitor<XMLCh> j_r(r);
int index = 0;
while (XMLString::startsWith(&(r[index]), DOTDOT_SLASH)) {
// Strip the last segment of the base
int lastIndex = XMLString::lastIndexOf(b, XERCES_CPP_NAMESPACE_QUALIFIER chForwardSlash);
if (lastIndex > 0)
b[lastIndex] = 0;
index += 3;
}
XSECnew(turi, XMLUri(b));
Janitor<XMLUri> j_turi(turi);
XSECnew(xmluri, XMLUri(turi, &(r[index])));
#else
XSECnew(turi, XMLUri(mp_baseURI));
Janitor<XMLUri> j_turi(turi);
XSECnew(xmluri, XMLUri(turi, uri));
#endif
}
else {
XSECnew(xmluri, XMLUri(uri));
}
Janitor<XMLUri> j_xmluri(xmluri);
// Determine what kind of URI this is and how to handle it.
if (!XMLString::compareIString(xmluri->getScheme(), gFileScheme)) {
// This is a file. We only really understand if this is localhost
// XMLUri has already cleaned of escape characters (%xx)
if (xmluri->getHost() == NULL ||
!XMLString::compareIString(xmluri->getHost(), XMLUni::fgLocalHostString)) {
// Localhost
BinFileInputStream* retStrm = new BinFileInputStream(xmluri->getPath());
if (!retStrm->getIsOpen())
{
delete retStrm;
return 0;
}
return retStrm;
}
else {
throw XSECException(XSECException::ErrorOpeningURI,
"XSECURIResolverGenericWin32 - unable to open non-localhost file");
}
}
// Is the scheme a HTTP?
if (!XMLString::compareIString(xmluri->getScheme(), gHttpScheme)) {
// Pass straight to our local XSECBinHTTPUriInputStream
XSECBinHTTPURIInputStream *ret;
XSECnew(ret, XSECBinHTTPURIInputStream(*xmluri));
return ret;
}
throw XSECException(XSECException::ErrorOpeningURI,
"XSECURIResolverGenericWin32 - unknown URI scheme");
}
// -----------------------------------------------------------------------
// Clone me
// -----------------------------------------------------------------------
XSECURIResolver * XSECURIResolverGenericWin32::clone(void) {
XSECURIResolverGenericWin32 * ret;
ret = new XSECURIResolverGenericWin32();
if (this->mp_baseURI != NULL)
ret->mp_baseURI = XMLString::replicate(this->mp_baseURI);
else
ret->mp_baseURI = NULL;
return ret;
}
// -----------------------------------------------------------------------
// Set a base URI to map any incoming files against
// -----------------------------------------------------------------------
void XSECURIResolverGenericWin32::setBaseURI(const XMLCh * uri) {
if (mp_baseURI != NULL)
delete[] mp_baseURI;
mp_baseURI = XMLString::replicate(uri);
}<|endoftext|>
|
<commit_before>#ifndef _DESHA1_HPP
#define _DESHA1_HPP
/*-------------------------------------------------------------------------
* drawElements C++ Base Library
* -----------------------------
*
* Copyright 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief SHA1 hash functions
*//*--------------------------------------------------------------------*/
#include "deDefs.hpp"
#include "deSha1.h"
#include <string>
#include <vector>
namespace de
{
class Sha1
{
public:
Sha1 (const deSha1& hash) : m_hash(hash) {}
static Sha1 parse (const std::string& str);
static Sha1 compute (size_t size, const void* data);
bool operator== (const Sha1& other) const { return deSha1_equal(&m_hash, &other.m_hash); }
bool operator!= (const Sha1& other) const { return !(*this == other); }
private:
deSha1 m_hash;
};
class Sha1Stream
{
public:
Sha1Stream (void);
void process (size_t size, const void* data);
Sha1 finalize (void);
private:
deSha1Stream m_stream;
};
// Utility functions for building hash from values.
// \note This is not same as serializing the values and computing hash from the data.
// Some extra care is required when dealing with types that have platform
// specific size.
// All vectors and strings will include their size in the hash. Following codes
// produce different results:
// stream << "Hi" << "Hello";
// and
// stream << "HiHello";
inline Sha1Stream& operator<< (Sha1Stream& stream, bool b)
{
const deUint8 value = b ? 1 : 0;
stream.process(sizeof(value), &value);
return stream;
}
inline Sha1Stream& operator<< (Sha1Stream& stream, deUint32 value)
{
const deUint8 data[] =
{
(deUint8)(0xFFu & (value >> 24)),
(deUint8)(0xFFu & (value >> 16)),
(deUint8)(0xFFu & (value >> 8)),
(deUint8)(0xFFu & (value >> 0))
};
stream.process(sizeof(data), data);
return stream;
}
inline Sha1Stream& operator<< (Sha1Stream& stream, deInt32 value)
{
return stream << (deUint32)value;
}
inline Sha1Stream& operator<< (Sha1Stream& stream, deUint64 value)
{
const deUint8 data[] =
{
(deUint8)(0xFFull & (value >> 56)),
(deUint8)(0xFFull & (value >> 48)),
(deUint8)(0xFFull & (value >> 40)),
(deUint8)(0xFFull & (value >> 32)),
(deUint8)(0xFFull & (value >> 24)),
(deUint8)(0xFFull & (value >> 16)),
(deUint8)(0xFFull & (value >> 8)),
(deUint8)(0xFFull & (value >> 0))
};
stream.process(sizeof(data), data);
return stream;
}
inline Sha1Stream& operator<< (Sha1Stream& stream, deInt64 value)
{
return stream << (deUint64)value;
}
template<typename T>
inline Sha1Stream& operator<< (Sha1Stream& stream, const std::vector<T>& values)
{
stream << (deUint64)values.size();
for (size_t ndx = 0; ndx < values.size(); ndx++)
stream << values[ndx];
return stream;
}
inline Sha1Stream& operator<< (Sha1Stream& stream, const std::string& str)
{
stream << (deUint64)str.size();
stream.process(str.size(), str.c_str());
return stream;
}
} // de
#endif // _DESHA1_HPP
<commit_msg>Fix warning am: 7b87c35373<commit_after>#ifndef _DESHA1_HPP
#define _DESHA1_HPP
/*-------------------------------------------------------------------------
* drawElements C++ Base Library
* -----------------------------
*
* Copyright 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief SHA1 hash functions
*//*--------------------------------------------------------------------*/
#include "deDefs.hpp"
#include "deSha1.h"
#include <string>
#include <vector>
namespace de
{
class Sha1
{
public:
Sha1 (const deSha1& hash) : m_hash(hash) {}
static Sha1 parse (const std::string& str);
static Sha1 compute (size_t size, const void* data);
bool operator== (const Sha1& other) const { return deSha1_equal(&m_hash, &other.m_hash) == DE_TRUE; }
bool operator!= (const Sha1& other) const { return !(*this == other); }
private:
deSha1 m_hash;
};
class Sha1Stream
{
public:
Sha1Stream (void);
void process (size_t size, const void* data);
Sha1 finalize (void);
private:
deSha1Stream m_stream;
};
// Utility functions for building hash from values.
// \note This is not same as serializing the values and computing hash from the data.
// Some extra care is required when dealing with types that have platform
// specific size.
// All vectors and strings will include their size in the hash. Following codes
// produce different results:
// stream << "Hi" << "Hello";
// and
// stream << "HiHello";
inline Sha1Stream& operator<< (Sha1Stream& stream, bool b)
{
const deUint8 value = b ? 1 : 0;
stream.process(sizeof(value), &value);
return stream;
}
inline Sha1Stream& operator<< (Sha1Stream& stream, deUint32 value)
{
const deUint8 data[] =
{
(deUint8)(0xFFu & (value >> 24)),
(deUint8)(0xFFu & (value >> 16)),
(deUint8)(0xFFu & (value >> 8)),
(deUint8)(0xFFu & (value >> 0))
};
stream.process(sizeof(data), data);
return stream;
}
inline Sha1Stream& operator<< (Sha1Stream& stream, deInt32 value)
{
return stream << (deUint32)value;
}
inline Sha1Stream& operator<< (Sha1Stream& stream, deUint64 value)
{
const deUint8 data[] =
{
(deUint8)(0xFFull & (value >> 56)),
(deUint8)(0xFFull & (value >> 48)),
(deUint8)(0xFFull & (value >> 40)),
(deUint8)(0xFFull & (value >> 32)),
(deUint8)(0xFFull & (value >> 24)),
(deUint8)(0xFFull & (value >> 16)),
(deUint8)(0xFFull & (value >> 8)),
(deUint8)(0xFFull & (value >> 0))
};
stream.process(sizeof(data), data);
return stream;
}
inline Sha1Stream& operator<< (Sha1Stream& stream, deInt64 value)
{
return stream << (deUint64)value;
}
template<typename T>
inline Sha1Stream& operator<< (Sha1Stream& stream, const std::vector<T>& values)
{
stream << (deUint64)values.size();
for (size_t ndx = 0; ndx < values.size(); ndx++)
stream << values[ndx];
return stream;
}
inline Sha1Stream& operator<< (Sha1Stream& stream, const std::string& str)
{
stream << (deUint64)str.size();
stream.process(str.size(), str.c_str());
return stream;
}
} // de
#endif // _DESHA1_HPP
<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include "../NModule.h"
#include "../../base/NString.h"
#include "../../Util/NFileUtil.h"
namespace nui
{
namespace Data
{
NModule NModule::instance_;
NModule::NModule()
{
nuiModule_ = ::GetModuleHandle(NULL);
bigIcon_ = NULL;
smallIcon_ = NULL;
}
NModule::~NModule()
{
nuiModule_ = NULL;
}
NModule& NModule::GetInst()
{
return instance_;
}
bool NModule::Init(HMODULE nuiModule)
{
nuiModule_ = nuiModule;
TCHAR tempPath[1024];
::GetModuleFileName(NULL, tempPath, 1024);
appFullName_ = tempPath;
appPath_ = Util::File::GetParentFolder(tempPath);
return true;
}
bool NModule::IsValid() const
{
return (nuiModule_ != NULL);
}
HICON NModule::GetBigIcon()
{
if(bigIcon_ != NULL)
return bigIcon_;
::ExtractIconEx(appFullName_, 0, &bigIcon_, &smallIcon_, 1);
return bigIcon_;
}
HICON NModule::GetSmallIcon()
{
if(smallIcon_ != NULL)
return smallIcon_;
::ExtractIconEx(GetAppPath(), 0, &bigIcon_, &smallIcon_, 1);
return smallIcon_;
}
HMODULE NModule::GetNUIModule() const
{
return nuiModule_;
}
Base::NString NModule::GetAppPath() const
{
return appPath_;
}
Base::NString NModule::GetAppFullName() const
{
return appFullName_;
}
}
};
<commit_msg>never set nuiModule_ to NULL<commit_after>#include "stdafx.h"
#include "../NModule.h"
#include "../../base/NString.h"
#include "../../Util/NFileUtil.h"
namespace nui
{
namespace Data
{
NModule NModule::instance_;
NModule::NModule()
{
nuiModule_ = ::GetModuleHandle(NULL);
bigIcon_ = NULL;
smallIcon_ = NULL;
}
NModule::~NModule()
{
nuiModule_ = NULL;
}
NModule& NModule::GetInst()
{
return instance_;
}
bool NModule::Init(HMODULE nuiModule)
{
if(nuiModule != NULL)
nuiModule_ = nuiModule;
TCHAR tempPath[1024];
::GetModuleFileName(NULL, tempPath, 1024);
appFullName_ = tempPath;
appPath_ = Util::File::GetParentFolder(tempPath);
return true;
}
bool NModule::IsValid() const
{
return (nuiModule_ != NULL);
}
HICON NModule::GetBigIcon()
{
if(bigIcon_ != NULL)
return bigIcon_;
::ExtractIconEx(appFullName_, 0, &bigIcon_, &smallIcon_, 1);
return bigIcon_;
}
HICON NModule::GetSmallIcon()
{
if(smallIcon_ != NULL)
return smallIcon_;
::ExtractIconEx(GetAppPath(), 0, &bigIcon_, &smallIcon_, 1);
return smallIcon_;
}
HMODULE NModule::GetNUIModule() const
{
return nuiModule_;
}
Base::NString NModule::GetAppPath() const
{
return appPath_;
}
Base::NString NModule::GetAppFullName() const
{
return appFullName_;
}
}
};
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: iras.cxx,v $
* $Revision: 1.9 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_goodies.hxx"
#include <vcl/graph.hxx>
#include <vcl/bmpacc.hxx>
#include <svtools/fltcall.hxx>
#define RAS_TYPE_OLD 0x00000000 // supported formats by this filter
#define RAS_TYPE_STANDARD 0x00000001
#define RAS_TYPE_BYTE_ENCODED 0x00000002
#define RAS_TYPE_RGB_FORMAT 0x00000003
#define RAS_COLOR_NO_MAP 0x00000000
#define RAS_COLOR_RGB_MAP 0x00000001
#define RAS_COLOR_RAW_MAP 0x00000002
#define SUNRASTER_MAGICNUMBER 0x59a66a95
//============================ RASReader ==================================
class RASReader {
private:
SvStream* mpRAS; // Die einzulesende RAS-Datei
BOOL mbStatus;
Bitmap maBmp;
BitmapWriteAccess* mpAcc;
sal_uInt32 mnWidth, mnHeight; // Bildausmass in Pixeln
USHORT mnDstBitsPerPix;
USHORT mnDstColors;
sal_uInt32 mnDepth, mnImageDatSize, mnType;
sal_uInt32 mnColorMapType, mnColorMapSize;
BYTE mnRepCount, mnRepVal; // RLE Decoding
BOOL mbPalette;
BOOL ImplCallback( USHORT nPercent );
BOOL ImplReadBody();
BOOL ImplReadHeader();
BYTE ImplGetByte();
public:
RASReader();
~RASReader();
BOOL ReadRAS( SvStream & rRAS, Graphic & rGraphic );
};
//=================== Methoden von RASReader ==============================
RASReader::RASReader() :
mbStatus ( TRUE ),
mpAcc ( NULL ),
mnRepCount ( 0 ),
mbPalette ( FALSE )
{
}
RASReader::~RASReader()
{
}
//----------------------------------------------------------------------------
BOOL RASReader::ImplCallback( USHORT /*nPercent*/ )
{
/*
if ( pCallback != NULL )
{
if ( ( (*pCallback)( pCallerData, nPercent ) ) == TRUE )
{
mpRAS->SetError( SVSTREAM_FILEFORMAT_ERROR );
return TRUE;
}
}
*/
return FALSE;
}
//----------------------------------------------------------------------------
BOOL RASReader::ReadRAS( SvStream & rRAS, Graphic & rGraphic )
{
UINT32 nMagicNumber;
if ( rRAS.GetError() )
return FALSE;
mpRAS = &rRAS;
mpRAS->SetNumberFormatInt( NUMBERFORMAT_INT_BIGENDIAN );
*mpRAS >> nMagicNumber;
if ( nMagicNumber != SUNRASTER_MAGICNUMBER )
return FALSE;
// Kopf einlesen:
if ( ( mbStatus = ImplReadHeader() ) == FALSE )
return FALSE;
maBmp = Bitmap( Size( mnWidth, mnHeight ), mnDstBitsPerPix );
if ( ( mpAcc = maBmp.AcquireWriteAccess() ) == FALSE )
return FALSE;
if ( mnDstBitsPerPix <= 8 ) // paletten bildchen
{
if ( mnColorMapType == RAS_COLOR_RAW_MAP ) // RAW Colormap wird geskipped
{
ULONG nCurPos = mpRAS->Tell();
mpRAS->Seek( nCurPos + mnColorMapSize );
}
else if ( mnColorMapType == RAS_COLOR_RGB_MAP ) // RGB koennen wir auslesen
{
mnDstColors = (USHORT)( mnColorMapSize / 3 );
if ( ( 1 << mnDstBitsPerPix ) < mnDstColors )
return FALSE;
if ( ( mnDstColors >= 2 ) && ( ( mnColorMapSize % 3 ) == 0 ) )
{
mpAcc->SetPaletteEntryCount( mnDstColors );
USHORT i;
BYTE nRed[256], nGreen[256], nBlue[256];
for ( i = 0; i < mnDstColors; i++ ) *mpRAS >> nRed[ i ];
for ( i = 0; i < mnDstColors; i++ ) *mpRAS >> nGreen[ i ];
for ( i = 0; i < mnDstColors; i++ ) *mpRAS >> nBlue[ i ];
for ( i = 0; i < mnDstColors; i++ )
{
mpAcc->SetPaletteColor( i, BitmapColor( nRed[ i ], nGreen[ i ], nBlue[ i ] ) );
}
mbPalette = TRUE;
}
else
return FALSE;
}
else if ( mnColorMapType != RAS_COLOR_NO_MAP ) // alles andere ist kein standard
return FALSE;
if ( !mbPalette )
{
mnDstColors = 1 << mnDstBitsPerPix;
mpAcc->SetPaletteEntryCount( mnDstColors );
for ( USHORT i = 0; i < mnDstColors; i++ )
{
ULONG nCount = 255 - ( 255 * i / ( mnDstColors - 1 ) );
mpAcc->SetPaletteColor( i, BitmapColor( (BYTE)nCount, (BYTE)nCount, (BYTE)nCount ) );
}
}
}
else
{
if ( mnColorMapType != RAS_COLOR_NO_MAP ) // when graphic has more then 256 colors and a color map we skip
{ // the colormap
ULONG nCurPos = mpRAS->Tell();
mpRAS->Seek( nCurPos + mnColorMapSize );
}
}
// Bitmap-Daten einlesen
mbStatus = ImplReadBody();
if ( mpAcc )
{
maBmp.ReleaseAccess( mpAcc ), mpAcc = NULL;
}
if ( mbStatus )
rGraphic = maBmp;
return mbStatus;
}
//----------------------------------------------------------------------------
BOOL RASReader::ImplReadHeader()
{
*mpRAS >> mnWidth >> mnHeight >> mnDepth >> mnImageDatSize >>
mnType >> mnColorMapType >> mnColorMapSize;
if ( mnWidth == 0 || mnHeight == 0 )
mbStatus = FALSE;
switch ( mnDepth )
{
case 24 :
case 8 :
case 1 :
mnDstBitsPerPix = (USHORT)mnDepth;
break;
case 32 :
mnDstBitsPerPix = 24;
break;
default :
mbStatus = FALSE;
}
switch ( mnType )
{
case RAS_TYPE_OLD :
case RAS_TYPE_STANDARD :
case RAS_TYPE_RGB_FORMAT :
case RAS_TYPE_BYTE_ENCODED : // this type will be supported later
break;
default:
mbStatus = FALSE;
}
return mbStatus;
}
//----------------------------------------------------------------------------
BOOL RASReader::ImplReadBody()
{
ULONG x, y;
BYTE nDat = 0;
BYTE nRed, nGreen, nBlue;
switch ( mnDstBitsPerPix )
{
case 1 :
for ( y = 0; y < mnHeight; y++ )
{
for ( x = 0; x < mnWidth; x++ )
{
if (!(x & 7))
nDat = ImplGetByte();
mpAcc->SetPixel (
y, x,
sal::static_int_cast< BYTE >(
nDat >> ( ( x & 7 ) ^ 7 )) );
}
if (!( ( x - 1 ) & 0x8 ) ) ImplGetByte(); // WORD ALIGNMENT ???
}
break;
case 8 :
for ( y = 0; y < mnHeight; y++ )
{
for ( x = 0; x < mnWidth; x++ )
{
nDat = ImplGetByte();
mpAcc->SetPixel ( y, x, nDat );
}
if ( x & 1 ) ImplGetByte(); // WORD ALIGNMENT ???
}
break;
case 24 :
switch ( mnDepth )
{
case 24 :
for ( y = 0; y < mnHeight; y++ )
{
for ( x = 0; x < mnWidth; x++ )
{
if ( mnType == RAS_TYPE_RGB_FORMAT )
{
nRed = ImplGetByte();
nGreen = ImplGetByte();
nBlue = ImplGetByte();
}
else
{
nBlue = ImplGetByte();
nGreen = ImplGetByte();
nRed = ImplGetByte();
}
mpAcc->SetPixel ( y, x, BitmapColor( nRed, nGreen, nBlue ) );
}
if ( x & 1 ) ImplGetByte(); // WORD ALIGNMENT ???
}
break;
case 32 :
for ( y = 0; y < mnHeight; y++ )
{
for ( x = 0; x < mnWidth; x++ )
{
nDat = ImplGetByte(); // pad byte > nil
if ( mnType == RAS_TYPE_RGB_FORMAT )
{
nRed = ImplGetByte();
nGreen = ImplGetByte();
nBlue = ImplGetByte();
}
else
{
nBlue = ImplGetByte();
nGreen = ImplGetByte();
nRed = ImplGetByte();
}
mpAcc->SetPixel ( y, x, BitmapColor( nRed, nGreen, nBlue ) );
}
}
break;
}
break;
default:
mbStatus = FALSE;
break;
}
return mbStatus;
}
//----------------------------------------------------------------------------
BYTE RASReader::ImplGetByte()
{
BYTE nRetVal;
if ( mnType != RAS_TYPE_BYTE_ENCODED )
{
*mpRAS >> nRetVal;
return nRetVal;
}
else
{
if ( mnRepCount )
{
mnRepCount--;
return mnRepVal;
}
else
{
*mpRAS >> nRetVal;
if ( nRetVal != 0x80 )
return nRetVal;
*mpRAS >> nRetVal;
if ( nRetVal == 0 )
return 0x80;
mnRepCount = nRetVal ;
*mpRAS >> mnRepVal;
return mnRepVal;
}
}
}
//================== GraphicImport - die exportierte Funktion ================
extern "C" BOOL __LOADONCALLAPI GraphicImport(SvStream & rStream, Graphic & rGraphic, FilterConfigItem*, BOOL )
{
RASReader aRASReader;
return aRASReader.ReadRAS( rStream, rGraphic );
}
//================== ein bischen Muell fuer Windows ==========================
#ifndef GCC
#endif
#ifdef WIN
static HINSTANCE hDLLInst = 0; // HANDLE der DLL
extern "C" int CALLBACK LibMain( HINSTANCE hDLL, WORD, WORD nHeap, LPSTR )
{
#ifndef WNT
if ( nHeap )
UnlockData( 0 );
#endif
hDLLInst = hDLL;
return TRUE;
}
extern "C" int CALLBACK WEP( int )
{
return 1;
}
#endif
<commit_msg>INTEGRATION: CWS impress143 (1.9.18); FILE MERGED 2008/05/26 12:12:24 sj 1.9.18.1: #i89579# applied patch from cmc (removed unused code)<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: iras.cxx,v $
* $Revision: 1.10 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_goodies.hxx"
#include <vcl/graph.hxx>
#include <vcl/bmpacc.hxx>
#include <svtools/fltcall.hxx>
#define RAS_TYPE_OLD 0x00000000 // supported formats by this filter
#define RAS_TYPE_STANDARD 0x00000001
#define RAS_TYPE_BYTE_ENCODED 0x00000002
#define RAS_TYPE_RGB_FORMAT 0x00000003
#define RAS_COLOR_NO_MAP 0x00000000
#define RAS_COLOR_RGB_MAP 0x00000001
#define RAS_COLOR_RAW_MAP 0x00000002
#define SUNRASTER_MAGICNUMBER 0x59a66a95
//============================ RASReader ==================================
class RASReader {
private:
SvStream* mpRAS; // Die einzulesende RAS-Datei
BOOL mbStatus;
Bitmap maBmp;
BitmapWriteAccess* mpAcc;
sal_uInt32 mnWidth, mnHeight; // Bildausmass in Pixeln
USHORT mnDstBitsPerPix;
USHORT mnDstColors;
sal_uInt32 mnDepth, mnImageDatSize, mnType;
sal_uInt32 mnColorMapType, mnColorMapSize;
BYTE mnRepCount, mnRepVal; // RLE Decoding
BOOL mbPalette;
BOOL ImplReadBody();
BOOL ImplReadHeader();
BYTE ImplGetByte();
public:
RASReader();
~RASReader();
BOOL ReadRAS( SvStream & rRAS, Graphic & rGraphic );
};
//=================== Methoden von RASReader ==============================
RASReader::RASReader() :
mbStatus ( TRUE ),
mpAcc ( NULL ),
mnRepCount ( 0 ),
mbPalette ( FALSE )
{
}
RASReader::~RASReader()
{
}
//----------------------------------------------------------------------------
BOOL RASReader::ReadRAS( SvStream & rRAS, Graphic & rGraphic )
{
UINT32 nMagicNumber;
if ( rRAS.GetError() )
return FALSE;
mpRAS = &rRAS;
mpRAS->SetNumberFormatInt( NUMBERFORMAT_INT_BIGENDIAN );
*mpRAS >> nMagicNumber;
if ( nMagicNumber != SUNRASTER_MAGICNUMBER )
return FALSE;
// Kopf einlesen:
if ( ( mbStatus = ImplReadHeader() ) == FALSE )
return FALSE;
maBmp = Bitmap( Size( mnWidth, mnHeight ), mnDstBitsPerPix );
if ( ( mpAcc = maBmp.AcquireWriteAccess() ) == FALSE )
return FALSE;
if ( mnDstBitsPerPix <= 8 ) // paletten bildchen
{
if ( mnColorMapType == RAS_COLOR_RAW_MAP ) // RAW Colormap wird geskipped
{
ULONG nCurPos = mpRAS->Tell();
mpRAS->Seek( nCurPos + mnColorMapSize );
}
else if ( mnColorMapType == RAS_COLOR_RGB_MAP ) // RGB koennen wir auslesen
{
mnDstColors = (USHORT)( mnColorMapSize / 3 );
if ( ( 1 << mnDstBitsPerPix ) < mnDstColors )
return FALSE;
if ( ( mnDstColors >= 2 ) && ( ( mnColorMapSize % 3 ) == 0 ) )
{
mpAcc->SetPaletteEntryCount( mnDstColors );
USHORT i;
BYTE nRed[256], nGreen[256], nBlue[256];
for ( i = 0; i < mnDstColors; i++ ) *mpRAS >> nRed[ i ];
for ( i = 0; i < mnDstColors; i++ ) *mpRAS >> nGreen[ i ];
for ( i = 0; i < mnDstColors; i++ ) *mpRAS >> nBlue[ i ];
for ( i = 0; i < mnDstColors; i++ )
{
mpAcc->SetPaletteColor( i, BitmapColor( nRed[ i ], nGreen[ i ], nBlue[ i ] ) );
}
mbPalette = TRUE;
}
else
return FALSE;
}
else if ( mnColorMapType != RAS_COLOR_NO_MAP ) // alles andere ist kein standard
return FALSE;
if ( !mbPalette )
{
mnDstColors = 1 << mnDstBitsPerPix;
mpAcc->SetPaletteEntryCount( mnDstColors );
for ( USHORT i = 0; i < mnDstColors; i++ )
{
ULONG nCount = 255 - ( 255 * i / ( mnDstColors - 1 ) );
mpAcc->SetPaletteColor( i, BitmapColor( (BYTE)nCount, (BYTE)nCount, (BYTE)nCount ) );
}
}
}
else
{
if ( mnColorMapType != RAS_COLOR_NO_MAP ) // when graphic has more then 256 colors and a color map we skip
{ // the colormap
ULONG nCurPos = mpRAS->Tell();
mpRAS->Seek( nCurPos + mnColorMapSize );
}
}
// Bitmap-Daten einlesen
mbStatus = ImplReadBody();
if ( mpAcc )
{
maBmp.ReleaseAccess( mpAcc ), mpAcc = NULL;
}
if ( mbStatus )
rGraphic = maBmp;
return mbStatus;
}
//----------------------------------------------------------------------------
BOOL RASReader::ImplReadHeader()
{
*mpRAS >> mnWidth >> mnHeight >> mnDepth >> mnImageDatSize >>
mnType >> mnColorMapType >> mnColorMapSize;
if ( mnWidth == 0 || mnHeight == 0 )
mbStatus = FALSE;
switch ( mnDepth )
{
case 24 :
case 8 :
case 1 :
mnDstBitsPerPix = (USHORT)mnDepth;
break;
case 32 :
mnDstBitsPerPix = 24;
break;
default :
mbStatus = FALSE;
}
switch ( mnType )
{
case RAS_TYPE_OLD :
case RAS_TYPE_STANDARD :
case RAS_TYPE_RGB_FORMAT :
case RAS_TYPE_BYTE_ENCODED : // this type will be supported later
break;
default:
mbStatus = FALSE;
}
return mbStatus;
}
//----------------------------------------------------------------------------
BOOL RASReader::ImplReadBody()
{
ULONG x, y;
BYTE nDat = 0;
BYTE nRed, nGreen, nBlue;
switch ( mnDstBitsPerPix )
{
case 1 :
for ( y = 0; y < mnHeight; y++ )
{
for ( x = 0; x < mnWidth; x++ )
{
if (!(x & 7))
nDat = ImplGetByte();
mpAcc->SetPixel (
y, x,
sal::static_int_cast< BYTE >(
nDat >> ( ( x & 7 ) ^ 7 )) );
}
if (!( ( x - 1 ) & 0x8 ) ) ImplGetByte(); // WORD ALIGNMENT ???
}
break;
case 8 :
for ( y = 0; y < mnHeight; y++ )
{
for ( x = 0; x < mnWidth; x++ )
{
nDat = ImplGetByte();
mpAcc->SetPixel ( y, x, nDat );
}
if ( x & 1 ) ImplGetByte(); // WORD ALIGNMENT ???
}
break;
case 24 :
switch ( mnDepth )
{
case 24 :
for ( y = 0; y < mnHeight; y++ )
{
for ( x = 0; x < mnWidth; x++ )
{
if ( mnType == RAS_TYPE_RGB_FORMAT )
{
nRed = ImplGetByte();
nGreen = ImplGetByte();
nBlue = ImplGetByte();
}
else
{
nBlue = ImplGetByte();
nGreen = ImplGetByte();
nRed = ImplGetByte();
}
mpAcc->SetPixel ( y, x, BitmapColor( nRed, nGreen, nBlue ) );
}
if ( x & 1 ) ImplGetByte(); // WORD ALIGNMENT ???
}
break;
case 32 :
for ( y = 0; y < mnHeight; y++ )
{
for ( x = 0; x < mnWidth; x++ )
{
nDat = ImplGetByte(); // pad byte > nil
if ( mnType == RAS_TYPE_RGB_FORMAT )
{
nRed = ImplGetByte();
nGreen = ImplGetByte();
nBlue = ImplGetByte();
}
else
{
nBlue = ImplGetByte();
nGreen = ImplGetByte();
nRed = ImplGetByte();
}
mpAcc->SetPixel ( y, x, BitmapColor( nRed, nGreen, nBlue ) );
}
}
break;
}
break;
default:
mbStatus = FALSE;
break;
}
return mbStatus;
}
//----------------------------------------------------------------------------
BYTE RASReader::ImplGetByte()
{
BYTE nRetVal;
if ( mnType != RAS_TYPE_BYTE_ENCODED )
{
*mpRAS >> nRetVal;
return nRetVal;
}
else
{
if ( mnRepCount )
{
mnRepCount--;
return mnRepVal;
}
else
{
*mpRAS >> nRetVal;
if ( nRetVal != 0x80 )
return nRetVal;
*mpRAS >> nRetVal;
if ( nRetVal == 0 )
return 0x80;
mnRepCount = nRetVal ;
*mpRAS >> mnRepVal;
return mnRepVal;
}
}
}
//================== GraphicImport - die exportierte Funktion ================
extern "C" BOOL __LOADONCALLAPI GraphicImport(SvStream & rStream, Graphic & rGraphic, FilterConfigItem*, BOOL )
{
RASReader aRASReader;
return aRASReader.ReadRAS( rStream, rGraphic );
}
//================== ein bischen Muell fuer Windows ==========================
#ifndef GCC
#endif
#ifdef WIN
static HINSTANCE hDLLInst = 0; // HANDLE der DLL
extern "C" int CALLBACK LibMain( HINSTANCE hDLL, WORD, WORD nHeap, LPSTR )
{
#ifndef WNT
if ( nHeap )
UnlockData( 0 );
#endif
hDLLInst = hDLL;
return TRUE;
}
extern "C" int CALLBACK WEP( int )
{
return 1;
}
#endif
<|endoftext|>
|
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log$
* Revision 1.3 2004/08/19 21:24:12 peiyongz
* Jira[1255], patch from Neil Sharman
*
* Revision 1.2 2003/11/17 16:18:01 peiyongz
* Fix to #4556
*
* Revision 1.1.1.1 2002/02/01 22:22:25 peiyongz
* sane_include
*
* Revision 1.4 2000/03/02 19:55:30 roddey
* This checkin includes many changes done while waiting for the
* 1.1.0 code to be finished. I can't list them all here, but a list is
* available elsewhere.
*
* Revision 1.3 2000/02/17 03:36:54 rahulj
* Fixed a cut-paste typo in the comments.
*
* Revision 1.2 2000/02/06 07:48:30 rahulj
* Year 2K copyright swat.
*
* Revision 1.1.1.1 1999/11/09 01:06:30 twl
* Initial checkin
*
* Revision 1.2 1999/11/08 20:45:32 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
// ---------------------------------------------------------------------------
// Detect endian mode
// ---------------------------------------------------------------------------
#include <sys/isa_defs.h>
#ifdef _LITTLE_ENDIAN
#define ENDIANMODE_LITTLE
#elif defined(_BIG_ENDIAN)
#define ENDIANMODE_BIG
#else
#error : unknown byte order!
#endif
#ifndef SOLARIS
#define SOLARIS
#endif
<commit_msg>The missing FileHandle<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log$
* Revision 1.4 2004/08/23 16:05:49 peiyongz
* The missing FileHandle
*
* Revision 1.3 2004/08/19 21:24:12 peiyongz
* Jira[1255], patch from Neil Sharman
*
* Revision 1.2 2003/11/17 16:18:01 peiyongz
* Fix to #4556
*
* Revision 1.1.1.1 2002/02/01 22:22:25 peiyongz
* sane_include
*
* Revision 1.4 2000/03/02 19:55:30 roddey
* This checkin includes many changes done while waiting for the
* 1.1.0 code to be finished. I can't list them all here, but a list is
* available elsewhere.
*
* Revision 1.3 2000/02/17 03:36:54 rahulj
* Fixed a cut-paste typo in the comments.
*
* Revision 1.2 2000/02/06 07:48:30 rahulj
* Year 2K copyright swat.
*
* Revision 1.1.1.1 1999/11/09 01:06:30 twl
* Initial checkin
*
* Revision 1.2 1999/11/08 20:45:32 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
// ---------------------------------------------------------------------------
// Detect endian mode
// ---------------------------------------------------------------------------
#include <sys/isa_defs.h>
#ifdef _LITTLE_ENDIAN
#define ENDIANMODE_LITTLE
#elif defined(_BIG_ENDIAN)
#define ENDIANMODE_BIG
#else
#error : unknown byte order!
#endif
typedef int FileHandle;
#ifndef SOLARIS
#define SOLARIS
#endif
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "webkit/tools/test_shell/test_shell_webkit_init.h"
#include "base/path_service.h"
#include "base/stats_counters.h"
#include "media/base/media.h"
#include "third_party/WebKit/WebKit/chromium/public/WebDatabase.h"
#include "third_party/WebKit/WebKit/chromium/public/WebKit.h"
#include "third_party/WebKit/WebKit/chromium/public/WebRuntimeFeatures.h"
#include "third_party/WebKit/WebKit/chromium/public/WebScriptController.h"
#include "third_party/WebKit/WebKit/chromium/public/WebSecurityPolicy.h"
#include "webkit/extensions/v8/gears_extension.h"
#include "webkit/extensions/v8/interval_extension.h"
#include "webkit/tools/test_shell/test_shell.h"
#if defined(OS_WIN)
#include "webkit/tools/test_shell/test_shell_webthemeengine.h"
#endif
TestShellWebKitInit::TestShellWebKitInit(bool layout_test_mode) {
v8::V8::SetCounterFunction(StatsTable::FindLocation);
WebKit::initialize(this);
WebKit::setLayoutTestMode(layout_test_mode);
WebKit::WebSecurityPolicy::registerURLSchemeAsLocal(
WebKit::WebString::fromUTF8("test-shell-resource"));
WebKit::WebSecurityPolicy::registerURLSchemeAsNoAccess(
WebKit::WebString::fromUTF8("test-shell-resource"));
WebKit::WebScriptController::enableV8SingleThreadMode();
WebKit::WebScriptController::registerExtension(
extensions_v8::GearsExtension::Get());
WebKit::WebScriptController::registerExtension(
extensions_v8::IntervalExtension::Get());
WebKit::WebRuntimeFeatures::enableSockets(true);
WebKit::WebRuntimeFeatures::enableApplicationCache(true);
WebKit::WebRuntimeFeatures::enableDatabase(true);
WebKit::WebRuntimeFeatures::enableWebGL(true);
WebKit::WebRuntimeFeatures::enablePushState(true);
WebKit::WebRuntimeFeatures::enableNotifications(true);
WebKit::WebRuntimeFeatures::enableTouch(true);
WebKit::WebRuntimeFeatures::enableIndexedDatabase(true);
// Load libraries for media and enable the media player.
FilePath module_path;
WebKit::WebRuntimeFeatures::enableMediaPlayer(
PathService::Get(base::DIR_MODULE, &module_path) &&
media::InitializeMediaLibrary(module_path));
WebKit::WebRuntimeFeatures::enableGeolocation(true);
// Construct and initialize an appcache system for this scope.
// A new empty temp directory is created to house any cached
// content during the run. Upon exit that directory is deleted.
// If we can't create a tempdir, we'll use in-memory storage.
if (!appcache_dir_.CreateUniqueTempDir()) {
LOG(WARNING) << "Failed to create a temp dir for the appcache, "
"using in-memory storage.";
DCHECK(appcache_dir_.path().empty());
}
SimpleAppCacheSystem::InitializeOnUIThread(appcache_dir_.path());
WebKit::WebDatabase::setObserver(&database_system_);
file_system_.set_sandbox_enabled(false);
#if defined(OS_WIN)
// Ensure we pick up the default theme engine.
SetThemeEngine(NULL);
#endif
}
TestShellWebKitInit::~TestShellWebKitInit() {
WebKit::shutdown();
}
WebKit::WebClipboard* TestShellWebKitInit::clipboard() {
// Mock out clipboard calls in layout test mode so that tests don't mess
// with each other's copies/pastes when running in parallel.
if (TestShell::layout_test_mode()) {
return &mock_clipboard_;
} else {
return &real_clipboard_;
}
}
WebKit::WebData TestShellWebKitInit::loadResource(const char* name) {
if (!strcmp(name, "deleteButton")) {
// Create a red 30x30 square.
const char red_square[] =
"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52"
"\x00\x00\x00\x1e\x00\x00\x00\x1e\x04\x03\x00\x00\x00\xc9\x1e\xb3"
"\x91\x00\x00\x00\x30\x50\x4c\x54\x45\x00\x00\x00\x80\x00\x00\x00"
"\x80\x00\x80\x80\x00\x00\x00\x80\x80\x00\x80\x00\x80\x80\x80\x80"
"\x80\xc0\xc0\xc0\xff\x00\x00\x00\xff\x00\xff\xff\x00\x00\x00\xff"
"\xff\x00\xff\x00\xff\xff\xff\xff\xff\x7b\x1f\xb1\xc4\x00\x00\x00"
"\x09\x70\x48\x59\x73\x00\x00\x0b\x13\x00\x00\x0b\x13\x01\x00\x9a"
"\x9c\x18\x00\x00\x00\x17\x49\x44\x41\x54\x78\x01\x63\x98\x89\x0a"
"\x18\x50\xb9\x33\x47\xf9\xa8\x01\x32\xd4\xc2\x03\x00\x33\x84\x0d"
"\x02\x3a\x91\xeb\xa5\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60"
"\x82";
return WebKit::WebData(red_square, arraysize(red_square));
}
return webkit_glue::WebKitClientImpl::loadResource(name);
}
<commit_msg>Disable run-time flag for device orientation in test_shell<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "webkit/tools/test_shell/test_shell_webkit_init.h"
#include "base/path_service.h"
#include "base/stats_counters.h"
#include "media/base/media.h"
#include "third_party/WebKit/WebKit/chromium/public/WebDatabase.h"
#include "third_party/WebKit/WebKit/chromium/public/WebKit.h"
#include "third_party/WebKit/WebKit/chromium/public/WebRuntimeFeatures.h"
#include "third_party/WebKit/WebKit/chromium/public/WebScriptController.h"
#include "third_party/WebKit/WebKit/chromium/public/WebSecurityPolicy.h"
#include "webkit/extensions/v8/gears_extension.h"
#include "webkit/extensions/v8/interval_extension.h"
#include "webkit/tools/test_shell/test_shell.h"
#if defined(OS_WIN)
#include "webkit/tools/test_shell/test_shell_webthemeengine.h"
#endif
TestShellWebKitInit::TestShellWebKitInit(bool layout_test_mode) {
v8::V8::SetCounterFunction(StatsTable::FindLocation);
WebKit::initialize(this);
WebKit::setLayoutTestMode(layout_test_mode);
WebKit::WebSecurityPolicy::registerURLSchemeAsLocal(
WebKit::WebString::fromUTF8("test-shell-resource"));
WebKit::WebSecurityPolicy::registerURLSchemeAsNoAccess(
WebKit::WebString::fromUTF8("test-shell-resource"));
WebKit::WebScriptController::enableV8SingleThreadMode();
WebKit::WebScriptController::registerExtension(
extensions_v8::GearsExtension::Get());
WebKit::WebScriptController::registerExtension(
extensions_v8::IntervalExtension::Get());
WebKit::WebRuntimeFeatures::enableSockets(true);
WebKit::WebRuntimeFeatures::enableApplicationCache(true);
WebKit::WebRuntimeFeatures::enableDatabase(true);
WebKit::WebRuntimeFeatures::enableWebGL(true);
WebKit::WebRuntimeFeatures::enablePushState(true);
WebKit::WebRuntimeFeatures::enableNotifications(true);
WebKit::WebRuntimeFeatures::enableTouch(true);
WebKit::WebRuntimeFeatures::enableIndexedDatabase(true);
// TODO(hwennborg): Enable this once the implementation supports it.
WebKit::WebRuntimeFeatures::enableDeviceOrientation(false);
// Load libraries for media and enable the media player.
FilePath module_path;
WebKit::WebRuntimeFeatures::enableMediaPlayer(
PathService::Get(base::DIR_MODULE, &module_path) &&
media::InitializeMediaLibrary(module_path));
WebKit::WebRuntimeFeatures::enableGeolocation(true);
// Construct and initialize an appcache system for this scope.
// A new empty temp directory is created to house any cached
// content during the run. Upon exit that directory is deleted.
// If we can't create a tempdir, we'll use in-memory storage.
if (!appcache_dir_.CreateUniqueTempDir()) {
LOG(WARNING) << "Failed to create a temp dir for the appcache, "
"using in-memory storage.";
DCHECK(appcache_dir_.path().empty());
}
SimpleAppCacheSystem::InitializeOnUIThread(appcache_dir_.path());
WebKit::WebDatabase::setObserver(&database_system_);
file_system_.set_sandbox_enabled(false);
#if defined(OS_WIN)
// Ensure we pick up the default theme engine.
SetThemeEngine(NULL);
#endif
}
TestShellWebKitInit::~TestShellWebKitInit() {
WebKit::shutdown();
}
WebKit::WebClipboard* TestShellWebKitInit::clipboard() {
// Mock out clipboard calls in layout test mode so that tests don't mess
// with each other's copies/pastes when running in parallel.
if (TestShell::layout_test_mode()) {
return &mock_clipboard_;
} else {
return &real_clipboard_;
}
}
WebKit::WebData TestShellWebKitInit::loadResource(const char* name) {
if (!strcmp(name, "deleteButton")) {
// Create a red 30x30 square.
const char red_square[] =
"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52"
"\x00\x00\x00\x1e\x00\x00\x00\x1e\x04\x03\x00\x00\x00\xc9\x1e\xb3"
"\x91\x00\x00\x00\x30\x50\x4c\x54\x45\x00\x00\x00\x80\x00\x00\x00"
"\x80\x00\x80\x80\x00\x00\x00\x80\x80\x00\x80\x00\x80\x80\x80\x80"
"\x80\xc0\xc0\xc0\xff\x00\x00\x00\xff\x00\xff\xff\x00\x00\x00\xff"
"\xff\x00\xff\x00\xff\xff\xff\xff\xff\x7b\x1f\xb1\xc4\x00\x00\x00"
"\x09\x70\x48\x59\x73\x00\x00\x0b\x13\x00\x00\x0b\x13\x01\x00\x9a"
"\x9c\x18\x00\x00\x00\x17\x49\x44\x41\x54\x78\x01\x63\x98\x89\x0a"
"\x18\x50\xb9\x33\x47\xf9\xa8\x01\x32\xd4\xc2\x03\x00\x33\x84\x0d"
"\x02\x3a\x91\xeb\xa5\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60"
"\x82";
return WebKit::WebData(red_square, arraysize(red_square));
}
return webkit_glue::WebKitClientImpl::loadResource(name);
}
<|endoftext|>
|
<commit_before>// vim:cindent:cino=\:0:et:fenc=utf-8:ff=unix:sw=4:ts=4:
#include <sstream>
#include <string>
#include <stdexcept>
#include <QtGlobal>
#include <conveyor/address.h>
#include <conveyor/pipeaddress.h>
#include <conveyor/tcpaddress.h>
#include <conveyor/exceptions.h>
namespace
{
conveyor::TcpAddress DefaultTcpAddress ("localhost", 9999);
conveyor::PipeAddress DefaultPipeAddress
(
#ifdef __APPLE__
/** Mac OS X treats /var/run differently than other unices and
launchd has no reliable way to create a /var/run/conveyor on launch.
Ideally conveyord should create this directory itself on OS X. However
we're going to leave that aside for now and get it done.
*/
"/var/run/conveyord.socket"
#else
"/var/run/conveyor/conveyord.socket"
#endif
);
static
conveyor::Address *
parseTcpAddress (std::string const & hostport)
{
std::string::size_type const colon (hostport.find (":"));
if (std::string::npos == colon)
{
throw std::runtime_error ("Error on hostport");
}
else
{
std::string const host (hostport.substr (0, colon));
std::istringstream stream (hostport.substr (colon + 1));
int port;
stream >> port;
if (stream.bad () or stream.fail ())
{
throw std::runtime_error ("Error writing to string stream");
}
else
{
conveyor::Address * const address
( new conveyor::TcpAddress (host, port)
);
return address;
}
}
}
static
conveyor::Address *
parsePipeAddress (std::string const & path)
{
conveyor::Address * const address (new conveyor::PipeAddress (path));
return address;
}
}
namespace conveyor
{
Address *
Address::defaultAddress()
{
#if defined (CONVEYOR_ADDRESS)
return CONVEYOR_ADDRESS;
#elif defined (Q_OS_LINUX) || defined (Q_OS_MAC)
return & DefaultPipeAddress;
#elif defined (Q_OS_WIN32)
return & DefaultTcpAddress;
#else
# error No CONVEYOR_ADDRESS defined and no default location known for this platform
#endif
}
Address *
Address::parse (std::string const & str)
{
try
{
Address * address;
if ("tcp:" == str.substr (0, 4))
{
address = parseTcpAddress (str.substr (4));
}
else
if (("pipe:" == str.substr (0, 5))
or ("unix:" == str.substr (0, 5)))
{
address = parsePipeAddress (str.substr (5));
}
else
{
throw InvalidAddressError(str);
}
return address;
}
catch (std::out_of_range const & exception)
{
throw;
}
}
Address::~Address (void)
{
}
}
<commit_msg>Use /var/tmp/conveyord.socket as the default socket path on OSX.<commit_after>// vim:cindent:cino=\:0:et:fenc=utf-8:ff=unix:sw=4:ts=4:
#include <sstream>
#include <string>
#include <stdexcept>
#include <QtGlobal>
#include <conveyor/address.h>
#include <conveyor/pipeaddress.h>
#include <conveyor/tcpaddress.h>
#include <conveyor/exceptions.h>
namespace
{
conveyor::TcpAddress DefaultTcpAddress ("localhost", 9999);
conveyor::PipeAddress DefaultPipeAddress
(
#ifdef __APPLE__
// The OSX developer documentation says that non-root daemons
// should use /var/tmp for such socket files.
"/var/tmp/conveyord.socket"
#else
"/var/run/conveyor/conveyord.socket"
#endif
);
static
conveyor::Address *
parseTcpAddress (std::string const & hostport)
{
std::string::size_type const colon (hostport.find (":"));
if (std::string::npos == colon)
{
throw std::runtime_error ("Error on hostport");
}
else
{
std::string const host (hostport.substr (0, colon));
std::istringstream stream (hostport.substr (colon + 1));
int port;
stream >> port;
if (stream.bad () or stream.fail ())
{
throw std::runtime_error ("Error writing to string stream");
}
else
{
conveyor::Address * const address
( new conveyor::TcpAddress (host, port)
);
return address;
}
}
}
static
conveyor::Address *
parsePipeAddress (std::string const & path)
{
conveyor::Address * const address (new conveyor::PipeAddress (path));
return address;
}
}
namespace conveyor
{
Address *
Address::defaultAddress()
{
#if defined (CONVEYOR_ADDRESS)
return CONVEYOR_ADDRESS;
#elif defined (Q_OS_LINUX) || defined (Q_OS_MAC)
return & DefaultPipeAddress;
#elif defined (Q_OS_WIN32)
return & DefaultTcpAddress;
#else
# error No CONVEYOR_ADDRESS defined and no default location known for this platform
#endif
}
Address *
Address::parse (std::string const & str)
{
try
{
Address * address;
if ("tcp:" == str.substr (0, 4))
{
address = parseTcpAddress (str.substr (4));
}
else
if (("pipe:" == str.substr (0, 5))
or ("unix:" == str.substr (0, 5)))
{
address = parsePipeAddress (str.substr (5));
}
else
{
throw InvalidAddressError(str);
}
return address;
}
catch (std::out_of_range const & exception)
{
throw;
}
}
Address::~Address (void)
{
}
}
<|endoftext|>
|
<commit_before>/** interpreter.cc ---
*
* Copyright (C) 2012 OpenCog Foundation
*
* Author: Nil Geisweiller
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "interpreter.h"
#include "../combo/iostream_combo.h"
#include "../crutil/exception.h"
#include <opencog/util/numeric.h>
#include <opencog/util/exceptions.h>
#include <opencog/util/mt19937ar.h>
namespace opencog { namespace combo {
/////////////////////////
// Boolean interpreter //
/////////////////////////
boolean_interpreter::boolean_interpreter(const std::vector<builtin>& inputs)
: boolean_inputs(inputs) {}
builtin boolean_interpreter::operator()(const combo_tree& tr) const {
return boolean_eval(tr.begin());
}
builtin boolean_interpreter::operator()(const combo_tree::iterator it) const {
return boolean_eval(it);
}
builtin boolean_interpreter::boolean_eval(combo_tree::iterator it) const
{
typedef combo_tree::sibling_iterator sib_it;
const vertex& v = *it;
if (const argument* a = boost::get<argument>(&v)) {
arity_t idx = a->idx;
return idx > 0? boolean_inputs[idx - 1]
: negate_builtin(boolean_inputs[-idx - 1]);
}
// boolean builtin
else if (const builtin* b = boost::get<builtin>(&v)) {
switch (*b) {
// Boolean operators
case id::logical_false :
case id::logical_true :
return *b;
case id::logical_and : {
if (it.is_childless()) // For correct foldr behaviour
return id::logical_and;
for (sib_it sib = it.begin(); sib != it.end(); ++sib)
if (boolean_eval(sib) == id::logical_false)
return id::logical_false;
return id::logical_true;
}
case id::logical_or : {
if (it.is_childless()) // For correct foldr behaviour
return id::logical_or;
for (sib_it sib = it.begin(); sib != it.end(); ++sib)
if (boolean_eval(sib) == id::logical_true)
return id::logical_true;
return id::logical_false;
}
case id::logical_not :
return negate_builtin(boolean_eval(it.begin()));
default: {
std::stringstream ss;
ss << *b;
OC_ASSERT(false, "boolean_interpreter does not handle builtin %s",
ss.str().c_str());
return builtin();
}
}
} else {
std::stringstream ss;
ss << v;
OC_ASSERT(false, "boolean_interpreter does not handle vertex %s",
ss.str().c_str());
return builtin();
}
}
////////////////////////
// Contin interpreter //
////////////////////////
contin_interpreter::contin_interpreter(const std::vector<contin_t>& inputs)
: contin_inputs(inputs) {}
contin_t contin_interpreter::operator()(const combo_tree& tr) const {
return contin_eval(tr.begin());
}
contin_t contin_interpreter::operator()(const combo_tree::iterator it) const {
return contin_eval(it);
}
contin_t contin_interpreter::contin_eval(combo_tree::iterator it) const
{
typedef combo_tree::sibling_iterator sib_it;
const vertex& v = *it;
if (const argument* a = boost::get<argument>(&v)) {
return contin_inputs[a->idx - 1];
}
// contin builtin
else if (const builtin* b = boost::get<builtin>(&v)) {
switch (*b) {
// Continuous operators
case id::plus : {
// If plus does not have any argument, return plus operator
if (it.is_childless()) // For correct foldr behaviour
return *b;
contin_t res = 0;
// Assumption : plus can have 1 or more arguments
for (sib_it sib = it.begin(); sib != it.end(); ++sib)
res += contin_eval(sib);
return res;
}
case id::times : {
// If times does not have any argument, return times operator
if (it.is_childless()) // For correct foldr behaviour
return *b;
contin_t res = 1;
// Assumption : times can have 1 or more arguments
for (sib_it sib = it.begin(); sib != it.end(); ++sib) {
res *= contin_eval(sib);
if (0.0 == res) return res; // avoid pointless evals
}
return res;
}
case id::div : {
contin_t x, y;
sib_it sib = it.begin();
x = contin_eval(sib);
if (0.0 == x) return x; // avoid pointless evals
++sib;
y = contin_eval(sib);
contin_t res = x / y;
if (isnan(res) || isinf(res))
throw OverflowException(vertex(res));
return res;
}
case id::log : {
contin_t x = contin_eval(it.begin());
#ifdef ABS_LOG
contin_t res = log(std::abs(x));
#else
contin_t res = log(x);
#endif
if (isnan(res) || isinf(res))
throw OverflowException(vertex(res));
return res;
}
case id::exp : {
contin_t res = exp(contin_eval(it.begin()));
// This may happen when the argument is too large, then
// exp will be infty
if (isinf(res)) throw OverflowException(vertex(res));
return res;
}
case id::sin : {
return sin(contin_eval(it.begin()));
}
case id::rand :
return randGen().randfloat();
default: {
std::stringstream ss;
ss << *b;
throw ComboException(TRACE_INFO,
"contin_interpreter does not handle builtin %s",
ss.str().c_str());
return contin_t();
}
}
}
// contin constant
else if (const contin_t* c = boost::get<contin_t>(&v)) {
if (isnan(*c) || isinf(*c))
throw OverflowException(vertex(*c));
return *c;
}
else {
std::stringstream ss;
ss << v;
throw ComboException(TRACE_INFO,
"contin_interpreter does not handle vertex %s",
ss.str().c_str());
return contin_t();
}
}
///////////////////////
// Mixed interpreter //
///////////////////////
mixed_interpreter::mixed_interpreter(const std::vector<vertex>& inputs) :
_use_boolean_inputs(false),
_use_contin_inputs(false),
_mixed_inputs(inputs)
{}
mixed_interpreter::mixed_interpreter(const std::vector<contin_t>& inputs) :
contin_interpreter(inputs),
_use_boolean_inputs(false),
_use_contin_inputs(true),
_mixed_inputs(std::vector<vertex>())
{}
mixed_interpreter::mixed_interpreter(const std::vector<builtin>& inputs) :
boolean_interpreter(inputs),
_use_boolean_inputs(true),
_use_contin_inputs(false),
_mixed_inputs(std::vector<vertex>())
{}
vertex mixed_interpreter::operator()(const combo_tree& tr) const
{
return mixed_eval(tr.begin());
}
vertex mixed_interpreter::operator()(const combo_tree::iterator it) const
{
return mixed_eval(it);
}
builtin mixed_interpreter::boolean_eval(combo_tree::iterator it) const
{
return get_builtin(mixed_eval(it));
}
contin_t mixed_interpreter::contin_eval(combo_tree::iterator it) const
{
return get_contin(mixed_eval(it));
}
vertex mixed_interpreter::mixed_eval(combo_tree::iterator it) const
{
typedef combo_tree::sibling_iterator sib_it;
const vertex& v = *it;
if (const argument* a = boost::get<argument>(&v)) {
arity_t idx = a->idx;
// The mixed interpreter could be getting an array of
// all contins, if the signature of the problem is
// ->(contin ... contin boolean) or ->(contin ... contin enum_t)
// so deal with this case.
// XXX FIXME, we should also handle the cases
// ->(bool ... bool contin) and ->(bool ... bool enum)
// which would have an empty contin and an empty mixed ...
if (_use_contin_inputs)
return contin_inputs[idx - 1];
// A negative index means boolean-negate.
return idx > 0 ? _mixed_inputs[idx - 1]
: negate_vertex(_mixed_inputs[-idx - 1]);
}
// mixed, boolean and contin builtin
else if (const builtin* b = boost::get<builtin>(&v)) {
switch (*b) {
// Boolean operators
case id::logical_false :
case id::logical_true :
case id::logical_and :
case id::logical_or :
case id::logical_not :
return boolean_interpreter::boolean_eval(it);
// Contin operators
case id::plus :
case id::times :
case id::div :
case id::log :
case id::exp :
case id::sin :
case id::rand :
return contin_interpreter::contin_eval(it);
// Mixed operators
case id::greater_than_zero : {
sib_it sib = it.begin();
vertex x;
try {
// A divide-by-zero in the contin could throw. We want
// to return a boolean in this case, anyway. Values
// might be +inf -inf or nan and we can still get a
// sign bit off two of these cases...
x = mixed_eval(sib);
} catch (OverflowException& e) {
x = e.get_vertex();
}
return bool_to_vertex(0 < get_contin(x));
}
case id::impulse : {
vertex i = mixed_eval(it.begin());
return (i == id::logical_true ? 1.0 : 0.0);
}
// XXX TODO: contin_if should go away.
case id::contin_if :
case id::cond : {
sib_it sib = it.begin();
while (1) {
OC_ASSERT (sib != it.end(), "Error: mal-formed cond statement");
vertex vcond = mixed_eval(sib);
++sib; // move past the condition
// The very last value is the universal "else" clause,
// taken when none of the previous predicates were true.
if (sib == it.end())
return vcond;
// If condition is true, then return the consequent
// (i.e. the value immediately following.) Else, skip
// the consequent, and loop around again.
if (vcond == id::logical_true)
return mixed_eval(sib);
++sib; // move past the consequent
}
}
default: {
std::stringstream ss;
ss << *b;
OC_ASSERT(false, "mixed_interpreter does not handle builtin %s",
ss.str().c_str());
return vertex();
}
}
}
// contin constant
else if (is_contin(v)) {
return contin_interpreter::contin_eval(it);
}
// string constant
else if (is_definite_object(v)) {
return v;
}
else {
std::stringstream ss;
ss << v;
OC_ASSERT(false, "mixed_interpreter does not handle vertex %s",
ss.str().c_str());
return vertex();
}
}
}} // ~namespaces combo opencog
<commit_msg>combo: get mixed interpreter to use boolean inputs.<commit_after>/** interpreter.cc ---
*
* Copyright (C) 2012 OpenCog Foundation
*
* Author: Nil Geisweiller
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "interpreter.h"
#include "../combo/iostream_combo.h"
#include "../crutil/exception.h"
#include <opencog/util/numeric.h>
#include <opencog/util/exceptions.h>
#include <opencog/util/mt19937ar.h>
namespace opencog { namespace combo {
/////////////////////////
// Boolean interpreter //
/////////////////////////
boolean_interpreter::boolean_interpreter(const std::vector<builtin>& inputs)
: boolean_inputs(inputs) {}
builtin boolean_interpreter::operator()(const combo_tree& tr) const {
return boolean_eval(tr.begin());
}
builtin boolean_interpreter::operator()(const combo_tree::iterator it) const {
return boolean_eval(it);
}
builtin boolean_interpreter::boolean_eval(combo_tree::iterator it) const
{
typedef combo_tree::sibling_iterator sib_it;
const vertex& v = *it;
if (const argument* a = boost::get<argument>(&v)) {
arity_t idx = a->idx;
return idx > 0? boolean_inputs[idx - 1]
: negate_builtin(boolean_inputs[-idx - 1]);
}
// boolean builtin
else if (const builtin* b = boost::get<builtin>(&v)) {
switch (*b) {
// Boolean operators
case id::logical_false :
case id::logical_true :
return *b;
case id::logical_and : {
if (it.is_childless()) // For correct foldr behaviour
return id::logical_and;
for (sib_it sib = it.begin(); sib != it.end(); ++sib)
if (boolean_eval(sib) == id::logical_false)
return id::logical_false;
return id::logical_true;
}
case id::logical_or : {
if (it.is_childless()) // For correct foldr behaviour
return id::logical_or;
for (sib_it sib = it.begin(); sib != it.end(); ++sib)
if (boolean_eval(sib) == id::logical_true)
return id::logical_true;
return id::logical_false;
}
case id::logical_not :
return negate_builtin(boolean_eval(it.begin()));
default: {
std::stringstream ss;
ss << *b;
OC_ASSERT(false, "boolean_interpreter does not handle builtin %s",
ss.str().c_str());
return builtin();
}
}
} else {
std::stringstream ss;
ss << v;
OC_ASSERT(false, "boolean_interpreter does not handle vertex %s",
ss.str().c_str());
return builtin();
}
}
////////////////////////
// Contin interpreter //
////////////////////////
contin_interpreter::contin_interpreter(const std::vector<contin_t>& inputs)
: contin_inputs(inputs) {}
contin_t contin_interpreter::operator()(const combo_tree& tr) const {
return contin_eval(tr.begin());
}
contin_t contin_interpreter::operator()(const combo_tree::iterator it) const {
return contin_eval(it);
}
contin_t contin_interpreter::contin_eval(combo_tree::iterator it) const
{
typedef combo_tree::sibling_iterator sib_it;
const vertex& v = *it;
if (const argument* a = boost::get<argument>(&v)) {
return contin_inputs[a->idx - 1];
}
// contin builtin
else if (const builtin* b = boost::get<builtin>(&v)) {
switch (*b) {
// Continuous operators
case id::plus : {
// If plus does not have any argument, return plus operator
if (it.is_childless()) // For correct foldr behaviour
return *b;
contin_t res = 0;
// Assumption : plus can have 1 or more arguments
for (sib_it sib = it.begin(); sib != it.end(); ++sib)
res += contin_eval(sib);
return res;
}
case id::times : {
// If times does not have any argument, return times operator
if (it.is_childless()) // For correct foldr behaviour
return *b;
contin_t res = 1;
// Assumption : times can have 1 or more arguments
for (sib_it sib = it.begin(); sib != it.end(); ++sib) {
res *= contin_eval(sib);
if (0.0 == res) return res; // avoid pointless evals
}
return res;
}
case id::div : {
contin_t x, y;
sib_it sib = it.begin();
x = contin_eval(sib);
if (0.0 == x) return x; // avoid pointless evals
++sib;
y = contin_eval(sib);
contin_t res = x / y;
if (isnan(res) || isinf(res))
throw OverflowException(vertex(res));
return res;
}
case id::log : {
contin_t x = contin_eval(it.begin());
#ifdef ABS_LOG
contin_t res = log(std::abs(x));
#else
contin_t res = log(x);
#endif
if (isnan(res) || isinf(res))
throw OverflowException(vertex(res));
return res;
}
case id::exp : {
contin_t res = exp(contin_eval(it.begin()));
// This may happen when the argument is too large, then
// exp will be infty
if (isinf(res)) throw OverflowException(vertex(res));
return res;
}
case id::sin : {
return sin(contin_eval(it.begin()));
}
case id::rand :
return randGen().randfloat();
default: {
std::stringstream ss;
ss << *b;
throw ComboException(TRACE_INFO,
"contin_interpreter does not handle builtin %s",
ss.str().c_str());
return contin_t();
}
}
}
// contin constant
else if (const contin_t* c = boost::get<contin_t>(&v)) {
if (isnan(*c) || isinf(*c))
throw OverflowException(vertex(*c));
return *c;
}
else {
std::stringstream ss;
ss << v;
throw ComboException(TRACE_INFO,
"contin_interpreter does not handle vertex %s",
ss.str().c_str());
return contin_t();
}
}
///////////////////////
// Mixed interpreter //
///////////////////////
mixed_interpreter::mixed_interpreter(const std::vector<vertex>& inputs) :
_use_boolean_inputs(false),
_use_contin_inputs(false),
_mixed_inputs(inputs)
{}
mixed_interpreter::mixed_interpreter(const std::vector<contin_t>& inputs) :
contin_interpreter(inputs),
_use_boolean_inputs(false),
_use_contin_inputs(true),
_mixed_inputs(std::vector<vertex>())
{}
mixed_interpreter::mixed_interpreter(const std::vector<builtin>& inputs) :
boolean_interpreter(inputs),
_use_boolean_inputs(true),
_use_contin_inputs(false),
_mixed_inputs(std::vector<vertex>())
{}
vertex mixed_interpreter::operator()(const combo_tree& tr) const
{
return mixed_eval(tr.begin());
}
vertex mixed_interpreter::operator()(const combo_tree::iterator it) const
{
return mixed_eval(it);
}
builtin mixed_interpreter::boolean_eval(combo_tree::iterator it) const
{
return get_builtin(mixed_eval(it));
}
contin_t mixed_interpreter::contin_eval(combo_tree::iterator it) const
{
return get_contin(mixed_eval(it));
}
vertex mixed_interpreter::mixed_eval(combo_tree::iterator it) const
{
typedef combo_tree::sibling_iterator sib_it;
const vertex& v = *it;
if (const argument* a = boost::get<argument>(&v)) {
arity_t idx = a->idx;
// The mixed interpreter could be getting an array of
// all contins, if the signature of the problem is
// ->(contin ... contin boolean) or ->(contin ... contin enum_t)
// so deal with this case.
if (_use_contin_inputs)
return contin_inputs[idx - 1];
// The mixed interpreter could be getting an array of
// all booleans, if the signature of the problem is
// ->(bool ... bool contin) or ->(bool ... bool enum)
// so deal with this case.
if (_use_boolean_inputs)
return idx > 0 ? boolean_inputs[idx - 1]
: negate_builtin(boolean_inputs[-idx - 1]);
// A negative index means boolean-negate.
return idx > 0 ? _mixed_inputs[idx - 1]
: negate_vertex(_mixed_inputs[-idx - 1]);
}
// mixed, boolean and contin builtin
else if (const builtin* b = boost::get<builtin>(&v)) {
switch (*b) {
// Boolean operators
case id::logical_false :
case id::logical_true :
case id::logical_and :
case id::logical_or :
case id::logical_not :
return boolean_interpreter::boolean_eval(it);
// Contin operators
case id::plus :
case id::times :
case id::div :
case id::log :
case id::exp :
case id::sin :
case id::rand :
return contin_interpreter::contin_eval(it);
// Mixed operators
case id::greater_than_zero : {
sib_it sib = it.begin();
vertex x;
try {
// A divide-by-zero in the contin could throw. We want
// to return a boolean in this case, anyway. Values
// might be +inf -inf or nan and we can still get a
// sign bit off two of these cases...
x = mixed_eval(sib);
} catch (OverflowException& e) {
x = e.get_vertex();
}
return bool_to_vertex(0 < get_contin(x));
}
case id::impulse : {
vertex i = mixed_eval(it.begin());
return (i == id::logical_true ? 1.0 : 0.0);
}
// XXX TODO: contin_if should go away.
case id::contin_if :
case id::cond : {
sib_it sib = it.begin();
while (1) {
OC_ASSERT (sib != it.end(), "Error: mal-formed cond statement");
vertex vcond = mixed_eval(sib);
++sib; // move past the condition
// The very last value is the universal "else" clause,
// taken when none of the previous predicates were true.
if (sib == it.end())
return vcond;
// If condition is true, then return the consequent
// (i.e. the value immediately following.) Else, skip
// the consequent, and loop around again.
if (vcond == id::logical_true)
return mixed_eval(sib);
++sib; // move past the consequent
}
}
default: {
std::stringstream ss;
ss << *b;
OC_ASSERT(false, "mixed_interpreter does not handle builtin %s",
ss.str().c_str());
return vertex();
}
}
}
// contin constant
else if (is_contin(v)) {
return contin_interpreter::contin_eval(it);
}
// string constant
else if (is_definite_object(v)) {
return v;
}
else {
std::stringstream ss;
ss << v;
OC_ASSERT(false, "mixed_interpreter does not handle vertex %s",
ss.str().c_str());
return vertex();
}
}
}} // ~namespaces combo opencog
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2017 SUSE LLC
*
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as published
* by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, contact SUSE LLC.
*
* To contact SUSE LLC about this file by physical or electronic mail, you may
* find current contact information at www.suse.com.
*/
#include "storage/CompoundAction/Formatter/StrayBlkDevice.h"
#include "storage/Devices/LvmPv.h"
#include "storage/Filesystems/Swap.h"
namespace storage
{
CompoundAction::Formatter::StrayBlkDevice::StrayBlkDevice(const CompoundAction::Impl* compound_action) :
CompoundAction::Formatter(compound_action, "StrayBlkDevice"),
stray_blk_device(to_stray_blk_device(compound_action->get_target_device()))
{}
Text
CompoundAction::Formatter::StrayBlkDevice::text() const
{
if ( has_create<storage::LvmPv>() )
{
if ( encrypting() )
return encrypted_pv_text();
else
return pv_text();
}
else if ( formatting() && is_swap( get_created_filesystem() ) )
{
if ( encrypting() )
return format_as_encrypted_swap_text();
else
return format_as_swap_text();
}
else
{
if ( encrypting() && formatting() && mounting() )
return encrypted_with_fs_and_mount_point_text();
else if ( encrypting() && formatting() )
return encrypted_with_fs_text();
else if ( encrypting() )
return encrypted_text();
else if ( formatting() && mounting() )
return fs_and_mount_point_text();
else if ( formatting() )
return fs_text();
else if ( mounting() )
return mount_point_text();
else
return default_text();
}
}
Text
CompoundAction::Formatter::StrayBlkDevice::format_as_swap_text() const
{
// TRANSLATORS:
// %1$s is replaced with the partition name (e.g. /dev/sda1),
// %2$s is replaced with the size (e.g. 2GiB)
Text text = _("Format partition %1$s (%2$s) as swap");
return sformat(text, get_device_name().c_str(), get_size().c_str());
}
Text
CompoundAction::Formatter::StrayBlkDevice::format_as_encrypted_swap_text() const
{
// TRANSLATORS:
// %1$s is replaced with the partition name (e.g. /dev/sda1),
// %2$s is replaced with the size (e.g. 2GiB)
Text text = _("Format partition %1$s (%2$s) as encryped swap");
return sformat(text, get_device_name().c_str(), get_size().c_str());
}
Text
CompoundAction::Formatter::StrayBlkDevice::encrypted_pv_text() const
{
// TRANSLATORS:
// %1$s is replaced with the partition name (e.g. /dev/sda1),
// %2$s is replaced with the size (e.g. 2GiB)
Text text = _("Create LVM physical volume over encrypted %1$s (%2$s)");
return sformat(text, get_device_name().c_str(), get_size().c_str());
}
Text
CompoundAction::Formatter::StrayBlkDevice::pv_text() const
{
// TRANSLATORS:
// %1$s is replaced with the partition name (e.g. /dev/sda1),
// %2$s is replaced with the size (e.g. 2GiB)
Text text = _("Create LVM physical volume over %1$s (%2$s)");
return sformat(text, get_device_name().c_str(), get_size().c_str());
}
Text
CompoundAction::Formatter::StrayBlkDevice::encrypted_with_fs_and_mount_point_text() const
{
// TRANSLATORS:
// %1$s is replaced with the partition name (e.g. /dev/sda1),
// %2$s is replaced with the size (e.g. 2GiB),
// %3$s is replaced with the mount point (e.g. /home),
// %4$s is replaced by file system name (e.g. ext4)
Text text = _("Encrypt partition %1$s (%2$s) for %3$s with %4$s");
return sformat(text,
get_device_name().c_str(),
get_size().c_str(),
get_mount_point().c_str(),
get_filesystem_type().c_str());
}
Text
CompoundAction::Formatter::StrayBlkDevice::encrypted_with_fs_text() const
{
// TRANSLATORS:
// %1$s is replaced with the partition name (e.g. /dev/sda1),
// %2$s is replaced with the size (e.g. 2GiB),
// %3$s is replaced by file system name (e.g. ext4)
Text text = _("Encrypt partition %1$s (%2$s) with %3$s");
return sformat(text,
get_device_name().c_str(),
get_size().c_str(),
get_filesystem_type().c_str());
}
Text
CompoundAction::Formatter::StrayBlkDevice::encrypted_text() const
{
// TRANSLATORS:
// %1$s is replaced with the partition name (e.g. /dev/sda1),
// %2$s is replaced with the size (e.g. 2GiB),
Text text = _("Encrypt partition %1$s (%2$s)");
return sformat(text, get_device_name().c_str(), get_size().c_str());
}
Text
CompoundAction::Formatter::StrayBlkDevice::fs_and_mount_point_text() const
{
// TRANSLATORS:
// %1$s is replaced with the partition name (e.g. /dev/sda1),
// %2$s is replaced with the size (e.g. 2GiB),
// %3$s is replaced with the mount point (e.g. /home),
// %4$s is replaced by file system name (e.g. ext4)
Text text = _("Format partition %1$s (%2$s) for %3$s with %4$s");
return sformat(text,
get_device_name().c_str(),
get_size().c_str(),
get_mount_point().c_str(),
get_filesystem_type().c_str());
}
Text
CompoundAction::Formatter::StrayBlkDevice::fs_text() const
{
// TRANSLATORS:
// %1$s is replaced with the partition name (e.g. /dev/sda1),
// %2$s is replaced with the size (e.g. 2GiB),
// %3$s is replaced by file system name (e.g. ext4)
Text text = _("Format partition %1$s (%2$s) with %3$s");
return sformat(text,
get_device_name().c_str(),
get_size().c_str(),
get_filesystem_type().c_str());
}
Text
CompoundAction::Formatter::StrayBlkDevice::mount_point_text() const
{
string mount_point = get_created_mount_point()->get_path();
// TRANSLATORS:
// %1$s is replaced with the partition name (e.g. /dev/sda1),
// %2$s is replaced with the size (e.g. 2GiB),
// %3$s is replaced with the mount point (e.g. /home)
Text text = _("Mount partition %1$s (%2$s) at %3$s");
return sformat(text,
get_device_name().c_str(),
get_size().c_str(),
mount_point.c_str());
}
}
<commit_msg>Use actual output for translator examples<commit_after>/*
* Copyright (c) 2017 SUSE LLC
*
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as published
* by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, contact SUSE LLC.
*
* To contact SUSE LLC about this file by physical or electronic mail, you may
* find current contact information at www.suse.com.
*/
#include "storage/CompoundAction/Formatter/StrayBlkDevice.h"
#include "storage/Devices/LvmPv.h"
#include "storage/Filesystems/Swap.h"
namespace storage
{
CompoundAction::Formatter::StrayBlkDevice::StrayBlkDevice(const CompoundAction::Impl* compound_action) :
CompoundAction::Formatter(compound_action, "StrayBlkDevice"),
stray_blk_device(to_stray_blk_device(compound_action->get_target_device()))
{}
Text
CompoundAction::Formatter::StrayBlkDevice::text() const
{
if ( has_create<storage::LvmPv>() )
{
if ( encrypting() )
return encrypted_pv_text();
else
return pv_text();
}
else if ( formatting() && is_swap( get_created_filesystem() ) )
{
if ( encrypting() )
return format_as_encrypted_swap_text();
else
return format_as_swap_text();
}
else
{
if ( encrypting() && formatting() && mounting() )
return encrypted_with_fs_and_mount_point_text();
else if ( encrypting() && formatting() )
return encrypted_with_fs_text();
else if ( encrypting() )
return encrypted_text();
else if ( formatting() && mounting() )
return fs_and_mount_point_text();
else if ( formatting() )
return fs_text();
else if ( mounting() )
return mount_point_text();
else
return default_text();
}
}
Text
CompoundAction::Formatter::StrayBlkDevice::format_as_swap_text() const
{
// TRANSLATORS:
// %1$s is replaced with the partition name (e.g. /dev/sda1),
// %2$s is replaced with the size (e.g. 2 GiB)
Text text = _("Format partition %1$s (%2$s) as swap");
return sformat(text, get_device_name().c_str(), get_size().c_str());
}
Text
CompoundAction::Formatter::StrayBlkDevice::format_as_encrypted_swap_text() const
{
// TRANSLATORS:
// %1$s is replaced with the partition name (e.g. /dev/sda1),
// %2$s is replaced with the size (e.g. 2 GiB)
Text text = _("Format partition %1$s (%2$s) as encryped swap");
return sformat(text, get_device_name().c_str(), get_size().c_str());
}
Text
CompoundAction::Formatter::StrayBlkDevice::encrypted_pv_text() const
{
// TRANSLATORS:
// %1$s is replaced with the partition name (e.g. /dev/sda1),
// %2$s is replaced with the size (e.g. 2 GiB)
Text text = _("Create LVM physical volume over encrypted %1$s (%2$s)");
return sformat(text, get_device_name().c_str(), get_size().c_str());
}
Text
CompoundAction::Formatter::StrayBlkDevice::pv_text() const
{
// TRANSLATORS:
// %1$s is replaced with the partition name (e.g. /dev/sda1),
// %2$s is replaced with the size (e.g. 2 GiB)
Text text = _("Create LVM physical volume over %1$s (%2$s)");
return sformat(text, get_device_name().c_str(), get_size().c_str());
}
Text
CompoundAction::Formatter::StrayBlkDevice::encrypted_with_fs_and_mount_point_text() const
{
// TRANSLATORS:
// %1$s is replaced with the partition name (e.g. /dev/sda1),
// %2$s is replaced with the size (e.g. 2 GiB),
// %3$s is replaced with the mount point (e.g. /home),
// %4$s is replaced with the file system name (e.g. ext4)
Text text = _("Encrypt partition %1$s (%2$s) for %3$s with %4$s");
return sformat(text,
get_device_name().c_str(),
get_size().c_str(),
get_mount_point().c_str(),
get_filesystem_type().c_str());
}
Text
CompoundAction::Formatter::StrayBlkDevice::encrypted_with_fs_text() const
{
// TRANSLATORS:
// %1$s is replaced with the partition name (e.g. /dev/sda1),
// %2$s is replaced with the size (e.g. 2 GiB),
// %3$s is replaced with the file system name (e.g. ext4)
Text text = _("Encrypt partition %1$s (%2$s) with %3$s");
return sformat(text,
get_device_name().c_str(),
get_size().c_str(),
get_filesystem_type().c_str());
}
Text
CompoundAction::Formatter::StrayBlkDevice::encrypted_text() const
{
// TRANSLATORS:
// %1$s is replaced with the partition name (e.g. /dev/sda1),
// %2$s is replaced with the size (e.g. 2 GiB),
Text text = _("Encrypt partition %1$s (%2$s)");
return sformat(text, get_device_name().c_str(), get_size().c_str());
}
Text
CompoundAction::Formatter::StrayBlkDevice::fs_and_mount_point_text() const
{
// TRANSLATORS:
// %1$s is replaced with the partition name (e.g. /dev/sda1),
// %2$s is replaced with the size (e.g. 2 GiB),
// %3$s is replaced with the mount point (e.g. /home),
// %4$s is replaced with the file system name (e.g. ext4)
Text text = _("Format partition %1$s (%2$s) for %3$s with %4$s");
return sformat(text,
get_device_name().c_str(),
get_size().c_str(),
get_mount_point().c_str(),
get_filesystem_type().c_str());
}
Text
CompoundAction::Formatter::StrayBlkDevice::fs_text() const
{
// TRANSLATORS:
// %1$s is replaced with the partition name (e.g. /dev/sda1),
// %2$s is replaced with the size (e.g. 2 GiB),
// %3$s is replaced with the file system name (e.g. ext4)
Text text = _("Format partition %1$s (%2$s) with %3$s");
return sformat(text,
get_device_name().c_str(),
get_size().c_str(),
get_filesystem_type().c_str());
}
Text
CompoundAction::Formatter::StrayBlkDevice::mount_point_text() const
{
string mount_point = get_created_mount_point()->get_path();
// TRANSLATORS:
// %1$s is replaced with the partition name (e.g. /dev/sda1),
// %2$s is replaced with the size (e.g. 2 GiB),
// %3$s is replaced with the mount point (e.g. /home)
Text text = _("Mount partition %1$s (%2$s) at %3$s");
return sformat(text,
get_device_name().c_str(),
get_size().c_str(),
mount_point.c_str());
}
}
<|endoftext|>
|
<commit_before>#include <sstream>
#include <algorithm>
#include "board.h"
#include "entity.h"
#include "entity_factory.h"
#include "game.h"
#include "../parser_yaml/ruleset_parser.h"
#include "../parser_yaml/scenario_parser.h"
using namespace std;
//-----------------------------------------------------------------------------
ABoard::ABoard(Game& game, RulesetParser& rulesetParser, string name, int sizeX, int sizeY, long maxResources) :
game(game),
dt(rulesetParser.getConfiguracion().dt),
name(name),
sizeX(sizeX), sizeY(sizeY),
maxResources(maxResources),
state(BoardState::building),
started(false)
{
stringstream message;
message << "Creating board " << this << " of size " << sizeX << "x" << sizeY;
Logger::getInstance()->writeInformation(message.str());
terrain.resize(sizeX * sizeY);
createEntityFactory(PROTAGONISTA_DEFAULT_NOMBRE, {PROTAGONISTA_DEFAULT_ANCHO_BASE, PROTAGONISTA_DEFAULT_ALTO_BASE}, VELOCIDAD_PERSONAJE_DEFAULT, ENTIDAD_DEFAULT_SIGHT_RADIUS,true, ENTIDAD_DEFAULT_CAPACITY, ENTIDAD_DEFAULT_BEHAVIOUR);
createEntityFactory(ENTIDAD_DEFAULT_NOMBRE, {ENTIDAD_DEFAULT_ANCHO_BASE, ENTIDAD_DEFAULT_ALTO_BASE}, ENTIDAD_DEFAULT_SPEED, ENTIDAD_DEFAULT_SIGHT_RADIUS, true, ENTIDAD_DEFAULT_CAPACITY, ENTIDAD_DEFAULT_BEHAVIOUR);
createEntityFactory(TERRENO_DEFAULT_NOMBRE, {TERRENO_DEFAULT_ANCHO_BASE, TERRENO_DEFAULT_ALTO_BASE}, TERRENO_DEFAULT_SPEED, TERRENO_DEFAULT_SIGHT_RADIUS, false, TERRENO_DEFAULT_CAPACITY, TERRENO_DEFAULT_BEHAVIOUR);
createPlayer(DEFAULT_PLAYER_NAME, false);
for(auto& t : rulesetParser.getTiposUnidades()) {
createEntityFactory(t.nombre, {t.ancho_base, t.alto_base}, t.speed, t.sight_radius, t.solid, t.capacity, t.behaviour);
}
for (auto& t : rulesetParser.getTiposEstructuras()) {
createEntityFactory(t.nombre, { t.ancho_base, t.alto_base }, t.speed, t.sight_radius, t.solid, t.capacity, t.behaviour);
}
for(auto& t : rulesetParser.getTiposTerrenos()) {
createEntityFactory(t.nombre, {t.ancho_base, t.alto_base}, t.speed, t.sight_radius, t.solid, t.capacity, t.behaviour);
}
for (auto& t : rulesetParser.getTiposRecursos()) {
createEntityFactory(t.nombre, { t.ancho_base, t.alto_base }, t.speed, t.sight_radius, t.solid, t.capacity, t.behaviour);
}
state = BoardState::running;
}
ABoard::~ABoard() {
if(started) {
th.join();
}
}
void ABoard::fillTerrain() {
for(size_t x = 0; x < sizeX; x++) {
for(size_t y = 0; y < sizeY; y++) {
if (!getTerrain(x, y)) {
setTerrain(TERRENO_DEFAULT_NOMBRE, x, y);
}
}
}
}
std::vector<std::shared_ptr<Player>> ABoard::getPlayers() {
std::vector<std::shared_ptr<Player>> ret;
for(auto& i : players) {
ret.push_back(i.second);
}
return ret;
}
shared_ptr<Player> ABoard::createPlayer(string name, bool human) {
if (players.find(name) != players.end()) {
Logger::getInstance()->writeError("Jugador " + name + " ya existe");
return nullptr;
}
return (players[name] = make_shared<Player>(*this, name, human));
}
Player& ABoard::findPlayer(string name) {
return *(players.find(name)->second);
}
shared_ptr<Entity> ABoard::createEntity(string name, string playerName, r2 position) {
if (entityFactories.find(name) == entityFactories.end()) {
Logger::getInstance()->writeError("No existe el tipo de entidad " + name);
return nullptr;
}
auto factory = entityFactories[name];
if (findEntity(rectangle(position, factory->size))) {
Logger::getInstance()->writeError("Lugar ya ocupado para entidad " + name);
return nullptr;
}
auto pEntity = factory->createEntity(*players[playerName], position);
entities.push_back(pEntity);
return pEntity;
}
shared_ptr<EntityFactory> ABoard::createEntityFactory(string name, r2 size, double speed, int sight_radius, bool solid, int capacity, std::string behaviour) {
shared_ptr<EntityFactory> pFactory;
if (behaviour == "resource") {
pFactory = make_shared<ResourceFactory>(name, size, sight_radius, solid, capacity, *this);
}else if (behaviour == "terrain") {
pFactory = make_shared<TerrainFactory>(name, size, sight_radius, solid, *this);
}else if(behaviour == "unit") {
pFactory = make_shared<UnitFactory>(name, size, speed, sight_radius, solid, *this);
} else if(behaviour == "worker") {
pFactory = make_shared<WorkerFactory>(name, size, speed, sight_radius, solid, *this);
} else if(behaviour == "king") {
pFactory = make_shared<KingFactory>(name, size, speed, sight_radius, solid, *this);
} else if (behaviour == "building") {
pFactory = make_shared<BuildingFactory>(name, size, sight_radius, solid, *this);
} else if(behaviour == "producer_building") {
//TODO: products
pFactory = make_shared<ProducerBuildingFactory>(name, size, sight_radius, solid, *this);
} else if(behaviour == "town_center") {
//TODO: products
pFactory = make_shared<TownCenterFactory>(name, size, sight_radius, solid, *this);
} else if(behaviour == "flag") {
pFactory = make_shared<FlagFactory>(name, size, sight_radius, solid, *this);
}
else {
pFactory = make_shared<UnitFactory>(name, size, speed, sight_radius, solid, *this);
}
entityFactories[name] = pFactory;
return pFactory;
}
shared_ptr<Entity> ABoard::getTerrain(size_t x, size_t y) {
if (x >= sizeX || y >= sizeY) {
return nullptr;
}
return terrain[(sizeX*y) + x];
}
void ABoard::setTerrain(string name, size_t x, size_t y) {
if (entityFactories.find(name) == entityFactories.end()) {
Logger::getInstance()->writeError("No existe el tipo de entidad " + name);
} else {
terrain[(sizeX*y) + x] = entityFactories[name]->createEntity(*players[DEFAULT_PLAYER_NAME], {(double)x, (double)y});
}
}
void ABoard::mapEntities(EntityFunction fun) {
for(size_t i = 0; i < entities.size(); i++) {
fun(entities[i]);
}
}
std::vector<std::shared_ptr<Entity>> ABoard::selectEntities(EntityPredicate pred) {
std::vector<std::shared_ptr<Entity>> ret;
mapEntities((EntityFunction)[&ret, pred] (std::shared_ptr<Entity> e) {if (pred(e)) {ret.push_back(e);};});
return ret;
}
std::shared_ptr<Entity> ABoard::findEntity(EntityPredicate pred) {
shared_ptr<Entity> ret = nullptr;
for(size_t i = 0; i < entities.size(); i++) {
if(pred(entities[i])) {
ret = entities[i];
break;
}
}
return ret;
}
shared_ptr<Entity> ABoard::findEntity(size_t id) {
return findEntity([id](shared_ptr<Entity> e) {
return e?e->getId() == id:false;
});
}
shared_ptr<Entity> ABoard::findEntity(rectangle r) {
return findEntity([r](shared_ptr<Entity> e) {
return rectangle(e->getPosition(), e->size).intersects(r);
});
}
std::vector<shared_ptr<Entity>> ABoard::selectEntities(rectangle r) {
std::vector<shared_ptr<Entity>> ret;
for (auto e : entities) {
if (rectangle(e->getPosition(), e->size).intersects(r))
ret.push_back(e);
}
return ret;
}
shared_ptr<Entity> ABoard::findEntity(r2 pos) {
return findEntity(rectangle(pos, {0,0}));
}
void ABoard::pushCommand(std::shared_ptr<Command> command) {
commandMutex.lock();
commands.push(command);
commandMutex.unlock();
}
enum ABoard::BoardState ABoard::getState() {
return state;
}
void ABoard::setState(enum ABoard::BoardState newState) {
state = newState;
}
bool ABoard::isRunning() {
return state == BoardState::running;
}
void ABoard::start() {
if(!started) {
started = true;
th = thread(&ABoard::run, this);
}
}
void ABoard::run() {
while (isRunning()) {
update();
timer.elapse(dt);
}
}
void ABoard::update() {
if(!isRunning()) {
return;
}
frame++;
for(size_t i = 0; i < entities.size();) {
if (entities[i]->getDeletable()) {
game.notifyDeath(entities[i]->getId());
entities.erase(entities.begin() + i);
} else {
i++;
}
}
commandMutex.lock();
while(commands.size() > 0) {
commands.front()->execute(*this);
commands.pop();
}
commandMutex.unlock();
}
SmartBoard::SmartBoard(Game& game, RulesetParser& rulesetParser, ScenarioParser& scenarioParser) :
ABoard(game,
rulesetParser,
scenarioParser.getEscenario().nombre,
scenarioParser.getEscenario().size_x, scenarioParser.getEscenario().size_y,
scenarioParser.getEscenario().max_resources)
{
stringstream message;
message << "Creating SmartBoard " << this;
Logger::getInstance()->writeInformation(message.str());
auto te = scenarioParser.getEscenario();
for(auto& t : te.terrenos) {
setTerrain(t.tipoEntidad, (size_t)t.pos.x, (size_t)t.pos.y);
}
// Relleno con TERRENO_DEFAULT
fillTerrain();
for (auto& jugador : te.jugadores) {
createPlayer(jugador.name, jugador.isHuman);
for (auto& entidadJugador : jugador.entidades) {
if (!createEntity(entidadJugador.tipoEntidad,jugador.name , entidadJugador.pos)) {
Logger::getInstance()->writeInformation("Se crea un protagonista default");
createEntity(PROTAGONISTA_DEFAULT_NOMBRE, jugador.name, { PROTAGONISTA_DEFAULT_POSX, PROTAGONISTA_DEFAULT_POSY });
}
}
}
for(auto& t : te.entidades) {
createEntity(t.tipoEntidad, DEFAULT_PLAYER_NAME, t.pos);
}
// posinicialización
for(auto& f : entityFactories) {
f.second->populate();
}
}
SmartBoard::~SmartBoard() {
stringstream message;
message << "Killing SmartBoard " << this;
Logger::getInstance()->writeInformation(message.str());
}
void SmartBoard::update() {
if(!isRunning()) {
return;
}
ABoard::update();
for(auto& p : players) {
p.second->update();
}
for(auto& e : entities) {
e->update();
}
}
void SmartBoard::execute(StopCommand& command) {
auto e = findEntity(command.entityId);
if (e) {
if (e->owner.getAlive()) {
e->unsetTarget();
}
}
}
void SmartBoard::execute(MoveCommand& command) {
auto e = findEntity(command.entityId);
if (e) {
if (e->owner.getAlive()) {
e->addTarget(command.position);
}
}
}
<commit_msg>Arreglo ABoard.selectEntities(rectangle)<commit_after>#include <sstream>
#include <algorithm>
#include "board.h"
#include "entity.h"
#include "entity_factory.h"
#include "game.h"
#include "../parser_yaml/ruleset_parser.h"
#include "../parser_yaml/scenario_parser.h"
using namespace std;
//-----------------------------------------------------------------------------
ABoard::ABoard(Game& game, RulesetParser& rulesetParser, string name, int sizeX, int sizeY, long maxResources) :
game(game),
dt(rulesetParser.getConfiguracion().dt),
name(name),
sizeX(sizeX), sizeY(sizeY),
maxResources(maxResources),
state(BoardState::building),
started(false)
{
stringstream message;
message << "Creating board " << this << " of size " << sizeX << "x" << sizeY;
Logger::getInstance()->writeInformation(message.str());
terrain.resize(sizeX * sizeY);
createEntityFactory(PROTAGONISTA_DEFAULT_NOMBRE, {PROTAGONISTA_DEFAULT_ANCHO_BASE, PROTAGONISTA_DEFAULT_ALTO_BASE}, VELOCIDAD_PERSONAJE_DEFAULT, ENTIDAD_DEFAULT_SIGHT_RADIUS,true, ENTIDAD_DEFAULT_CAPACITY, ENTIDAD_DEFAULT_BEHAVIOUR);
createEntityFactory(ENTIDAD_DEFAULT_NOMBRE, {ENTIDAD_DEFAULT_ANCHO_BASE, ENTIDAD_DEFAULT_ALTO_BASE}, ENTIDAD_DEFAULT_SPEED, ENTIDAD_DEFAULT_SIGHT_RADIUS, true, ENTIDAD_DEFAULT_CAPACITY, ENTIDAD_DEFAULT_BEHAVIOUR);
createEntityFactory(TERRENO_DEFAULT_NOMBRE, {TERRENO_DEFAULT_ANCHO_BASE, TERRENO_DEFAULT_ALTO_BASE}, TERRENO_DEFAULT_SPEED, TERRENO_DEFAULT_SIGHT_RADIUS, false, TERRENO_DEFAULT_CAPACITY, TERRENO_DEFAULT_BEHAVIOUR);
createPlayer(DEFAULT_PLAYER_NAME, false);
for(auto& t : rulesetParser.getTiposUnidades()) {
createEntityFactory(t.nombre, {t.ancho_base, t.alto_base}, t.speed, t.sight_radius, t.solid, t.capacity, t.behaviour);
}
for (auto& t : rulesetParser.getTiposEstructuras()) {
createEntityFactory(t.nombre, { t.ancho_base, t.alto_base }, t.speed, t.sight_radius, t.solid, t.capacity, t.behaviour);
}
for(auto& t : rulesetParser.getTiposTerrenos()) {
createEntityFactory(t.nombre, {t.ancho_base, t.alto_base}, t.speed, t.sight_radius, t.solid, t.capacity, t.behaviour);
}
for (auto& t : rulesetParser.getTiposRecursos()) {
createEntityFactory(t.nombre, { t.ancho_base, t.alto_base }, t.speed, t.sight_radius, t.solid, t.capacity, t.behaviour);
}
state = BoardState::running;
}
ABoard::~ABoard() {
if(started) {
th.join();
}
}
void ABoard::fillTerrain() {
for(size_t x = 0; x < sizeX; x++) {
for(size_t y = 0; y < sizeY; y++) {
if (!getTerrain(x, y)) {
setTerrain(TERRENO_DEFAULT_NOMBRE, x, y);
}
}
}
}
std::vector<std::shared_ptr<Player>> ABoard::getPlayers() {
std::vector<std::shared_ptr<Player>> ret;
for(auto& i : players) {
ret.push_back(i.second);
}
return ret;
}
shared_ptr<Player> ABoard::createPlayer(string name, bool human) {
if (players.find(name) != players.end()) {
Logger::getInstance()->writeError("Jugador " + name + " ya existe");
return nullptr;
}
return (players[name] = make_shared<Player>(*this, name, human));
}
Player& ABoard::findPlayer(string name) {
return *(players.find(name)->second);
}
shared_ptr<Entity> ABoard::createEntity(string name, string playerName, r2 position) {
if (entityFactories.find(name) == entityFactories.end()) {
Logger::getInstance()->writeError("No existe el tipo de entidad " + name);
return nullptr;
}
auto factory = entityFactories[name];
if (findEntity(rectangle(position, factory->size))) {
Logger::getInstance()->writeError("Lugar ya ocupado para entidad " + name);
return nullptr;
}
auto pEntity = factory->createEntity(*players[playerName], position);
entities.push_back(pEntity);
return pEntity;
}
shared_ptr<EntityFactory> ABoard::createEntityFactory(string name, r2 size, double speed, int sight_radius, bool solid, int capacity, std::string behaviour) {
shared_ptr<EntityFactory> pFactory;
if (behaviour == "resource") {
pFactory = make_shared<ResourceFactory>(name, size, sight_radius, solid, capacity, *this);
}else if (behaviour == "terrain") {
pFactory = make_shared<TerrainFactory>(name, size, sight_radius, solid, *this);
}else if(behaviour == "unit") {
pFactory = make_shared<UnitFactory>(name, size, speed, sight_radius, solid, *this);
} else if(behaviour == "worker") {
pFactory = make_shared<WorkerFactory>(name, size, speed, sight_radius, solid, *this);
} else if(behaviour == "king") {
pFactory = make_shared<KingFactory>(name, size, speed, sight_radius, solid, *this);
} else if (behaviour == "building") {
pFactory = make_shared<BuildingFactory>(name, size, sight_radius, solid, *this);
} else if(behaviour == "producer_building") {
//TODO: products
pFactory = make_shared<ProducerBuildingFactory>(name, size, sight_radius, solid, *this);
} else if(behaviour == "town_center") {
//TODO: products
pFactory = make_shared<TownCenterFactory>(name, size, sight_radius, solid, *this);
} else if(behaviour == "flag") {
pFactory = make_shared<FlagFactory>(name, size, sight_radius, solid, *this);
}
else {
pFactory = make_shared<UnitFactory>(name, size, speed, sight_radius, solid, *this);
}
entityFactories[name] = pFactory;
return pFactory;
}
shared_ptr<Entity> ABoard::getTerrain(size_t x, size_t y) {
if (x >= sizeX || y >= sizeY) {
return nullptr;
}
return terrain[(sizeX*y) + x];
}
void ABoard::setTerrain(string name, size_t x, size_t y) {
if (entityFactories.find(name) == entityFactories.end()) {
Logger::getInstance()->writeError("No existe el tipo de entidad " + name);
} else {
terrain[(sizeX*y) + x] = entityFactories[name]->createEntity(*players[DEFAULT_PLAYER_NAME], {(double)x, (double)y});
}
}
void ABoard::mapEntities(EntityFunction fun) {
for(size_t i = 0; i < entities.size(); i++) {
fun(entities[i]);
}
}
std::vector<std::shared_ptr<Entity>> ABoard::selectEntities(EntityPredicate pred) {
std::vector<std::shared_ptr<Entity>> ret;
mapEntities((EntityFunction)[&ret, pred] (std::shared_ptr<Entity> e) {if (pred(e)) {ret.push_back(e);};});
return ret;
}
std::vector<shared_ptr<Entity>> ABoard::selectEntities(rectangle r) {
return selectEntities([r](shared_ptr<Entity> e) {
return rectangle(e->getPosition(), e->size).intersects(r)
});
}
std::shared_ptr<Entity> ABoard::findEntity(EntityPredicate pred) {
shared_ptr<Entity> ret = nullptr;
for(size_t i = 0; i < entities.size(); i++) {
if(pred(entities[i])) {
ret = entities[i];
break;
}
}
return ret;
}
shared_ptr<Entity> ABoard::findEntity(size_t id) {
return findEntity([id](shared_ptr<Entity> e) {
return e?e->getId() == id:false;
});
}
shared_ptr<Entity> ABoard::findEntity(rectangle r) {
return findEntity([r](shared_ptr<Entity> e) {
return rectangle(e->getPosition(), e->size).intersects(r);
});
}
shared_ptr<Entity> ABoard::findEntity(r2 pos) {
return findEntity(rectangle(pos, {0,0}));
}
void ABoard::pushCommand(std::shared_ptr<Command> command) {
commandMutex.lock();
commands.push(command);
commandMutex.unlock();
}
enum ABoard::BoardState ABoard::getState() {
return state;
}
void ABoard::setState(enum ABoard::BoardState newState) {
state = newState;
}
bool ABoard::isRunning() {
return state == BoardState::running;
}
void ABoard::start() {
if(!started) {
started = true;
th = thread(&ABoard::run, this);
}
}
void ABoard::run() {
while (isRunning()) {
update();
timer.elapse(dt);
}
}
void ABoard::update() {
if(!isRunning()) {
return;
}
frame++;
for(size_t i = 0; i < entities.size();) {
if (entities[i]->getDeletable()) {
game.notifyDeath(entities[i]->getId());
entities.erase(entities.begin() + i);
} else {
i++;
}
}
commandMutex.lock();
while(commands.size() > 0) {
commands.front()->execute(*this);
commands.pop();
}
commandMutex.unlock();
}
SmartBoard::SmartBoard(Game& game, RulesetParser& rulesetParser, ScenarioParser& scenarioParser) :
ABoard(game,
rulesetParser,
scenarioParser.getEscenario().nombre,
scenarioParser.getEscenario().size_x, scenarioParser.getEscenario().size_y,
scenarioParser.getEscenario().max_resources)
{
stringstream message;
message << "Creating SmartBoard " << this;
Logger::getInstance()->writeInformation(message.str());
auto te = scenarioParser.getEscenario();
for(auto& t : te.terrenos) {
setTerrain(t.tipoEntidad, (size_t)t.pos.x, (size_t)t.pos.y);
}
// Relleno con TERRENO_DEFAULT
fillTerrain();
for (auto& jugador : te.jugadores) {
createPlayer(jugador.name, jugador.isHuman);
for (auto& entidadJugador : jugador.entidades) {
if (!createEntity(entidadJugador.tipoEntidad,jugador.name , entidadJugador.pos)) {
Logger::getInstance()->writeInformation("Se crea un protagonista default");
createEntity(PROTAGONISTA_DEFAULT_NOMBRE, jugador.name, { PROTAGONISTA_DEFAULT_POSX, PROTAGONISTA_DEFAULT_POSY });
}
}
}
for(auto& t : te.entidades) {
createEntity(t.tipoEntidad, DEFAULT_PLAYER_NAME, t.pos);
}
// posinicialización
for(auto& f : entityFactories) {
f.second->populate();
}
}
SmartBoard::~SmartBoard() {
stringstream message;
message << "Killing SmartBoard " << this;
Logger::getInstance()->writeInformation(message.str());
}
void SmartBoard::update() {
if(!isRunning()) {
return;
}
ABoard::update();
for(auto& p : players) {
p.second->update();
}
for(auto& e : entities) {
e->update();
}
}
void SmartBoard::execute(StopCommand& command) {
auto e = findEntity(command.entityId);
if (e) {
if (e->owner.getAlive()) {
e->unsetTarget();
}
}
}
void SmartBoard::execute(MoveCommand& command) {
auto e = findEntity(command.entityId);
if (e) {
if (e->owner.getAlive()) {
e->addTarget(command.position);
}
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: AccessibleContextBase.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: af $ $Date: 2002-02-08 16:59:32 $
*
* 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): _______________________________________
*
*
************************************************************************/
#include "AccessibleContextBase.hxx"
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_
#include <drafts/com/sun/star/accessibility/AccessibleRole.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYCHANGEEVENT_HPP_
#include <com/sun/star/beans/PropertyChangeEvent.hpp>
#endif
#ifndef _RTL_UUID_H_
#include <rtl/uuid.h>
#endif
using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::drafts::com::sun::star::accessibility;
namespace accessibility {
//===== internal ============================================================
AccessibleContextBase::AccessibleContextBase (
const uno::Reference<XAccessible>& rxParent,
const sal_Int16 aRole)
:
maRole(aRole),
mxParent(rxParent)
{
}
AccessibleContextBase::~AccessibleContextBase(void)
{
}
//===== XAccessible =========================================================
uno::Reference< XAccessibleContext> SAL_CALL
AccessibleContextBase::getAccessibleContext (void)
throw (uno::RuntimeException)
{
return this;
}
//===== XAccessibleContext ==================================================
/** No children.
*/
sal_Int32 SAL_CALL
AccessibleContextBase::getAccessibleChildCount (void)
throw (uno::RuntimeException)
{
return 0;
}
/** Forward the request to the shape. Return the requested shape or throw
an exception for a wrong index.
*/
uno::Reference<XAccessible> SAL_CALL
AccessibleContextBase::getAccessibleChild (long nIndex)
throw (::com::sun::star::uno::RuntimeException)
{
throw lang::IndexOutOfBoundsException (
::rtl::OUString::createFromAscii ("no child with index " + nIndex),
NULL);
}
uno::Reference<XAccessible> SAL_CALL
AccessibleContextBase::getAccessibleParent (void)
throw (::com::sun::star::uno::RuntimeException)
{
return mxParent;
}
sal_Int32 SAL_CALL
AccessibleContextBase::getAccessibleIndexInParent (void)
throw (::com::sun::star::uno::RuntimeException)
{
// Use a simple but slow solution for now. Optimize later.
// Iterate over all the parent's children and search for this object.
if (mxParent.is())
{
uno::Reference<XAccessibleContext> xParentContext (
mxParent->getAccessibleContext());
if (xParentContext.is())
{
sal_Int32 nChildCount = xParentContext->getAccessibleChildCount();
for (sal_Int32 i=0; i<nChildCount; i++)
{
uno::Reference<XAccessible> xChild (xParentContext->getAccessibleChild (i));
if (xChild.is())
{
uno::Reference<XAccessibleContext> xChildContext = xChild->getAccessibleContext();
if (xChildContext == (XAccessibleContext*)this)
return i;
}
}
}
}
// Return -1 to indicate that this object's parent does not know about the
// object.
return -1;
}
sal_Int16 SAL_CALL
AccessibleContextBase::getAccessibleRole (void)
throw (::com::sun::star::uno::RuntimeException)
{
return maRole;
}
::rtl::OUString SAL_CALL
AccessibleContextBase::getAccessibleDescription (void)
throw (::com::sun::star::uno::RuntimeException)
{
return msDescription;
}
OUString SAL_CALL
AccessibleContextBase::getAccessibleName (void)
throw (::com::sun::star::uno::RuntimeException)
{
return msName;
}
/** Return empty reference to indicate that the relation set is not
supported.
*/
uno::Reference<XAccessibleRelationSet> SAL_CALL
AccessibleContextBase::getAccessibleRelationSet (void)
throw (::com::sun::star::uno::RuntimeException)
{
return uno::Reference<XAccessibleRelationSet>();
}
/** Create the set of states the object is in. Possible states are:
EDITABLE
ENABLED
SHOWING
VISIBLE
For now, return only an empty reference and wait for an implementation of
the XAccessibleStateSet interface.
*/
uno::Reference<XAccessibleStateSet> SAL_CALL
AccessibleContextBase::getAccessibleStateSet (void)
throw (::com::sun::star::uno::RuntimeException)
{
return uno::Reference<XAccessibleStateSet>();
}
lang::Locale SAL_CALL
AccessibleContextBase::getLocale (void)
throw (IllegalAccessibleComponentStateException,
::com::sun::star::uno::RuntimeException)
{
if (mxParent.is())
{
uno::Reference<XAccessibleContext> xParentContext (
mxParent->getAccessibleContext());
if (xParentContext.is())
return xParentContext->getLocale ();
}
// No locale and no parent. Therefore throw exception to indicate this
// cluelessness.
throw IllegalAccessibleComponentStateException ();
}
void SAL_CALL
AccessibleContextBase::addPropertyChangeListener (
const uno::Reference<beans::XPropertyChangeListener>& xListener)
throw (::com::sun::star::uno::RuntimeException)
{
if (xListener.is())
{
// Make sure that the given listener is not already a member of the
// listener list.
sal_Bool bFound(sal_False);
PropertyChangeListenerListType::iterator aItr = mxPropertyChangeListeners.begin();
while (!bFound && (aItr != mxPropertyChangeListeners.end()))
if (*aItr == xListener)
bFound = sal_True;
else
aItr++;
if (!bFound)
{
// Append the new listener to the end of the listener list.
::vos::OGuard aGuard (maMutex);
mxPropertyChangeListeners.push_back (xListener);
}
}
}
void SAL_CALL
AccessibleContextBase::removePropertyChangeListener (
const uno::Reference<beans::XPropertyChangeListener>& xListener)
throw (::com::sun::star::uno::RuntimeException)
{
if (xListener.is())
{
// Find the listener to remove by iterating over the whole list.
sal_Bool bFound(sal_False);
PropertyChangeListenerListType::iterator aItr = mxPropertyChangeListeners.begin();
while(!bFound && (aItr != mxPropertyChangeListeners.end()))
{
if (*aItr == xListener)
{
// Remove the listener and leave the iteration loop.
::vos::OGuard aGuard (maMutex);
mxPropertyChangeListeners.erase (aItr);
bFound = sal_True;
}
else
aItr++;
}
}
}
//===== XServiceInfo ========================================================
::rtl::OUString SAL_CALL
AccessibleContextBase::getImplementationName (void)
throw (::com::sun::star::uno::RuntimeException)
{
return OUString(RTL_CONSTASCII_USTRINGPARAM ("AccessibleContextBase"));
}
sal_Bool SAL_CALL
AccessibleContextBase::supportsService (const OUString& sServiceName)
throw (::com::sun::star::uno::RuntimeException)
{
// Iterate over all supported service names and return true if on of them
// matches the given name.
uno::Sequence< ::rtl::OUString> aSupportedServices (
getSupportedServiceNames ());
for (int i=0; i<aSupportedServices.getLength(); i++)
if (sServiceName == aSupportedServices[i])
return sal_True;
return sal_False;
}
uno::Sequence< ::rtl::OUString> SAL_CALL
AccessibleContextBase::getSupportedServiceNames (void)
throw (::com::sun::star::uno::RuntimeException)
{
const OUString sServiceName (RTL_CONSTASCII_USTRINGPARAM (
"drafts.com.sun.star.accessibility.AccessibleContext"));
return uno::Sequence<OUString> (&sServiceName, 1);
}
//===== XTypeProvider =======================================================
uno::Sequence< ::com::sun::star::uno::Type>
AccessibleContextBase::getTypes (void)
throw (::com::sun::star::uno::RuntimeException)
{
const ::com::sun::star::uno::Type aTypeList[] = {
::getCppuType((const uno::Reference<
XAccessible>*)0),
::getCppuType((const uno::Reference<
XAccessibleContext>*)0),
::getCppuType((const uno::Reference<
lang::XServiceInfo>*)0),
::getCppuType((const uno::Reference<
lang::XTypeProvider>*)0),
::getCppuType((const uno::Reference<
lang::XServiceName>*)0)
};
::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type>
aTypeSequence (aTypeList, 5);
return aTypeSequence;
}
uno::Sequence<sal_Int8> SAL_CALL
AccessibleContextBase::getImplementationId (void)
throw (::com::sun::star::uno::RuntimeException)
{
static uno::Sequence<sal_Int8> aId;
if (aId.getLength() == 0)
{
::vos::OGuard aGuard (maMutex);
aId.realloc (16);
rtl_createUuid ((sal_uInt8 *)aId.getArray(), 0, sal_True);
}
return aId;
}
//===== XServiceName ========================================================
::rtl::OUString
AccessibleContextBase::getServiceName (void)
throw (::com::sun::star::uno::RuntimeException)
{
return OUString(RTL_CONSTASCII_USTRINGPARAM (
"drafts.com.sun.star.accessibility.AccessibleContext"));
}
//===== internal ============================================================
void
AccessibleContextBase::setAccessibleDescription (const ::rtl::OUString& rDescription)
throw (uno::RuntimeException)
{
if (msDescription != rDescription)
{
uno::Any aOldValue, aNewValue;
aOldValue <<= msDescription;
aNewValue <<= rDescription;
msDescription = rDescription;
CommitChange(OUString::createFromAscii ("AccessibleDescription"), aNewValue, aOldValue);
}
}
void
AccessibleContextBase::setAccessibleName (const ::rtl::OUString& rName)
throw (uno::RuntimeException)
{
if (msName != rName)
{
uno::Any aOldValue, aNewValue;
aOldValue <<= msName;
aNewValue <<= rName;
msName = rName;
CommitChange(OUString::createFromAscii ("AccessibleName"), aNewValue, aOldValue);
}
}
::rtl::OUString AccessibleContextBase::createAccessibleDescription (void)
throw (::com::sun::star::uno::RuntimeException)
{
return ::rtl::OUString::createFromAscii ("Empty Description");
}
::rtl::OUString AccessibleContextBase::createAccessibleName (void)
throw (::com::sun::star::uno::RuntimeException)
{
return ::rtl::OUString::createFromAscii ("Empty Name");
}
void AccessibleContextBase::CommitChange(const rtl::OUString& rPropertyName,
const uno::Any& rNewValue,
const uno::Any& rOldValue)
{
beans::PropertyChangeEvent aEvent;
aEvent.PropertyName = rPropertyName;
aEvent.Further = sal_False;
aEvent.PropertyHandle = -1;
aEvent.OldValue = rOldValue;
aEvent.NewValue = rNewValue;
// Call all listeners.
PropertyChangeListenerListType::iterator I;
for (I=mxPropertyChangeListeners.begin();
I!=mxPropertyChangeListeners.end(); I++)
{
(*I)->propertyChange (aEvent);
}
}
} // end of namespace accessibility
<commit_msg>#65293# compiler error<commit_after>/*************************************************************************
*
* $RCSfile: AccessibleContextBase.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: vg $ $Date: 2002-02-08 17:35:56 $
*
* 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): _______________________________________
*
*
************************************************************************/
#include "AccessibleContextBase.hxx"
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_
#include <drafts/com/sun/star/accessibility/AccessibleRole.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYCHANGEEVENT_HPP_
#include <com/sun/star/beans/PropertyChangeEvent.hpp>
#endif
#ifndef _RTL_UUID_H_
#include <rtl/uuid.h>
#endif
using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::drafts::com::sun::star::accessibility;
namespace accessibility {
//===== internal ============================================================
AccessibleContextBase::AccessibleContextBase (
const uno::Reference<XAccessible>& rxParent,
const sal_Int16 aRole)
:
maRole(aRole),
mxParent(rxParent)
{
}
AccessibleContextBase::~AccessibleContextBase(void)
{
}
//===== XAccessible =========================================================
uno::Reference< XAccessibleContext> SAL_CALL
AccessibleContextBase::getAccessibleContext (void)
throw (uno::RuntimeException)
{
return this;
}
//===== XAccessibleContext ==================================================
/** No children.
*/
sal_Int32 SAL_CALL
AccessibleContextBase::getAccessibleChildCount (void)
throw (uno::RuntimeException)
{
return 0;
}
/** Forward the request to the shape. Return the requested shape or throw
an exception for a wrong index.
*/
uno::Reference<XAccessible> SAL_CALL
AccessibleContextBase::getAccessibleChild (long nIndex)
throw (::com::sun::star::uno::RuntimeException)
{
throw lang::IndexOutOfBoundsException (
::rtl::OUString::createFromAscii ("no child with index " + nIndex),
NULL);
}
uno::Reference<XAccessible> SAL_CALL
AccessibleContextBase::getAccessibleParent (void)
throw (::com::sun::star::uno::RuntimeException)
{
return mxParent;
}
sal_Int32 SAL_CALL
AccessibleContextBase::getAccessibleIndexInParent (void)
throw (::com::sun::star::uno::RuntimeException)
{
// Use a simple but slow solution for now. Optimize later.
// Iterate over all the parent's children and search for this object.
if (mxParent.is())
{
uno::Reference<XAccessibleContext> xParentContext (
mxParent->getAccessibleContext());
if (xParentContext.is())
{
sal_Int32 nChildCount = xParentContext->getAccessibleChildCount();
for (sal_Int32 i=0; i<nChildCount; i++)
{
uno::Reference<XAccessible> xChild (xParentContext->getAccessibleChild (i));
if (xChild.is())
{
uno::Reference<XAccessibleContext> xChildContext = xChild->getAccessibleContext();
if (xChildContext == (XAccessibleContext*)this)
return i;
}
}
}
}
// Return -1 to indicate that this object's parent does not know about the
// object.
return -1;
}
sal_Int16 SAL_CALL
AccessibleContextBase::getAccessibleRole (void)
throw (::com::sun::star::uno::RuntimeException)
{
return maRole;
}
::rtl::OUString SAL_CALL
AccessibleContextBase::getAccessibleDescription (void)
throw (::com::sun::star::uno::RuntimeException)
{
return msDescription;
}
OUString SAL_CALL
AccessibleContextBase::getAccessibleName (void)
throw (::com::sun::star::uno::RuntimeException)
{
return msName;
}
/** Return empty reference to indicate that the relation set is not
supported.
*/
uno::Reference<XAccessibleRelationSet> SAL_CALL
AccessibleContextBase::getAccessibleRelationSet (void)
throw (::com::sun::star::uno::RuntimeException)
{
return uno::Reference<XAccessibleRelationSet>();
}
/** Create the set of states the object is in. Possible states are:
EDITABLE
ENABLED
SHOWING
VISIBLE
For now, return only an empty reference and wait for an implementation of
the XAccessibleStateSet interface.
*/
uno::Reference<XAccessibleStateSet> SAL_CALL
AccessibleContextBase::getAccessibleStateSet (void)
throw (::com::sun::star::uno::RuntimeException)
{
return uno::Reference<XAccessibleStateSet>();
}
lang::Locale SAL_CALL
AccessibleContextBase::getLocale (void)
throw (IllegalAccessibleComponentStateException,
::com::sun::star::uno::RuntimeException)
{
if (mxParent.is())
{
uno::Reference<XAccessibleContext> xParentContext (
mxParent->getAccessibleContext());
if (xParentContext.is())
return xParentContext->getLocale ();
}
// No locale and no parent. Therefore throw exception to indicate this
// cluelessness.
throw IllegalAccessibleComponentStateException ();
}
void SAL_CALL
AccessibleContextBase::addPropertyChangeListener (
const uno::Reference<beans::XPropertyChangeListener>& xListener)
throw (::com::sun::star::uno::RuntimeException)
{
if (xListener.is())
{
// Make sure that the given listener is not already a member of the
// listener list.
sal_Bool bFound(sal_False);
PropertyChangeListenerListType::iterator aItr = mxPropertyChangeListeners.begin();
while (!bFound && (aItr != mxPropertyChangeListeners.end()))
if (*aItr == xListener)
bFound = sal_True;
else
aItr++;
if (!bFound)
{
// Append the new listener to the end of the listener list.
::vos::OGuard aGuard (maMutex);
mxPropertyChangeListeners.push_back (xListener);
}
}
}
void SAL_CALL
AccessibleContextBase::removePropertyChangeListener (
const uno::Reference<beans::XPropertyChangeListener>& xListener)
throw (::com::sun::star::uno::RuntimeException)
{
if (xListener.is())
{
// Find the listener to remove by iterating over the whole list.
sal_Bool bFound(sal_False);
PropertyChangeListenerListType::iterator aItr = mxPropertyChangeListeners.begin();
while(!bFound && (aItr != mxPropertyChangeListeners.end()))
{
if (*aItr == xListener)
{
// Remove the listener and leave the iteration loop.
::vos::OGuard aGuard (maMutex);
mxPropertyChangeListeners.erase (aItr);
bFound = sal_True;
}
else
aItr++;
}
}
}
//===== XServiceInfo ========================================================
::rtl::OUString SAL_CALL
AccessibleContextBase::getImplementationName (void)
throw (::com::sun::star::uno::RuntimeException)
{
return OUString(RTL_CONSTASCII_USTRINGPARAM ("AccessibleContextBase"));
}
sal_Bool SAL_CALL
AccessibleContextBase::supportsService (const OUString& sServiceName)
throw (::com::sun::star::uno::RuntimeException)
{
// Iterate over all supported service names and return true if on of them
// matches the given name.
uno::Sequence< ::rtl::OUString> aSupportedServices (
getSupportedServiceNames ());
for (int i=0; i<aSupportedServices.getLength(); i++)
if (sServiceName == aSupportedServices[i])
return sal_True;
return sal_False;
}
uno::Sequence< ::rtl::OUString> SAL_CALL
AccessibleContextBase::getSupportedServiceNames (void)
throw (::com::sun::star::uno::RuntimeException)
{
const OUString sServiceName (RTL_CONSTASCII_USTRINGPARAM ("drafts.com.sun.star.accessibility.AccessibleContext"));
return uno::Sequence<OUString> (&sServiceName, 1);
}
//===== XTypeProvider =======================================================
uno::Sequence< ::com::sun::star::uno::Type>
AccessibleContextBase::getTypes (void)
throw (::com::sun::star::uno::RuntimeException)
{
const ::com::sun::star::uno::Type aTypeList[] = {
::getCppuType((const uno::Reference<
XAccessible>*)0),
::getCppuType((const uno::Reference<
XAccessibleContext>*)0),
::getCppuType((const uno::Reference<
lang::XServiceInfo>*)0),
::getCppuType((const uno::Reference<
lang::XTypeProvider>*)0),
::getCppuType((const uno::Reference<
lang::XServiceName>*)0)
};
::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type>
aTypeSequence (aTypeList, 5);
return aTypeSequence;
}
uno::Sequence<sal_Int8> SAL_CALL
AccessibleContextBase::getImplementationId (void)
throw (::com::sun::star::uno::RuntimeException)
{
static uno::Sequence<sal_Int8> aId;
if (aId.getLength() == 0)
{
::vos::OGuard aGuard (maMutex);
aId.realloc (16);
rtl_createUuid ((sal_uInt8 *)aId.getArray(), 0, sal_True);
}
return aId;
}
//===== XServiceName ========================================================
::rtl::OUString
AccessibleContextBase::getServiceName (void)
throw (::com::sun::star::uno::RuntimeException)
{
return OUString(RTL_CONSTASCII_USTRINGPARAM ("drafts.com.sun.star.accessibility.AccessibleContext"));
}
//===== internal ============================================================
void
AccessibleContextBase::setAccessibleDescription (const ::rtl::OUString& rDescription)
throw (uno::RuntimeException)
{
if (msDescription != rDescription)
{
uno::Any aOldValue, aNewValue;
aOldValue <<= msDescription;
aNewValue <<= rDescription;
msDescription = rDescription;
CommitChange(OUString::createFromAscii ("AccessibleDescription"), aNewValue, aOldValue);
}
}
void
AccessibleContextBase::setAccessibleName (const ::rtl::OUString& rName)
throw (uno::RuntimeException)
{
if (msName != rName)
{
uno::Any aOldValue, aNewValue;
aOldValue <<= msName;
aNewValue <<= rName;
msName = rName;
CommitChange(OUString::createFromAscii ("AccessibleName"), aNewValue, aOldValue);
}
}
::rtl::OUString AccessibleContextBase::createAccessibleDescription (void)
throw (::com::sun::star::uno::RuntimeException)
{
return ::rtl::OUString::createFromAscii ("Empty Description");
}
::rtl::OUString AccessibleContextBase::createAccessibleName (void)
throw (::com::sun::star::uno::RuntimeException)
{
return ::rtl::OUString::createFromAscii ("Empty Name");
}
void AccessibleContextBase::CommitChange(const rtl::OUString& rPropertyName,
const uno::Any& rNewValue,
const uno::Any& rOldValue)
{
beans::PropertyChangeEvent aEvent;
aEvent.PropertyName = rPropertyName;
aEvent.Further = sal_False;
aEvent.PropertyHandle = -1;
aEvent.OldValue = rOldValue;
aEvent.NewValue = rNewValue;
// Call all listeners.
PropertyChangeListenerListType::iterator I;
for (I=mxPropertyChangeListeners.begin();
I!=mxPropertyChangeListeners.end(); I++)
{
(*I)->propertyChange (aEvent);
}
}
} // end of namespace accessibility
<|endoftext|>
|
<commit_before>/*
* Copyright 2011, 2012 Esrille Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "StackingContext.h"
// TODO: Do not inlcude GL in this file
#include <GL/gl.h>
#include <GL/glu.h>
#include <new>
#include <iostream>
#include "Box.h"
#include "ViewCSSImp.h"
namespace org { namespace w3c { namespace dom { namespace bootstrap {
StackingContext* StackingContext::removeChild(StackingContext* item)
{
StackingContext* next = item->nextSibling;
StackingContext* prev = item->previousSibling;
if (!next)
lastChild = prev;
else
next->previousSibling = prev;
if (!prev)
firstChild = next;
else
prev->nextSibling = next;
item->parent = item->nextSibling = item->previousSibling = 0;
--childCount;
return item;
}
StackingContext* StackingContext::insertBefore(StackingContext* item, StackingContext* after)
{
if (!after)
return appendChild(item);
item->previousSibling = after->previousSibling;
item->nextSibling = after;
after->previousSibling = item;
if (!item->previousSibling)
firstChild = item;
else
item->previousSibling->nextSibling = item;
item->parent = this;
++childCount;
return item;
}
StackingContext* StackingContext::appendChild(StackingContext* item)
{
StackingContext* prev = lastChild;
if (!prev)
firstChild = item;
else
prev->nextSibling = item;
item->previousSibling = prev;
item->nextSibling = 0;
lastChild = item;
item->parent = this;
++childCount;
return item;
}
StackingContext::StackingContext(bool auto_, int zIndex, CSSStyleDeclarationImp* style) :
count(0),
style(style),
auto_(auto_),
zIndex(zIndex),
parent(0),
firstChild(0),
lastChild(0),
previousSibling(0),
nextSibling(0),
childCount(0),
positioned(0),
firstBase(0),
lastBase(0),
clipBox(0),
firstFloat(0),
lastFloat(0),
currentFloat(0)
{
}
StackingContext::~StackingContext()
{
if (parent)
parent->removeChild(this);
while (0 < childCount) {
StackingContext* child = removeChild(firstChild);
delete child;
}
}
StackingContext* StackingContext::addContext(bool auto_, int zIndex, CSSStyleDeclarationImp* style)
{
StackingContext* item = new(std::nothrow) StackingContext(auto_, zIndex, style);
if (item)
insertContext(item);
return item;
}
void StackingContext::insertContext(StackingContext* item)
{
assert(item);
if (isAuto()) {
parent->insertContext(item);
item->positioned = this;
return;
}
// TODO: Preserve the order in the DOM tree
StackingContext* after = 0;
for (auto i = getFirstChild(); i; i = i->getNextSibling()) {
if (item->zIndex < i->zIndex) {
after = i;
break;
}
}
insertBefore(item, after);
item->positioned = this;
}
void StackingContext::setZIndex(bool auto_, int index)
{
if (isAuto() == auto_ && zIndex == index)
return;
this->auto_ = auto_;
zIndex = index;
if (parent) {
parent->removeChild(this);
positioned->insertContext(this);
// TODO: Reorganize child contexts, too!
}
}
void StackingContext::clip(StackingContext* s, float relativeX, float relativeY)
{
for (Block* clip = s->clipBox; clip && clip != s->positioned->clipBox; clip = clip->clipBox) {
if (clip->stackingContext == s)
continue;
if (clip->style->overflow.getValue() != CSSOverflowValueImp::Visible) { // TODO: check this
Element element = interface_cast<Element>(clip->node);
glTranslatef(-element.getScrollLeft(), -element.getScrollTop(), 0.0f);
if (clip != s->clipBox) {
clipLeft -= element.getScrollLeft();
clipTop -= element.getScrollTop();
}
}
if (clipWidth == HUGE_VALF) {
clipLeft = clip->x + clip->marginLeft + clip->borderLeft - relativeX;
clipTop = clip->y + clip->marginTop + clip->borderTop - relativeY;
clipWidth = clip->getPaddingWidth();
clipHeight = clip->getPaddingHeight();
} else {
Box::unionRect(clipLeft, clipTop, clipWidth, clipHeight,
clip->x + clip->marginLeft + clip->borderLeft - relativeX,
clip->y + clip->marginTop + clip->borderTop - relativeY,
clip->getPaddingWidth(), clip->getPaddingHeight());
}
}
}
bool StackingContext::resolveRelativeOffset(float& x, float &y)
{
bool result = false;
for (StackingContext* s = this; s != parent; s = s->positioned) {
assert(s->style);
result |= s->style->resolveRelativeOffset(x, y);
clip(s, x, y);
}
return result;
}
void StackingContext::render(ViewCSSImp* view)
{
clipLeft = clipTop = 0.0f;
clipWidth = clipHeight = HUGE_VALF;
glPushMatrix();
float relativeX = 0.0f;
float relativeY = 0.0f;
if (resolveRelativeOffset(relativeX, relativeY))
glTranslatef(relativeX, relativeY, 0.0f);
if (clipWidth != HUGE_VALF && clipHeight != HUGE_VALF)
view->clip(clipLeft, clipTop, clipWidth, clipHeight);
currentFloat = firstFloat = lastFloat = 0;
for (Box* base = firstBase; base; base = base->nextBase) {
glPushMatrix();
Block* block = dynamic_cast<Block*>(base);
unsigned overflow = CSSOverflowValueImp::Visible;
if (block)
overflow = block->renderBegin(view);
StackingContext* childContext = getFirstChild();
for (; childContext && childContext->zIndex < 0; childContext = childContext->getNextSibling())
childContext->render(view);
if (block)
block->renderNonInline(view, this);
else
base->render(view, this);
for (currentFloat = firstFloat; currentFloat; currentFloat = currentFloat->nextBase)
currentFloat->render(view, this);
if (block)
block->renderInline(view, this);
for (; childContext; childContext = childContext->getNextSibling())
childContext->render(view);
if (block) {
if (0.0f < block->getOutlineWidth())
block->renderOutline(view, block->x, block->y + block->getTopBorderEdge());
block->renderEnd(view, overflow);
}
glPopMatrix();
}
if (clipWidth != HUGE_VALF && clipHeight != HUGE_VALF)
view->unclip(clipLeft, clipTop, clipWidth, clipHeight);
glPopMatrix();
}
void StackingContext::addBase(Box* box)
{
#ifndef NDEBUG
for (Box* i = firstBase; i; i = i->nextBase)
assert(box != i);
#endif
if (!firstBase)
firstBase = lastBase = box;
else {
lastBase->nextBase = box;
lastBase = box;
}
box->nextBase = 0;
}
void StackingContext::addBox(Box* box, Box* parentBox)
{
assert(parentBox);
if (parentBox->stackingContext != this)
addBase(box);
}
void StackingContext::addFloat(Box* box)
{
#ifndef NDEBUG
for (Box* i = firstFloat; i; i = i->nextBase) {
assert(box != i);
}
#endif
if (currentFloat) {
box->nextBase = currentFloat->nextBase;
currentFloat->nextBase = box;
return;
}
if (!firstFloat)
firstFloat = lastFloat = box;
else {
lastFloat->nextBase = box;
lastFloat = box;
}
box->nextBase = 0;
}
void StackingContext::removeBox(Box* box)
{
Box* p = 0;
for (Box* i = firstBase; i ; p = i, i = i->nextBase) {
if (i == box) {
if (!p)
firstBase = i->nextBase;
else
p->nextBase = i->nextBase;
if (lastBase == box)
lastBase = p;
break;
}
}
}
void StackingContext::layOutAbsolute(ViewCSSImp* view)
{
for (Box* base = firstBase; base; base = base->nextBase) {
Block* block = dynamic_cast<Block*>(base);
if (!block || !block->isAbsolutelyPositioned())
continue;
block->layOutAbsolute(view);
block->resolveXY(view, block->x, block->y, block->clipBox);
}
for (StackingContext* childContext = getFirstChild(); childContext; childContext = childContext->getNextSibling())
childContext->layOutAbsolute(view);
}
void StackingContext::dump(std::string indent)
{
std::cout << indent << "z-index: " << zIndex << '\n';
indent += " ";
for (auto child = getFirstChild(); child; child = child->getNextSibling())
child->dump(indent);
}
}}}} // org::w3c::dom::bootstrap
<commit_msg>(StackingContext::addBase) : Add a runtime check<commit_after>/*
* Copyright 2011, 2012 Esrille Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "StackingContext.h"
// TODO: Do not inlcude GL in this file
#include <GL/gl.h>
#include <GL/glu.h>
#include <new>
#include <iostream>
#include "Box.h"
#include "ViewCSSImp.h"
namespace org { namespace w3c { namespace dom { namespace bootstrap {
StackingContext* StackingContext::removeChild(StackingContext* item)
{
StackingContext* next = item->nextSibling;
StackingContext* prev = item->previousSibling;
if (!next)
lastChild = prev;
else
next->previousSibling = prev;
if (!prev)
firstChild = next;
else
prev->nextSibling = next;
item->parent = item->nextSibling = item->previousSibling = 0;
--childCount;
return item;
}
StackingContext* StackingContext::insertBefore(StackingContext* item, StackingContext* after)
{
if (!after)
return appendChild(item);
item->previousSibling = after->previousSibling;
item->nextSibling = after;
after->previousSibling = item;
if (!item->previousSibling)
firstChild = item;
else
item->previousSibling->nextSibling = item;
item->parent = this;
++childCount;
return item;
}
StackingContext* StackingContext::appendChild(StackingContext* item)
{
StackingContext* prev = lastChild;
if (!prev)
firstChild = item;
else
prev->nextSibling = item;
item->previousSibling = prev;
item->nextSibling = 0;
lastChild = item;
item->parent = this;
++childCount;
return item;
}
StackingContext::StackingContext(bool auto_, int zIndex, CSSStyleDeclarationImp* style) :
count(0),
style(style),
auto_(auto_),
zIndex(zIndex),
parent(0),
firstChild(0),
lastChild(0),
previousSibling(0),
nextSibling(0),
childCount(0),
positioned(0),
firstBase(0),
lastBase(0),
clipBox(0),
firstFloat(0),
lastFloat(0),
currentFloat(0)
{
}
StackingContext::~StackingContext()
{
if (parent)
parent->removeChild(this);
while (0 < childCount) {
StackingContext* child = removeChild(firstChild);
delete child;
}
}
StackingContext* StackingContext::addContext(bool auto_, int zIndex, CSSStyleDeclarationImp* style)
{
StackingContext* item = new(std::nothrow) StackingContext(auto_, zIndex, style);
if (item)
insertContext(item);
return item;
}
void StackingContext::insertContext(StackingContext* item)
{
assert(item);
if (isAuto()) {
parent->insertContext(item);
item->positioned = this;
return;
}
// TODO: Preserve the order in the DOM tree
StackingContext* after = 0;
for (auto i = getFirstChild(); i; i = i->getNextSibling()) {
if (item->zIndex < i->zIndex) {
after = i;
break;
}
}
insertBefore(item, after);
item->positioned = this;
}
void StackingContext::setZIndex(bool auto_, int index)
{
if (isAuto() == auto_ && zIndex == index)
return;
this->auto_ = auto_;
zIndex = index;
if (parent) {
parent->removeChild(this);
positioned->insertContext(this);
// TODO: Reorganize child contexts, too!
}
}
void StackingContext::clip(StackingContext* s, float relativeX, float relativeY)
{
for (Block* clip = s->clipBox; clip && clip != s->positioned->clipBox; clip = clip->clipBox) {
if (clip->stackingContext == s)
continue;
if (clip->style->overflow.getValue() != CSSOverflowValueImp::Visible) { // TODO: check this
Element element = interface_cast<Element>(clip->node);
glTranslatef(-element.getScrollLeft(), -element.getScrollTop(), 0.0f);
if (clip != s->clipBox) {
clipLeft -= element.getScrollLeft();
clipTop -= element.getScrollTop();
}
}
if (clipWidth == HUGE_VALF) {
clipLeft = clip->x + clip->marginLeft + clip->borderLeft - relativeX;
clipTop = clip->y + clip->marginTop + clip->borderTop - relativeY;
clipWidth = clip->getPaddingWidth();
clipHeight = clip->getPaddingHeight();
} else {
Box::unionRect(clipLeft, clipTop, clipWidth, clipHeight,
clip->x + clip->marginLeft + clip->borderLeft - relativeX,
clip->y + clip->marginTop + clip->borderTop - relativeY,
clip->getPaddingWidth(), clip->getPaddingHeight());
}
}
}
bool StackingContext::resolveRelativeOffset(float& x, float &y)
{
bool result = false;
for (StackingContext* s = this; s != parent; s = s->positioned) {
assert(s->style);
result |= s->style->resolveRelativeOffset(x, y);
clip(s, x, y);
}
return result;
}
void StackingContext::render(ViewCSSImp* view)
{
clipLeft = clipTop = 0.0f;
clipWidth = clipHeight = HUGE_VALF;
glPushMatrix();
float relativeX = 0.0f;
float relativeY = 0.0f;
if (resolveRelativeOffset(relativeX, relativeY))
glTranslatef(relativeX, relativeY, 0.0f);
if (clipWidth != HUGE_VALF && clipHeight != HUGE_VALF)
view->clip(clipLeft, clipTop, clipWidth, clipHeight);
currentFloat = firstFloat = lastFloat = 0;
for (Box* base = firstBase; base; base = base->nextBase) {
glPushMatrix();
Block* block = dynamic_cast<Block*>(base);
unsigned overflow = CSSOverflowValueImp::Visible;
if (block)
overflow = block->renderBegin(view);
StackingContext* childContext = getFirstChild();
for (; childContext && childContext->zIndex < 0; childContext = childContext->getNextSibling())
childContext->render(view);
if (block)
block->renderNonInline(view, this);
else
base->render(view, this);
for (currentFloat = firstFloat; currentFloat; currentFloat = currentFloat->nextBase)
currentFloat->render(view, this);
if (block)
block->renderInline(view, this);
for (; childContext; childContext = childContext->getNextSibling())
childContext->render(view);
if (block) {
if (0.0f < block->getOutlineWidth())
block->renderOutline(view, block->x, block->y + block->getTopBorderEdge());
block->renderEnd(view, overflow);
}
glPopMatrix();
}
if (clipWidth != HUGE_VALF && clipHeight != HUGE_VALF)
view->unclip(clipLeft, clipTop, clipWidth, clipHeight);
glPopMatrix();
}
void StackingContext::addBase(Box* box)
{
#ifndef NDEBUG
for (Box* i = firstBase; i; i = i->nextBase)
assert(box != i);
if (dynamic_cast<Block*>(box))
assert(!firstBase);
#endif
if (!firstBase)
firstBase = lastBase = box;
else {
lastBase->nextBase = box;
lastBase = box;
}
box->nextBase = 0;
}
void StackingContext::addBox(Box* box, Box* parentBox)
{
assert(parentBox);
if (parentBox->stackingContext != this)
addBase(box);
}
void StackingContext::addFloat(Box* box)
{
#ifndef NDEBUG
for (Box* i = firstFloat; i; i = i->nextBase) {
assert(box != i);
}
#endif
if (currentFloat) {
box->nextBase = currentFloat->nextBase;
currentFloat->nextBase = box;
return;
}
if (!firstFloat)
firstFloat = lastFloat = box;
else {
lastFloat->nextBase = box;
lastFloat = box;
}
box->nextBase = 0;
}
void StackingContext::removeBox(Box* box)
{
Box* p = 0;
for (Box* i = firstBase; i ; p = i, i = i->nextBase) {
if (i == box) {
if (!p)
firstBase = i->nextBase;
else
p->nextBase = i->nextBase;
if (lastBase == box)
lastBase = p;
break;
}
}
}
void StackingContext::layOutAbsolute(ViewCSSImp* view)
{
for (Box* base = firstBase; base; base = base->nextBase) {
Block* block = dynamic_cast<Block*>(base);
if (!block || !block->isAbsolutelyPositioned())
continue;
block->layOutAbsolute(view);
block->resolveXY(view, block->x, block->y, block->clipBox);
}
for (StackingContext* childContext = getFirstChild(); childContext; childContext = childContext->getNextSibling())
childContext->layOutAbsolute(view);
}
void StackingContext::dump(std::string indent)
{
std::cout << indent << "z-index: " << zIndex << '\n';
indent += " ";
for (auto child = getFirstChild(); child; child = child->getNextSibling())
child->dump(indent);
}
}}}} // org::w3c::dom::bootstrap
<|endoftext|>
|
<commit_before>/*
* main.cpp
* Program: kalarm
* Copyright © 2001-2007 by David Jarvie <software@astrojar.org.uk>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "kalarm.h"
#include <stdlib.h>
#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include <klocale.h>
#include <kdebug.h>
#include "kalarmapp.h"
#define PROGRAM_NAME "kalarm"
int main(int argc, char *argv[])
{
KAboutData aboutData(PROGRAM_NAME, 0, ki18n("KAlarm"), KALARM_VERSION,
ki18n("Personal alarm message, command and email scheduler for KDE"),
KAboutData::License_GPL,
ki18n("Copyright 2001-2007, David Jarvie"), KLocalizedString(), "http://www.astrojar.org.uk/kalarm");
aboutData.addAuthor(ki18n("David Jarvie"), KLocalizedString(), "software@astrojar.org.uk");
aboutData.setOrganizationDomain("kde.org");
KCmdLineArgs::init(argc, argv, &aboutData);
KCmdLineOptions options;
options.add("a");
options.add("ack-confirm", ki18n("Prompt for confirmation when alarm is acknowledged"));
options.add("A");
options.add("attach <url>", ki18n("Attach file to email (repeat as needed)"));
options.add("auto-close", ki18n("Auto-close alarm window after --late-cancel period"));
options.add("bcc", ki18n("Blind copy email to self"));
options.add("b");
options.add("beep", ki18n("Beep when message is displayed"));
options.add("colour");
options.add("c");
options.add("color <color>", ki18n("Message background color (name or hex 0xRRGGBB)"));
options.add("colourfg");
options.add("C");
options.add("colorfg <color>", ki18n("Message foreground color (name or hex 0xRRGGBB)"));
options.add("cancelEvent <eventID>", ki18n("Cancel alarm with the specified event ID"));
options.add("d");
options.add("disable", ki18n("Disable the alarm"));
options.add("e");
options.add("!exec <commandline>", ki18n("Execute a shell command line"));
options.add("E");
options.add("!exec-display <commandline>", ki18n("Command line to generate alarm message text"));
options.add("edit <eventID>", ki18n("Display the alarm edit dialog to edit the specified alarm"));
options.add("edit-new-display", ki18n("Display the alarm edit dialog to edit a new display alarm"));
options.add("edit-new-command", ki18n("Display the alarm edit dialog to edit a new command alarm"));
options.add("edit-new-email", ki18n("Display the alarm edit dialog to edit a new email alarm"));
options.add("edit-new-preset <templateName>", ki18n("Display the alarm edit dialog, preset with a template"));
options.add("f");
options.add("file <url>", ki18n("File to display"));
options.add("F");
options.add("from-id <ID>", ki18n("KMail identity to use as sender of email"));
options.add("handleEvent <eventID>", ki18n("Trigger or cancel alarm with the specified event ID"));
options.add("i");
options.add("interval <period>", ki18n("Interval between alarm repetitions"));
options.add("k");
options.add("korganizer", ki18n("Show alarm as an event in KOrganizer"));
options.add("l");
options.add("late-cancel <period>", ki18n("Cancel alarm if more than 'period' late when triggered"), "1");
options.add("L");
options.add("login", ki18n("Repeat alarm at every login"));
options.add("m");
options.add("mail <address>", ki18n("Send an email to the given address (repeat as needed)"));
options.add("p");
options.add("play <url>", ki18n("Audio file to play once"));
options.add("P");
options.add("play-repeat <url>", ki18n("Audio file to play repeatedly"));
options.add("recurrence <spec>", ki18n("Specify alarm recurrence using iCalendar syntax"));
options.add("R");
options.add("reminder <period>", ki18n("Display reminder in advance of alarm"));
options.add("reminder-once <period>", ki18n("Display reminder once, before first alarm recurrence"));
options.add("r");
options.add("repeat <count>", ki18n("Number of times to repeat alarm (including initial occasion)"));
options.add("reset", ki18n("Reset the alarm scheduling daemon"));
options.add("s");
options.add("speak", ki18n("Speak the message when it is displayed"));
options.add("stop", ki18n("Stop the alarm scheduling daemon"));
options.add("S");
options.add("subject", ki18n("Email subject line"));
options.add("t");
options.add("time <time>", ki18n("Trigger alarm at time [[[yyyy-]mm-]dd-]hh:mm [TZ], or date yyyy-mm-dd [TZ]"));
options.add("tray", ki18n("Display system tray icon"));
options.add("triggerEvent <eventID>", ki18n("Trigger alarm with the specified event ID"));
options.add("u");
options.add("until <time>", ki18n("Repeat until time [[[yyyy-]mm-]dd-]hh:mm [TZ], or date yyyy-mm-dd [TZ]"));
options.add("V");
options.add("volume <percent>", ki18n("Volume to play audio file"));
options.add("+[message]", ki18n("Message text to display"));
KCmdLineArgs::addCmdLineOptions(options);
KUniqueApplication::addCmdLineOptions();
if (!KAlarmApp::start())
{
// An instance of the application is already running
exit(0);
}
// This is the first time through
kDebug(5950) << "main(): initialising";
KAlarmApp* app = KAlarmApp::getInstance();
app->restoreSession();
return app->exec();
}
<commit_msg>Update email address<commit_after>/*
* main.cpp
* Program: kalarm
* Copyright © 2001-2007 by David Jarvie <djarvie@kde.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "kalarm.h"
#include <stdlib.h>
#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include <klocale.h>
#include <kdebug.h>
#include "kalarmapp.h"
#define PROGRAM_NAME "kalarm"
int main(int argc, char *argv[])
{
KAboutData aboutData(PROGRAM_NAME, 0, ki18n("KAlarm"), KALARM_VERSION,
ki18n("Personal alarm message, command and email scheduler for KDE"),
KAboutData::License_GPL,
ki18n("Copyright 2001-2007, David Jarvie"), KLocalizedString(), "http://www.astrojar.org.uk/kalarm");
aboutData.addAuthor(ki18n("David Jarvie"), KLocalizedString(), "djarvie@kde.org");
aboutData.setOrganizationDomain("kde.org");
KCmdLineArgs::init(argc, argv, &aboutData);
KCmdLineOptions options;
options.add("a");
options.add("ack-confirm", ki18n("Prompt for confirmation when alarm is acknowledged"));
options.add("A");
options.add("attach <url>", ki18n("Attach file to email (repeat as needed)"));
options.add("auto-close", ki18n("Auto-close alarm window after --late-cancel period"));
options.add("bcc", ki18n("Blind copy email to self"));
options.add("b");
options.add("beep", ki18n("Beep when message is displayed"));
options.add("colour");
options.add("c");
options.add("color <color>", ki18n("Message background color (name or hex 0xRRGGBB)"));
options.add("colourfg");
options.add("C");
options.add("colorfg <color>", ki18n("Message foreground color (name or hex 0xRRGGBB)"));
options.add("cancelEvent <eventID>", ki18n("Cancel alarm with the specified event ID"));
options.add("d");
options.add("disable", ki18n("Disable the alarm"));
options.add("e");
options.add("!exec <commandline>", ki18n("Execute a shell command line"));
options.add("E");
options.add("!exec-display <commandline>", ki18n("Command line to generate alarm message text"));
options.add("edit <eventID>", ki18n("Display the alarm edit dialog to edit the specified alarm"));
options.add("edit-new-display", ki18n("Display the alarm edit dialog to edit a new display alarm"));
options.add("edit-new-command", ki18n("Display the alarm edit dialog to edit a new command alarm"));
options.add("edit-new-email", ki18n("Display the alarm edit dialog to edit a new email alarm"));
options.add("edit-new-preset <templateName>", ki18n("Display the alarm edit dialog, preset with a template"));
options.add("f");
options.add("file <url>", ki18n("File to display"));
options.add("F");
options.add("from-id <ID>", ki18n("KMail identity to use as sender of email"));
options.add("handleEvent <eventID>", ki18n("Trigger or cancel alarm with the specified event ID"));
options.add("i");
options.add("interval <period>", ki18n("Interval between alarm repetitions"));
options.add("k");
options.add("korganizer", ki18n("Show alarm as an event in KOrganizer"));
options.add("l");
options.add("late-cancel <period>", ki18n("Cancel alarm if more than 'period' late when triggered"), "1");
options.add("L");
options.add("login", ki18n("Repeat alarm at every login"));
options.add("m");
options.add("mail <address>", ki18n("Send an email to the given address (repeat as needed)"));
options.add("p");
options.add("play <url>", ki18n("Audio file to play once"));
options.add("P");
options.add("play-repeat <url>", ki18n("Audio file to play repeatedly"));
options.add("recurrence <spec>", ki18n("Specify alarm recurrence using iCalendar syntax"));
options.add("R");
options.add("reminder <period>", ki18n("Display reminder in advance of alarm"));
options.add("reminder-once <period>", ki18n("Display reminder once, before first alarm recurrence"));
options.add("r");
options.add("repeat <count>", ki18n("Number of times to repeat alarm (including initial occasion)"));
options.add("reset", ki18n("Reset the alarm scheduling daemon"));
options.add("s");
options.add("speak", ki18n("Speak the message when it is displayed"));
options.add("stop", ki18n("Stop the alarm scheduling daemon"));
options.add("S");
options.add("subject", ki18n("Email subject line"));
options.add("t");
options.add("time <time>", ki18n("Trigger alarm at time [[[yyyy-]mm-]dd-]hh:mm [TZ], or date yyyy-mm-dd [TZ]"));
options.add("tray", ki18n("Display system tray icon"));
options.add("triggerEvent <eventID>", ki18n("Trigger alarm with the specified event ID"));
options.add("u");
options.add("until <time>", ki18n("Repeat until time [[[yyyy-]mm-]dd-]hh:mm [TZ], or date yyyy-mm-dd [TZ]"));
options.add("V");
options.add("volume <percent>", ki18n("Volume to play audio file"));
options.add("+[message]", ki18n("Message text to display"));
KCmdLineArgs::addCmdLineOptions(options);
KUniqueApplication::addCmdLineOptions();
if (!KAlarmApp::start())
{
// An instance of the application is already running
exit(0);
}
// This is the first time through
kDebug(5950) << "main(): initialising";
KAlarmApp* app = KAlarmApp::getInstance();
app->restoreSession();
return app->exec();
}
<|endoftext|>
|
<commit_before>/*
* opencog/atomspace/NodeIndex.cc
*
* Copyright (C) 2008 Linas Vepstas <linasvepstas@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <opencog/atomspace/NodeIndex.h>
#include <opencog/atomspace/ClassServer.h>
#include <opencog/atomspace/HandleEntry.h>
#include <opencog/atomspace/TLB.h>
#include <opencog/atomspace/atom_types.h>
using namespace opencog;
NodeIndex::NodeIndex(void)
{
resize();
}
void NodeIndex::resize()
{
this->idx.resize(classserver().getNumberOfClasses());
}
void NodeIndex::insertHandle(Handle h)
{
Atom *a = TLB::getAtom(h);
Type t = a->getType();
NameIndex &ni = idx[t];
ni.insertHandle(h); // XXX perf optimization if we pass atom not handle!
}
void NodeIndex::removeHandle(Handle h)
{
Atom *a = TLB::getAtom(h);
Type t = a->getType();
NameIndex &ni = idx[t];
ni.removeHandle(h); // XXX perf optimization if we pass atom not handle!
}
Handle NodeIndex::getHandle(Type t, const char *name) const
{
if (t >= idx.size()) throw RuntimeException(TRACE_INFO,
"Index out of bounds for atom type (t = %lu)", t);
const NameIndex &ni = idx[t];
return ni.get(name);
}
void NodeIndex::remove(bool (*filter)(Handle))
{
std::vector<NameIndex>::iterator s;
for (s = idx.begin(); s != idx.end(); s++)
{
s->remove(filter);
}
}
HandleEntry * NodeIndex::getHandleSet(Type type, const char *name, bool subclass) const
{
if (subclass)
{
HandleEntry *he = NULL;
int max = classserver().getNumberOfClasses();
for (Type s = 0; s < max; s++)
{
// The 'AssignableFrom' direction is unit-tested in AtomSpaceUTest.cxxtest
if (classserver().isA(s, type))
{
if (s >= idx.size()) throw RuntimeException(TRACE_INFO,
"Index out of bounds for atom type (s = %lu)", s);
const NameIndex &ni = idx[s];
Handle h = ni.get(name);
if (TLB::isValidHandle(h))
he = new HandleEntry(h, he);
}
}
return he;
}
else
{
return new HandleEntry(getHandle(type, name));
}
}
// ================================================================
<commit_msg>bug fix for invalid handles, as per email from David Crane <dncrane@gmail.com> Subject: [opencog-dev] list command doesn't worth properly with -T <type> -n <name><commit_after>/*
* opencog/atomspace/NodeIndex.cc
*
* Copyright (C) 2008 Linas Vepstas <linasvepstas@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <opencog/atomspace/NodeIndex.h>
#include <opencog/atomspace/ClassServer.h>
#include <opencog/atomspace/HandleEntry.h>
#include <opencog/atomspace/TLB.h>
#include <opencog/atomspace/atom_types.h>
using namespace opencog;
NodeIndex::NodeIndex(void)
{
resize();
}
void NodeIndex::resize()
{
this->idx.resize(classserver().getNumberOfClasses());
}
void NodeIndex::insertHandle(Handle h)
{
Atom *a = TLB::getAtom(h);
Type t = a->getType();
NameIndex &ni = idx[t];
ni.insertHandle(h); // XXX perf optimization if we pass atom not handle!
}
void NodeIndex::removeHandle(Handle h)
{
Atom *a = TLB::getAtom(h);
Type t = a->getType();
NameIndex &ni = idx[t];
ni.removeHandle(h); // XXX perf optimization if we pass atom not handle!
}
Handle NodeIndex::getHandle(Type t, const char *name) const
{
if (t >= idx.size()) throw RuntimeException(TRACE_INFO,
"Index out of bounds for atom type (t = %lu)", t);
const NameIndex &ni = idx[t];
return ni.get(name);
}
void NodeIndex::remove(bool (*filter)(Handle))
{
std::vector<NameIndex>::iterator s;
for (s = idx.begin(); s != idx.end(); s++)
{
s->remove(filter);
}
}
HandleEntry * NodeIndex::getHandleSet(Type type, const char *name, bool subclass) const
{
if (subclass)
{
HandleEntry *he = NULL;
int max = classserver().getNumberOfClasses();
for (Type s = 0; s < max; s++)
{
// The 'AssignableFrom' direction is unit-tested in AtomSpaceUTest.cxxtest
if (classserver().isA(s, type))
{
if (s >= idx.size()) throw RuntimeException(TRACE_INFO,
"Index out of bounds for atom type (s = %lu)", s);
const NameIndex &ni = idx[s];
Handle h = ni.get(name);
if (TLB::isValidHandle(h))
he = new HandleEntry(h, he);
}
}
return he;
}
else
{
Handle h = getHandle(type, name);
if (TLB::isValidHandle(h)) return new HandleEntry(h);
return NULL;
}
}
// ================================================================
<|endoftext|>
|
<commit_before>#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
#define ll long long
#define mem(Arr,x) memset(Arr,x,sizeof(Arr))
const int maxN=12;
const int inf=2147483647;
int n,m;
char Mp[maxN+5][maxN+5];
ll F[2][1594323+100],Pow3[maxN];
int main(){
Pow3[0]=1;for (int i=1;i<=15;i++) Pow3[i]=Pow3[i-1]*3;
scanf("%d%d",&n,&m);
for (int i=1;i<=n;i++) scanf("%s",Mp[i]+1);
int lstx=0,lsty;
for (int i=n;(i>=1)&&(lstx==0);i--) for (int j=m;(j>=1)&&(lstx==0);j--) if (Mp[i][j]=='.') lstx=i,lsty=j;
int now=0;
int up=3;for (int i=1;i<=m;i++) up=up*3;
ll Ans=0;
F[now][0]=1;
cout<<lstx<<" "<<lsty<<endl;
for (int i=1;i<=n;i++)
for (int j=1;j<=m;j++){
now^=1;mem(F[now],0);
for (int k=0;k<up;k++)
if (F[now^1][k]){
int x=k%3,y=k/Pow3[j]%3,key=F[now^1][k];
if (Mp[i][j]=='.'){
if (x==0){
if ((y==0)&&(i<n)&&(j<m)) F[now][k+Pow3[j]+1]+=key;
if (y==1) F[now][k]+=key,F[now][k-Pow3[j]+1]+=key;
if (y==2) F[now][k]+=key,F[now][k-Pow3[j]*2+2]+=key;
}
if (x==1){
if (y==0) F[now][k]+=key,F[now][k-1+Pow3[j]]+=key;
if (y==1){
int opt=0,p=j+1;
while (((k/Pow3[p]%3!=2)||opt)&&(p<=m)){
if (k/Pow3[p]%3==1) ++opt;
else if (k/Pow3[p]%3==2) --opt;
++p;
}
if (p<=m) F[now][k-Pow3[j]-1-Pow3[p]]+=key;
}
if ((y==2)&&(i==lstx)&&(j==lsty)) Ans+=key;
}
if (x==2){
if (y==0) F[now][k]+=key,F[now][k-2+Pow3[j]*2]+=key;
if (y==1) F[now][k-2-Pow3[j]]+=key;
if (y==2){
int opt=0,p=j-1;
while (((k/Pow3[p]%3!=1)||opt)&&(p>=1)){
if (k/Pow3[p]%3==1) --opt;
else if (k/Pow3[p]%3==2) ++opt;
--p;
}
if (p>=1) F[now][k-2-Pow3[j]*2+Pow3[p]]+=key;
}
}
}
else{
if ((x==0)&&(y==0)) F[now][k]+=key;
}
}
}
printf("%lld\n",Ans);return 0;
}
<commit_msg>2018.12.8 pm-night<commit_after>#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
#define ll long long
#define mem(Arr,x) memset(Arr,x,sizeof(Arr))
const int maxN=12;
const int inf=2147483647;
int n,m;
char Mp[maxN+5][maxN+5];
ll F[2][1594323+100],Pow3[maxN];
int main(){
Pow3[0]=1;for (int i=1;i<=15;i++) Pow3[i]=Pow3[i-1]*3;
scanf("%d%d",&n,&m);
for (int i=1;i<=n;i++) scanf("%s",Mp[i]+1);
int lstx=0,lsty;
for (int i=n;(i>=1)&&(lstx==0);i--) for (int j=m;(j>=1)&&(lstx==0);j--) if (Mp[i][j]=='.') lstx=i,lsty=j;
int now=0;
int up=3;for (int i=1;i<=m;i++) up=up*3;
ll Ans=0;
F[now][0]=1;
for (int i=1;i<=n;i++)
for (int j=1;j<=m;j++){
now^=1;mem(F[now],0);
for (int k=0;k<up;k++)
if (F[now^1][k]){
int x=k%3,y=k/Pow3[j-1]%3,key=F[now^1][k];
if (j==1) cout<<i-1<<" "<<m<<" "<<k<<" "<<key<<" "<<x<<" "<<y<<endl;
else cout<<i<<" "<<j-1<<" "<<k<<" "<<key<<" "<<x<<" "<<y<<endl;
if (Mp[i][j]=='.'){
if (x==0){
if ((y==0)&&(i<n)&&(j<m)) F[now][k+Pow3[j-1]+2]+=key;
if (y==1) F[now][k]+=key,F[now][k-Pow3[j-1]+1]+=key;
if (y==2) F[now][k]+=key,F[now][k-Pow3[j-1]*2+2]+=key;
}
if (x==1){
if (y==0) F[now][k]+=key,F[now][k-1+Pow3[j-1]]+=key;
if (y==1){
int opt=0,p=j;
while (((k/Pow3[p]%3!=2)||opt)&&(p<=m)){
if (k/Pow3[p]%3==1) ++opt;
else if (k/Pow3[p]%3==2) --opt;
++p;
}
if (p<=m) F[now][k-Pow3[j-1]-1-Pow3[p]]+=key;
}
if ((y==2)&&(i==lstx)&&(j==lsty)) Ans+=key;
}
if (x==2){
if (y==0) F[now][k]+=key,F[now][k-2+Pow3[j-1]*2]+=key;
if (y==1) F[now][k-2-Pow3[j-1]]+=key;
if ((y==2)&&(j>=2)){
int opt=0,p=j-2;
while (((k/Pow3[p]%3!=1)||opt)&&(p>=1)){
if (k/Pow3[p]%3==1) --opt;
else if (k/Pow3[p]%3==2) ++opt;
--p;
}
if (p>=1) F[now][k-2-Pow3[j-1]*2+Pow3[p]]+=key;
}
}
}
else{
if ((x==0)&&(y==0)) F[now][k]+=key;
}
}
}
printf("%lld\n",Ans);return 0;
}
<|endoftext|>
|
<commit_before>//===-- WebAssemblyPeephole.cpp - WebAssembly Peephole Optimiztions -------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief Late peephole optimizations for WebAssembly.
///
//===----------------------------------------------------------------------===//
#include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
#include "WebAssembly.h"
#include "WebAssemblyMachineFunctionInfo.h"
#include "WebAssemblySubtarget.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
using namespace llvm;
#define DEBUG_TYPE "wasm-peephole"
static cl::opt<bool> DisableWebAssemblyFallthroughReturnOpt(
"disable-wasm-fallthrough-return-opt", cl::Hidden,
cl::desc("WebAssembly: Disable fallthrough-return optimizations."),
cl::init(false));
namespace {
class WebAssemblyPeephole final : public MachineFunctionPass {
const char *getPassName() const override {
return "WebAssembly late peephole optimizer";
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesCFG();
AU.addRequired<TargetLibraryInfoWrapperPass>();
MachineFunctionPass::getAnalysisUsage(AU);
}
bool runOnMachineFunction(MachineFunction &MF) override;
public:
static char ID;
WebAssemblyPeephole() : MachineFunctionPass(ID) {}
};
} // end anonymous namespace
char WebAssemblyPeephole::ID = 0;
FunctionPass *llvm::createWebAssemblyPeephole() {
return new WebAssemblyPeephole();
}
/// If desirable, rewrite NewReg to a drop register.
static bool MaybeRewriteToDrop(unsigned OldReg, unsigned NewReg,
MachineOperand &MO, WebAssemblyFunctionInfo &MFI,
MachineRegisterInfo &MRI) {
bool Changed = false;
if (OldReg == NewReg) {
Changed = true;
unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg));
MO.setReg(NewReg);
MO.setIsDead();
MFI.stackifyVReg(NewReg);
}
return Changed;
}
static bool MaybeRewriteToFallthrough(MachineInstr &MI, MachineBasicBlock &MBB,
const MachineFunction &MF,
WebAssemblyFunctionInfo &MFI,
MachineRegisterInfo &MRI,
const WebAssemblyInstrInfo &TII,
unsigned FallthroughOpc,
unsigned CopyLocalOpc) {
if (DisableWebAssemblyFallthroughReturnOpt)
return false;
if (&MBB != &MF.back())
return false;
if (&MI != &MBB.back())
return false;
// If the operand isn't stackified, insert a COPY_LOCAL to read the operand
// and stackify it.
MachineOperand &MO = MI.getOperand(0);
unsigned Reg = MO.getReg();
if (!MFI.isVRegStackified(Reg)) {
unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg));
BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(CopyLocalOpc), NewReg)
.addReg(Reg);
MO.setReg(NewReg);
MFI.stackifyVReg(NewReg);
}
// Rewrite the return.
MI.setDesc(TII.get(FallthroughOpc));
return true;
}
bool WebAssemblyPeephole::runOnMachineFunction(MachineFunction &MF) {
DEBUG({
dbgs() << "********** Peephole **********\n"
<< "********** Function: " << MF.getName() << '\n';
});
MachineRegisterInfo &MRI = MF.getRegInfo();
WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
const auto &Subtarget = MF.getSubtarget<WebAssemblySubtarget>();
const auto &TII = *Subtarget.getInstrInfo();
const WebAssemblyTargetLowering &TLI =
*MF.getSubtarget<WebAssemblySubtarget>().getTargetLowering();
auto &LibInfo = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
bool Changed = false;
for (auto &MBB : MF)
for (auto &MI : MBB)
switch (MI.getOpcode()) {
default:
break;
case WebAssembly::STORE8_I32:
case WebAssembly::STORE16_I32:
case WebAssembly::STORE8_I64:
case WebAssembly::STORE16_I64:
case WebAssembly::STORE32_I64:
case WebAssembly::STORE_F32:
case WebAssembly::STORE_F64:
case WebAssembly::STORE_I32:
case WebAssembly::STORE_I64: {
// Store instructions return their value operand. If we ended up using
// the same register for both, replace it with a dead def so that it
// can use $drop instead.
MachineOperand &MO = MI.getOperand(0);
unsigned OldReg = MO.getReg();
unsigned NewReg =
MI.getOperand(WebAssembly::StoreValueOperandNo).getReg();
Changed |= MaybeRewriteToDrop(OldReg, NewReg, MO, MFI, MRI);
break;
}
case WebAssembly::CALL_I32:
case WebAssembly::CALL_I64: {
MachineOperand &Op1 = MI.getOperand(1);
if (Op1.isSymbol()) {
StringRef Name(Op1.getSymbolName());
if (Name == TLI.getLibcallName(RTLIB::MEMCPY) ||
Name == TLI.getLibcallName(RTLIB::MEMMOVE) ||
Name == TLI.getLibcallName(RTLIB::MEMSET)) {
LibFunc::Func Func;
if (LibInfo.getLibFunc(Name, Func)) {
const auto &Op2 = MI.getOperand(2);
if (!Op2.isReg())
report_fatal_error("Peephole: call to builtin function with "
"wrong signature, not consuming reg");
MachineOperand &MO = MI.getOperand(0);
unsigned OldReg = MO.getReg();
unsigned NewReg = Op2.getReg();
if (MRI.getRegClass(NewReg) != MRI.getRegClass(OldReg))
report_fatal_error("Peephole: call to builtin function with "
"wrong signature, from/to mismatch");
Changed |= MaybeRewriteToDrop(OldReg, NewReg, MO, MFI, MRI);
}
}
}
break;
}
// Optimize away an explicit void return at the end of the function.
case WebAssembly::RETURN_I32:
Changed |= MaybeRewriteToFallthrough(
MI, MBB, MF, MFI, MRI, TII, WebAssembly::FALLTHROUGH_RETURN_I32,
WebAssembly::COPY_LOCAL_I32);
break;
case WebAssembly::RETURN_I64:
Changed |= MaybeRewriteToFallthrough(
MI, MBB, MF, MFI, MRI, TII, WebAssembly::FALLTHROUGH_RETURN_I64,
WebAssembly::COPY_LOCAL_I64);
break;
case WebAssembly::RETURN_F32:
Changed |= MaybeRewriteToFallthrough(
MI, MBB, MF, MFI, MRI, TII, WebAssembly::FALLTHROUGH_RETURN_F32,
WebAssembly::COPY_LOCAL_F32);
break;
case WebAssembly::RETURN_F64:
Changed |= MaybeRewriteToFallthrough(
MI, MBB, MF, MFI, MRI, TII, WebAssembly::FALLTHROUGH_RETURN_F64,
WebAssembly::COPY_LOCAL_F64);
break;
case WebAssembly::RETURN_v16i8:
Changed |=
Subtarget.hasSIMD128() &&
MaybeRewriteToFallthrough(MI, MBB, MF, MFI, MRI, TII,
WebAssembly::FALLTHROUGH_RETURN_v16i8,
WebAssembly::COPY_LOCAL_V128);
break;
case WebAssembly::RETURN_v8i16:
Changed |=
Subtarget.hasSIMD128() &&
MaybeRewriteToFallthrough(MI, MBB, MF, MFI, MRI, TII,
WebAssembly::FALLTHROUGH_RETURN_v8i16,
WebAssembly::COPY_LOCAL_V128);
break;
case WebAssembly::RETURN_v4i32:
Changed |=
Subtarget.hasSIMD128() &&
MaybeRewriteToFallthrough(MI, MBB, MF, MFI, MRI, TII,
WebAssembly::FALLTHROUGH_RETURN_v4i32,
WebAssembly::COPY_LOCAL_V128);
break;
case WebAssembly::RETURN_v4f32:
Changed |=
Subtarget.hasSIMD128() &&
MaybeRewriteToFallthrough(MI, MBB, MF, MFI, MRI, TII,
WebAssembly::FALLTHROUGH_RETURN_v4f32,
WebAssembly::COPY_LOCAL_V128);
break;
case WebAssembly::RETURN_VOID:
if (!DisableWebAssemblyFallthroughReturnOpt &&
&MBB == &MF.back() && &MI == &MBB.back())
MI.setDesc(TII.get(WebAssembly::FALLTHROUGH_RETURN_VOID));
break;
}
return Changed;
}
<commit_msg>[WebAssembly] Remove unnecessary subtarget checks in peephole pass<commit_after>//===-- WebAssemblyPeephole.cpp - WebAssembly Peephole Optimiztions -------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief Late peephole optimizations for WebAssembly.
///
//===----------------------------------------------------------------------===//
#include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
#include "WebAssembly.h"
#include "WebAssemblyMachineFunctionInfo.h"
#include "WebAssemblySubtarget.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
using namespace llvm;
#define DEBUG_TYPE "wasm-peephole"
static cl::opt<bool> DisableWebAssemblyFallthroughReturnOpt(
"disable-wasm-fallthrough-return-opt", cl::Hidden,
cl::desc("WebAssembly: Disable fallthrough-return optimizations."),
cl::init(false));
namespace {
class WebAssemblyPeephole final : public MachineFunctionPass {
const char *getPassName() const override {
return "WebAssembly late peephole optimizer";
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesCFG();
AU.addRequired<TargetLibraryInfoWrapperPass>();
MachineFunctionPass::getAnalysisUsage(AU);
}
bool runOnMachineFunction(MachineFunction &MF) override;
public:
static char ID;
WebAssemblyPeephole() : MachineFunctionPass(ID) {}
};
} // end anonymous namespace
char WebAssemblyPeephole::ID = 0;
FunctionPass *llvm::createWebAssemblyPeephole() {
return new WebAssemblyPeephole();
}
/// If desirable, rewrite NewReg to a drop register.
static bool MaybeRewriteToDrop(unsigned OldReg, unsigned NewReg,
MachineOperand &MO, WebAssemblyFunctionInfo &MFI,
MachineRegisterInfo &MRI) {
bool Changed = false;
if (OldReg == NewReg) {
Changed = true;
unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg));
MO.setReg(NewReg);
MO.setIsDead();
MFI.stackifyVReg(NewReg);
}
return Changed;
}
static bool MaybeRewriteToFallthrough(MachineInstr &MI, MachineBasicBlock &MBB,
const MachineFunction &MF,
WebAssemblyFunctionInfo &MFI,
MachineRegisterInfo &MRI,
const WebAssemblyInstrInfo &TII,
unsigned FallthroughOpc,
unsigned CopyLocalOpc) {
if (DisableWebAssemblyFallthroughReturnOpt)
return false;
if (&MBB != &MF.back())
return false;
if (&MI != &MBB.back())
return false;
// If the operand isn't stackified, insert a COPY_LOCAL to read the operand
// and stackify it.
MachineOperand &MO = MI.getOperand(0);
unsigned Reg = MO.getReg();
if (!MFI.isVRegStackified(Reg)) {
unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg));
BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(CopyLocalOpc), NewReg)
.addReg(Reg);
MO.setReg(NewReg);
MFI.stackifyVReg(NewReg);
}
// Rewrite the return.
MI.setDesc(TII.get(FallthroughOpc));
return true;
}
bool WebAssemblyPeephole::runOnMachineFunction(MachineFunction &MF) {
DEBUG({
dbgs() << "********** Peephole **********\n"
<< "********** Function: " << MF.getName() << '\n';
});
MachineRegisterInfo &MRI = MF.getRegInfo();
WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
const WebAssemblyTargetLowering &TLI =
*MF.getSubtarget<WebAssemblySubtarget>().getTargetLowering();
auto &LibInfo = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
bool Changed = false;
for (auto &MBB : MF)
for (auto &MI : MBB)
switch (MI.getOpcode()) {
default:
break;
case WebAssembly::STORE8_I32:
case WebAssembly::STORE16_I32:
case WebAssembly::STORE8_I64:
case WebAssembly::STORE16_I64:
case WebAssembly::STORE32_I64:
case WebAssembly::STORE_F32:
case WebAssembly::STORE_F64:
case WebAssembly::STORE_I32:
case WebAssembly::STORE_I64: {
// Store instructions return their value operand. If we ended up using
// the same register for both, replace it with a dead def so that it
// can use $drop instead.
MachineOperand &MO = MI.getOperand(0);
unsigned OldReg = MO.getReg();
unsigned NewReg =
MI.getOperand(WebAssembly::StoreValueOperandNo).getReg();
Changed |= MaybeRewriteToDrop(OldReg, NewReg, MO, MFI, MRI);
break;
}
case WebAssembly::CALL_I32:
case WebAssembly::CALL_I64: {
MachineOperand &Op1 = MI.getOperand(1);
if (Op1.isSymbol()) {
StringRef Name(Op1.getSymbolName());
if (Name == TLI.getLibcallName(RTLIB::MEMCPY) ||
Name == TLI.getLibcallName(RTLIB::MEMMOVE) ||
Name == TLI.getLibcallName(RTLIB::MEMSET)) {
LibFunc::Func Func;
if (LibInfo.getLibFunc(Name, Func)) {
const auto &Op2 = MI.getOperand(2);
if (!Op2.isReg())
report_fatal_error("Peephole: call to builtin function with "
"wrong signature, not consuming reg");
MachineOperand &MO = MI.getOperand(0);
unsigned OldReg = MO.getReg();
unsigned NewReg = Op2.getReg();
if (MRI.getRegClass(NewReg) != MRI.getRegClass(OldReg))
report_fatal_error("Peephole: call to builtin function with "
"wrong signature, from/to mismatch");
Changed |= MaybeRewriteToDrop(OldReg, NewReg, MO, MFI, MRI);
}
}
}
break;
}
// Optimize away an explicit void return at the end of the function.
case WebAssembly::RETURN_I32:
Changed |= MaybeRewriteToFallthrough(
MI, MBB, MF, MFI, MRI, TII, WebAssembly::FALLTHROUGH_RETURN_I32,
WebAssembly::COPY_LOCAL_I32);
break;
case WebAssembly::RETURN_I64:
Changed |= MaybeRewriteToFallthrough(
MI, MBB, MF, MFI, MRI, TII, WebAssembly::FALLTHROUGH_RETURN_I64,
WebAssembly::COPY_LOCAL_I64);
break;
case WebAssembly::RETURN_F32:
Changed |= MaybeRewriteToFallthrough(
MI, MBB, MF, MFI, MRI, TII, WebAssembly::FALLTHROUGH_RETURN_F32,
WebAssembly::COPY_LOCAL_F32);
break;
case WebAssembly::RETURN_F64:
Changed |= MaybeRewriteToFallthrough(
MI, MBB, MF, MFI, MRI, TII, WebAssembly::FALLTHROUGH_RETURN_F64,
WebAssembly::COPY_LOCAL_F64);
break;
case WebAssembly::RETURN_v16i8:
Changed |= MaybeRewriteToFallthrough(
MI, MBB, MF, MFI, MRI, TII, WebAssembly::FALLTHROUGH_RETURN_v16i8,
WebAssembly::COPY_LOCAL_V128);
break;
case WebAssembly::RETURN_v8i16:
Changed |= MaybeRewriteToFallthrough(
MI, MBB, MF, MFI, MRI, TII, WebAssembly::FALLTHROUGH_RETURN_v8i16,
WebAssembly::COPY_LOCAL_V128);
break;
case WebAssembly::RETURN_v4i32:
Changed |= MaybeRewriteToFallthrough(
MI, MBB, MF, MFI, MRI, TII, WebAssembly::FALLTHROUGH_RETURN_v4i32,
WebAssembly::COPY_LOCAL_V128);
break;
case WebAssembly::RETURN_v4f32:
Changed |= MaybeRewriteToFallthrough(
MI, MBB, MF, MFI, MRI, TII, WebAssembly::FALLTHROUGH_RETURN_v4f32,
WebAssembly::COPY_LOCAL_V128);
break;
case WebAssembly::RETURN_VOID:
if (!DisableWebAssemblyFallthroughReturnOpt &&
&MBB == &MF.back() && &MI == &MBB.back())
MI.setDesc(TII.get(WebAssembly::FALLTHROUGH_RETURN_VOID));
break;
}
return Changed;
}
<|endoftext|>
|
<commit_before><commit_msg>Related: i#113308 null pointer check for the unit test<commit_after><|endoftext|>
|
<commit_before>/****************************************************************************
This file is part of the QtMediaHub project on http://www.gitorious.org.
Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).*
All rights reserved.
Contact: Nokia Corporation (qt-info@nokia.com)**
You may use this file under the terms of the BSD license as follows:
"Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Nokia Corporation and its Subsidiary(-ies) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
****************************************************************************/
#include "mediamodel.h"
#include "mediascanner.h"
#include "dbreader.h"
#include "backend.h"
#define DEBUG if (1) qDebug() << __PRETTY_FUNCTION__
MediaModel::MediaModel(QObject *parent)
: QAbstractItemModel(parent), m_loading(false), m_loaded(false), m_reader(0), m_readerThread(0)
{
}
MediaModel::~MediaModel()
{
}
QString MediaModel::part() const
{
return m_structure.split("|").value(m_cursor.length());
}
QString MediaModel::mediaType() const
{
return m_mediaType;
}
void MediaModel::setMediaType(const QString &type)
{
if (type == m_mediaType)
return;
DEBUG << type;
m_mediaType = type;
emit mediaTypeChanged();
// Add the fields of the table as role names
QSqlDriver *driver = Backend::instance()->mediaDatabase().driver();
QSqlRecord record = driver->record(m_mediaType);
if (record.isEmpty())
qWarning() << "Table " << type << " is not valid it seems";
QHash<int, QByteArray> hash = roleNames();
hash.insert(DotDotRole, "dotdot");
hash.insert(IsLeafRole, "isLeaf");
hash.insert(ModelIndexRole,"modelIndex");
hash.insert(PreviewUrlRole, "previewUrl");
for (int i = 0; i < record.count(); i++) {
hash.insert(FieldRolesBegin + i, record.fieldName(i).toUtf8());
}
setRoleNames(hash);
initialize();
}
void MediaModel::addSearchPath(const QString &path, const QString &name)
{
if (m_mediaType.isEmpty()) {
qWarning() << m_mediaType << " is not set yet";
return;
}
QMetaObject::invokeMethod(MediaScanner::instance(), "addSearchPath", Qt::QueuedConnection,
Q_ARG(QString, m_mediaType), Q_ARG(QString, path), Q_ARG(QString, name));
}
void MediaModel::removeSearchPath(int index)
{
Q_UNUSED(index);
}
QString MediaModel::structure() const
{
return m_structure;
}
void MediaModel::setStructure(const QString &str)
{
if (str == m_structure)
return;
DEBUG << str;
m_structure = str;
m_layoutInfo.clear();
foreach(const QString &part, m_structure.split("|"))
m_layoutInfo.append(part.split(","));
initialize();
emit structureChanged();
}
void MediaModel::enter(int index)
{
if (m_cursor.count() + 1 == m_layoutInfo.count() && index != 0 /* up on leaf node is OK */) {
DEBUG << "Refusing to enter leaf node";
return;
}
if (index == 0 && !m_cursor.isEmpty()) {
back();
return;
}
DEBUG << "Entering " << index;
m_cursor.append(m_data[index]);
initialize();
emit partChanged();
}
void MediaModel::back()
{
m_cursor.removeLast();
initialize();
emit partChanged();
}
QVariant MediaModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
if (role == ModelIndexRole)
return qVariantFromValue(index);
return m_data.value(index.row()).value(role);
}
QModelIndex MediaModel::index(int row, int col, const QModelIndex &parent) const
{
if (parent.isValid())
return QModelIndex();
return createIndex(row, col);
}
QModelIndex MediaModel::parent(const QModelIndex &idx) const
{
Q_UNUSED(idx);
return QModelIndex();
}
int MediaModel::rowCount(const QModelIndex &parent) const
{
if (parent.isValid())
return 0;
return m_data.count();
}
int MediaModel::columnCount(const QModelIndex &idx) const
{
Q_UNUSED(idx);
return 1;
}
bool MediaModel::hasChildren(const QModelIndex &parent) const
{
return !parent.isValid();
}
bool MediaModel::canFetchMore(const QModelIndex &parent) const
{
if (parent.isValid() || m_mediaType.isEmpty() || m_layoutInfo.isEmpty()) {
DEBUG << "false " << parent.isValid() << m_mediaType.isEmpty() << m_layoutInfo.isEmpty();
return false;
}
DEBUG << (!m_loading && !m_loaded);
return !m_loading && !m_loaded;
}
void MediaModel::fetchMore(const QModelIndex &parent)
{
if (!canFetchMore(parent))
return;
DEBUG << "";
m_loading = true;
QSqlQuery q = buildQuery();
DEBUG << q.lastQuery();
QMetaObject::invokeMethod(m_reader, "execute", Qt::QueuedConnection, Q_ARG(QSqlQuery, q));
}
void MediaModel::initialize()
{
DEBUG << "";
DbReader *newReader = new DbReader;
if (m_reader) {
disconnect(m_reader, 0, this, 0);
m_reader->stop();
m_reader->deleteLater();
}
m_reader = newReader;
if (!m_readerThread) {
m_readerThread = new QThread(this);
m_readerThread->start();
}
m_reader->moveToThread(m_readerThread);
QMetaObject::invokeMethod(m_reader, "initialize", Q_ARG(QSqlDatabase, Backend::instance()->mediaDatabase()));
connect(m_reader, SIGNAL(dataReady(DbReader *, QList<QSqlRecord>, void *)),
this, SLOT(handleDataReady(DbReader *, QList<QSqlRecord>, void *)));
beginResetModel();
m_loading = m_loaded = false;
m_data.clear();
endResetModel();
}
void MediaModel::handleDataReady(DbReader *reader, const QList<QSqlRecord> &records, void *node)
{
Q_ASSERT(reader == m_reader);
Q_UNUSED(reader);
Q_UNUSED(node);
DEBUG << "Received response from db of size " << records.size();
if (records.isEmpty())
return;
if (!m_cursor.isEmpty()) {
beginInsertRows(QModelIndex(), 0, records.count());
QHash<int, QVariant> data;
data.insert(Qt::DisplayRole, tr(".."));
data.insert(DotDotRole, true);
data.insert(IsLeafRole, false);
m_data.append(data);
} else {
beginInsertRows(QModelIndex(), 0, records.count() - 1);
}
const bool isLeaf = m_cursor.count() + 1 == m_layoutInfo.count();
QSqlDriver *driver = Backend::instance()->mediaDatabase().driver();
const QSqlRecord tableRecord = driver->record(m_mediaType);
for (int i = 0; i < records.count(); i++) {
QHash<int, QVariant> data;
for (int j = 0; j < records[i].count(); j++) {
int idx = tableRecord.indexOf(records[i].fieldName(j));
data.insert(FieldRolesBegin + idx, records[i].value(j));
}
// Provide 'display' role as , separated values
QStringList cols = m_layoutInfo.value(m_cursor.count());
QStringList displayString;
for (int j = 0; j < cols.count(); j++) {
displayString << records[i].value(cols[j]).toString();
}
data.insert(Qt::DisplayRole, displayString.join(", "));
data.insert(DotDotRole, false);
data.insert(IsLeafRole, isLeaf);
data.insert(PreviewUrlRole, records[i].value("thumbnail").toString());
m_data.append(data);
}
m_loading = false;
m_loaded = true;
endInsertRows();
}
void MediaModel::handleDatabaseUpdated(const QList<QSqlRecord> &records)
{
Q_UNUSED(records);
// not implemented yet
}
QSqlQuery MediaModel::buildQuery() const
{
QSqlDriver *driver = Backend::instance()->mediaDatabase().driver();
QStringList escapedCurParts;
QStringList curParts = m_layoutInfo[m_cursor.count()];
for (int i = 0; i < curParts.count(); i++)
escapedCurParts.append(driver->escapeIdentifier(curParts[i], QSqlDriver::FieldName));
QString escapedCurPart = escapedCurParts.join(",");
QSqlQuery query(Backend::instance()->mediaDatabase());
query.setForwardOnly(true);
QStringList placeHolders;
const bool lastPart = m_cursor.count() == m_layoutInfo.count()-1;
QString queryString;
// SQLite allows us to select columns that are not present in the GROUP BY. We use this feature
// to select thumbnails for non-leaf nodes
queryString.append("SELECT *");
queryString.append(" FROM " + driver->escapeIdentifier(m_mediaType, QSqlDriver::TableName));
if (!m_cursor.isEmpty()) {
QStringList where;
const QSqlRecord tableRecord = driver->record(m_mediaType);
for (int i = 0; i < m_cursor.count(); i++) {
QStringList subParts = m_layoutInfo[i];
for (int j = 0; j < subParts.count(); j++) {
where.append(subParts[j] + " = ?");
const int role = FieldRolesBegin + tableRecord.indexOf(subParts[j]);
placeHolders << m_cursor[i].value(role).toString();
}
}
queryString.append(" WHERE " + where.join(" AND "));
}
if (!lastPart)
queryString.append(" GROUP BY " + escapedCurPart);
queryString.append(" ORDER BY " + escapedCurPart);
query.prepare(queryString);
foreach(const QString &placeHolder, placeHolders)
query.addBindValue(placeHolder);
return query;
}
<commit_msg>Turn off debugs in MediaModel<commit_after>/****************************************************************************
This file is part of the QtMediaHub project on http://www.gitorious.org.
Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).*
All rights reserved.
Contact: Nokia Corporation (qt-info@nokia.com)**
You may use this file under the terms of the BSD license as follows:
"Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Nokia Corporation and its Subsidiary(-ies) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
****************************************************************************/
#include "mediamodel.h"
#include "mediascanner.h"
#include "dbreader.h"
#include "backend.h"
#define DEBUG if (0) qDebug() << __PRETTY_FUNCTION__
MediaModel::MediaModel(QObject *parent)
: QAbstractItemModel(parent), m_loading(false), m_loaded(false), m_reader(0), m_readerThread(0)
{
}
MediaModel::~MediaModel()
{
}
QString MediaModel::part() const
{
return m_structure.split("|").value(m_cursor.length());
}
QString MediaModel::mediaType() const
{
return m_mediaType;
}
void MediaModel::setMediaType(const QString &type)
{
if (type == m_mediaType)
return;
DEBUG << type;
m_mediaType = type;
emit mediaTypeChanged();
// Add the fields of the table as role names
QSqlDriver *driver = Backend::instance()->mediaDatabase().driver();
QSqlRecord record = driver->record(m_mediaType);
if (record.isEmpty())
qWarning() << "Table " << type << " is not valid it seems";
QHash<int, QByteArray> hash = roleNames();
hash.insert(DotDotRole, "dotdot");
hash.insert(IsLeafRole, "isLeaf");
hash.insert(ModelIndexRole,"modelIndex");
hash.insert(PreviewUrlRole, "previewUrl");
for (int i = 0; i < record.count(); i++) {
hash.insert(FieldRolesBegin + i, record.fieldName(i).toUtf8());
}
setRoleNames(hash);
initialize();
}
void MediaModel::addSearchPath(const QString &path, const QString &name)
{
if (m_mediaType.isEmpty()) {
qWarning() << m_mediaType << " is not set yet";
return;
}
QMetaObject::invokeMethod(MediaScanner::instance(), "addSearchPath", Qt::QueuedConnection,
Q_ARG(QString, m_mediaType), Q_ARG(QString, path), Q_ARG(QString, name));
}
void MediaModel::removeSearchPath(int index)
{
Q_UNUSED(index);
}
QString MediaModel::structure() const
{
return m_structure;
}
void MediaModel::setStructure(const QString &str)
{
if (str == m_structure)
return;
DEBUG << str;
m_structure = str;
m_layoutInfo.clear();
foreach(const QString &part, m_structure.split("|"))
m_layoutInfo.append(part.split(","));
initialize();
emit structureChanged();
}
void MediaModel::enter(int index)
{
if (m_cursor.count() + 1 == m_layoutInfo.count() && index != 0 /* up on leaf node is OK */) {
DEBUG << "Refusing to enter leaf node";
return;
}
if (index == 0 && !m_cursor.isEmpty()) {
back();
return;
}
DEBUG << "Entering " << index;
m_cursor.append(m_data[index]);
initialize();
emit partChanged();
}
void MediaModel::back()
{
m_cursor.removeLast();
initialize();
emit partChanged();
}
QVariant MediaModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
if (role == ModelIndexRole)
return qVariantFromValue(index);
return m_data.value(index.row()).value(role);
}
QModelIndex MediaModel::index(int row, int col, const QModelIndex &parent) const
{
if (parent.isValid())
return QModelIndex();
return createIndex(row, col);
}
QModelIndex MediaModel::parent(const QModelIndex &idx) const
{
Q_UNUSED(idx);
return QModelIndex();
}
int MediaModel::rowCount(const QModelIndex &parent) const
{
if (parent.isValid())
return 0;
return m_data.count();
}
int MediaModel::columnCount(const QModelIndex &idx) const
{
Q_UNUSED(idx);
return 1;
}
bool MediaModel::hasChildren(const QModelIndex &parent) const
{
return !parent.isValid();
}
bool MediaModel::canFetchMore(const QModelIndex &parent) const
{
if (parent.isValid() || m_mediaType.isEmpty() || m_layoutInfo.isEmpty()) {
DEBUG << "false " << parent.isValid() << m_mediaType.isEmpty() << m_layoutInfo.isEmpty();
return false;
}
DEBUG << (!m_loading && !m_loaded);
return !m_loading && !m_loaded;
}
void MediaModel::fetchMore(const QModelIndex &parent)
{
if (!canFetchMore(parent))
return;
DEBUG << "";
m_loading = true;
QSqlQuery q = buildQuery();
DEBUG << q.lastQuery();
QMetaObject::invokeMethod(m_reader, "execute", Qt::QueuedConnection, Q_ARG(QSqlQuery, q));
}
void MediaModel::initialize()
{
DEBUG << "";
DbReader *newReader = new DbReader;
if (m_reader) {
disconnect(m_reader, 0, this, 0);
m_reader->stop();
m_reader->deleteLater();
}
m_reader = newReader;
if (!m_readerThread) {
m_readerThread = new QThread(this);
m_readerThread->start();
}
m_reader->moveToThread(m_readerThread);
QMetaObject::invokeMethod(m_reader, "initialize", Q_ARG(QSqlDatabase, Backend::instance()->mediaDatabase()));
connect(m_reader, SIGNAL(dataReady(DbReader *, QList<QSqlRecord>, void *)),
this, SLOT(handleDataReady(DbReader *, QList<QSqlRecord>, void *)));
beginResetModel();
m_loading = m_loaded = false;
m_data.clear();
endResetModel();
}
void MediaModel::handleDataReady(DbReader *reader, const QList<QSqlRecord> &records, void *node)
{
Q_ASSERT(reader == m_reader);
Q_UNUSED(reader);
Q_UNUSED(node);
DEBUG << "Received response from db of size " << records.size();
if (records.isEmpty())
return;
if (!m_cursor.isEmpty()) {
beginInsertRows(QModelIndex(), 0, records.count());
QHash<int, QVariant> data;
data.insert(Qt::DisplayRole, tr(".."));
data.insert(DotDotRole, true);
data.insert(IsLeafRole, false);
m_data.append(data);
} else {
beginInsertRows(QModelIndex(), 0, records.count() - 1);
}
const bool isLeaf = m_cursor.count() + 1 == m_layoutInfo.count();
QSqlDriver *driver = Backend::instance()->mediaDatabase().driver();
const QSqlRecord tableRecord = driver->record(m_mediaType);
for (int i = 0; i < records.count(); i++) {
QHash<int, QVariant> data;
for (int j = 0; j < records[i].count(); j++) {
int idx = tableRecord.indexOf(records[i].fieldName(j));
data.insert(FieldRolesBegin + idx, records[i].value(j));
}
// Provide 'display' role as , separated values
QStringList cols = m_layoutInfo.value(m_cursor.count());
QStringList displayString;
for (int j = 0; j < cols.count(); j++) {
displayString << records[i].value(cols[j]).toString();
}
data.insert(Qt::DisplayRole, displayString.join(", "));
data.insert(DotDotRole, false);
data.insert(IsLeafRole, isLeaf);
data.insert(PreviewUrlRole, records[i].value("thumbnail").toString());
m_data.append(data);
}
m_loading = false;
m_loaded = true;
endInsertRows();
}
void MediaModel::handleDatabaseUpdated(const QList<QSqlRecord> &records)
{
Q_UNUSED(records);
// not implemented yet
}
QSqlQuery MediaModel::buildQuery() const
{
QSqlDriver *driver = Backend::instance()->mediaDatabase().driver();
QStringList escapedCurParts;
QStringList curParts = m_layoutInfo[m_cursor.count()];
for (int i = 0; i < curParts.count(); i++)
escapedCurParts.append(driver->escapeIdentifier(curParts[i], QSqlDriver::FieldName));
QString escapedCurPart = escapedCurParts.join(",");
QSqlQuery query(Backend::instance()->mediaDatabase());
query.setForwardOnly(true);
QStringList placeHolders;
const bool lastPart = m_cursor.count() == m_layoutInfo.count()-1;
QString queryString;
// SQLite allows us to select columns that are not present in the GROUP BY. We use this feature
// to select thumbnails for non-leaf nodes
queryString.append("SELECT *");
queryString.append(" FROM " + driver->escapeIdentifier(m_mediaType, QSqlDriver::TableName));
if (!m_cursor.isEmpty()) {
QStringList where;
const QSqlRecord tableRecord = driver->record(m_mediaType);
for (int i = 0; i < m_cursor.count(); i++) {
QStringList subParts = m_layoutInfo[i];
for (int j = 0; j < subParts.count(); j++) {
where.append(subParts[j] + " = ?");
const int role = FieldRolesBegin + tableRecord.indexOf(subParts[j]);
placeHolders << m_cursor[i].value(role).toString();
}
}
queryString.append(" WHERE " + where.join(" AND "));
}
if (!lastPart)
queryString.append(" GROUP BY " + escapedCurPart);
queryString.append(" ORDER BY " + escapedCurPart);
query.prepare(queryString);
foreach(const QString &placeHolder, placeHolders)
query.addBindValue(placeHolder);
return query;
}
<|endoftext|>
|
<commit_before>#include "NewGameMenu.h"
#include "Player.h"
#ifdef _WIN32
#include <string>
#endif
/** @namespace Symp */
namespace Symp {
extern int g_WindowHeight;
extern int g_WindowWidth;
/**
* @brief NewGameMenu constructor
* Responsible for the initialization of the private attributes of the #NewGameMenuMenu class. This function
* is not responsible for drawing the graphical elements that compose the menu, the #init() function is.
* @see Player
* @see MenuManager
* @see State
* @see init()
* @see ~NewGameMenu()
*/
NewGameMenu::NewGameMenu()
: State()
{
int avatarX = g_WindowWidth*0.3;
int avatarY = g_WindowHeight*0.4;
m_avatarVector.clear();
//Load the avatar available
Image* image0 = new Image("../assets/menu/avatar0.png", avatarX, avatarY);
m_avatarVector.push_back(image0);
Image* image1 = new Image("../assets/menu/avatar1.png", avatarX, avatarY);
m_avatarVector.push_back(image1);
Image* image2 = new Image("../assets/menu/avatar2.png", avatarX, avatarY);
m_avatarVector.push_back(image2);
Image* image3 = new Image("../assets/menu/avatar3.png", avatarX, avatarY);
m_avatarVector.push_back(image3);
}
/**
* @brief NewGameMenu elements initialization
* The elements that compose the menu are created in this function.
* @see Player
* @see MenuManager
* @see State
* @see end()
* @see NewGameMenuMenu()
*/
void NewGameMenu::init(){
m_background = new Image("../assets/menu/new-game.png");
m_background->setWidth(g_WindowWidth);
m_background->setHeight(g_WindowHeight);
m_background->setAspectRatio(AspectRatio::IGNORE_ASPECT_RATIO);
MenuManager::getInstance()->addGuiComponent(m_background, 0);
m_background->update();
// The go back button up-left of the window
m_pBackButton = new Image("../assets/menu/back-to-menu-outgame.png", g_WindowWidth*0.05, g_WindowHeight*0.05, 0.5);
m_pBackButton->setColor(Color::YELLOWDINO);
m_pBackButton->enable();
m_pBackButton->setAspectRatio(AspectRatio::EXPAND_ASPECT_RATIO);
MenuManager::getInstance()->addGuiComponent(m_pBackButton, 1);
//Explanations
m_pExplanation1 = new Text("NAME : ", Color::WHITE, g_WindowWidth*0.4, g_WindowHeight*0.42, true);
m_pExplanation1->getIND_Entity2d()->setAlign(IND_LEFT);
MenuManager::getInstance()->addGuiComponent(m_pExplanation1, 1);
// All the Avatars are initialized hidden
for (unsigned int i = 0; i < m_avatarVector.size(); ++i){
m_avatarVector[i]->setWidth(g_WindowWidth*0.2);
m_avatarVector[i]->setHeight(g_WindowHeight*0.2);
m_avatarVector[i]->update();
m_avatarVector[i]->hide();
MenuManager::getInstance()->addGuiComponent(m_avatarVector[i], 1);
}
// Only show one
m_iCurrentAvatar = 0;
m_avatarVector[0]->show();
//Arrows for naviguation between avatars
m_pArrowLayout = new Layout(g_WindowWidth*0.3, g_WindowHeight*0.6, g_WindowWidth*0.1, g_WindowHeight*0.2);
m_pLeftArrow = new Button("../assets/menu/left_arrow.png");
m_pArrowLayout->addComponent(m_pLeftArrow, 0, 0);
m_pRightArrow = new Button("../assets/menu/right_arrow.png");
m_pArrowLayout->addComponent(m_pRightArrow, 1, 0);
MenuManager::getInstance()->addGuiLayout(m_pArrowLayout, 1);
//Explanations
m_pExplanation2 = new Text("Select your avatar", Color::WHITE, g_WindowWidth*0.35, g_WindowHeight*0.64, true);
m_pExplanation2->getIND_Entity2d()->setAlign(IND_CENTER);
MenuManager::getInstance()->addGuiComponent(m_pExplanation2, 1);
//Line edit
m_pLineEdit = new LineEdit(g_WindowWidth*0.4, g_WindowHeight*0.45, g_WindowWidth*0.3, g_WindowHeight*0.1);
MenuManager::getInstance()->addGuiComponent(m_pLineEdit, 1);
MenuManager::getInstance()->addGuiComponent(m_pLineEdit->getCursor(), 2);
MenuManager::getInstance()->addGuiComponent(m_pLineEdit->getTextEntity(), 1);
//Launch button
m_pLaunchButton = new Image("../assets/menu/create-new-game.png", g_WindowWidth*0.75, g_WindowHeight*0.45);
m_pLaunchButton->setColor(Color::BLUEDINO);
m_pLaunchButton->setHeight(g_WindowHeight*0.1);
m_pLaunchButton->setAspectRatio(AspectRatio::KEEP_ASPECT_RATIO);
m_pLaunchButton->enable();
MenuManager::getInstance()->addGuiComponent(m_pLaunchButton, 1);
}
/**
* @brief Handle mouse clic events
* @param mouseX the x coordinate of the mouse position
* @param mouseY the y coordinate of the mouse position
* @see MenuManager
* @see State
* @see InputManager
* @see init()
*/
void NewGameMenu::handleMouseClic(int mouseX, int mouseY){
if (m_pLaunchButton->isTargetedByMouse(mouseX, mouseY)){
int index = MenuManager::getInstance()->getPlayerIndex();
MenuManager::getInstance()->setPlayerIndex(index + 1);
Player* player = new Player(index, m_pLineEdit->getText(), m_iCurrentAvatar, 1);
MenuManager::getInstance()->setLastPlayer(player);
MenuManager::getInstance()->setHasPlayerDataChanged(true);
MenuManager::getInstance()->setLevelToLoad("../assets/map/level1.xml");
MenuManager::getInstance()->setLevelChoosen(true);
}
else if(m_pLineEdit->isTargetedByMouse(mouseX, mouseY)){
//Trigger the focus
m_pLineEdit->triggerFocus();
}else if(m_pLineEdit->hasFocus() && !m_pLineEdit->isTargetedByMouse(mouseX, mouseY)){
//Trigger the focus
m_pLineEdit->triggerFocus();
}else if(m_pBackButton->isTargetedByMouse(mouseX, mouseY)){
// Go back
MenuManager::getInstance()->goBack();
}
else if (m_pLeftArrow->isTargetedByMouse(mouseX, mouseY)){
// Display the previous avatar in the list
if(m_iCurrentAvatar != 0){
m_avatarVector[m_iCurrentAvatar]->hide();
m_avatarVector[m_iCurrentAvatar-1]->show();
m_iCurrentAvatar = m_iCurrentAvatar-1;
}
}
else if (m_pRightArrow->isTargetedByMouse(mouseX, mouseY)){
// Display the following avatar in the list
if(m_iCurrentAvatar != m_avatarVector.size()-1){
m_avatarVector[m_iCurrentAvatar]->hide();
m_avatarVector[m_iCurrentAvatar+1]->show();
m_iCurrentAvatar = m_iCurrentAvatar+1;
}
}
}
/**
* @brief Handle key event for the #LineEdit
* @see MenuManager
* @see State
* @see InputManager
* @see init()
*/
void NewGameMenu::receiveKeyEvent(std::string key){
m_pLineEdit->setText(m_pLineEdit->getText() + key.c_str());
}
/**
* @brief Erase the character which is before the cursor index
* @see MenuManager
* @see State
* @see InputManager
* @see init()
*/
void NewGameMenu::erasePreviousCharacter(){
m_pLineEdit->erasePreviousToCursor();
}
/**
* @brief Erase the character which is after the cursor index
* @see MenuManager
* @see State
* @see InputManager
* @see init()
*/
void NewGameMenu::eraseNextCharacter(){
m_pLineEdit->eraseNextToCursor();
}
/**
* @brief Move the cursor of the #LineEdit to the left
* @see MenuManager
* @see State
* @see InputManager
* @see init()
*/
void NewGameMenu::moveCursorLeft(){
m_pLineEdit->moveCursorLeft();
}
/**
* @brief Move the cursor of the #LineEdit to the right
* @see MenuManager
* @see State
* @see InputManager
* @see init()
*/
void NewGameMenu::moveCursorRight(){
m_pLineEdit->moveCursorRight();
}
/**
* @brief Handle key down event
* @see MenuManager
* @see State
* @see InputManager
* @see init()
*/
void NewGameMenu::keyDownPressed(){
std::cout << "Key down pressed" <<std::endl;
}
/**
* @brief Handle key up event
* @see MenuManager
* @see State
* @see InputManager
* @see init()
*/
void NewGameMenu::keyUpPressed(){
std::cout << "Key up pressed" <<std::endl;
}
}<commit_msg>Center "Select Your Avatar" in the "CreateNewGameMenu". fix #168<commit_after>#include "NewGameMenu.h"
#include "Player.h"
#ifdef _WIN32
#include <string>
#endif
/** @namespace Symp */
namespace Symp {
extern int g_WindowHeight;
extern int g_WindowWidth;
/**
* @brief NewGameMenu constructor
* Responsible for the initialization of the private attributes of the #NewGameMenuMenu class. This function
* is not responsible for drawing the graphical elements that compose the menu, the #init() function is.
* @see Player
* @see MenuManager
* @see State
* @see init()
* @see ~NewGameMenu()
*/
NewGameMenu::NewGameMenu()
: State()
{
int avatarX = g_WindowWidth*0.298;
int avatarY = g_WindowHeight*0.4;
m_avatarVector.clear();
//Load the avatar available
Image* image0 = new Image("../assets/menu/avatar0.png", avatarX, avatarY);
m_avatarVector.push_back(image0);
Image* image1 = new Image("../assets/menu/avatar1.png", avatarX, avatarY);
m_avatarVector.push_back(image1);
Image* image2 = new Image("../assets/menu/avatar2.png", avatarX, avatarY);
m_avatarVector.push_back(image2);
Image* image3 = new Image("../assets/menu/avatar3.png", avatarX, avatarY);
m_avatarVector.push_back(image3);
}
/**
* @brief NewGameMenu elements initialization
* The elements that compose the menu are created in this function.
* @see Player
* @see MenuManager
* @see State
* @see end()
* @see NewGameMenuMenu()
*/
void NewGameMenu::init(){
m_background = new Image("../assets/menu/new-game.png");
m_background->setWidth(g_WindowWidth);
m_background->setHeight(g_WindowHeight);
m_background->setAspectRatio(AspectRatio::IGNORE_ASPECT_RATIO);
MenuManager::getInstance()->addGuiComponent(m_background, 0);
m_background->update();
// The go back button up-left of the window
m_pBackButton = new Image("../assets/menu/back-to-menu-outgame.png", g_WindowWidth*0.05, g_WindowHeight*0.05, 0.5);
m_pBackButton->setColor(Color::YELLOWDINO);
m_pBackButton->enable();
m_pBackButton->setAspectRatio(AspectRatio::EXPAND_ASPECT_RATIO);
MenuManager::getInstance()->addGuiComponent(m_pBackButton, 1);
//Explanations
m_pExplanation1 = new Text("NAME : ", Color::WHITE, g_WindowWidth*0.4, g_WindowHeight*0.42, true);
m_pExplanation1->getIND_Entity2d()->setAlign(IND_LEFT);
MenuManager::getInstance()->addGuiComponent(m_pExplanation1, 1);
// All the Avatars are initialized hidden
for (unsigned int i = 0; i < m_avatarVector.size(); ++i){
m_avatarVector[i]->setWidth(g_WindowWidth*0.2);
m_avatarVector[i]->setHeight(g_WindowHeight*0.2);
m_avatarVector[i]->update();
m_avatarVector[i]->hide();
MenuManager::getInstance()->addGuiComponent(m_avatarVector[i], 1);
}
// Only show one
m_iCurrentAvatar = 0;
m_avatarVector[0]->show();
//Arrows for naviguation between avatars
m_pArrowLayout = new Layout(g_WindowWidth*0.305, g_WindowHeight*0.6, g_WindowWidth*0.1, g_WindowHeight*0.2);
m_pLeftArrow = new Button("../assets/menu/left_arrow.png");
m_pArrowLayout->addComponent(m_pLeftArrow, 0, 0);
m_pRightArrow = new Button("../assets/menu/right_arrow.png");
m_pArrowLayout->addComponent(m_pRightArrow, 1, 0);
MenuManager::getInstance()->addGuiLayout(m_pArrowLayout, 1);
//Explanations
m_pExplanation2 = new Text("Select your avatar", Color::WHITE, g_WindowWidth*0.34, g_WindowHeight*0.64, true);
m_pExplanation2->getIND_Entity2d()->setAlign(IND_CENTER);
MenuManager::getInstance()->addGuiComponent(m_pExplanation2, 1);
//Line edit
m_pLineEdit = new LineEdit(g_WindowWidth*0.4, g_WindowHeight*0.45, g_WindowWidth*0.3, g_WindowHeight*0.1);
MenuManager::getInstance()->addGuiComponent(m_pLineEdit, 1);
MenuManager::getInstance()->addGuiComponent(m_pLineEdit->getCursor(), 2);
MenuManager::getInstance()->addGuiComponent(m_pLineEdit->getTextEntity(), 1);
//Launch button
m_pLaunchButton = new Image("../assets/menu/create-new-game.png", g_WindowWidth*0.75, g_WindowHeight*0.45);
m_pLaunchButton->setColor(Color::BLUEDINO);
m_pLaunchButton->setHeight(g_WindowHeight*0.1);
m_pLaunchButton->setAspectRatio(AspectRatio::KEEP_ASPECT_RATIO);
m_pLaunchButton->enable();
MenuManager::getInstance()->addGuiComponent(m_pLaunchButton, 1);
}
/**
* @brief Handle mouse clic events
* @param mouseX the x coordinate of the mouse position
* @param mouseY the y coordinate of the mouse position
* @see MenuManager
* @see State
* @see InputManager
* @see init()
*/
void NewGameMenu::handleMouseClic(int mouseX, int mouseY){
if (m_pLaunchButton->isTargetedByMouse(mouseX, mouseY)){
int index = MenuManager::getInstance()->getPlayerIndex();
MenuManager::getInstance()->setPlayerIndex(index + 1);
Player* player = new Player(index, m_pLineEdit->getText(), m_iCurrentAvatar, 1);
MenuManager::getInstance()->setLastPlayer(player);
MenuManager::getInstance()->setHasPlayerDataChanged(true);
MenuManager::getInstance()->setLevelToLoad("../assets/map/level1.xml");
MenuManager::getInstance()->setLevelChoosen(true);
}
else if(m_pLineEdit->isTargetedByMouse(mouseX, mouseY)){
//Trigger the focus
m_pLineEdit->triggerFocus();
}else if(m_pLineEdit->hasFocus() && !m_pLineEdit->isTargetedByMouse(mouseX, mouseY)){
//Trigger the focus
m_pLineEdit->triggerFocus();
}else if(m_pBackButton->isTargetedByMouse(mouseX, mouseY)){
// Go back
MenuManager::getInstance()->goBack();
}
else if (m_pLeftArrow->isTargetedByMouse(mouseX, mouseY)){
// Display the previous avatar in the list
if(m_iCurrentAvatar != 0){
m_avatarVector[m_iCurrentAvatar]->hide();
m_avatarVector[m_iCurrentAvatar-1]->show();
m_iCurrentAvatar = m_iCurrentAvatar-1;
}
}
else if (m_pRightArrow->isTargetedByMouse(mouseX, mouseY)){
// Display the following avatar in the list
if(m_iCurrentAvatar != m_avatarVector.size()-1){
m_avatarVector[m_iCurrentAvatar]->hide();
m_avatarVector[m_iCurrentAvatar+1]->show();
m_iCurrentAvatar = m_iCurrentAvatar+1;
}
}
}
/**
* @brief Handle key event for the #LineEdit
* @see MenuManager
* @see State
* @see InputManager
* @see init()
*/
void NewGameMenu::receiveKeyEvent(std::string key){
m_pLineEdit->setText(m_pLineEdit->getText() + key.c_str());
}
/**
* @brief Erase the character which is before the cursor index
* @see MenuManager
* @see State
* @see InputManager
* @see init()
*/
void NewGameMenu::erasePreviousCharacter(){
m_pLineEdit->erasePreviousToCursor();
}
/**
* @brief Erase the character which is after the cursor index
* @see MenuManager
* @see State
* @see InputManager
* @see init()
*/
void NewGameMenu::eraseNextCharacter(){
m_pLineEdit->eraseNextToCursor();
}
/**
* @brief Move the cursor of the #LineEdit to the left
* @see MenuManager
* @see State
* @see InputManager
* @see init()
*/
void NewGameMenu::moveCursorLeft(){
m_pLineEdit->moveCursorLeft();
}
/**
* @brief Move the cursor of the #LineEdit to the right
* @see MenuManager
* @see State
* @see InputManager
* @see init()
*/
void NewGameMenu::moveCursorRight(){
m_pLineEdit->moveCursorRight();
}
/**
* @brief Handle key down event
* @see MenuManager
* @see State
* @see InputManager
* @see init()
*/
void NewGameMenu::keyDownPressed(){
std::cout << "Key down pressed" <<std::endl;
}
/**
* @brief Handle key up event
* @see MenuManager
* @see State
* @see InputManager
* @see init()
*/
void NewGameMenu::keyUpPressed(){
std::cout << "Key up pressed" <<std::endl;
}
}<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <assert.h>
#include <jni.h>
#include "webrtc/modules/audio_device/android/audio_device_template.h"
#include "webrtc/modules/audio_device/android/audio_record_jni.h"
#include "webrtc/modules/audio_device/android/audio_track_jni.h"
#include "webrtc/modules/audio_device/android/opensles_input.h"
#include "webrtc/modules/audio_device/android/opensles_output.h"
#include "webrtc/modules/audio_device/android/test/fake_audio_device_buffer.h"
#include "webrtc/system_wrappers/interface/scoped_ptr.h"
// Java globals
static JavaVM* g_vm = NULL;
static jclass g_osr = NULL;
namespace webrtc {
template <class InputType, class OutputType>
class OpenSlRunnerTemplate {
public:
OpenSlRunnerTemplate()
: output_(0),
input_(0, &output_) {
output_.AttachAudioBuffer(&audio_buffer_);
if (output_.Init() != 0) {
assert(false);
}
if (output_.InitPlayout() != 0) {
assert(false);
}
input_.AttachAudioBuffer(&audio_buffer_);
if (input_.Init() != 0) {
assert(false);
}
if (input_.InitRecording() != 0) {
assert(false);
}
}
~OpenSlRunnerTemplate() {}
void StartPlayRecord() {
output_.StartPlayout();
input_.StartRecording();
}
void StopPlayRecord() {
// There are large enough buffers to compensate for recording and playing
// jitter such that the timing of stopping playing or recording should not
// result in over or underrun.
input_.StopRecording();
output_.StopPlayout();
audio_buffer_.ClearBuffer();
}
void RegisterApplicationContext(
JNIEnv* env,
jobject obj,
jobject context) {
OutputType::SetAndroidAudioDeviceObjects(env, obj, context);
InputType::SetAndroidAudioDeviceObjects(env, obj, context);
}
private:
OutputType output_;
InputType input_;
FakeAudioDeviceBuffer audio_buffer_;
};
class OpenSlRunner
: public OpenSlRunnerTemplate<OpenSlesInput, OpenSlesOutput> {
public:
// Global class implementing native code.
static OpenSlRunner* g_runner;
OpenSlRunner() {}
virtual ~OpenSlRunner() {}
static JNIEXPORT void JNICALL RegisterApplicationContext(
JNIEnv* env,
jobject obj,
jobject context) {
assert(!g_runner); // Should only be called once.
g_runner = new OpenSlRunner();
}
static JNIEXPORT void JNICALL Start(JNIEnv * env, jobject) {
g_runner->StartPlayRecord();
}
static JNIEXPORT void JNICALL Stop(JNIEnv * env, jobject) {
g_runner->StopPlayRecord();
}
};
OpenSlRunner* OpenSlRunner::g_runner = NULL;
} // namespace webrtc
jint JNI_OnLoad(JavaVM* vm, void* reserved) {
// Only called once.
assert(!g_vm);
JNIEnv* env;
if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
return -1;
}
jclass local_osr = env->FindClass("org/webrtc/app/OpenSlRunner");
assert(local_osr != NULL);
g_osr = static_cast<jclass>(env->NewGlobalRef(local_osr));
JNINativeMethod nativeFunctions[] = {
{"RegisterApplicationContext", "(Landroid/content/Context;)V",
reinterpret_cast<void*>(
&webrtc::OpenSlRunner::RegisterApplicationContext)},
{"Start", "()V", reinterpret_cast<void*>(&webrtc::OpenSlRunner::Start)},
{"Stop", "()V", reinterpret_cast<void*>(&webrtc::OpenSlRunner::Stop)}
};
int ret_val = env->RegisterNatives(g_osr, nativeFunctions, 3);
if (ret_val != 0) {
assert(false);
}
g_vm = vm;
return JNI_VERSION_1_6;
}
<commit_msg>Android, OpenSlDemo: fixes issue where app would crash as soon as the application is started.<commit_after>/*
* Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <assert.h>
#include <jni.h>
#include "webrtc/modules/audio_device/android/audio_device_template.h"
#include "webrtc/modules/audio_device/android/audio_record_jni.h"
#include "webrtc/modules/audio_device/android/audio_track_jni.h"
#include "webrtc/modules/audio_device/android/opensles_input.h"
#include "webrtc/modules/audio_device/android/opensles_output.h"
#include "webrtc/modules/audio_device/android/test/fake_audio_device_buffer.h"
#include "webrtc/system_wrappers/interface/scoped_ptr.h"
// Java globals
static JavaVM* g_vm = NULL;
static jclass g_osr = NULL;
namespace webrtc {
template <class InputType, class OutputType>
class OpenSlRunnerTemplate {
public:
OpenSlRunnerTemplate()
: output_(0),
input_(0, &output_) {
output_.AttachAudioBuffer(&audio_buffer_);
if (output_.Init() != 0) {
assert(false);
}
if (output_.InitPlayout() != 0) {
assert(false);
}
input_.AttachAudioBuffer(&audio_buffer_);
if (input_.Init() != 0) {
assert(false);
}
if (input_.InitRecording() != 0) {
assert(false);
}
}
~OpenSlRunnerTemplate() {}
void StartPlayRecord() {
output_.StartPlayout();
input_.StartRecording();
}
void StopPlayRecord() {
// There are large enough buffers to compensate for recording and playing
// jitter such that the timing of stopping playing or recording should not
// result in over or underrun.
input_.StopRecording();
output_.StopPlayout();
audio_buffer_.ClearBuffer();
}
private:
OutputType output_;
InputType input_;
FakeAudioDeviceBuffer audio_buffer_;
};
class OpenSlRunner
: public OpenSlRunnerTemplate<OpenSlesInput, OpenSlesOutput> {
public:
// Global class implementing native code.
static OpenSlRunner* g_runner;
OpenSlRunner() {}
virtual ~OpenSlRunner() {}
static JNIEXPORT void JNICALL RegisterApplicationContext(
JNIEnv* env,
jobject obj,
jobject context) {
assert(!g_runner); // Should only be called once.
// Register the application context in the superclass to avoid having to
// qualify the template instantiation again.
OpenSlesInput::SetAndroidAudioDeviceObjects(g_vm, env, context);
OpenSlesOutput::SetAndroidAudioDeviceObjects(g_vm, env, context);
g_runner = new OpenSlRunner();
}
static JNIEXPORT void JNICALL Start(JNIEnv * env, jobject) {
g_runner->StartPlayRecord();
}
static JNIEXPORT void JNICALL Stop(JNIEnv * env, jobject) {
g_runner->StopPlayRecord();
}
};
OpenSlRunner* OpenSlRunner::g_runner = NULL;
} // namespace webrtc
jint JNI_OnLoad(JavaVM* vm, void* reserved) {
// Only called once.
assert(!g_vm);
JNIEnv* env;
if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
return -1;
}
jclass local_osr = env->FindClass("org/webrtc/app/OpenSlRunner");
assert(local_osr != NULL);
g_osr = static_cast<jclass>(env->NewGlobalRef(local_osr));
JNINativeMethod nativeFunctions[] = {
{"RegisterApplicationContext", "(Landroid/content/Context;)V",
reinterpret_cast<void*>(
&webrtc::OpenSlRunner::RegisterApplicationContext)},
{"Start", "()V", reinterpret_cast<void*>(&webrtc::OpenSlRunner::Start)},
{"Stop", "()V", reinterpret_cast<void*>(&webrtc::OpenSlRunner::Stop)}
};
int ret_val = env->RegisterNatives(g_osr, nativeFunctions, 3);
if (ret_val != 0) {
assert(false);
}
g_vm = vm;
return JNI_VERSION_1_6;
}
<|endoftext|>
|
<commit_before>#include "Logger.h"
#ifdef _WIN32
#include <stdio.h>
#include "Console.h"
#elif defined(ANDROID)
#include <android/log.h>
#endif
#ifdef DESKTOP
#include <glew.h>
#else
#include <GLES2/gl2.h>
#endif
namespace star {
Logger * Logger::m_LoggerPtr = nullptr;
Logger::Logger()
#ifdef _WIN32
:m_ConsoleHandle(nullptr)
#endif
{
}
Logger::~Logger()
{
CloseHandle(m_ConsoleHandle);
}
Logger * Logger::GetInstance()
{
if(m_LoggerPtr == nullptr)
{
m_LoggerPtr = new Logger();
}
return m_LoggerPtr;
}
void Logger::ResetSingleton()
{
//Delete resources.
}
void Logger::Initialize()
{
#ifdef _WIN32
WindowsConsole::RedirectIOToConsole();
m_ConsoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
#endif
}
void Logger::Log(LogLevel level, const tstring& pMessage, const tstring& tag) const
{
#if LOGGER_MIN_LEVEL > 0
#ifdef DESKTOP
tstring levelName;
switch(level)
{
case LogLevel::Info :
levelName = _T("INFO");
break;
case LogLevel::Warning:
levelName = _T("WARNING");
break;
case LogLevel::Error:
levelName = _T("ERROR");
break;
case LogLevel::Debug:
levelName = _T("DEBUG");
break;
}
tstringstream messageBuffer;
messageBuffer << _T("[") << tag << _T("] ") << _T("[") << levelName << _T("] ") << pMessage << std::endl;
tstring combinedMessage = messageBuffer.str();
switch(level)
{
case LogLevel::Info :
#if LOGGER_MIN_LEVEL < 2
SetConsoleTextAttribute(m_ConsoleHandle, FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
tprintf(combinedMessage.c_str());
#endif
break;
case LogLevel::Warning :
#if LOGGER_MIN_LEVEL < 3
SetConsoleTextAttribute(m_ConsoleHandle, FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN);
tprintf(combinedMessage.c_str());
#endif
break;
case LogLevel::Error :
#if LOGGER_MIN_LEVEL < 4
SetConsoleTextAttribute(m_ConsoleHandle, FOREGROUND_INTENSITY | FOREGROUND_RED);
tprintf(combinedMessage.c_str());
break;
#endif
case LogLevel::Debug :
#if LOGGER_MIN_LEVEL < 5
#ifdef DEBUG
SetConsoleTextAttribute(m_ConsoleHandle, FOREGROUND_INTENSITY | FOREGROUND_GREEN);
tprintf(combinedMessage.c_str());
#endif
#endif
break;
}
#else
switch(level)
{
case LogLevel::Info:
#if LOGGER_MIN_LEVEL < 2
__android_log_print(ANDROID_LOG_INFO, tag.c_str(), "%s", pMessage.c_str());
#endif
break;
case LogLevel::Warning:
#if LOGGER_MIN_LEVEL < 3
__android_log_print(ANDROID_LOG_WARN, tag.c_str(), "%s", pMessage.c_str());
#endif
break;
case LogLevel::Error:
#if LOGGER_MIN_LEVEL < 4
__android_log_print(ANDROID_LOG_ERROR, tag.c_str(), "%s", pMessage.c_str());
#endif
break;
case LogLevel::Debug:
#if LOGGER_MIN_LEVEL < 5
#ifdef DEBUG
__android_log_print(ANDROID_LOG_DEBUG, tag.c_str(), pMessage.c_str());
#endif
#endif
break;
}
#endif
#endif
}
void Logger::_CheckGlError(const char* file, int line)
{
#if LOGGER_MIN_LEVEL > 0
GLenum err (glGetError());
while(err!= GL_NO_ERROR)
{
tstring error;
switch(err)
{
case GL_INVALID_OPERATION:
error = _T("INVALID_OPERATION");
break;
case GL_INVALID_ENUM:
error = _T("INVALID_ENUM");
break;
case GL_INVALID_VALUE:
error = _T("INVALID_VALUE");
break;
case GL_OUT_OF_MEMORY:
error = _T("OUT_OF_MEMORY");
break;
case GL_INVALID_FRAMEBUFFER_OPERATION:
error = _T("INVALID_FRAMEBUFFER_OPERATION");
break;
default:
error =_T("UNKNOWN_ERROR");
break;
}
tstringstream buffer;
buffer << "GL_" << error << " - " << file << ":" << line << std::endl;
Logger::GetInstance()->Log(LogLevel::Error,buffer.str(),_T("OPENGL"));
err = glGetError();
}
#endif
}
}
<commit_msg>Hot fix android<commit_after>#include "Logger.h"
#ifdef _WIN32
#include <stdio.h>
#include "Console.h"
#elif defined(ANDROID)
#include <android/log.h>
#endif
#ifdef DESKTOP
#include <glew.h>
#else
#include <GLES2/gl2.h>
#endif
namespace star {
Logger * Logger::m_LoggerPtr = nullptr;
Logger::Logger()
#ifdef _WIN32
:m_ConsoleHandle(nullptr)
#endif
{
}
Logger::~Logger()
{
#ifdef _WIN32
CloseHandle(m_ConsoleHandle);
#endif
}
Logger * Logger::GetInstance()
{
if(m_LoggerPtr == nullptr)
{
m_LoggerPtr = new Logger();
}
return m_LoggerPtr;
}
void Logger::ResetSingleton()
{
//Delete resources.
}
void Logger::Initialize()
{
#ifdef _WIN32
WindowsConsole::RedirectIOToConsole();
m_ConsoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
#endif
}
void Logger::Log(LogLevel level, const tstring& pMessage, const tstring& tag) const
{
#if LOGGER_MIN_LEVEL > 0
#ifdef DESKTOP
tstring levelName;
switch(level)
{
case LogLevel::Info :
levelName = _T("INFO");
break;
case LogLevel::Warning:
levelName = _T("WARNING");
break;
case LogLevel::Error:
levelName = _T("ERROR");
break;
case LogLevel::Debug:
levelName = _T("DEBUG");
break;
}
tstringstream messageBuffer;
messageBuffer << _T("[") << tag << _T("] ") << _T("[") << levelName << _T("] ") << pMessage << std::endl;
tstring combinedMessage = messageBuffer.str();
switch(level)
{
case LogLevel::Info :
#if LOGGER_MIN_LEVEL < 2
SetConsoleTextAttribute(m_ConsoleHandle, FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
tprintf(combinedMessage.c_str());
#endif
break;
case LogLevel::Warning :
#if LOGGER_MIN_LEVEL < 3
SetConsoleTextAttribute(m_ConsoleHandle, FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN);
tprintf(combinedMessage.c_str());
#endif
break;
case LogLevel::Error :
#if LOGGER_MIN_LEVEL < 4
SetConsoleTextAttribute(m_ConsoleHandle, FOREGROUND_INTENSITY | FOREGROUND_RED);
tprintf(combinedMessage.c_str());
break;
#endif
case LogLevel::Debug :
#if LOGGER_MIN_LEVEL < 5
#ifdef DEBUG
SetConsoleTextAttribute(m_ConsoleHandle, FOREGROUND_INTENSITY | FOREGROUND_GREEN);
tprintf(combinedMessage.c_str());
#endif
#endif
break;
}
#else
switch(level)
{
case LogLevel::Info:
#if LOGGER_MIN_LEVEL < 2
__android_log_print(ANDROID_LOG_INFO, tag.c_str(), "%s", pMessage.c_str());
#endif
break;
case LogLevel::Warning:
#if LOGGER_MIN_LEVEL < 3
__android_log_print(ANDROID_LOG_WARN, tag.c_str(), "%s", pMessage.c_str());
#endif
break;
case LogLevel::Error:
#if LOGGER_MIN_LEVEL < 4
__android_log_print(ANDROID_LOG_ERROR, tag.c_str(), "%s", pMessage.c_str());
#endif
break;
case LogLevel::Debug:
#if LOGGER_MIN_LEVEL < 5
#ifdef DEBUG
__android_log_print(ANDROID_LOG_DEBUG, tag.c_str(), pMessage.c_str());
#endif
#endif
break;
}
#endif
#endif
}
void Logger::_CheckGlError(const char* file, int line)
{
#if LOGGER_MIN_LEVEL > 0
GLenum err (glGetError());
while(err!= GL_NO_ERROR)
{
tstring error;
switch(err)
{
case GL_INVALID_OPERATION:
error = _T("INVALID_OPERATION");
break;
case GL_INVALID_ENUM:
error = _T("INVALID_ENUM");
break;
case GL_INVALID_VALUE:
error = _T("INVALID_VALUE");
break;
case GL_OUT_OF_MEMORY:
error = _T("OUT_OF_MEMORY");
break;
case GL_INVALID_FRAMEBUFFER_OPERATION:
error = _T("INVALID_FRAMEBUFFER_OPERATION");
break;
default:
error =_T("UNKNOWN_ERROR");
break;
}
tstringstream buffer;
buffer << "GL_" << error << " - " << file << ":" << line << std::endl;
Logger::GetInstance()->Log(LogLevel::Error,buffer.str(),_T("OPENGL"));
err = glGetError();
}
#endif
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: FilteredContainer.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: rt $ $Date: 2008-01-30 08:28:22 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_dbaccess.hxx"
#ifndef DBACCESS_CORE_FILTERED_CONTAINER_HXX
#include "FilteredContainer.hxx"
#endif
#ifndef DBA_CORE_REFRESHLISTENER_HXX
#include "RefreshListener.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include "connectivity/dbtools.hxx"
#endif
#ifndef _WLDCRD_HXX
#include <tools/wldcrd.hxx>
#endif
namespace dbaccess
{
using namespace dbtools;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::container;
using namespace ::osl;
using namespace ::comphelper;
using namespace ::cppu;
using namespace ::connectivity::sdbcx;
//------------------------------------------------------------------------------
/** creates a vector of WildCards and reduce the _rTableFilter of the length of WildsCards
*/
sal_Int32 createWildCardVector(Sequence< ::rtl::OUString >& _rTableFilter, ::std::vector< WildCard >& _rOut)
{
// for wildcard search : remove all table filters which are a wildcard expression and build a WilCard
// for them
::rtl::OUString* pTableFilters = _rTableFilter.getArray();
::rtl::OUString* pEnd = pTableFilters + _rTableFilter.getLength();
sal_Int32 nShiftPos = 0;
for (sal_Int32 i=0; pEnd != pTableFilters; ++pTableFilters,++i)
{
if (pTableFilters->indexOf('%') != -1)
{
_rOut.push_back(WildCard(pTableFilters->replace('%', '*')));
}
else
{
if (nShiftPos != i)
{
_rTableFilter.getArray()[nShiftPos] = _rTableFilter.getArray()[i];
}
++nShiftPos;
}
}
// now aTableFilter contains nShiftPos non-wc-strings and aWCSearch all wc-strings
_rTableFilter.realloc(nShiftPos);
return nShiftPos;
}
//==========================================================================
//= OViewContainer
//==========================================================================
OFilteredContainer::OFilteredContainer(::cppu::OWeakObject& _rParent,
::osl::Mutex& _rMutex,
const Reference< XConnection >& _xCon,
sal_Bool _bCase,
IRefreshListener* _pRefreshListener,
IWarningsContainer* _pWarningsContainer
,oslInterlockedCount& _nInAppend)
:OCollection(_rParent,_bCase,_rMutex,::std::vector< ::rtl::OUString>())
,m_pWarningsContainer(_pWarningsContainer)
,m_pRefreshListener(_pRefreshListener)
,m_nInAppend(_nInAppend)
,m_xConnection(_xCon)
,m_bConstructed(sal_False)
{
}
// -------------------------------------------------------------------------
void OFilteredContainer::construct(const Reference< XNameAccess >& _rxMasterContainer,
const Sequence< ::rtl::OUString >& _rTableFilter,
const Sequence< ::rtl::OUString >& _rTableTypeFilter)
{
try
{
Reference<XConnection> xCon = m_xConnection;
if ( xCon.is() )
m_xMetaData = xCon->getMetaData();
}
catch(SQLException&)
{
}
m_xMasterContainer = _rxMasterContainer;
if(m_xMasterContainer.is())
{
addMasterContainerListener();
sal_Int32 nTableFilterLen = _rTableFilter.getLength();
connectivity::TStringVector aTableNames;
sal_Bool bNoTableFilters = ((nTableFilterLen == 1) && _rTableFilter[0].equalsAsciiL("%", 1));
if(!bNoTableFilters)
{
Sequence< ::rtl::OUString > aTableFilter = _rTableFilter;
Sequence< ::rtl::OUString > aTableTypeFilter = _rTableTypeFilter;
// build sorted versions of the filter sequences, so the visibility decision is faster
::std::sort( aTableFilter.getArray(), aTableFilter.getArray() + nTableFilterLen );
// as we want to modify nTableFilterLen, remember this
// for wildcard search : remove all table filters which are a wildcard expression and build a WilCard
// for them
::std::vector< WildCard > aWCSearch; // contains the wildcards for the table filter
nTableFilterLen = createWildCardVector(aTableFilter,aWCSearch);
aTableNames.reserve(nTableFilterLen + (aWCSearch.size() * 10));
Sequence< ::rtl::OUString> aNames = m_xMasterContainer->getElementNames();
const ::rtl::OUString* pBegin = aNames.getConstArray();
const ::rtl::OUString* pEnd = pBegin + aNames.getLength();
for(;pBegin != pEnd;++pBegin)
{
if(isNameValid(*pBegin,aTableFilter,aTableTypeFilter,aWCSearch))
aTableNames.push_back(*pBegin);
}
}
else
{
// no filter so insert all names
Sequence< ::rtl::OUString> aNames = m_xMasterContainer->getElementNames();
const ::rtl::OUString* pBegin = aNames.getConstArray();
const ::rtl::OUString* pEnd = pBegin + aNames.getLength();
aTableNames = connectivity::TStringVector(pBegin,pEnd);
}
reFill(aTableNames);
m_bConstructed = sal_True;
}
else
{
construct(_rTableFilter,_rTableTypeFilter);
}
}
//------------------------------------------------------------------------------
void OFilteredContainer::construct(const Sequence< ::rtl::OUString >& _rTableFilter, const Sequence< ::rtl::OUString >& _rTableTypeFilter)
{
try
{
Reference<XConnection> xCon = m_xConnection;
if ( xCon.is() )
m_xMetaData = xCon->getMetaData();
}
catch(SQLException&)
{
}
// build sorted versions of the filter sequences, so the visibility decision is faster
Sequence< ::rtl::OUString > aTableFilter(_rTableFilter);
sal_Int32 nTableFilterLen = aTableFilter.getLength();
if (nTableFilterLen)
::std::sort( aTableFilter.getArray(), aTableFilter.getArray() + nTableFilterLen );
sal_Bool bNoTableFilters = ((nTableFilterLen == 1) && _rTableFilter[0].equalsAsciiL("%", 1));
// as we want to modify nTableFilterLen, remember this
// for wildcard search : remove all table filters which are a wildcard expression and build a WilCard
// for them
::std::vector< WildCard > aWCSearch;
nTableFilterLen = createWildCardVector(aTableFilter,aWCSearch);
try
{
if (m_xMetaData.is())
{
static const ::rtl::OUString sAll = ::rtl::OUString::createFromAscii("%");
Sequence< ::rtl::OUString > sTableTypes = getTableTypeFilter(_rTableTypeFilter);
if ( m_bConstructed && sTableTypes.getLength() == 0 )
return;
Reference< XResultSet > xTables = m_xMetaData->getTables(Any(), sAll, sAll, sTableTypes);
Reference< XRow > xCurrentRow(xTables, UNO_QUERY);
if (xCurrentRow.is())
{
// after creation the set is positioned before the first record, per definitionem
::rtl::OUString sCatalog, sSchema, sName, sType;
::rtl::OUString sComposedName;
// we first collect the names and construct the OTable objects later, as the ctor of the table may need
// another result set from the connection, and some drivers support only one statement per connection
sal_Bool bFilterMatch;
while (xTables->next())
{
sCatalog = xCurrentRow->getString(1);
sSchema = xCurrentRow->getString(2);
sName = xCurrentRow->getString(3);
#if OSL_DEBUG_LEVEL > 0
::rtl::OUString sTableType = xCurrentRow->getString(4);
#endif
// we're not interested in the "wasNull", as the getStrings would return an empty string in
// that case, which is sufficient here
sComposedName = composeTableName( m_xMetaData, sCatalog, sSchema, sName, sal_False, ::dbtools::eInDataManipulation );
const ::rtl::OUString* tableFilter = aTableFilter.getConstArray();
const ::rtl::OUString* tableFilterEnd = aTableFilter.getConstArray() + nTableFilterLen;
bool composedNameInFilter = ::std::find( tableFilter, tableFilterEnd, sComposedName ) != tableFilterEnd;
bFilterMatch = bNoTableFilters
|| ( ( nTableFilterLen != 0 )
&& composedNameInFilter
);
// the table is allowed to "pass" if we had no filters at all or any of the non-wildcard filters matches
if (!bFilterMatch && aWCSearch.size())
{ // or if one of the wildcrad expression matches
for ( ::std::vector< WildCard >::const_iterator aLoop = aWCSearch.begin();
aLoop != aWCSearch.end() && !bFilterMatch;
++aLoop
)
bFilterMatch = aLoop->Matches(sComposedName);
}
if (bFilterMatch)
{ // the table name is allowed (not filtered out)
insertElement(sComposedName,NULL);
}
}
// dispose the tables result set, in case the connection can handle only one concurrent statement
// (the table object creation will need it's own statements)
disposeComponent(xTables);
}
else
OSL_ENSURE(0,"OFilteredContainer::construct : did not get a XRow from the tables result set !");
}
else
OSL_ENSURE(0,"OFilteredContainer::construct : no connection meta data !");
}
catch (SQLException&)
{
OSL_ENSURE(0,"OFilteredContainer::construct: caught an SQL-Exception !");
disposing();
return;
}
m_bConstructed = sal_True;
}
//------------------------------------------------------------------------------
void OFilteredContainer::disposing()
{
OCollection::disposing();
removeMasterContainerListener();
m_xMasterContainer = NULL;
m_xMetaData = NULL;
m_pWarningsContainer = NULL;
m_pRefreshListener = NULL;
m_bConstructed = sal_False;
}
// -------------------------------------------------------------------------
void OFilteredContainer::impl_refresh() throw(RuntimeException)
{
if ( m_pRefreshListener )
{
m_bConstructed = sal_False;
Reference<XRefreshable> xRefresh(m_xMasterContainer,UNO_QUERY);
if ( xRefresh.is() )
xRefresh->refresh();
m_pRefreshListener->refresh(this);
}
}
// -------------------------------------------------------------------------
sal_Bool OFilteredContainer::isNameValid( const ::rtl::OUString& _rName,
const Sequence< ::rtl::OUString >& _rTableFilter,
const Sequence< ::rtl::OUString >& /*_rTableTypeFilter*/,
const ::std::vector< WildCard >& _rWCSearch) const
{
sal_Int32 nTableFilterLen = _rTableFilter.getLength();
const ::rtl::OUString* tableFilter = _rTableFilter.getConstArray();
const ::rtl::OUString* tableFilterEnd = _rTableFilter.getConstArray() + nTableFilterLen;
bool bFilterMatch = ::std::find( tableFilter, tableFilterEnd, _rName ) != tableFilterEnd;
// the table is allowed to "pass" if we had no filters at all or any of the non-wildcard filters matches
if (!bFilterMatch && !_rWCSearch.empty())
{ // or if one of the wildcrad expression matches
String sWCCompare = (const sal_Unicode*)_rName;
for ( ::std::vector< WildCard >::const_iterator aLoop = _rWCSearch.begin();
aLoop != _rWCSearch.end() && !bFilterMatch;
++aLoop
)
bFilterMatch = aLoop->Matches(sWCCompare);
}
return bFilterMatch;
}
// -----------------------------------------------------------------------------
::rtl::OUString OFilteredContainer::getNameForObject(const ObjectType& _xObject)
{
OSL_ENSURE(_xObject.is(),"OTables::getNameForObject: Object is NULL!");
return ::dbtools::composeTableName( m_xMetaData, _xObject, ::dbtools::eInDataManipulation, false, false, false );
}
// ..............................................................................
} // namespace
// ..............................................................................
<commit_msg>INTEGRATION: CWS changefileheader (1.10.36); FILE MERGED 2008/03/31 13:26:42 rt 1.10.36.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: FilteredContainer.cxx,v $
* $Revision: 1.11 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_dbaccess.hxx"
#ifndef DBACCESS_CORE_FILTERED_CONTAINER_HXX
#include "FilteredContainer.hxx"
#endif
#ifndef DBA_CORE_REFRESHLISTENER_HXX
#include "RefreshListener.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include "connectivity/dbtools.hxx"
#endif
#ifndef _WLDCRD_HXX
#include <tools/wldcrd.hxx>
#endif
namespace dbaccess
{
using namespace dbtools;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::container;
using namespace ::osl;
using namespace ::comphelper;
using namespace ::cppu;
using namespace ::connectivity::sdbcx;
//------------------------------------------------------------------------------
/** creates a vector of WildCards and reduce the _rTableFilter of the length of WildsCards
*/
sal_Int32 createWildCardVector(Sequence< ::rtl::OUString >& _rTableFilter, ::std::vector< WildCard >& _rOut)
{
// for wildcard search : remove all table filters which are a wildcard expression and build a WilCard
// for them
::rtl::OUString* pTableFilters = _rTableFilter.getArray();
::rtl::OUString* pEnd = pTableFilters + _rTableFilter.getLength();
sal_Int32 nShiftPos = 0;
for (sal_Int32 i=0; pEnd != pTableFilters; ++pTableFilters,++i)
{
if (pTableFilters->indexOf('%') != -1)
{
_rOut.push_back(WildCard(pTableFilters->replace('%', '*')));
}
else
{
if (nShiftPos != i)
{
_rTableFilter.getArray()[nShiftPos] = _rTableFilter.getArray()[i];
}
++nShiftPos;
}
}
// now aTableFilter contains nShiftPos non-wc-strings and aWCSearch all wc-strings
_rTableFilter.realloc(nShiftPos);
return nShiftPos;
}
//==========================================================================
//= OViewContainer
//==========================================================================
OFilteredContainer::OFilteredContainer(::cppu::OWeakObject& _rParent,
::osl::Mutex& _rMutex,
const Reference< XConnection >& _xCon,
sal_Bool _bCase,
IRefreshListener* _pRefreshListener,
IWarningsContainer* _pWarningsContainer
,oslInterlockedCount& _nInAppend)
:OCollection(_rParent,_bCase,_rMutex,::std::vector< ::rtl::OUString>())
,m_pWarningsContainer(_pWarningsContainer)
,m_pRefreshListener(_pRefreshListener)
,m_nInAppend(_nInAppend)
,m_xConnection(_xCon)
,m_bConstructed(sal_False)
{
}
// -------------------------------------------------------------------------
void OFilteredContainer::construct(const Reference< XNameAccess >& _rxMasterContainer,
const Sequence< ::rtl::OUString >& _rTableFilter,
const Sequence< ::rtl::OUString >& _rTableTypeFilter)
{
try
{
Reference<XConnection> xCon = m_xConnection;
if ( xCon.is() )
m_xMetaData = xCon->getMetaData();
}
catch(SQLException&)
{
}
m_xMasterContainer = _rxMasterContainer;
if(m_xMasterContainer.is())
{
addMasterContainerListener();
sal_Int32 nTableFilterLen = _rTableFilter.getLength();
connectivity::TStringVector aTableNames;
sal_Bool bNoTableFilters = ((nTableFilterLen == 1) && _rTableFilter[0].equalsAsciiL("%", 1));
if(!bNoTableFilters)
{
Sequence< ::rtl::OUString > aTableFilter = _rTableFilter;
Sequence< ::rtl::OUString > aTableTypeFilter = _rTableTypeFilter;
// build sorted versions of the filter sequences, so the visibility decision is faster
::std::sort( aTableFilter.getArray(), aTableFilter.getArray() + nTableFilterLen );
// as we want to modify nTableFilterLen, remember this
// for wildcard search : remove all table filters which are a wildcard expression and build a WilCard
// for them
::std::vector< WildCard > aWCSearch; // contains the wildcards for the table filter
nTableFilterLen = createWildCardVector(aTableFilter,aWCSearch);
aTableNames.reserve(nTableFilterLen + (aWCSearch.size() * 10));
Sequence< ::rtl::OUString> aNames = m_xMasterContainer->getElementNames();
const ::rtl::OUString* pBegin = aNames.getConstArray();
const ::rtl::OUString* pEnd = pBegin + aNames.getLength();
for(;pBegin != pEnd;++pBegin)
{
if(isNameValid(*pBegin,aTableFilter,aTableTypeFilter,aWCSearch))
aTableNames.push_back(*pBegin);
}
}
else
{
// no filter so insert all names
Sequence< ::rtl::OUString> aNames = m_xMasterContainer->getElementNames();
const ::rtl::OUString* pBegin = aNames.getConstArray();
const ::rtl::OUString* pEnd = pBegin + aNames.getLength();
aTableNames = connectivity::TStringVector(pBegin,pEnd);
}
reFill(aTableNames);
m_bConstructed = sal_True;
}
else
{
construct(_rTableFilter,_rTableTypeFilter);
}
}
//------------------------------------------------------------------------------
void OFilteredContainer::construct(const Sequence< ::rtl::OUString >& _rTableFilter, const Sequence< ::rtl::OUString >& _rTableTypeFilter)
{
try
{
Reference<XConnection> xCon = m_xConnection;
if ( xCon.is() )
m_xMetaData = xCon->getMetaData();
}
catch(SQLException&)
{
}
// build sorted versions of the filter sequences, so the visibility decision is faster
Sequence< ::rtl::OUString > aTableFilter(_rTableFilter);
sal_Int32 nTableFilterLen = aTableFilter.getLength();
if (nTableFilterLen)
::std::sort( aTableFilter.getArray(), aTableFilter.getArray() + nTableFilterLen );
sal_Bool bNoTableFilters = ((nTableFilterLen == 1) && _rTableFilter[0].equalsAsciiL("%", 1));
// as we want to modify nTableFilterLen, remember this
// for wildcard search : remove all table filters which are a wildcard expression and build a WilCard
// for them
::std::vector< WildCard > aWCSearch;
nTableFilterLen = createWildCardVector(aTableFilter,aWCSearch);
try
{
if (m_xMetaData.is())
{
static const ::rtl::OUString sAll = ::rtl::OUString::createFromAscii("%");
Sequence< ::rtl::OUString > sTableTypes = getTableTypeFilter(_rTableTypeFilter);
if ( m_bConstructed && sTableTypes.getLength() == 0 )
return;
Reference< XResultSet > xTables = m_xMetaData->getTables(Any(), sAll, sAll, sTableTypes);
Reference< XRow > xCurrentRow(xTables, UNO_QUERY);
if (xCurrentRow.is())
{
// after creation the set is positioned before the first record, per definitionem
::rtl::OUString sCatalog, sSchema, sName, sType;
::rtl::OUString sComposedName;
// we first collect the names and construct the OTable objects later, as the ctor of the table may need
// another result set from the connection, and some drivers support only one statement per connection
sal_Bool bFilterMatch;
while (xTables->next())
{
sCatalog = xCurrentRow->getString(1);
sSchema = xCurrentRow->getString(2);
sName = xCurrentRow->getString(3);
#if OSL_DEBUG_LEVEL > 0
::rtl::OUString sTableType = xCurrentRow->getString(4);
#endif
// we're not interested in the "wasNull", as the getStrings would return an empty string in
// that case, which is sufficient here
sComposedName = composeTableName( m_xMetaData, sCatalog, sSchema, sName, sal_False, ::dbtools::eInDataManipulation );
const ::rtl::OUString* tableFilter = aTableFilter.getConstArray();
const ::rtl::OUString* tableFilterEnd = aTableFilter.getConstArray() + nTableFilterLen;
bool composedNameInFilter = ::std::find( tableFilter, tableFilterEnd, sComposedName ) != tableFilterEnd;
bFilterMatch = bNoTableFilters
|| ( ( nTableFilterLen != 0 )
&& composedNameInFilter
);
// the table is allowed to "pass" if we had no filters at all or any of the non-wildcard filters matches
if (!bFilterMatch && aWCSearch.size())
{ // or if one of the wildcrad expression matches
for ( ::std::vector< WildCard >::const_iterator aLoop = aWCSearch.begin();
aLoop != aWCSearch.end() && !bFilterMatch;
++aLoop
)
bFilterMatch = aLoop->Matches(sComposedName);
}
if (bFilterMatch)
{ // the table name is allowed (not filtered out)
insertElement(sComposedName,NULL);
}
}
// dispose the tables result set, in case the connection can handle only one concurrent statement
// (the table object creation will need it's own statements)
disposeComponent(xTables);
}
else
OSL_ENSURE(0,"OFilteredContainer::construct : did not get a XRow from the tables result set !");
}
else
OSL_ENSURE(0,"OFilteredContainer::construct : no connection meta data !");
}
catch (SQLException&)
{
OSL_ENSURE(0,"OFilteredContainer::construct: caught an SQL-Exception !");
disposing();
return;
}
m_bConstructed = sal_True;
}
//------------------------------------------------------------------------------
void OFilteredContainer::disposing()
{
OCollection::disposing();
removeMasterContainerListener();
m_xMasterContainer = NULL;
m_xMetaData = NULL;
m_pWarningsContainer = NULL;
m_pRefreshListener = NULL;
m_bConstructed = sal_False;
}
// -------------------------------------------------------------------------
void OFilteredContainer::impl_refresh() throw(RuntimeException)
{
if ( m_pRefreshListener )
{
m_bConstructed = sal_False;
Reference<XRefreshable> xRefresh(m_xMasterContainer,UNO_QUERY);
if ( xRefresh.is() )
xRefresh->refresh();
m_pRefreshListener->refresh(this);
}
}
// -------------------------------------------------------------------------
sal_Bool OFilteredContainer::isNameValid( const ::rtl::OUString& _rName,
const Sequence< ::rtl::OUString >& _rTableFilter,
const Sequence< ::rtl::OUString >& /*_rTableTypeFilter*/,
const ::std::vector< WildCard >& _rWCSearch) const
{
sal_Int32 nTableFilterLen = _rTableFilter.getLength();
const ::rtl::OUString* tableFilter = _rTableFilter.getConstArray();
const ::rtl::OUString* tableFilterEnd = _rTableFilter.getConstArray() + nTableFilterLen;
bool bFilterMatch = ::std::find( tableFilter, tableFilterEnd, _rName ) != tableFilterEnd;
// the table is allowed to "pass" if we had no filters at all or any of the non-wildcard filters matches
if (!bFilterMatch && !_rWCSearch.empty())
{ // or if one of the wildcrad expression matches
String sWCCompare = (const sal_Unicode*)_rName;
for ( ::std::vector< WildCard >::const_iterator aLoop = _rWCSearch.begin();
aLoop != _rWCSearch.end() && !bFilterMatch;
++aLoop
)
bFilterMatch = aLoop->Matches(sWCCompare);
}
return bFilterMatch;
}
// -----------------------------------------------------------------------------
::rtl::OUString OFilteredContainer::getNameForObject(const ObjectType& _xObject)
{
OSL_ENSURE(_xObject.is(),"OTables::getNameForObject: Object is NULL!");
return ::dbtools::composeTableName( m_xMetaData, _xObject, ::dbtools::eInDataManipulation, false, false, false );
}
// ..............................................................................
} // namespace
// ..............................................................................
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: documentcontroller.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: hr $ $Date: 2005-09-23 12:39:23 $
*
* 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 DBACCESS_SOURCE_UI_INC_DOCUMENTCONTROLLER_HXX
#include "documentcontroller.hxx"
#endif
/** === begin UNO includes === **/
/** === end UNO includes === **/
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
//........................................................................
namespace dbaui
{
//........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::frame;
//====================================================================
//= ModelControllerConnector
//====================================================================
DBG_NAME( ModelControllerConnector )
//--------------------------------------------------------------------
ModelControllerConnector::ModelControllerConnector()
{
DBG_CTOR( ModelControllerConnector, NULL );
}
//--------------------------------------------------------------------
ModelControllerConnector::ModelControllerConnector( const Reference< XModel >& _rxModel, const Reference< XController >& _rxController )
:m_xModel( _rxModel )
,m_xController( _rxController )
{
DBG_CTOR( ModelControllerConnector, NULL );
DBG_ASSERT( m_xModel.is() && m_xController.is(), "ModelControllerConnector::ModelControllerConnector: invalid model or controller!" );
impl_connect();
}
//--------------------------------------------------------------------
ModelControllerConnector::ModelControllerConnector( const ModelControllerConnector& _rSource )
{
DBG_CTOR( ModelControllerConnector, NULL );
impl_copyFrom( _rSource );
}
//--------------------------------------------------------------------
ModelControllerConnector& ModelControllerConnector::operator=( const ModelControllerConnector& _rSource )
{
if ( this != &_rSource )
impl_copyFrom( _rSource );
return *this;
}
//--------------------------------------------------------------------
void ModelControllerConnector::swap( ModelControllerConnector& _rSource )
{
ModelControllerConnector aTemp( _rSource );
_rSource.impl_copyFrom( *this );
impl_copyFrom( aTemp );
}
//--------------------------------------------------------------------
void ModelControllerConnector::impl_copyFrom( const ModelControllerConnector& _rSource )
{
Model aNewModel( _rSource.m_xModel );
Controller aNewController( _rSource.m_xController );
impl_disconnect();
m_xModel = aNewModel;
m_xController = aNewController;
impl_connect();
}
//--------------------------------------------------------------------
ModelControllerConnector::~ModelControllerConnector()
{
impl_disconnect();
DBG_DTOR( ModelControllerConnector, NULL );
}
//--------------------------------------------------------------------
void ModelControllerConnector::impl_connect()
{
try
{
if ( m_xModel.is() && m_xController.is() )
m_xModel->connectController( m_xController );
}
catch( const Exception& )
{
OSL_ENSURE( sal_False, "ModelControllerConnector::impl_connect: caught an exception!" );
}
}
//--------------------------------------------------------------------
void ModelControllerConnector::impl_disconnect()
{
try
{
if ( m_xModel.is() && m_xController.is() )
m_xModel->disconnectController( m_xController );
}
catch( const Exception& )
{
OSL_ENSURE( sal_False, "ModelControllerConnector::impl_disconnect: caught an exception!" );
}
}
//........................................................................
} // namespace dbaui
//........................................................................
<commit_msg>INTEGRATION: CWS hr21 (1.2.24); FILE MERGED 2005/10/18 15:49:15 hr 1.2.24.1: #i55503#: fix license header<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: documentcontroller.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-10-19 11:52:03 $
*
* 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 DBACCESS_SOURCE_UI_INC_DOCUMENTCONTROLLER_HXX
#include "documentcontroller.hxx"
#endif
/** === begin UNO includes === **/
/** === end UNO includes === **/
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
//........................................................................
namespace dbaui
{
//........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::frame;
//====================================================================
//= ModelControllerConnector
//====================================================================
DBG_NAME( ModelControllerConnector )
//--------------------------------------------------------------------
ModelControllerConnector::ModelControllerConnector()
{
DBG_CTOR( ModelControllerConnector, NULL );
}
//--------------------------------------------------------------------
ModelControllerConnector::ModelControllerConnector( const Reference< XModel >& _rxModel, const Reference< XController >& _rxController )
:m_xModel( _rxModel )
,m_xController( _rxController )
{
DBG_CTOR( ModelControllerConnector, NULL );
DBG_ASSERT( m_xModel.is() && m_xController.is(), "ModelControllerConnector::ModelControllerConnector: invalid model or controller!" );
impl_connect();
}
//--------------------------------------------------------------------
ModelControllerConnector::ModelControllerConnector( const ModelControllerConnector& _rSource )
{
DBG_CTOR( ModelControllerConnector, NULL );
impl_copyFrom( _rSource );
}
//--------------------------------------------------------------------
ModelControllerConnector& ModelControllerConnector::operator=( const ModelControllerConnector& _rSource )
{
if ( this != &_rSource )
impl_copyFrom( _rSource );
return *this;
}
//--------------------------------------------------------------------
void ModelControllerConnector::swap( ModelControllerConnector& _rSource )
{
ModelControllerConnector aTemp( _rSource );
_rSource.impl_copyFrom( *this );
impl_copyFrom( aTemp );
}
//--------------------------------------------------------------------
void ModelControllerConnector::impl_copyFrom( const ModelControllerConnector& _rSource )
{
Model aNewModel( _rSource.m_xModel );
Controller aNewController( _rSource.m_xController );
impl_disconnect();
m_xModel = aNewModel;
m_xController = aNewController;
impl_connect();
}
//--------------------------------------------------------------------
ModelControllerConnector::~ModelControllerConnector()
{
impl_disconnect();
DBG_DTOR( ModelControllerConnector, NULL );
}
//--------------------------------------------------------------------
void ModelControllerConnector::impl_connect()
{
try
{
if ( m_xModel.is() && m_xController.is() )
m_xModel->connectController( m_xController );
}
catch( const Exception& )
{
OSL_ENSURE( sal_False, "ModelControllerConnector::impl_connect: caught an exception!" );
}
}
//--------------------------------------------------------------------
void ModelControllerConnector::impl_disconnect()
{
try
{
if ( m_xModel.is() && m_xController.is() )
m_xModel->disconnectController( m_xController );
}
catch( const Exception& )
{
OSL_ENSURE( sal_False, "ModelControllerConnector::impl_disconnect: caught an exception!" );
}
}
//........................................................................
} // namespace dbaui
//........................................................................
<|endoftext|>
|
<commit_before>/*
* Bayes++ the Bayesian Filtering Library
* Copyright (c) 2002 Michael Stevens, Australian Centre for Field Robotics
* See Bayes++.htm for copyright license details
*
* $Header$
*/
/*
* Test the FastSLAM alogorithm
* A linear filter with one state and constant noises
*/
// Types Required for SLAM classes
#include <vector>
#include <map>
// Include all the Bayes++ Bayesian filtering library
#include "BayesFilter/allFilters.hpp"
#include "SLAM.hpp"
#include "fastSLAM.hpp"
#include "kalmanSLAM.hpp"
#include <boost/random.hpp>
#include <iostream>
#include <boost/numeric/ublas/io.hpp>
using namespace SLAM_filter;
// Random numbers for filters from Boost
class Boost_random : public BF::SIR_random, public BF::General_LiInAd_predict_model::Random
/*
* Random number distributions
*/
{
public:
Boost_random() : gen_normal(rng), gen_uniform(rng)
{}
double normal(const double mean, const double sigma)
{
boost::normal_distribution<boost::mt19937> gen(rng, mean, sigma);
return gen();
}
void normal(FM::Vec& v)
{
std::generate (v.begin(), v.end(), gen_normal);
}
void uniform_01(FM::Vec& v)
{
std::generate (v.begin(), v.end(), gen_uniform);
}
void reseed()
{
rng.seed();
}
private:
boost::mt19937 rng;
boost::normal_distribution<boost::mt19937> gen_normal;
boost::uniform_01<boost::mt19937> gen_uniform;
};
/*
* Demonstrate a SLAM example
*/
struct SLAMDemo
{
void OneDExperiment ();
void InformationLooseExperiment ();
Boost_random goodRandom;
// Relative Observation with Noise model
struct Simple_observe : BF::Linear_uncorrelated_observe_model
{
Simple_observe (Float i_Zv) : Linear_uncorrelated_observe_model(2,1)
// Construct a linear model with const Hx
{
Hx(0,0) = -1.; // Location
Hx(0,1) = 1.; // Map
Zv[0] = i_Zv;
}
};
struct Simple_observe_inverse : BF::Uncorrelated_addative_observe_model
{
Simple_observe_inverse (Float i_Zv) : Uncorrelated_addative_observe_model(1), t(1)
{
Zv[0] = i_Zv;
}
const FM::Vec& h(const FM::Vec& lz) const
{
t[0] = lz[1]+lz[0];
return t;
}
mutable FM::Vec t;
};
class Kalman_statistics : public BF::Kalman_state_filter
// Kalman_statistics without any filtering
{ public:
Kalman_statistics (size_t x_size) : Kalman_state_filter(x_size) {}
void init() {}
void update() {}
};
void display( const std::string label, const BF::Kalman_state_filter& stats)
{
std::cout << label << stats.x << stats.X << std::endl;
}
};
void SLAMDemo::OneDExperiment()
// Experiment with a one dimensional problem
{
// State size
const unsigned nL = 1; // Location
const unsigned nM = 2; // Map
// Construct simple Prediction models
BF::General_LiAd_predict_model location_predict(nL,1, goodRandom);
BF::General_LiAd_predict_model all_predict(nL+nM,1, goodRandom);
// Stationary Prediction model (Identity)
FM::identity(location_predict.Fx); FM::identity(all_predict.Fx);
// Constant Noise model
location_predict.q[0] = 1000.; all_predict.q[0] = 1000.;
location_predict.G.clear(); all_predict.G.clear();
location_predict.G(0,0) = 1.; all_predict.G(0,0) = 1.;
// Relative Observation with Noise model
Simple_observe observe0(5.), observe1(3.);
Simple_observe_inverse observe_new0(5.), observe_new1(3.);
// Setup the initial state and covariance
// Location with no uncertainty
FM::Vec x_init(nL); FM::SymMatrix X_init(nL, nL);
x_init[0] = 20.;
X_init(0,0) = 0.;
// Truth model : location plus one map feature
FM::Vec true0(nL+1), true1(nL+1);
true0(0,nL) = x_init; true0[nL] = 50.;
true1(0,nL) = x_init; true1[nL] = 70.;
FM::Vec z(1);
// Kalman_SLAM filter
BF::Unscented_scheme full_filter(nL+nM);
full_filter.x.clear(); full_filter.X.clear();
full_filter.x[0] = x_init[0];
full_filter.X(0,0) = X_init(0,0);
full_filter.init();
Kalman_SLAM kalm(full_filter, nL);
// Fast_SLAM filter
#ifdef NDEBUG
unsigned nParticles = 1000000;
#else
unsigned nParticles = 20;
#endif
BF::SIR_kalman_scheme fast_location(nL, nParticles, goodRandom);
fast_location.init_kalman(x_init, X_init);
Fast_SLAM_Kstatistics fast(fast_location);
Kalman_statistics stat(nL+nM);
// Initial feature states
z = observe0.h(true0); // Observe a relative position between location and map landmark
z[0] += 0.5;
kalm.observe_new (0, observe_new0, z);
fast.observe_new (0, observe_new0, z);
z = observe1.h(true1);
z[0] += -1.0;
kalm.observe_new (1, observe_new1, z);
fast.observe_new (1, observe_new1, z);
// Experiment with highly correlated features
//
kalm.update(); display("Initial Kalm", full_filter);
fast.update(); fast.statistics(stat); display("Initial Fast", stat);
// Predict the filter forward
full_filter.predict (all_predict);
kalm.update(); display("Predict Kalm", full_filter);
fast_location.predict (location_predict);
fast.update(); fast.statistics(stat); display("Predict Fast", stat);
// Observation feature 0
z = observe0.h(true0);
z[0] += 0.5; // Observe a relative position between location and map landmark
kalm.observe( 0, observe0, z );
kalm.update(); display("ObserveA Kalm", full_filter);
fast.observe( 0, observe0, z );
fast.update(); fast.statistics(stat); display("ObserveA Fast", stat);
// Observation feature 1
z = observe1.h(true1);
z[0] += 1.0; // Observe a relative position between location and map landmark
kalm.observe( 1, observe1, z );
kalm.update(); display("ObserveB Kalm", full_filter);
fast.observe( 1, observe1, z );
fast.update(); fast.statistics(stat); display("ObserveB Fast", stat);
// Observation feature 0
z = observe0.h(true0);
z[0] += 0.5; // Observe a relative position between location and map landmark
kalm.observe( 0, observe0, z );
kalm.update(); display("ObserveC Kalm", full_filter);
fast.observe( 0, observe0, z );
fast.update(); fast.statistics(stat); display("ObserveC Fast", stat);
// Forget feature 0
kalm.forget(0);
kalm.update(); display("Forget Kalm", full_filter);
fast.forget(0);
fast.update(); fast.statistics(stat); display("Forget Fast", stat);
}
void SLAMDemo::InformationLooseExperiment()
// Experiment with information loose due to resampling
{
// State size
const unsigned nL = 1; // Location
const unsigned nM = 2; // Map
// Construct simple Prediction models
BF::General_LiAd_predict_model location_predict(nL,1, goodRandom);
BF::General_LiAd_predict_model all_predict(nL+nM,1, goodRandom);
// Stationary Prediction model (Identity)
FM::identity(location_predict.Fx); FM::identity(all_predict.Fx);
// Constant Noise model
location_predict.q[0] = 1000.; all_predict.q[0] = 1000.;
location_predict.G.clear(); all_predict.G.clear();
location_predict.G(0,0) = 1.; all_predict.G(0,0) = 1.;
// Relative Observation with Noise model
Simple_observe observe0(5.), observe1(3.);
Simple_observe_inverse observe_new0(5.), observe_new1(3.);
// Setup the initial state and covariance
// Location with no uncertainty
FM::Vec x_init(nL); FM::SymMatrix X_init(nL, nL);
x_init[0] = 20.;
X_init(0,0) = 0.;
// Truth model : location plus one map feature
FM::Vec true0(nL+1), true1(nL+1);
true0(0,nL) = x_init; true0[nL] = 50.;
true1(0,nL) = x_init; true1[nL] = 70.;
FM::Vec z(1);
// Kalman_SLAM filter
BF::Unscented_scheme full_filter(nL+nM);
full_filter.x.clear(); full_filter.X.clear();
full_filter.x[0] = x_init[0];
full_filter.X(0,0) = X_init(0,0);
full_filter.init();
Kalman_SLAM kalm(full_filter, nL);
// Fast_SLAM filter
unsigned nParticles = 1000;
BF::SIR_kalman_scheme fast_location(nL, nParticles, goodRandom);
fast_location.init_kalman(x_init, X_init);
Fast_SLAM_Kstatistics fast(fast_location);
Kalman_statistics stat(nL+nM);
// Initial feature states
z = observe0.h(true0); // Observe a relative position between location and map landmark
z[0] += 0.5;
kalm.observe_new (0, observe_new0, z);
fast.observe_new (0, observe_new0, z);
z = observe1.h(true1);
z[0] += -1.0;
kalm.observe_new (1, observe_new1, z);
fast.observe_new (1, observe_new1, z);
unsigned it = 0;
for (;;) {
++it;
std::cout << it << std::endl;
// Groups of observations without resampling
{
// Predict the filter forward
full_filter.predict (all_predict);
fast_location.predict (location_predict);
// Observation feature 0 with bias
z = observe0.h(true0); // Observe a relative position between location and map landmark
z[0] += 0.5;
kalm.observe( 0, observe0, z );
fast.observe( 0, observe0, z );
// Predict the filter forward
full_filter.predict (all_predict);
fast_location.predict (location_predict);
// Observation feature 1 with bias
z = observe1.h(true1); // Observe a relative position between location and map landmark
z[0] += -1.0;
kalm.observe( 1, observe1, z );
fast.observe( 1, observe1, z );
}
// Update and resample
kalm.update();
try {
fast.update();
}
catch (BF::Filter_exception ne)
{
std::cout << ne.what() << std::endl;
std::cout.flush();
throw; // re-throw
}
display("Kalm", full_filter);
fast.statistics(stat); display("Fast", stat);
std::cout << fast_location.stochastic_samples <<','<< fast_location.unique_samples()
<<' '<< fast.feature_unique_samples(0) <<','<< fast.feature_unique_samples(1) <<std::endl;
std::cout.flush();
}
}
int main()
{
// Global setup for test output
std::cout.flags(std::ios::fixed); std::cout.precision(4);
// Create test and run experiments
SLAMDemo test;
test.OneDExperiment();
test.InformationLooseExperiment();
}
<commit_msg>spell Loss<commit_after>/*
* Bayes++ the Bayesian Filtering Library
* Copyright (c) 2002 Michael Stevens, Australian Centre for Field Robotics
* See Bayes++.htm for copyright license details
*
* $Header$
*/
/*
* Test the FastSLAM alogorithm
* A linear filter with one state and constant noises
*/
// Types Required for SLAM classes
#include <vector>
#include <map>
// Include all the Bayes++ Bayesian filtering library
#include "BayesFilter/allFilters.hpp"
#include "SLAM.hpp"
#include "fastSLAM.hpp"
#include "kalmanSLAM.hpp"
#include <boost/random.hpp>
#include <iostream>
#include <boost/numeric/ublas/io.hpp>
using namespace SLAM_filter;
// Random numbers for filters from Boost
class Boost_random : public BF::SIR_random, public BF::General_LiInAd_predict_model::Random
/*
* Random number distributions
*/
{
public:
Boost_random() : gen_normal(rng), gen_uniform(rng)
{}
double normal(const double mean, const double sigma)
{
boost::normal_distribution<boost::mt19937> gen(rng, mean, sigma);
return gen();
}
void normal(FM::Vec& v)
{
std::generate (v.begin(), v.end(), gen_normal);
}
void uniform_01(FM::Vec& v)
{
std::generate (v.begin(), v.end(), gen_uniform);
}
void reseed()
{
rng.seed();
}
private:
boost::mt19937 rng;
boost::normal_distribution<boost::mt19937> gen_normal;
boost::uniform_01<boost::mt19937> gen_uniform;
};
/*
* Demonstrate a SLAM example
*/
struct SLAMDemo
{
void OneDExperiment ();
void InformationLossExperiment ();
Boost_random goodRandom;
// Relative Observation with Noise model
struct Simple_observe : BF::Linear_uncorrelated_observe_model
{
Simple_observe (Float i_Zv) : Linear_uncorrelated_observe_model(2,1)
// Construct a linear model with const Hx
{
Hx(0,0) = -1.; // Location
Hx(0,1) = 1.; // Map
Zv[0] = i_Zv;
}
};
struct Simple_observe_inverse : BF::Uncorrelated_addative_observe_model
{
Simple_observe_inverse (Float i_Zv) : Uncorrelated_addative_observe_model(1), t(1)
{
Zv[0] = i_Zv;
}
const FM::Vec& h(const FM::Vec& lz) const
{
t[0] = lz[1]+lz[0];
return t;
}
mutable FM::Vec t;
};
class Kalman_statistics : public BF::Kalman_state_filter
// Kalman_statistics without any filtering
{ public:
Kalman_statistics (size_t x_size) : Kalman_state_filter(x_size) {}
void init() {}
void update() {}
};
void display( const std::string label, const BF::Kalman_state_filter& stats)
{
std::cout << label << stats.x << stats.X << std::endl;
}
};
void SLAMDemo::OneDExperiment()
// Experiment with a one dimensional problem
{
// State size
const unsigned nL = 1; // Location
const unsigned nM = 2; // Map
// Construct simple Prediction models
BF::General_LiAd_predict_model location_predict(nL,1, goodRandom);
BF::General_LiAd_predict_model all_predict(nL+nM,1, goodRandom);
// Stationary Prediction model (Identity)
FM::identity(location_predict.Fx); FM::identity(all_predict.Fx);
// Constant Noise model
location_predict.q[0] = 1000.; all_predict.q[0] = 1000.;
location_predict.G.clear(); all_predict.G.clear();
location_predict.G(0,0) = 1.; all_predict.G(0,0) = 1.;
// Relative Observation with Noise model
Simple_observe observe0(5.), observe1(3.);
Simple_observe_inverse observe_new0(5.), observe_new1(3.);
// Setup the initial state and covariance
// Location with no uncertainty
FM::Vec x_init(nL); FM::SymMatrix X_init(nL, nL);
x_init[0] = 20.;
X_init(0,0) = 0.;
// Truth model : location plus one map feature
FM::Vec true0(nL+1), true1(nL+1);
true0(0,nL) = x_init; true0[nL] = 50.;
true1(0,nL) = x_init; true1[nL] = 70.;
FM::Vec z(1);
// Kalman_SLAM filter
BF::Unscented_scheme full_filter(nL+nM);
full_filter.x.clear(); full_filter.X.clear();
full_filter.x[0] = x_init[0];
full_filter.X(0,0) = X_init(0,0);
full_filter.init();
Kalman_SLAM kalm(full_filter, nL);
// Fast_SLAM filter
#ifdef NDEBUG
unsigned nParticles = 1000000;
#else
unsigned nParticles = 20;
#endif
BF::SIR_kalman_scheme fast_location(nL, nParticles, goodRandom);
fast_location.init_kalman(x_init, X_init);
Fast_SLAM_Kstatistics fast(fast_location);
Kalman_statistics stat(nL+nM);
// Initial feature states
z = observe0.h(true0); // Observe a relative position between location and map landmark
z[0] += 0.5;
kalm.observe_new (0, observe_new0, z);
fast.observe_new (0, observe_new0, z);
z = observe1.h(true1);
z[0] += -1.0;
kalm.observe_new (1, observe_new1, z);
fast.observe_new (1, observe_new1, z);
// Experiment with highly correlated features
//
kalm.update(); display("Initial Kalm", full_filter);
fast.update(); fast.statistics(stat); display("Initial Fast", stat);
// Predict the filter forward
full_filter.predict (all_predict);
kalm.update(); display("Predict Kalm", full_filter);
fast_location.predict (location_predict);
fast.update(); fast.statistics(stat); display("Predict Fast", stat);
// Observation feature 0
z = observe0.h(true0);
z[0] += 0.5; // Observe a relative position between location and map landmark
kalm.observe( 0, observe0, z );
kalm.update(); display("ObserveA Kalm", full_filter);
fast.observe( 0, observe0, z );
fast.update(); fast.statistics(stat); display("ObserveA Fast", stat);
// Observation feature 1
z = observe1.h(true1);
z[0] += 1.0; // Observe a relative position between location and map landmark
kalm.observe( 1, observe1, z );
kalm.update(); display("ObserveB Kalm", full_filter);
fast.observe( 1, observe1, z );
fast.update(); fast.statistics(stat); display("ObserveB Fast", stat);
// Observation feature 0
z = observe0.h(true0);
z[0] += 0.5; // Observe a relative position between location and map landmark
kalm.observe( 0, observe0, z );
kalm.update(); display("ObserveC Kalm", full_filter);
fast.observe( 0, observe0, z );
fast.update(); fast.statistics(stat); display("ObserveC Fast", stat);
// Forget feature 0
kalm.forget(0);
kalm.update(); display("Forget Kalm", full_filter);
fast.forget(0);
fast.update(); fast.statistics(stat); display("Forget Fast", stat);
}
void SLAMDemo::InformationLossExperiment()
// Experiment with information loss due to resampling
{
// State size
const unsigned nL = 1; // Location
const unsigned nM = 2; // Map
// Construct simple Prediction models
BF::General_LiAd_predict_model location_predict(nL,1, goodRandom);
BF::General_LiAd_predict_model all_predict(nL+nM,1, goodRandom);
// Stationary Prediction model (Identity)
FM::identity(location_predict.Fx); FM::identity(all_predict.Fx);
// Constant Noise model
location_predict.q[0] = 1000.; all_predict.q[0] = 1000.;
location_predict.G.clear(); all_predict.G.clear();
location_predict.G(0,0) = 1.; all_predict.G(0,0) = 1.;
// Relative Observation with Noise model
Simple_observe observe0(5.), observe1(3.);
Simple_observe_inverse observe_new0(5.), observe_new1(3.);
// Setup the initial state and covariance
// Location with no uncertainty
FM::Vec x_init(nL); FM::SymMatrix X_init(nL, nL);
x_init[0] = 20.;
X_init(0,0) = 0.;
// Truth model : location plus one map feature
FM::Vec true0(nL+1), true1(nL+1);
true0(0,nL) = x_init; true0[nL] = 50.;
true1(0,nL) = x_init; true1[nL] = 70.;
FM::Vec z(1);
// Kalman_SLAM filter
BF::Unscented_scheme full_filter(nL+nM);
full_filter.x.clear(); full_filter.X.clear();
full_filter.x[0] = x_init[0];
full_filter.X(0,0) = X_init(0,0);
full_filter.init();
Kalman_SLAM kalm(full_filter, nL);
// Fast_SLAM filter
unsigned nParticles = 1000;
BF::SIR_kalman_scheme fast_location(nL, nParticles, goodRandom);
fast_location.init_kalman(x_init, X_init);
Fast_SLAM_Kstatistics fast(fast_location);
Kalman_statistics stat(nL+nM);
// Initial feature states
z = observe0.h(true0); // Observe a relative position between location and map landmark
z[0] += 0.5;
kalm.observe_new (0, observe_new0, z);
fast.observe_new (0, observe_new0, z);
z = observe1.h(true1);
z[0] += -1.0;
kalm.observe_new (1, observe_new1, z);
fast.observe_new (1, observe_new1, z);
unsigned it = 0;
for (;;) {
++it;
std::cout << it << std::endl;
// Groups of observations without resampling
{
// Predict the filter forward
full_filter.predict (all_predict);
fast_location.predict (location_predict);
// Observation feature 0 with bias
z = observe0.h(true0); // Observe a relative position between location and map landmark
z[0] += 0.5;
kalm.observe( 0, observe0, z );
fast.observe( 0, observe0, z );
// Predict the filter forward
full_filter.predict (all_predict);
fast_location.predict (location_predict);
// Observation feature 1 with bias
z = observe1.h(true1); // Observe a relative position between location and map landmark
z[0] += -1.0;
kalm.observe( 1, observe1, z );
fast.observe( 1, observe1, z );
}
// Update and resample
kalm.update();
try {
fast.update();
}
catch (BF::Filter_exception ne)
{
std::cout << ne.what() << std::endl;
std::cout.flush();
throw; // re-throw
}
display("Kalm", full_filter);
fast.statistics(stat); display("Fast", stat);
std::cout << fast_location.stochastic_samples <<','<< fast_location.unique_samples()
<<' '<< fast.feature_unique_samples(0) <<','<< fast.feature_unique_samples(1) <<std::endl;
std::cout.flush();
}
}
int main()
{
// Global setup for test output
std::cout.flags(std::ios::fixed); std::cout.precision(4);
// Create test and run experiments
SLAMDemo test;
test.OneDExperiment();
//test.InformationLossExperiment();
}
<|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/common/vehicle_state/vehicle_state_provider.h"
#include <cmath>
#include "Eigen/Core"
#include "cyber/common/log.h"
#include "modules/common/configs/config_gflags.h"
#include "modules/common/math/euler_angles_zxy.h"
#include "modules/common/math/quaternion.h"
#include "modules/common/util/string_util.h"
#include "modules/localization/common/localization_gflags.h"
namespace apollo {
namespace common {
VehicleStateProvider::VehicleStateProvider() {}
Status VehicleStateProvider::Update(
const localization::LocalizationEstimate &localization,
const canbus::Chassis &chassis) {
original_localization_ = localization;
if (!ConstructExceptLinearVelocity(localization)) {
std::string msg = util::StrCat(
"Fail to update because ConstructExceptLinearVelocity error.",
"localization:\n", localization.DebugString());
return Status(ErrorCode::LOCALIZATION_ERROR, msg);
}
if (localization.has_measurement_time()) {
vehicle_state_.set_timestamp(localization.measurement_time());
} else if (localization.header().has_timestamp_sec()) {
vehicle_state_.set_timestamp(localization.header().timestamp_sec());
} else if (chassis.has_header() && chassis.header().has_timestamp_sec()) {
AERROR << "Unable to use location timestamp for vehicle state. Use chassis "
"time instead.";
vehicle_state_.set_timestamp(chassis.header().timestamp_sec());
}
if (chassis.has_gear_location()) {
vehicle_state_.set_gear(chassis.gear_location());
} else {
vehicle_state_.set_gear(canbus::Chassis::GEAR_NONE);
}
if (chassis.has_speed_mps()) {
vehicle_state_.set_linear_velocity(chassis.speed_mps());
if (!FLAGS_reverse_heading_vehicle_state &&
vehicle_state_.gear() == canbus::Chassis::GEAR_REVERSE) {
vehicle_state_.set_linear_velocity(-vehicle_state_.linear_velocity());
}
}
constexpr double kEpsilon = 1e-6;
if (std::abs(vehicle_state_.linear_velocity()) < kEpsilon) {
vehicle_state_.set_kappa(0.0);
} else {
vehicle_state_.set_kappa(vehicle_state_.angular_velocity() /
vehicle_state_.linear_velocity());
}
vehicle_state_.set_driving_mode(chassis.driving_mode());
return Status::OK();
}
bool VehicleStateProvider::ConstructExceptLinearVelocity(
const localization::LocalizationEstimate &localization) {
if (!localization.has_pose()) {
AERROR << "Invalid localization input.";
return false;
}
// skip localization update when it is in use_navigation_mode.
if (FLAGS_use_navigation_mode) {
ADEBUG << "Skip localization update when it is in use_navigation_mode.";
return true;
}
vehicle_state_.mutable_pose()->CopyFrom(localization.pose());
if (localization.pose().has_position()) {
vehicle_state_.set_x(localization.pose().position().x());
vehicle_state_.set_y(localization.pose().position().y());
vehicle_state_.set_z(localization.pose().position().z());
}
const auto &orientation = localization.pose().orientation();
if (localization.pose().has_heading()) {
vehicle_state_.set_heading(localization.pose().heading());
} else {
vehicle_state_.set_heading(
math::QuaternionToHeading(orientation.qw(), orientation.qx(),
orientation.qy(), orientation.qz()));
}
if (FLAGS_enable_map_reference_unify) {
if (!localization.pose().has_angular_velocity_vrf()) {
AERROR << "localization.pose().has_angular_velocity_vrf() must be true "
"when FLAGS_enable_map_reference_unify is true.";
return false;
}
vehicle_state_.set_angular_velocity(
localization.pose().angular_velocity_vrf().z());
if (!localization.pose().has_linear_acceleration_vrf()) {
AERROR << "localization.pose().has_linear_acceleration_vrf() must be "
"true when FLAGS_enable_map_reference_unify is true.";
return false;
}
vehicle_state_.set_linear_acceleration(
localization.pose().linear_acceleration_vrf().y());
} else {
if (!localization.pose().has_angular_velocity()) {
AERROR << "localization.pose() has no angular velocity.";
return false;
}
vehicle_state_.set_angular_velocity(
localization.pose().angular_velocity().z());
if (!localization.pose().has_linear_acceleration()) {
AERROR << "localization.pose() has no linear acceleration.";
return false;
}
vehicle_state_.set_linear_acceleration(
localization.pose().linear_acceleration().y());
}
if (localization.pose().has_euler_angles()) {
vehicle_state_.set_roll(localization.pose().euler_angles().x());
vehicle_state_.set_pitch(localization.pose().euler_angles().y());
vehicle_state_.set_yaw(localization.pose().euler_angles().z());
} else {
math::EulerAnglesZXYd euler_angle(orientation.qw(), orientation.qx(),
orientation.qy(), orientation.qz());
vehicle_state_.set_roll(euler_angle.roll());
vehicle_state_.set_pitch(euler_angle.pitch());
vehicle_state_.set_yaw(euler_angle.yaw());
}
return true;
}
double VehicleStateProvider::x() const { return vehicle_state_.x(); }
double VehicleStateProvider::y() const { return vehicle_state_.y(); }
double VehicleStateProvider::z() const { return vehicle_state_.z(); }
double VehicleStateProvider::roll() const { return vehicle_state_.roll(); }
double VehicleStateProvider::pitch() const { return vehicle_state_.pitch(); }
double VehicleStateProvider::yaw() const { return vehicle_state_.yaw(); }
double VehicleStateProvider::heading() const {
return vehicle_state_.heading();
}
double VehicleStateProvider::kappa() const { return vehicle_state_.kappa(); }
double VehicleStateProvider::linear_velocity() const {
return vehicle_state_.linear_velocity();
}
double VehicleStateProvider::angular_velocity() const {
return vehicle_state_.angular_velocity();
}
double VehicleStateProvider::linear_acceleration() const {
return vehicle_state_.linear_acceleration();
}
double VehicleStateProvider::gear() const { return vehicle_state_.gear(); }
double VehicleStateProvider::timestamp() const {
return vehicle_state_.timestamp();
}
const localization::Pose &VehicleStateProvider::pose() const {
return vehicle_state_.pose();
}
const localization::Pose &VehicleStateProvider::original_pose() const {
return original_localization_.pose();
}
void VehicleStateProvider::set_linear_velocity(const double linear_velocity) {
vehicle_state_.set_linear_velocity(linear_velocity);
}
const VehicleState &VehicleStateProvider::vehicle_state() const {
return vehicle_state_;
}
math::Vec2d VehicleStateProvider::EstimateFuturePosition(const double t) const {
Eigen::Vector3d vec_distance(0.0, 0.0, 0.0);
double v = vehicle_state_.linear_velocity();
// Predict distance travel vector
if (std::fabs(vehicle_state_.angular_velocity()) < 0.0001) {
vec_distance[0] = 0.0;
vec_distance[1] = v * t;
} else {
vec_distance[0] = -v / vehicle_state_.angular_velocity() *
(1.0 - std::cos(vehicle_state_.angular_velocity() * t));
vec_distance[1] = std::sin(vehicle_state_.angular_velocity() * t) * v /
vehicle_state_.angular_velocity();
}
// If we have rotation information, take it into consideration.
if (vehicle_state_.pose().has_orientation()) {
const auto &orientation = vehicle_state_.pose().orientation();
Eigen::Quaternion<double> quaternion(orientation.qw(), orientation.qx(),
orientation.qy(), orientation.qz());
Eigen::Vector3d pos_vec(vehicle_state_.x(), vehicle_state_.y(),
vehicle_state_.z());
auto future_pos_3d = quaternion.toRotationMatrix() * vec_distance + pos_vec;
return math::Vec2d(future_pos_3d[0], future_pos_3d[1]);
}
// If no valid rotation information provided from localization,
// return the estimated future position without rotation.
return math::Vec2d(vec_distance[0] + vehicle_state_.x(),
vec_distance[1] + vehicle_state_.y());
}
math::Vec2d VehicleStateProvider::ComputeCOMPosition(
const double rear_to_com_distance) const {
// set length as distance between rear wheel and center of mass.
Eigen::Vector3d v;
if ((FLAGS_state_transform_to_com_reverse &&
vehicle_state_.gear() == canbus::Chassis::GEAR_REVERSE) ||
(FLAGS_state_transform_to_com_drive &&
vehicle_state_.gear() == canbus::Chassis::GEAR_DRIVE)) {
v << 0.0, rear_to_com_distance, 0.0;
} else {
v << 0.0, 0.0, 0.0;
}
Eigen::Vector3d pos_vec(vehicle_state_.x(), vehicle_state_.y(),
vehicle_state_.z());
// Initialize the COM position without rotation
Eigen::Vector3d com_pos_3d = v + pos_vec;
// If we have rotation information, take it into consideration.
if (vehicle_state_.pose().has_orientation()) {
const auto &orientation = vehicle_state_.pose().orientation();
Eigen::Quaternion<double> quaternion(orientation.qw(), orientation.qx(),
orientation.qy(), orientation.qz());
// Update the COM position with rotation
com_pos_3d = quaternion.toRotationMatrix() * v + pos_vec;
}
return math::Vec2d(com_pos_3d[0], com_pos_3d[1]);
}
} // namespace common
} // namespace apollo
<commit_msg>remote Eigen auto in vehicle state provider<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/common/vehicle_state/vehicle_state_provider.h"
#include <cmath>
#include "Eigen/Core"
#include "cyber/common/log.h"
#include "modules/common/configs/config_gflags.h"
#include "modules/common/math/euler_angles_zxy.h"
#include "modules/common/math/quaternion.h"
#include "modules/common/util/string_util.h"
#include "modules/localization/common/localization_gflags.h"
namespace apollo {
namespace common {
VehicleStateProvider::VehicleStateProvider() {}
Status VehicleStateProvider::Update(
const localization::LocalizationEstimate &localization,
const canbus::Chassis &chassis) {
original_localization_ = localization;
if (!ConstructExceptLinearVelocity(localization)) {
std::string msg = util::StrCat(
"Fail to update because ConstructExceptLinearVelocity error.",
"localization:\n", localization.DebugString());
return Status(ErrorCode::LOCALIZATION_ERROR, msg);
}
if (localization.has_measurement_time()) {
vehicle_state_.set_timestamp(localization.measurement_time());
} else if (localization.header().has_timestamp_sec()) {
vehicle_state_.set_timestamp(localization.header().timestamp_sec());
} else if (chassis.has_header() && chassis.header().has_timestamp_sec()) {
AERROR << "Unable to use location timestamp for vehicle state. Use chassis "
"time instead.";
vehicle_state_.set_timestamp(chassis.header().timestamp_sec());
}
if (chassis.has_gear_location()) {
vehicle_state_.set_gear(chassis.gear_location());
} else {
vehicle_state_.set_gear(canbus::Chassis::GEAR_NONE);
}
if (chassis.has_speed_mps()) {
vehicle_state_.set_linear_velocity(chassis.speed_mps());
if (!FLAGS_reverse_heading_vehicle_state &&
vehicle_state_.gear() == canbus::Chassis::GEAR_REVERSE) {
vehicle_state_.set_linear_velocity(-vehicle_state_.linear_velocity());
}
}
constexpr double kEpsilon = 1e-6;
if (std::abs(vehicle_state_.linear_velocity()) < kEpsilon) {
vehicle_state_.set_kappa(0.0);
} else {
vehicle_state_.set_kappa(vehicle_state_.angular_velocity() /
vehicle_state_.linear_velocity());
}
vehicle_state_.set_driving_mode(chassis.driving_mode());
return Status::OK();
}
bool VehicleStateProvider::ConstructExceptLinearVelocity(
const localization::LocalizationEstimate &localization) {
if (!localization.has_pose()) {
AERROR << "Invalid localization input.";
return false;
}
// skip localization update when it is in use_navigation_mode.
if (FLAGS_use_navigation_mode) {
ADEBUG << "Skip localization update when it is in use_navigation_mode.";
return true;
}
vehicle_state_.mutable_pose()->CopyFrom(localization.pose());
if (localization.pose().has_position()) {
vehicle_state_.set_x(localization.pose().position().x());
vehicle_state_.set_y(localization.pose().position().y());
vehicle_state_.set_z(localization.pose().position().z());
}
const auto &orientation = localization.pose().orientation();
if (localization.pose().has_heading()) {
vehicle_state_.set_heading(localization.pose().heading());
} else {
vehicle_state_.set_heading(
math::QuaternionToHeading(orientation.qw(), orientation.qx(),
orientation.qy(), orientation.qz()));
}
if (FLAGS_enable_map_reference_unify) {
if (!localization.pose().has_angular_velocity_vrf()) {
AERROR << "localization.pose().has_angular_velocity_vrf() must be true "
"when FLAGS_enable_map_reference_unify is true.";
return false;
}
vehicle_state_.set_angular_velocity(
localization.pose().angular_velocity_vrf().z());
if (!localization.pose().has_linear_acceleration_vrf()) {
AERROR << "localization.pose().has_linear_acceleration_vrf() must be "
"true when FLAGS_enable_map_reference_unify is true.";
return false;
}
vehicle_state_.set_linear_acceleration(
localization.pose().linear_acceleration_vrf().y());
} else {
if (!localization.pose().has_angular_velocity()) {
AERROR << "localization.pose() has no angular velocity.";
return false;
}
vehicle_state_.set_angular_velocity(
localization.pose().angular_velocity().z());
if (!localization.pose().has_linear_acceleration()) {
AERROR << "localization.pose() has no linear acceleration.";
return false;
}
vehicle_state_.set_linear_acceleration(
localization.pose().linear_acceleration().y());
}
if (localization.pose().has_euler_angles()) {
vehicle_state_.set_roll(localization.pose().euler_angles().x());
vehicle_state_.set_pitch(localization.pose().euler_angles().y());
vehicle_state_.set_yaw(localization.pose().euler_angles().z());
} else {
math::EulerAnglesZXYd euler_angle(orientation.qw(), orientation.qx(),
orientation.qy(), orientation.qz());
vehicle_state_.set_roll(euler_angle.roll());
vehicle_state_.set_pitch(euler_angle.pitch());
vehicle_state_.set_yaw(euler_angle.yaw());
}
return true;
}
double VehicleStateProvider::x() const { return vehicle_state_.x(); }
double VehicleStateProvider::y() const { return vehicle_state_.y(); }
double VehicleStateProvider::z() const { return vehicle_state_.z(); }
double VehicleStateProvider::roll() const { return vehicle_state_.roll(); }
double VehicleStateProvider::pitch() const { return vehicle_state_.pitch(); }
double VehicleStateProvider::yaw() const { return vehicle_state_.yaw(); }
double VehicleStateProvider::heading() const {
return vehicle_state_.heading();
}
double VehicleStateProvider::kappa() const { return vehicle_state_.kappa(); }
double VehicleStateProvider::linear_velocity() const {
return vehicle_state_.linear_velocity();
}
double VehicleStateProvider::angular_velocity() const {
return vehicle_state_.angular_velocity();
}
double VehicleStateProvider::linear_acceleration() const {
return vehicle_state_.linear_acceleration();
}
double VehicleStateProvider::gear() const { return vehicle_state_.gear(); }
double VehicleStateProvider::timestamp() const {
return vehicle_state_.timestamp();
}
const localization::Pose &VehicleStateProvider::pose() const {
return vehicle_state_.pose();
}
const localization::Pose &VehicleStateProvider::original_pose() const {
return original_localization_.pose();
}
void VehicleStateProvider::set_linear_velocity(const double linear_velocity) {
vehicle_state_.set_linear_velocity(linear_velocity);
}
const VehicleState &VehicleStateProvider::vehicle_state() const {
return vehicle_state_;
}
math::Vec2d VehicleStateProvider::EstimateFuturePosition(const double t) const {
Eigen::Vector3d vec_distance(0.0, 0.0, 0.0);
double v = vehicle_state_.linear_velocity();
// Predict distance travel vector
if (std::fabs(vehicle_state_.angular_velocity()) < 0.0001) {
vec_distance[0] = 0.0;
vec_distance[1] = v * t;
} else {
vec_distance[0] = -v / vehicle_state_.angular_velocity() *
(1.0 - std::cos(vehicle_state_.angular_velocity() * t));
vec_distance[1] = std::sin(vehicle_state_.angular_velocity() * t) * v /
vehicle_state_.angular_velocity();
}
// If we have rotation information, take it into consideration.
if (vehicle_state_.pose().has_orientation()) {
const auto &orientation = vehicle_state_.pose().orientation();
Eigen::Quaternion<double> quaternion(orientation.qw(), orientation.qx(),
orientation.qy(), orientation.qz());
Eigen::Vector3d pos_vec(vehicle_state_.x(), vehicle_state_.y(),
vehicle_state_.z());
const Eigen::Vector3d future_pos_3d =
quaternion.toRotationMatrix() * vec_distance + pos_vec;
return math::Vec2d(future_pos_3d[0], future_pos_3d[1]);
}
// If no valid rotation information provided from localization,
// return the estimated future position without rotation.
return math::Vec2d(vec_distance[0] + vehicle_state_.x(),
vec_distance[1] + vehicle_state_.y());
}
math::Vec2d VehicleStateProvider::ComputeCOMPosition(
const double rear_to_com_distance) const {
// set length as distance between rear wheel and center of mass.
Eigen::Vector3d v;
if ((FLAGS_state_transform_to_com_reverse &&
vehicle_state_.gear() == canbus::Chassis::GEAR_REVERSE) ||
(FLAGS_state_transform_to_com_drive &&
vehicle_state_.gear() == canbus::Chassis::GEAR_DRIVE)) {
v << 0.0, rear_to_com_distance, 0.0;
} else {
v << 0.0, 0.0, 0.0;
}
Eigen::Vector3d pos_vec(vehicle_state_.x(), vehicle_state_.y(),
vehicle_state_.z());
// Initialize the COM position without rotation
Eigen::Vector3d com_pos_3d = v + pos_vec;
// If we have rotation information, take it into consideration.
if (vehicle_state_.pose().has_orientation()) {
const auto &orientation = vehicle_state_.pose().orientation();
Eigen::Quaternion<double> quaternion(orientation.qw(), orientation.qx(),
orientation.qy(), orientation.qz());
// Update the COM position with rotation
com_pos_3d = quaternion.toRotationMatrix() * v + pos_vec;
}
return math::Vec2d(com_pos_3d[0], com_pos_3d[1]);
}
} // namespace common
} // namespace apollo
<|endoftext|>
|
<commit_before>//===--- TypeCheckConstraintsDiag.cpp - Constraint Diagnostics ------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements diagnostics for the type checker.
//
//===----------------------------------------------------------------------===//
#include "ConstraintSystem.h"
using namespace swift;
using namespace constraints;
/// \brief Simplify the given locator by zeroing in on the most specific
/// subexpression described by the locator.
///
/// \param range1 Will be populated with an "interesting" range
static ConstraintLocator *simplifyLocator(ConstraintSystem &cs,
ConstraintLocator *locator,
SourceRange &range1,
SourceRange &range2) {
range1 = SourceRange();
range2 = SourceRange();
auto path = locator->getPath();
auto anchor = locator->getAnchor();
while (!path.empty()) {
switch (path[0].getKind()) {
case ConstraintLocator::ApplyArgument:
// Extract application argument.
if (auto applyExpr = dyn_cast<ApplyExpr>(anchor)) {
anchor = applyExpr->getArg();
path = path.slice(1);
continue;
}
break;
case ConstraintLocator::ApplyFunction:
// Extract application function.
if (auto applyExpr = dyn_cast<ApplyExpr>(anchor)) {
anchor = applyExpr->getArg();
path = path.slice(1);
continue;
}
break;
case ConstraintLocator::Load:
case ConstraintLocator::RvalueAdjustment:
// Loads and rvalue adjustments are implicit.
path = path.slice(1);
continue;
case ConstraintLocator::NamedTupleElement:
case ConstraintLocator::TupleElement:
// Extract tuple element.
if (auto tupleExpr = dyn_cast<TupleExpr>(anchor)) {
anchor = tupleExpr->getElement(path[0].getValue());
path = path.slice(1);
continue;
}
break;
case ConstraintLocator::MemberRefBase:
if (auto dotExpr = dyn_cast<UnresolvedDotExpr>(anchor)) {
range1 = dotExpr->getNameLoc();
anchor = dotExpr->getBase();
path = path.slice(1);
continue;
}
break;
default:
// FIXME: Lots of other cases to handle.
break;
}
// If we get here, we couldn't simplify the path further.
break;
}
if (anchor == locator->getAnchor() &&
path.size() == locator->getPath().size()) {
return locator;
}
return cs.getConstraintLocator(anchor, path);
}
bool ConstraintSystem::diagnose() {
// If there were no unavoidable failures, attempt to solve again, capturing
// any failures that come from our attempts to select overloads or bind
// type variables.
if (unavoidableFailures.empty()) {
SmallVector<Solution, 4> solutions;
// Set up solver state.
SolverState state;
state.recordFailures = true;
this->solverState = &state;
// Solve the system.
solve(solutions);
// FIXME: If we were able to actually fix things along the way,
// we may have to hunt for the best solution. For now, we don't care.
// Remove the solver state.
this->solverState = nullptr;
// Fall through to produce diagnostics.
}
if (unavoidableFailures.size() + failures.size() == 1) {
auto &failure = unavoidableFailures.empty()? *failures.begin()
: **unavoidableFailures.begin();
if (failure.getLocator() && failure.getLocator()->getAnchor()) {
SourceRange range1, range2;
auto locator = simplifyLocator(*this, failure.getLocator(), range1,
range2);
auto &tc = getTypeChecker();
auto anchor = locator->getAnchor();
auto loc = anchor->getLoc();
switch (failure.getKind()) {
case Failure::TupleSizeMismatch: {
auto tuple1 = failure.getFirstType()->castTo<TupleType>();
auto tuple2 = failure.getSecondType()->castTo<TupleType>();
tc.diagnose(loc, diag::invalid_tuple_size, tuple1, tuple2,
tuple1->getFields().size(),
tuple2->getFields().size())
.highlight(range1).highlight(range2);
break;
}
case Failure::TupleUnused:
tc.diagnose(loc, diag::invalid_tuple_element_unused,
failure.getFirstType(),
failure.getSecondType())
.highlight(range1).highlight(range2);
break;
case Failure::TypesNotEqual:
case Failure::TypesNotTrivialSubtypes:
case Failure::TypesNotSubtypes:
case Failure::TypesNotConvertible:
case Failure::TypesNotConstructible:
tc.diagnose(loc, diag::invalid_relation,
failure.getKind() - Failure::TypesNotEqual,
failure.getFirstType(),
failure.getSecondType())
.highlight(range1).highlight(range2);
break;
case Failure::DoesNotHaveMember:
tc.diagnose(loc, diag::does_not_have_member,
failure.getFirstType(),
failure.getName())
.highlight(range1).highlight(range2);
break;
case Failure::DoesNotConformToProtocol:
tc.diagnose(loc, diag::type_does_not_conform,
failure.getFirstType(),
failure.getSecondType())
.highlight(range1).highlight(range2);
break;
default:
// FIXME: Handle all failure kinds
return false;
}
return true;
}
}
return false;
}
<commit_msg>If we have any "unavoidable" failures, diagnose them immediately.<commit_after>//===--- TypeCheckConstraintsDiag.cpp - Constraint Diagnostics ------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements diagnostics for the type checker.
//
//===----------------------------------------------------------------------===//
#include "ConstraintSystem.h"
using namespace swift;
using namespace constraints;
/// \brief Simplify the given locator by zeroing in on the most specific
/// subexpression described by the locator.
///
/// \param range1 Will be populated with an "interesting" range
static ConstraintLocator *simplifyLocator(ConstraintSystem &cs,
ConstraintLocator *locator,
SourceRange &range1,
SourceRange &range2) {
range1 = SourceRange();
range2 = SourceRange();
auto path = locator->getPath();
auto anchor = locator->getAnchor();
while (!path.empty()) {
switch (path[0].getKind()) {
case ConstraintLocator::ApplyArgument:
// Extract application argument.
if (auto applyExpr = dyn_cast<ApplyExpr>(anchor)) {
anchor = applyExpr->getArg();
path = path.slice(1);
continue;
}
break;
case ConstraintLocator::ApplyFunction:
// Extract application function.
if (auto applyExpr = dyn_cast<ApplyExpr>(anchor)) {
anchor = applyExpr->getArg();
path = path.slice(1);
continue;
}
break;
case ConstraintLocator::Load:
case ConstraintLocator::RvalueAdjustment:
// Loads and rvalue adjustments are implicit.
path = path.slice(1);
continue;
case ConstraintLocator::NamedTupleElement:
case ConstraintLocator::TupleElement:
// Extract tuple element.
if (auto tupleExpr = dyn_cast<TupleExpr>(anchor)) {
anchor = tupleExpr->getElement(path[0].getValue());
path = path.slice(1);
continue;
}
break;
case ConstraintLocator::MemberRefBase:
if (auto dotExpr = dyn_cast<UnresolvedDotExpr>(anchor)) {
range1 = dotExpr->getNameLoc();
anchor = dotExpr->getBase();
path = path.slice(1);
continue;
}
break;
default:
// FIXME: Lots of other cases to handle.
break;
}
// If we get here, we couldn't simplify the path further.
break;
}
if (anchor == locator->getAnchor() &&
path.size() == locator->getPath().size()) {
return locator;
}
return cs.getConstraintLocator(anchor, path);
}
/// \brief Emit a diagnostic for the given failure.
///
/// \param cs The constraint system in which the diagnostic was generated.
/// \param failure The failure to emit.
///
/// \returns true if the diagnostic was emitted successfully.
static bool diagnoseFailure(ConstraintSystem &cs, Failure &failure) {
// If there's no anchor, we have no location information to use when emitting
// the diagnostic.
if (!failure.getLocator() || !failure.getLocator()->getAnchor())
return false;
SourceRange range1, range2;
auto locator = simplifyLocator(cs, failure.getLocator(), range1, range2);
auto &tc = cs.getTypeChecker();
auto anchor = locator->getAnchor();
auto loc = anchor->getLoc();
switch (failure.getKind()) {
case Failure::TupleSizeMismatch: {
auto tuple1 = failure.getFirstType()->castTo<TupleType>();
auto tuple2 = failure.getSecondType()->castTo<TupleType>();
tc.diagnose(loc, diag::invalid_tuple_size, tuple1, tuple2,
tuple1->getFields().size(),
tuple2->getFields().size())
.highlight(range1).highlight(range2);
break;
}
case Failure::TupleUnused:
tc.diagnose(loc, diag::invalid_tuple_element_unused,
failure.getFirstType(),
failure.getSecondType())
.highlight(range1).highlight(range2);
break;
case Failure::TypesNotEqual:
case Failure::TypesNotTrivialSubtypes:
case Failure::TypesNotSubtypes:
case Failure::TypesNotConvertible:
case Failure::TypesNotConstructible:
tc.diagnose(loc, diag::invalid_relation,
failure.getKind() - Failure::TypesNotEqual,
failure.getFirstType(),
failure.getSecondType())
.highlight(range1).highlight(range2);
break;
case Failure::DoesNotHaveMember:
tc.diagnose(loc, diag::does_not_have_member,
failure.getFirstType(),
failure.getName())
.highlight(range1).highlight(range2);
break;
case Failure::DoesNotConformToProtocol:
tc.diagnose(loc, diag::type_does_not_conform,
failure.getFirstType(),
failure.getSecondType())
.highlight(range1).highlight(range2);
break;
default:
// FIXME: Handle all failure kinds
return false;
}
return true;
}
bool ConstraintSystem::diagnose() {
// If there were any unavoidable failures, emit the first one we can.
if (!unavoidableFailures.empty()) {
for (auto failure : unavoidableFailures) {
if (diagnoseFailure(*this, *failure))
return true;
}
return false;
}
// There were no unavoidable failures, so attempt to solve again, capturing
// any failures that come from our attempts to select overloads or bind
// type variables.
{
SmallVector<Solution, 4> solutions;
// Set up solver state.
SolverState state;
state.recordFailures = true;
this->solverState = &state;
// Solve the system.
solve(solutions);
// FIXME: If we were able to actually fix things along the way,
// we may have to hunt for the best solution. For now, we don't care.
// Remove the solver state.
this->solverState = nullptr;
// Fall through to produce diagnostics.
}
if (failures.size() == 1) {
auto &failure = unavoidableFailures.empty()? *failures.begin()
: **unavoidableFailures.begin();
return diagnoseFailure(*this, failure);
}
return false;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2008-2013 The Communi Project
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*/
#include "ircchannel.h"
#include "ircchannel_p.h"
#include "ircusermodel.h"
#include "ircusermodel_p.h"
#include "ircbuffermodel.h"
#include "ircbuffermodel_p.h"
#include "ircconnection.h"
#include "ircnetwork.h"
#include "irccommand.h"
#include "ircuser_p.h"
#include "irc.h"
IRC_BEGIN_NAMESPACE
/*!
\file ircchannel.h
\brief \#include <IrcChannel>
*/
/*!
\class IrcChannel ircchannel.h <IrcChannel>
\ingroup models
\brief Keeps track of channel status.
\sa IrcBufferModel
*/
#ifndef IRC_DOXYGEN
static QString getPrefix(const QString& name, const QStringList& prefixes)
{
int i = 0;
while (i < name.length() && prefixes.contains(name.at(i)))
++i;
return name.left(i);
}
static QString channelName(const QString& title, const QStringList& prefixes)
{
int i = 0;
while (i < title.length() && prefixes.contains(title.at(i)))
++i;
return title.mid(i);
}
static QString userName(const QString& name, const QStringList& prefixes)
{
QString copy = name;
while (!copy.isEmpty() && prefixes.contains(copy.at(0)))
copy.remove(0, 1);
return Irc::nickFromPrefix(copy);
}
IrcChannelPrivate::IrcChannelPrivate() : joined(0), left(0)
{
}
IrcChannelPrivate::~IrcChannelPrivate()
{
}
void IrcChannelPrivate::init(const QString& title, IrcBufferModel* m)
{
IrcBufferPrivate::init(title, m);
const QStringList chanTypes = m->network()->channelTypes();
prefix = getPrefix(title, chanTypes);
name = channelName(title, chanTypes);
}
void IrcChannelPrivate::changeModes(const QString& value, const QStringList& arguments)
{
Q_Q(IrcChannel);
const IrcNetwork* network = q->network();
QMap<QString, QString> ms = modes;
QStringList args = arguments;
bool add = true;
for (int i = 0; i < value.size(); ++i) {
const QString m = value.at(i);
if (m == QLatin1String("+")) {
add = true;
} else if (m == QLatin1String("-")) {
add = false;
} else {
if (add) {
QString a;
if (!args.isEmpty() && network && network->channelModes(IrcNetwork::TypeB | IrcNetwork::TypeC).contains(m))
a = args.takeFirst();
ms.insert(m, a);
} else {
ms.remove(m);
}
}
}
if (modes != ms) {
setKey(ms.value(QLatin1String("k")));
modes = ms;
emit q->modeChanged(q->mode());
}
}
void IrcChannelPrivate::setModes(const QString& value, const QStringList& arguments)
{
Q_Q(IrcChannel);
const IrcNetwork* network = q->network();
QMap<QString, QString> ms;
QStringList args = arguments;
for (int i = 0; i < value.size(); ++i) {
const QString m = value.at(i);
if (m != QLatin1String("+") && m != QLatin1String("-")) {
QString a;
if (!args.isEmpty() && network && network->channelModes(IrcNetwork::TypeB | IrcNetwork::TypeC).contains(m))
a = args.takeFirst();
ms.insert(m, a);
}
}
if (modes != ms) {
setKey(ms.value(QLatin1String("k")));
modes = ms;
emit q->modeChanged(q->mode());
}
}
void IrcChannelPrivate::setTopic(const QString& value)
{
Q_Q(IrcChannel);
if (topic != value) {
topic = value;
emit q->topicChanged(topic);
}
}
void IrcChannelPrivate::setKey(const QString& value)
{
Q_Q(IrcChannel);
if (modes.value(QLatin1String("k")) != value) {
modes.insert(QLatin1String("k"), value);
emit q->keyChanged(value);
}
}
void IrcChannelPrivate::addUser(const QString& name)
{
Q_Q(IrcChannel);
const QStringList prefixes = q->network()->prefixes();
IrcUser* user = new IrcUser(q);
IrcUserPrivate* priv = IrcUserPrivate::get(user);
priv->channel = q;
priv->setName(userName(name, prefixes));
priv->setPrefix(getPrefix(name, prefixes));
priv->setMode(q->network()->prefixToMode(user->prefix()));
activeUsers.prepend(user);
userList.append(user);
userMap.insert(user->name(), user);
foreach (IrcUserModel* model, userModels)
IrcUserModelPrivate::get(model)->addUser(user);
}
bool IrcChannelPrivate::removeUser(const QString& name)
{
if (IrcUser* user = userMap.value(name)) {
userMap.remove(name);
userList.removeOne(user);
activeUsers.removeOne(user);
foreach (IrcUserModel* model, userModels)
IrcUserModelPrivate::get(model)->removeUser(user);
user->deleteLater();
return true;
}
return false;
}
void IrcChannelPrivate::setUsers(const QStringList& names)
{
Q_Q(IrcChannel);
const QStringList prefixes = q->network()->prefixes();
qDeleteAll(userList);
userMap.clear();
userList.clear();
activeUsers.clear();
QList<IrcUser*> users;
foreach (const QString& name, names) {
IrcUser* user = new IrcUser(q);
IrcUserPrivate* priv = IrcUserPrivate::get(user);
priv->channel = q;
priv->setName(userName(name, prefixes));
priv->setPrefix(getPrefix(name, prefixes));
priv->setMode(q->network()->prefixToMode(user->prefix()));
activeUsers.append(user);
userList.append(user);
userMap.insert(user->name(), user);
users.append(user);
}
foreach (IrcUserModel* model, userModels)
IrcUserModelPrivate::get(model)->setUsers(users);
}
bool IrcChannelPrivate::renameUser(const QString& from, const QString& to)
{
if (IrcUser* user = userMap.take(from)) {
IrcUserPrivate::get(user)->setName(to);
userMap.insert(to, user);
QStringList names = userMap.keys();
foreach (IrcUserModel* model, userModels) {
IrcUserModelPrivate::get(model)->renameUser(user);
emit model->namesChanged(names);
}
return true;
}
return false;
}
void IrcChannelPrivate::setUserMode(const QString& name, const QString& command)
{
if (IrcUser* user = userMap.value(name)) {
bool add = true;
QString mode = user->mode();
QString prefix = user->prefix();
const IrcNetwork* network = model->network();
for (int i = 0; i < command.size(); ++i) {
QChar c = command.at(i);
if (c == QLatin1Char('+')) {
add = true;
} else if (c == QLatin1Char('-')) {
add = false;
} else {
QString p = network->modeToPrefix(c);
if (add) {
if (!mode.contains(c))
mode += c;
if (!prefix.contains(p))
prefix += p;
} else {
mode.remove(c);
prefix.remove(p);
}
}
}
IrcUserPrivate* priv = IrcUserPrivate::get(user);
priv->setPrefix(prefix);
priv->setMode(mode);
foreach (IrcUserModel* model, userModels)
IrcUserModelPrivate::get(model)->setUserMode(user);
}
}
void IrcChannelPrivate::promoteUser(const QString& name)
{
if (IrcUser* user = userMap.value(name)) {
const int idx = activeUsers.indexOf(user);
Q_ASSERT(idx != -1);
activeUsers.move(idx, 0);
foreach (IrcUserModel* model, userModels)
IrcUserModelPrivate::get(model)->promoteUser(user);
}
}
bool IrcChannelPrivate::processJoinMessage(IrcJoinMessage* message)
{
if (message->flags() & IrcMessage::Own) {
++joined;
emitActiveChanged();
} else {
addUser(message->nick());
}
return true;
}
bool IrcChannelPrivate::processKickMessage(IrcKickMessage* message)
{
if (!message->user().compare(message->connection()->nickName(), Qt::CaseInsensitive)) {
++left;
emitActiveChanged();
return true;
}
return removeUser(message->user());
}
bool IrcChannelPrivate::processModeMessage(IrcModeMessage* message)
{
if (message->kind() == IrcModeMessage::Channel) {
if (message->isReply())
setModes(message->mode(), message->arguments());
else
changeModes(message->mode(), message->arguments());
return true;
} else if (!message->argument().isEmpty()) {
setUserMode(message->argument(), message->mode());
}
return true;
}
bool IrcChannelPrivate::processNamesMessage(IrcNamesMessage* message)
{
setUsers(message->names());
return true;
}
bool IrcChannelPrivate::processNickMessage(IrcNickMessage* message)
{
const bool renamed = renameUser(message->oldNick(), message->newNick());
if (renamed)
promoteUser(message->newNick());
return renamed;
}
bool IrcChannelPrivate::processNoticeMessage(IrcNoticeMessage* message)
{
promoteUser(message->nick());
return true;
}
bool IrcChannelPrivate::processNumericMessage(IrcNumericMessage* message)
{
promoteUser(message->nick());
return true;
}
bool IrcChannelPrivate::processPartMessage(IrcPartMessage* message)
{
if (message->flags() & IrcMessage::Own) {
++left;
emitActiveChanged();
return true;
}
return removeUser(message->nick());
}
bool IrcChannelPrivate::processPrivateMessage(IrcPrivateMessage* message)
{
const QString content = message->content();
const bool prefixed = !content.isEmpty() && message->network()->prefixes().contains(content.at(0));
foreach (IrcUser* user, activeUsers) {
const QString str = prefixed ? user->title() : user->name();
if (content.startsWith(str)) {
promoteUser(user->name());
break;
}
}
promoteUser(message->nick());
return true;
}
bool IrcChannelPrivate::processQuitMessage(IrcQuitMessage* message)
{
if (message->flags() & IrcMessage::Own) {
++left;
emitActiveChanged();
return true;
}
return removeUser(message->nick()) || IrcBufferPrivate::processQuitMessage(message);
}
bool IrcChannelPrivate::processTopicMessage(IrcTopicMessage* message)
{
setTopic(message->topic());
return true;
}
#endif // IRC_DOXYGEN
/*!
Constructs a new channel object with \a parent.
*/
IrcChannel::IrcChannel(QObject* parent)
: IrcBuffer(*new IrcChannelPrivate, parent)
{
}
/*!
Destructs the channel object.
*/
IrcChannel::~IrcChannel()
{
Q_D(IrcChannel);
qDeleteAll(d->userList);
d->userList.clear();
d->userMap.clear();
d->userModels.clear();
emit destroyed(this);
}
/*!
This property holds the channel key.
\par Access function:
\li QString <b>key</b>() const
\par Notifier signal:
\li void <b>keyChanged</b>(const QString& key)
*/
QString IrcChannel::key() const
{
Q_D(const IrcChannel);
return d->modes.value(QLatin1String("k"));
}
/*!
This property holds the complete channel mode including possible arguments.
\par Access function:
\li QString <b>mode</b>() const
\par Notifier signal:
\li void <b>modeChanged</b>(const QString& mode)
*/
QString IrcChannel::mode() const
{
Q_D(const IrcChannel);
QString m = QStringList(d->modes.keys()).join(QString());
QStringList a = d->modes.values();
a.removeAll(QString());
if (!a.isEmpty())
m += QLatin1String(" ") + a.join(QLatin1String(" "));
if (!m.isEmpty())
m.prepend(QLatin1String("+"));
return m;
}
/*!
This property holds the channel topic.
\par Access function:
\li QString <b>topic</b>() const
\par Notifier signal:
\li void <b>topicChanged</b>(const QString& topic)
*/
QString IrcChannel::topic() const
{
Q_D(const IrcChannel);
return d->topic;
}
bool IrcChannel::isActive() const
{
Q_D(const IrcChannel);
return IrcBuffer::isActive() && d->joined > d->left;
}
/*!
Joins the channel with an optional \a key.
This method is provided for convenience. It is equal to:
\code
IrcCommand* command = IrcCommand::createJoin(channel->title(), key);
channel->sendCommand(command);
\endcode
\sa IrcBuffer::sendCommand(), IrcCommand::createJoin()
*/
void IrcChannel::join(const QString& key)
{
Q_D(IrcChannel);
if (!key.isEmpty())
d->setKey(key);
sendCommand(IrcCommand::createJoin(title(), key));
}
/*!
Parts the channel with an optional \a reason.
This method is provided for convenience. It is equal to:
\code
IrcCommand* command = IrcCommand::createPart(channel->title(), reason);
channel->sendCommand(command);
\endcode
\sa IrcBuffer::sendCommand(), IrcCommand::createPart()
*/
void IrcChannel::part(const QString& reason)
{
sendCommand(IrcCommand::createPart(title(), reason));
}
#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug debug, const IrcChannel* channel)
{
if (!channel)
return debug << "IrcChannel(0x0) ";
debug.nospace() << channel->metaObject()->className() << '(' << (void*) channel;
if (!channel->objectName().isEmpty())
debug.nospace() << ", name=" << qPrintable(channel->objectName());
if (!channel->title().isEmpty())
debug.nospace() << ", title=" << qPrintable(channel->title());
debug.nospace() << ')';
return debug.space();
}
#endif // QT_NO_DEBUG_STREAM
#include "moc_ircchannel.cpp"
IRC_END_NAMESPACE
<commit_msg>Make IrcChannel::join() use the stored key<commit_after>/*
* Copyright (C) 2008-2013 The Communi Project
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*/
#include "ircchannel.h"
#include "ircchannel_p.h"
#include "ircusermodel.h"
#include "ircusermodel_p.h"
#include "ircbuffermodel.h"
#include "ircbuffermodel_p.h"
#include "ircconnection.h"
#include "ircnetwork.h"
#include "irccommand.h"
#include "ircuser_p.h"
#include "irc.h"
IRC_BEGIN_NAMESPACE
/*!
\file ircchannel.h
\brief \#include <IrcChannel>
*/
/*!
\class IrcChannel ircchannel.h <IrcChannel>
\ingroup models
\brief Keeps track of channel status.
\sa IrcBufferModel
*/
#ifndef IRC_DOXYGEN
static QString getPrefix(const QString& name, const QStringList& prefixes)
{
int i = 0;
while (i < name.length() && prefixes.contains(name.at(i)))
++i;
return name.left(i);
}
static QString channelName(const QString& title, const QStringList& prefixes)
{
int i = 0;
while (i < title.length() && prefixes.contains(title.at(i)))
++i;
return title.mid(i);
}
static QString userName(const QString& name, const QStringList& prefixes)
{
QString copy = name;
while (!copy.isEmpty() && prefixes.contains(copy.at(0)))
copy.remove(0, 1);
return Irc::nickFromPrefix(copy);
}
IrcChannelPrivate::IrcChannelPrivate() : joined(0), left(0)
{
}
IrcChannelPrivate::~IrcChannelPrivate()
{
}
void IrcChannelPrivate::init(const QString& title, IrcBufferModel* m)
{
IrcBufferPrivate::init(title, m);
const QStringList chanTypes = m->network()->channelTypes();
prefix = getPrefix(title, chanTypes);
name = channelName(title, chanTypes);
}
void IrcChannelPrivate::changeModes(const QString& value, const QStringList& arguments)
{
Q_Q(IrcChannel);
const IrcNetwork* network = q->network();
QMap<QString, QString> ms = modes;
QStringList args = arguments;
bool add = true;
for (int i = 0; i < value.size(); ++i) {
const QString m = value.at(i);
if (m == QLatin1String("+")) {
add = true;
} else if (m == QLatin1String("-")) {
add = false;
} else {
if (add) {
QString a;
if (!args.isEmpty() && network && network->channelModes(IrcNetwork::TypeB | IrcNetwork::TypeC).contains(m))
a = args.takeFirst();
ms.insert(m, a);
} else {
ms.remove(m);
}
}
}
if (modes != ms) {
setKey(ms.value(QLatin1String("k")));
modes = ms;
emit q->modeChanged(q->mode());
}
}
void IrcChannelPrivate::setModes(const QString& value, const QStringList& arguments)
{
Q_Q(IrcChannel);
const IrcNetwork* network = q->network();
QMap<QString, QString> ms;
QStringList args = arguments;
for (int i = 0; i < value.size(); ++i) {
const QString m = value.at(i);
if (m != QLatin1String("+") && m != QLatin1String("-")) {
QString a;
if (!args.isEmpty() && network && network->channelModes(IrcNetwork::TypeB | IrcNetwork::TypeC).contains(m))
a = args.takeFirst();
ms.insert(m, a);
}
}
if (modes != ms) {
setKey(ms.value(QLatin1String("k")));
modes = ms;
emit q->modeChanged(q->mode());
}
}
void IrcChannelPrivate::setTopic(const QString& value)
{
Q_Q(IrcChannel);
if (topic != value) {
topic = value;
emit q->topicChanged(topic);
}
}
void IrcChannelPrivate::setKey(const QString& value)
{
Q_Q(IrcChannel);
if (modes.value(QLatin1String("k")) != value) {
modes.insert(QLatin1String("k"), value);
emit q->keyChanged(value);
}
}
void IrcChannelPrivate::addUser(const QString& name)
{
Q_Q(IrcChannel);
const QStringList prefixes = q->network()->prefixes();
IrcUser* user = new IrcUser(q);
IrcUserPrivate* priv = IrcUserPrivate::get(user);
priv->channel = q;
priv->setName(userName(name, prefixes));
priv->setPrefix(getPrefix(name, prefixes));
priv->setMode(q->network()->prefixToMode(user->prefix()));
activeUsers.prepend(user);
userList.append(user);
userMap.insert(user->name(), user);
foreach (IrcUserModel* model, userModels)
IrcUserModelPrivate::get(model)->addUser(user);
}
bool IrcChannelPrivate::removeUser(const QString& name)
{
if (IrcUser* user = userMap.value(name)) {
userMap.remove(name);
userList.removeOne(user);
activeUsers.removeOne(user);
foreach (IrcUserModel* model, userModels)
IrcUserModelPrivate::get(model)->removeUser(user);
user->deleteLater();
return true;
}
return false;
}
void IrcChannelPrivate::setUsers(const QStringList& names)
{
Q_Q(IrcChannel);
const QStringList prefixes = q->network()->prefixes();
qDeleteAll(userList);
userMap.clear();
userList.clear();
activeUsers.clear();
QList<IrcUser*> users;
foreach (const QString& name, names) {
IrcUser* user = new IrcUser(q);
IrcUserPrivate* priv = IrcUserPrivate::get(user);
priv->channel = q;
priv->setName(userName(name, prefixes));
priv->setPrefix(getPrefix(name, prefixes));
priv->setMode(q->network()->prefixToMode(user->prefix()));
activeUsers.append(user);
userList.append(user);
userMap.insert(user->name(), user);
users.append(user);
}
foreach (IrcUserModel* model, userModels)
IrcUserModelPrivate::get(model)->setUsers(users);
}
bool IrcChannelPrivate::renameUser(const QString& from, const QString& to)
{
if (IrcUser* user = userMap.take(from)) {
IrcUserPrivate::get(user)->setName(to);
userMap.insert(to, user);
QStringList names = userMap.keys();
foreach (IrcUserModel* model, userModels) {
IrcUserModelPrivate::get(model)->renameUser(user);
emit model->namesChanged(names);
}
return true;
}
return false;
}
void IrcChannelPrivate::setUserMode(const QString& name, const QString& command)
{
if (IrcUser* user = userMap.value(name)) {
bool add = true;
QString mode = user->mode();
QString prefix = user->prefix();
const IrcNetwork* network = model->network();
for (int i = 0; i < command.size(); ++i) {
QChar c = command.at(i);
if (c == QLatin1Char('+')) {
add = true;
} else if (c == QLatin1Char('-')) {
add = false;
} else {
QString p = network->modeToPrefix(c);
if (add) {
if (!mode.contains(c))
mode += c;
if (!prefix.contains(p))
prefix += p;
} else {
mode.remove(c);
prefix.remove(p);
}
}
}
IrcUserPrivate* priv = IrcUserPrivate::get(user);
priv->setPrefix(prefix);
priv->setMode(mode);
foreach (IrcUserModel* model, userModels)
IrcUserModelPrivate::get(model)->setUserMode(user);
}
}
void IrcChannelPrivate::promoteUser(const QString& name)
{
if (IrcUser* user = userMap.value(name)) {
const int idx = activeUsers.indexOf(user);
Q_ASSERT(idx != -1);
activeUsers.move(idx, 0);
foreach (IrcUserModel* model, userModels)
IrcUserModelPrivate::get(model)->promoteUser(user);
}
}
bool IrcChannelPrivate::processJoinMessage(IrcJoinMessage* message)
{
if (message->flags() & IrcMessage::Own) {
++joined;
emitActiveChanged();
} else {
addUser(message->nick());
}
return true;
}
bool IrcChannelPrivate::processKickMessage(IrcKickMessage* message)
{
if (!message->user().compare(message->connection()->nickName(), Qt::CaseInsensitive)) {
++left;
emitActiveChanged();
return true;
}
return removeUser(message->user());
}
bool IrcChannelPrivate::processModeMessage(IrcModeMessage* message)
{
if (message->kind() == IrcModeMessage::Channel) {
if (message->isReply())
setModes(message->mode(), message->arguments());
else
changeModes(message->mode(), message->arguments());
return true;
} else if (!message->argument().isEmpty()) {
setUserMode(message->argument(), message->mode());
}
return true;
}
bool IrcChannelPrivate::processNamesMessage(IrcNamesMessage* message)
{
setUsers(message->names());
return true;
}
bool IrcChannelPrivate::processNickMessage(IrcNickMessage* message)
{
const bool renamed = renameUser(message->oldNick(), message->newNick());
if (renamed)
promoteUser(message->newNick());
return renamed;
}
bool IrcChannelPrivate::processNoticeMessage(IrcNoticeMessage* message)
{
promoteUser(message->nick());
return true;
}
bool IrcChannelPrivate::processNumericMessage(IrcNumericMessage* message)
{
promoteUser(message->nick());
return true;
}
bool IrcChannelPrivate::processPartMessage(IrcPartMessage* message)
{
if (message->flags() & IrcMessage::Own) {
++left;
emitActiveChanged();
return true;
}
return removeUser(message->nick());
}
bool IrcChannelPrivate::processPrivateMessage(IrcPrivateMessage* message)
{
const QString content = message->content();
const bool prefixed = !content.isEmpty() && message->network()->prefixes().contains(content.at(0));
foreach (IrcUser* user, activeUsers) {
const QString str = prefixed ? user->title() : user->name();
if (content.startsWith(str)) {
promoteUser(user->name());
break;
}
}
promoteUser(message->nick());
return true;
}
bool IrcChannelPrivate::processQuitMessage(IrcQuitMessage* message)
{
if (message->flags() & IrcMessage::Own) {
++left;
emitActiveChanged();
return true;
}
return removeUser(message->nick()) || IrcBufferPrivate::processQuitMessage(message);
}
bool IrcChannelPrivate::processTopicMessage(IrcTopicMessage* message)
{
setTopic(message->topic());
return true;
}
#endif // IRC_DOXYGEN
/*!
Constructs a new channel object with \a parent.
*/
IrcChannel::IrcChannel(QObject* parent)
: IrcBuffer(*new IrcChannelPrivate, parent)
{
}
/*!
Destructs the channel object.
*/
IrcChannel::~IrcChannel()
{
Q_D(IrcChannel);
qDeleteAll(d->userList);
d->userList.clear();
d->userMap.clear();
d->userModels.clear();
emit destroyed(this);
}
/*!
This property holds the channel key.
\par Access function:
\li QString <b>key</b>() const
\par Notifier signal:
\li void <b>keyChanged</b>(const QString& key)
*/
QString IrcChannel::key() const
{
Q_D(const IrcChannel);
return d->modes.value(QLatin1String("k"));
}
/*!
This property holds the complete channel mode including possible arguments.
\par Access function:
\li QString <b>mode</b>() const
\par Notifier signal:
\li void <b>modeChanged</b>(const QString& mode)
*/
QString IrcChannel::mode() const
{
Q_D(const IrcChannel);
QString m = QStringList(d->modes.keys()).join(QString());
QStringList a = d->modes.values();
a.removeAll(QString());
if (!a.isEmpty())
m += QLatin1String(" ") + a.join(QLatin1String(" "));
if (!m.isEmpty())
m.prepend(QLatin1String("+"));
return m;
}
/*!
This property holds the channel topic.
\par Access function:
\li QString <b>topic</b>() const
\par Notifier signal:
\li void <b>topicChanged</b>(const QString& topic)
*/
QString IrcChannel::topic() const
{
Q_D(const IrcChannel);
return d->topic;
}
bool IrcChannel::isActive() const
{
Q_D(const IrcChannel);
return IrcBuffer::isActive() && d->joined > d->left;
}
/*!
Joins the channel with an optional \a key.
This method is provided for convenience. It is equal to:
\code
IrcCommand* command = IrcCommand::createJoin(channel->title(), key);
channel->sendCommand(command);
\endcode
\sa IrcBuffer::sendCommand(), IrcCommand::createJoin()
*/
void IrcChannel::join(const QString& key)
{
Q_D(IrcChannel);
if (!key.isEmpty())
d->setKey(key);
sendCommand(IrcCommand::createJoin(title(), IrcChannel::key()));
}
/*!
Parts the channel with an optional \a reason.
This method is provided for convenience. It is equal to:
\code
IrcCommand* command = IrcCommand::createPart(channel->title(), reason);
channel->sendCommand(command);
\endcode
\sa IrcBuffer::sendCommand(), IrcCommand::createPart()
*/
void IrcChannel::part(const QString& reason)
{
sendCommand(IrcCommand::createPart(title(), reason));
}
#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug debug, const IrcChannel* channel)
{
if (!channel)
return debug << "IrcChannel(0x0) ";
debug.nospace() << channel->metaObject()->className() << '(' << (void*) channel;
if (!channel->objectName().isEmpty())
debug.nospace() << ", name=" << qPrintable(channel->objectName());
if (!channel->title().isEmpty())
debug.nospace() << ", title=" << qPrintable(channel->title());
debug.nospace() << ')';
return debug.space();
}
#endif // QT_NO_DEBUG_STREAM
#include "moc_ircchannel.cpp"
IRC_END_NAMESPACE
<|endoftext|>
|
<commit_before>// ----------------------------------------------------------------------------
// JsonStream.cpp
//
//
// Authors:
// Peter Polidoro polidorop@janelia.hhmi.org
// ----------------------------------------------------------------------------
#include "JsonStream.h"
CONSTANT_STRING(error_constant_string,"\"error\"");
CONSTANT_STRING(success_constant_string,"\"success\"");
CONSTANT_STRING(true_constant_string,"true");
CONSTANT_STRING(false_constant_string,"false");
CONSTANT_STRING(null_constant_string,"null");
CONSTANT_STRING(long_constant_string,"\"long\"");
CONSTANT_STRING(double_constant_string,"\"double\"");
CONSTANT_STRING(bool_constant_string,"\"bool\"");
CONSTANT_STRING(string_constant_string,"\"string\"");
CONSTANT_STRING(object_constant_string,"\"object\"");
CONSTANT_STRING(array_constant_string,"\"array\"");
JsonDepthTracker::JsonDepthTracker()
{
first_item_ = true;
inside_object_ = true;
}
JsonDepthTracker::JsonDepthTracker(bool first_item, bool inside_object) :
first_item_(first_item),
inside_object_(inside_object)
{
}
JsonStream::JsonStream(Stream &stream)
{
setStream(stream);
setCompactPrint();
indent_level_ = 0;
writing_ = false;
}
void JsonStream::setStream(Stream &stream)
{
stream_ptr_ = &stream;
}
// encoder methods
void JsonStream::beginObject()
{
if (!depth_tracker_.empty())
{
endArrayItem();
}
indent_level_++;
depth_tracker_.push_back(JsonDepthTracker(true,true));
*stream_ptr_ << "{";
}
void JsonStream::endObject()
{
indent_level_--;
if (pretty_print_ && (!depth_tracker_.back().first_item_))
{
*stream_ptr_ << "\n";
indent();
}
depth_tracker_.pop_back();
*stream_ptr_ << "}";
}
void JsonStream::beginArray()
{
indent_level_++;
depth_tracker_.push_back(JsonDepthTracker(true,false));
*stream_ptr_ << "[";
}
void JsonStream::endArray()
{
indent_level_--;
if (pretty_print_ && (!depth_tracker_.back().first_item_))
{
*stream_ptr_ << "\n";
indent();
}
depth_tracker_.pop_back();
*stream_ptr_ << "]";
}
void JsonStream::setCompactPrint()
{
pretty_print_ = false;
}
void JsonStream::setPrettyPrint()
{
pretty_print_ = true;
}
template <>
void JsonStream::writeKey<const char *>(const char *key)
{
endItem();
if (!depth_tracker_.empty() && depth_tracker_.back().inside_object_)
{
*stream_ptr_ << "\"" << key << "\"" << ":";
}
}
template <>
void JsonStream::writeKey<char *>(char *key)
{
endItem();
if (!depth_tracker_.empty() && depth_tracker_.back().inside_object_)
{
*stream_ptr_ << "\"" << key << "\"" << ":";
}
}
template <>
void JsonStream::writeKey<String>(String key)
{
endItem();
if (!depth_tracker_.empty() && depth_tracker_.back().inside_object_)
{
*stream_ptr_ << "\"" << key << "\"" << ":";
}
}
template <>
void JsonStream::writeKey<ConstantString>(ConstantString key)
{
endItem();
if (!depth_tracker_.empty() && depth_tracker_.back().inside_object_)
{
*stream_ptr_ << "\"" << key << "\"" << ":";
}
}
template <>
void JsonStream::writeKey<ConstantString const *>(ConstantString const *key_ptr)
{
endItem();
if (!depth_tracker_.empty() && depth_tracker_.back().inside_object_)
{
*stream_ptr_ << "\"" << *key_ptr << "\"" << ":";
}
}
template <>
void JsonStream::writeKey<ConstantString *>(ConstantString *key_ptr)
{
endItem();
if (!depth_tracker_.empty() && depth_tracker_.back().inside_object_)
{
*stream_ptr_ << "\"" << *key_ptr << "\"" << ":";
}
}
template <>
void JsonStream::write<char>(char value)
{
endArrayItem();
*stream_ptr_ << "\"" << value << "\"";
}
template <>
void JsonStream::write<const char*>(const char *value)
{
endArrayItem();
if (!depth_tracker_.empty())
{
*stream_ptr_ << "\"" << value << "\"";
}
else
{
*stream_ptr_ << value;
}
}
template <>
void JsonStream::write<char*>(char *value)
{
endArrayItem();
if (!depth_tracker_.empty())
{
*stream_ptr_ << "\"" << value << "\"";
}
else
{
*stream_ptr_ << value;
}
}
template <>
void JsonStream::write<String>(String value)
{
endArrayItem();
if (!depth_tracker_.empty())
{
*stream_ptr_ << "\"" << value << "\"";
}
else
{
*stream_ptr_ << value;
}
}
template <>
void JsonStream::write<String&>(String &value)
{
endArrayItem();
if (!depth_tracker_.empty())
{
*stream_ptr_ << "\"" << value << "\"";
}
else
{
*stream_ptr_ << value;
}
}
template <>
void JsonStream::write<ConstantString>(ConstantString value)
{
endArrayItem();
if (!depth_tracker_.empty())
{
*stream_ptr_ << "\"" << value << "\"";
}
else
{
*stream_ptr_ << value;
}
}
template <>
void JsonStream::write<ConstantString *>(ConstantString *value_ptr)
{
endArrayItem();
if (!depth_tracker_.empty())
{
*stream_ptr_ << "\"" << *value_ptr << "\"";
}
else
{
*stream_ptr_ << *value_ptr;
}
}
template <>
void JsonStream::write<ConstantString const *>(ConstantString const *value_ptr)
{
endArrayItem();
if (!depth_tracker_.empty())
{
*stream_ptr_ << "\"" << *value_ptr << "\"";
}
else
{
*stream_ptr_ << *value_ptr;
}
}
template <>
void JsonStream::write<unsigned char>(unsigned char value)
{
endArrayItem();
*stream_ptr_ << _DEC(value);
}
template <>
void JsonStream::write<int>(int value)
{
endArrayItem();
*stream_ptr_ << _DEC(value);
}
template <>
void JsonStream::write<unsigned int>(unsigned int value)
{
endArrayItem();
*stream_ptr_ << _DEC(value);
}
template <>
void JsonStream::write<long>(long value)
{
endArrayItem();
*stream_ptr_ << _DEC(value);
}
template <>
void JsonStream::write<unsigned long>(unsigned long value)
{
endArrayItem();
*stream_ptr_ << _DEC(value);
}
template <>
void JsonStream::write<long long>(long long value)
{
endArrayItem();
*stream_ptr_ << _DEC(value);
}
template <>
void JsonStream::write<unsigned long long>(unsigned long long value)
{
endArrayItem();
*stream_ptr_ << _DEC(value);
}
template <>
void JsonStream::write<JsonStream::ResponseCodes>(JsonStream::ResponseCodes value)
{
endArrayItem();
if (!pretty_print_)
{
*stream_ptr_ << value;
}
else
{
switch (value)
{
case ERROR:
*stream_ptr_ << error_constant_string;
break;
case SUCCESS:
*stream_ptr_ << success_constant_string;
break;
}
}
}
template <>
void JsonStream::write<JsonStream::JsonTypes>(JsonStream::JsonTypes value)
{
endArrayItem();
switch (value)
{
case LONG_TYPE:
*stream_ptr_ << long_constant_string;
break;
case DOUBLE_TYPE:
*stream_ptr_ << double_constant_string;
break;
case BOOL_TYPE:
*stream_ptr_ << bool_constant_string;
break;
case NULL_TYPE:
*stream_ptr_ << null_constant_string;
break;
case STRING_TYPE:
*stream_ptr_ << string_constant_string;
break;
case OBJECT_TYPE:
*stream_ptr_ << object_constant_string;
break;
case ARRAY_TYPE:
*stream_ptr_ << array_constant_string;
break;
}
}
template <>
void JsonStream::write<double>(double value)
{
endArrayItem();
char value_char_array[STRING_LENGTH_DOUBLE];
dtostrf(value,DOUBLE_DIGITS_DEFAULT,DOUBLE_DIGITS_DEFAULT,value_char_array);
*stream_ptr_ << value_char_array;
}
template <>
void JsonStream::write<float>(float value)
{
endArrayItem();
char value_char_array[STRING_LENGTH_DOUBLE];
dtostrf((double)value,DOUBLE_DIGITS_DEFAULT,DOUBLE_DIGITS_DEFAULT,value_char_array);
*stream_ptr_ << value_char_array;
}
template <>
void JsonStream::writeDouble<double>(double value, unsigned char prec)
{
endArrayItem();
char value_char_array[STRING_LENGTH_DOUBLE];
dtostrf(value,prec,prec,value_char_array);
*stream_ptr_ << value_char_array;
}
template <>
void JsonStream::writeDouble<float>(float value, unsigned char prec)
{
endArrayItem();
char value_char_array[STRING_LENGTH_DOUBLE];
dtostrf((double)value,prec,prec,value_char_array);
*stream_ptr_ << value_char_array;
}
template <>
void JsonStream::write<bool>(bool value)
{
if (value)
{
*stream_ptr_ << true_constant_string;
}
else
{
*stream_ptr_ << false_constant_string;
}
}
template <>
void JsonStream::write<ArduinoJson::JsonArray*>(ArduinoJson::JsonArray *array_ptr)
{
endArrayItem();
array_ptr->printTo(*stream_ptr_);
}
template <>
void JsonStream::write<ArduinoJson::JsonObject*>(ArduinoJson::JsonObject *object_ptr)
{
endArrayItem();
object_ptr->printTo(*stream_ptr_);
}
void JsonStream::writeNull()
{
endArrayItem();
*stream_ptr_ << null_constant_string;
}
template <>
void JsonStream::writeJson<const char*>(const char *value)
{
endArrayItem();
*stream_ptr_ << value;
}
template <>
void JsonStream::writeJson<char*>(char *value)
{
endArrayItem();
*stream_ptr_ << value;
}
template <>
void JsonStream::writeJson<String>(String value)
{
endArrayItem();
*stream_ptr_ << value;
}
template <>
void JsonStream::writeJson<String&>(String &value)
{
endArrayItem();
*stream_ptr_ << value;
}
template <>
void JsonStream::writeJson<ConstantString>(ConstantString value)
{
endArrayItem();
*stream_ptr_ << value;
}
template <>
void JsonStream::writeJson<ConstantString *>(ConstantString *value_ptr)
{
endArrayItem();
*stream_ptr_ << *value_ptr;
}
template <>
void JsonStream::writeJson<ConstantString const *>(ConstantString const *value_ptr)
{
endArrayItem();
*stream_ptr_ << *value_ptr;
}
template <>
void JsonStream::writeJson<ArduinoJson::JsonArray*>(ArduinoJson::JsonArray *array_ptr)
{
endArrayItem();
array_ptr->printTo(*stream_ptr_);
}
template <>
void JsonStream::writeJson<ArduinoJson::JsonObject*>(ArduinoJson::JsonObject *object_ptr)
{
endArrayItem();
object_ptr->printTo(*stream_ptr_);
}
void JsonStream::writeNewline()
{
if (depth_tracker_.empty())
{
*stream_ptr_ << "\n";
}
}
void JsonStream::writeChar(char c)
{
if (!writing_)
{
endArrayItem();
writing_ = true;
}
*stream_ptr_ << c;
}
void JsonStream::writeByte(byte b)
{
if (!writing_)
{
endArrayItem();
writing_ = true;
}
*stream_ptr_ << b;
}
// decoder methods
int JsonStream::available()
{
return stream_ptr_->available();
}
int JsonStream::readJsonIntoBuffer(char buffer[], unsigned int buffer_size)
{
return stream_ptr_->readBytesUntil(EOL,buffer,buffer_size);
}
// private methods
void JsonStream::indent()
{
if (pretty_print_)
{
for (int i=0; i<(RESPONSE_INDENT*indent_level_); ++i)
{
*stream_ptr_ << " ";
}
}
}
void JsonStream::endItem()
{
if (!depth_tracker_.empty())
{
if (!depth_tracker_.back().first_item_)
{
*stream_ptr_ << ",";
}
else
{
depth_tracker_.back().first_item_ = false;
}
if (pretty_print_)
{
*stream_ptr_ << "\n";
}
indent();
}
writing_ = false;
}
void JsonStream::endArrayItem()
{
if (!depth_tracker_.back().inside_object_)
{
endItem();
}
}
<commit_msg>Check for buffer overflow.<commit_after>// ----------------------------------------------------------------------------
// JsonStream.cpp
//
//
// Authors:
// Peter Polidoro polidorop@janelia.hhmi.org
// ----------------------------------------------------------------------------
#include "JsonStream.h"
CONSTANT_STRING(error_constant_string,"\"error\"");
CONSTANT_STRING(success_constant_string,"\"success\"");
CONSTANT_STRING(true_constant_string,"true");
CONSTANT_STRING(false_constant_string,"false");
CONSTANT_STRING(null_constant_string,"null");
CONSTANT_STRING(long_constant_string,"\"long\"");
CONSTANT_STRING(double_constant_string,"\"double\"");
CONSTANT_STRING(bool_constant_string,"\"bool\"");
CONSTANT_STRING(string_constant_string,"\"string\"");
CONSTANT_STRING(object_constant_string,"\"object\"");
CONSTANT_STRING(array_constant_string,"\"array\"");
JsonDepthTracker::JsonDepthTracker()
{
first_item_ = true;
inside_object_ = true;
}
JsonDepthTracker::JsonDepthTracker(bool first_item, bool inside_object) :
first_item_(first_item),
inside_object_(inside_object)
{
}
JsonStream::JsonStream(Stream &stream)
{
setStream(stream);
setCompactPrint();
indent_level_ = 0;
writing_ = false;
}
void JsonStream::setStream(Stream &stream)
{
stream_ptr_ = &stream;
}
// encoder methods
void JsonStream::beginObject()
{
if (!depth_tracker_.empty())
{
endArrayItem();
}
indent_level_++;
depth_tracker_.push_back(JsonDepthTracker(true,true));
*stream_ptr_ << "{";
}
void JsonStream::endObject()
{
indent_level_--;
if (pretty_print_ && (!depth_tracker_.back().first_item_))
{
*stream_ptr_ << "\n";
indent();
}
depth_tracker_.pop_back();
*stream_ptr_ << "}";
}
void JsonStream::beginArray()
{
indent_level_++;
depth_tracker_.push_back(JsonDepthTracker(true,false));
*stream_ptr_ << "[";
}
void JsonStream::endArray()
{
indent_level_--;
if (pretty_print_ && (!depth_tracker_.back().first_item_))
{
*stream_ptr_ << "\n";
indent();
}
depth_tracker_.pop_back();
*stream_ptr_ << "]";
}
void JsonStream::setCompactPrint()
{
pretty_print_ = false;
}
void JsonStream::setPrettyPrint()
{
pretty_print_ = true;
}
template <>
void JsonStream::writeKey<const char *>(const char *key)
{
endItem();
if (!depth_tracker_.empty() && depth_tracker_.back().inside_object_)
{
*stream_ptr_ << "\"" << key << "\"" << ":";
}
}
template <>
void JsonStream::writeKey<char *>(char *key)
{
endItem();
if (!depth_tracker_.empty() && depth_tracker_.back().inside_object_)
{
*stream_ptr_ << "\"" << key << "\"" << ":";
}
}
template <>
void JsonStream::writeKey<String>(String key)
{
endItem();
if (!depth_tracker_.empty() && depth_tracker_.back().inside_object_)
{
*stream_ptr_ << "\"" << key << "\"" << ":";
}
}
template <>
void JsonStream::writeKey<ConstantString>(ConstantString key)
{
endItem();
if (!depth_tracker_.empty() && depth_tracker_.back().inside_object_)
{
*stream_ptr_ << "\"" << key << "\"" << ":";
}
}
template <>
void JsonStream::writeKey<ConstantString const *>(ConstantString const *key_ptr)
{
endItem();
if (!depth_tracker_.empty() && depth_tracker_.back().inside_object_)
{
*stream_ptr_ << "\"" << *key_ptr << "\"" << ":";
}
}
template <>
void JsonStream::writeKey<ConstantString *>(ConstantString *key_ptr)
{
endItem();
if (!depth_tracker_.empty() && depth_tracker_.back().inside_object_)
{
*stream_ptr_ << "\"" << *key_ptr << "\"" << ":";
}
}
template <>
void JsonStream::write<char>(char value)
{
endArrayItem();
*stream_ptr_ << "\"" << value << "\"";
}
template <>
void JsonStream::write<const char*>(const char *value)
{
endArrayItem();
if (!depth_tracker_.empty())
{
*stream_ptr_ << "\"" << value << "\"";
}
else
{
*stream_ptr_ << value;
}
}
template <>
void JsonStream::write<char*>(char *value)
{
endArrayItem();
if (!depth_tracker_.empty())
{
*stream_ptr_ << "\"" << value << "\"";
}
else
{
*stream_ptr_ << value;
}
}
template <>
void JsonStream::write<String>(String value)
{
endArrayItem();
if (!depth_tracker_.empty())
{
*stream_ptr_ << "\"" << value << "\"";
}
else
{
*stream_ptr_ << value;
}
}
template <>
void JsonStream::write<String&>(String &value)
{
endArrayItem();
if (!depth_tracker_.empty())
{
*stream_ptr_ << "\"" << value << "\"";
}
else
{
*stream_ptr_ << value;
}
}
template <>
void JsonStream::write<ConstantString>(ConstantString value)
{
endArrayItem();
if (!depth_tracker_.empty())
{
*stream_ptr_ << "\"" << value << "\"";
}
else
{
*stream_ptr_ << value;
}
}
template <>
void JsonStream::write<ConstantString *>(ConstantString *value_ptr)
{
endArrayItem();
if (!depth_tracker_.empty())
{
*stream_ptr_ << "\"" << *value_ptr << "\"";
}
else
{
*stream_ptr_ << *value_ptr;
}
}
template <>
void JsonStream::write<ConstantString const *>(ConstantString const *value_ptr)
{
endArrayItem();
if (!depth_tracker_.empty())
{
*stream_ptr_ << "\"" << *value_ptr << "\"";
}
else
{
*stream_ptr_ << *value_ptr;
}
}
template <>
void JsonStream::write<unsigned char>(unsigned char value)
{
endArrayItem();
*stream_ptr_ << _DEC(value);
}
template <>
void JsonStream::write<int>(int value)
{
endArrayItem();
*stream_ptr_ << _DEC(value);
}
template <>
void JsonStream::write<unsigned int>(unsigned int value)
{
endArrayItem();
*stream_ptr_ << _DEC(value);
}
template <>
void JsonStream::write<long>(long value)
{
endArrayItem();
*stream_ptr_ << _DEC(value);
}
template <>
void JsonStream::write<unsigned long>(unsigned long value)
{
endArrayItem();
*stream_ptr_ << _DEC(value);
}
template <>
void JsonStream::write<long long>(long long value)
{
endArrayItem();
*stream_ptr_ << _DEC(value);
}
template <>
void JsonStream::write<unsigned long long>(unsigned long long value)
{
endArrayItem();
*stream_ptr_ << _DEC(value);
}
template <>
void JsonStream::write<JsonStream::ResponseCodes>(JsonStream::ResponseCodes value)
{
endArrayItem();
if (!pretty_print_)
{
*stream_ptr_ << value;
}
else
{
switch (value)
{
case ERROR:
*stream_ptr_ << error_constant_string;
break;
case SUCCESS:
*stream_ptr_ << success_constant_string;
break;
}
}
}
template <>
void JsonStream::write<JsonStream::JsonTypes>(JsonStream::JsonTypes value)
{
endArrayItem();
switch (value)
{
case LONG_TYPE:
*stream_ptr_ << long_constant_string;
break;
case DOUBLE_TYPE:
*stream_ptr_ << double_constant_string;
break;
case BOOL_TYPE:
*stream_ptr_ << bool_constant_string;
break;
case NULL_TYPE:
*stream_ptr_ << null_constant_string;
break;
case STRING_TYPE:
*stream_ptr_ << string_constant_string;
break;
case OBJECT_TYPE:
*stream_ptr_ << object_constant_string;
break;
case ARRAY_TYPE:
*stream_ptr_ << array_constant_string;
break;
}
}
template <>
void JsonStream::write<double>(double value)
{
endArrayItem();
char value_char_array[STRING_LENGTH_DOUBLE];
dtostrf(value,DOUBLE_DIGITS_DEFAULT,DOUBLE_DIGITS_DEFAULT,value_char_array);
*stream_ptr_ << value_char_array;
}
template <>
void JsonStream::write<float>(float value)
{
endArrayItem();
char value_char_array[STRING_LENGTH_DOUBLE];
dtostrf((double)value,DOUBLE_DIGITS_DEFAULT,DOUBLE_DIGITS_DEFAULT,value_char_array);
*stream_ptr_ << value_char_array;
}
template <>
void JsonStream::writeDouble<double>(double value, unsigned char prec)
{
endArrayItem();
char value_char_array[STRING_LENGTH_DOUBLE];
dtostrf(value,prec,prec,value_char_array);
*stream_ptr_ << value_char_array;
}
template <>
void JsonStream::writeDouble<float>(float value, unsigned char prec)
{
endArrayItem();
char value_char_array[STRING_LENGTH_DOUBLE];
dtostrf((double)value,prec,prec,value_char_array);
*stream_ptr_ << value_char_array;
}
template <>
void JsonStream::write<bool>(bool value)
{
if (value)
{
*stream_ptr_ << true_constant_string;
}
else
{
*stream_ptr_ << false_constant_string;
}
}
template <>
void JsonStream::write<ArduinoJson::JsonArray*>(ArduinoJson::JsonArray *array_ptr)
{
endArrayItem();
array_ptr->printTo(*stream_ptr_);
}
template <>
void JsonStream::write<ArduinoJson::JsonObject*>(ArduinoJson::JsonObject *object_ptr)
{
endArrayItem();
object_ptr->printTo(*stream_ptr_);
}
void JsonStream::writeNull()
{
endArrayItem();
*stream_ptr_ << null_constant_string;
}
template <>
void JsonStream::writeJson<const char*>(const char *value)
{
endArrayItem();
*stream_ptr_ << value;
}
template <>
void JsonStream::writeJson<char*>(char *value)
{
endArrayItem();
*stream_ptr_ << value;
}
template <>
void JsonStream::writeJson<String>(String value)
{
endArrayItem();
*stream_ptr_ << value;
}
template <>
void JsonStream::writeJson<String&>(String &value)
{
endArrayItem();
*stream_ptr_ << value;
}
template <>
void JsonStream::writeJson<ConstantString>(ConstantString value)
{
endArrayItem();
*stream_ptr_ << value;
}
template <>
void JsonStream::writeJson<ConstantString *>(ConstantString *value_ptr)
{
endArrayItem();
*stream_ptr_ << *value_ptr;
}
template <>
void JsonStream::writeJson<ConstantString const *>(ConstantString const *value_ptr)
{
endArrayItem();
*stream_ptr_ << *value_ptr;
}
template <>
void JsonStream::writeJson<ArduinoJson::JsonArray*>(ArduinoJson::JsonArray *array_ptr)
{
endArrayItem();
array_ptr->printTo(*stream_ptr_);
}
template <>
void JsonStream::writeJson<ArduinoJson::JsonObject*>(ArduinoJson::JsonObject *object_ptr)
{
endArrayItem();
object_ptr->printTo(*stream_ptr_);
}
void JsonStream::writeNewline()
{
if (depth_tracker_.empty())
{
*stream_ptr_ << "\n";
}
}
void JsonStream::writeChar(char c)
{
if (!writing_)
{
endArrayItem();
writing_ = true;
}
*stream_ptr_ << c;
}
void JsonStream::writeByte(byte b)
{
if (!writing_)
{
endArrayItem();
writing_ = true;
}
*stream_ptr_ << b;
}
// decoder methods
int JsonStream::available()
{
return stream_ptr_->available();
}
int JsonStream::readJsonIntoBuffer(char buffer[], unsigned int buffer_size)
{
unsigned int bytes_read = stream_ptr_->readBytesUntil(EOL,buffer,buffer_size);
if (bytes_read < buffer_size)
{
// terminate string
buffer[bytes_read] = 0;
}
else
{
// set buffer to empty string
buffer[0] = 0;
// clear stream of remaining characters
stream_ptr_->find(EOL);
return -1;
}
return bytes_read;
}
// private methods
void JsonStream::indent()
{
if (pretty_print_)
{
for (int i=0; i<(RESPONSE_INDENT*indent_level_); ++i)
{
*stream_ptr_ << " ";
}
}
}
void JsonStream::endItem()
{
if (!depth_tracker_.empty())
{
if (!depth_tracker_.back().first_item_)
{
*stream_ptr_ << ",";
}
else
{
depth_tracker_.back().first_item_ = false;
}
if (pretty_print_)
{
*stream_ptr_ << "\n";
}
indent();
}
writing_ = false;
}
void JsonStream::endArrayItem()
{
if (!depth_tracker_.back().inside_object_)
{
endItem();
}
}
<|endoftext|>
|
<commit_before>/*
* This file is part of TelepathyQt4
*
* Copyright (C) 2008-2009 Collabora Ltd. <http://www.collabora.co.uk/>
* Copyright (C) 2008-2009 Nokia Corporation
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.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
*/
#include <TelepathyQt4/KeyFile>
#include <QtCore/QByteArray>
#include <QtCore/QFile>
#include <QtCore/QHash>
#include <QtCore/QString>
#include <QtCore/QStringList>
#include "TelepathyQt4/debug-internal.h"
namespace Tp
{
struct TELEPATHY_QT4_NO_EXPORT KeyFile::Private
{
QString fileName;
KeyFile::Status status;
QHash<QString, QHash<QString, QByteArray> > groups;
QString currentGroup;
Private();
Private(const QString &fName);
void setFileName(const QString &fName);
void setError(KeyFile::Status status, const QString &reason);
bool read();
bool validateKey(const QByteArray &data, int from, int to, QString &result);
bool unescapeString(const QByteArray &data, int from, int to, QString &result) const;
bool unescapeStringList(const QByteArray &data, int from, int to, QStringList &result) const;
QStringList allGroups() const;
QStringList allKeys() const;
QStringList keys() const;
bool contains(const QString &key) const;
QString rawValue(const QString &key) const;
QString value(const QString &key) const;
QStringList valueAsStringList(const QString &key) const;
};
KeyFile::Private::Private()
: status(KeyFile::None)
{
}
KeyFile::Private::Private(const QString &fName)
: fileName(fName),
status(KeyFile::NoError)
{
read();
}
void KeyFile::Private::setFileName(const QString &fName)
{
fileName = fName;
status = KeyFile::NoError;
currentGroup = QString();
groups.clear();
read();
}
void KeyFile::Private::setError(KeyFile::Status st, const QString &reason)
{
warning() << QString(QLatin1String("ERROR: filename(%1) reason(%2)"))
.arg(fileName).arg(reason);
status = st;
groups.clear();
}
bool KeyFile::Private::read()
{
QFile file(fileName);
if (!file.exists()) {
setError(KeyFile::NotFoundError,
QLatin1String("file does not exist"));
return false;
}
if (!file.open(QFile::ReadOnly)) {
setError(KeyFile::AccessError,
QLatin1String("cannot open file for readonly access"));
return false;
}
QByteArray data;
QByteArray group;
QString currentGroup;
QHash<QString, QByteArray> groupMap;
QByteArray rawValue;
int line = 0;
int idx;
while (!file.atEnd()) {
data = file.readLine().trimmed();
line++;
if (data.size() == 0) {
// skip empty lines
continue;
}
char ch = data.at(0);
if (ch == '#') {
// skip comments
continue;
}
else if (ch == '[') {
if (groupMap.size()) {
groups[currentGroup] = groupMap;
groupMap.clear();
}
idx = data.indexOf(']');
if (idx == -1) {
// line starts with [ and it's not a group
setError(KeyFile::FormatError,
QString(QLatin1String("invalid group at line %2 - missing ']'"))
.arg(line));
return false;
}
group = data.mid(1, idx - 1).trimmed();
if (groups.contains(QLatin1String(group))) {
setError(KeyFile::FormatError,
QString(QLatin1String("duplicated group '%1' at line %2"))
.arg(QLatin1String(group)).arg(line));
return false;
}
currentGroup = QLatin1String("");
if (!unescapeString(group, 0, group.size(), currentGroup)) {
setError(KeyFile::FormatError,
QString(QLatin1String("invalid group '%1' at line %2"))
.arg(currentGroup).arg(line));
return false;
}
}
else {
idx = data.indexOf('=');
if (idx == -1) {
setError(KeyFile::FormatError,
QString(QLatin1String("format error at line %1 - missing '='"))
.arg(line));
return false;
}
// remove trailing spaces
char ch;
int idxKeyEnd = idx;
while ((ch = data.at(idxKeyEnd - 1)) == ' ' || ch == '\t') {
--idxKeyEnd;
}
QString key;
if (!validateKey(data, 0, idxKeyEnd, key)) {
setError(KeyFile::FormatError,
QString(QLatin1String("invalid key '%1' at line %2"))
.arg(key).arg(line));
return false;
}
if (groupMap.contains(key)) {
setError(KeyFile::FormatError,
QString(QLatin1String("duplicated key '%1' on group '%2' at line %3"))
.arg(key).arg(currentGroup).arg(line));
return false;
}
data = data.mid(idx + 1).trimmed();
rawValue = data.mid(0, data.size());
groupMap[key] = rawValue;
}
}
if (groupMap.size()) {
groups[currentGroup] = groupMap;
groupMap.clear();
}
return true;
}
bool KeyFile::Private::validateKey(const QByteArray &data, int from, int to, QString &result)
{
int i = from;
bool ret = true;
while (i < to) {
uint ch = data.at(i++);
// as an extension to the Desktop Entry spec, we allow " ", "_", "." and "@"
// as valid key characters - "_" and "." are needed for keys that are
// D-Bus property names, and GKeyFile and KConfigIniBackend also accept
// all four of those characters.
if (!((ch >= 'a' && ch <= 'z') ||
(ch >= 'A' && ch <= 'Z') ||
(ch >= '0' && ch <= '9') ||
(ch == ' ') ||
(ch == '-') || (ch == '_') ||
(ch == '.') || (ch == '@'))) {
ret = false;
}
result += ch;
}
return ret;
}
bool KeyFile::Private::unescapeString(const QByteArray &data, int from, int to, QString &result) const
{
int i = from;
while (i < to) {
uint ch = data.at(i++);
if (ch == '\\') {
if (i == to) {
result += QLatin1String("\\");
return true;
}
char nextCh = data.at(i++);
switch (nextCh) {
case 's':
result += QLatin1String(" ");
break;
case 'n':
result += QLatin1String("\n");
break;
case 't':
result += QLatin1String("\t");
break;
case 'r':
result += QLatin1String("\r");
break;
case ';':
result += QLatin1String(";");
break;
case '\\':
result += QLatin1String("\\");
break;
default:
return false;
}
}
else {
result += ch;
}
}
return true;
}
bool KeyFile::Private::unescapeStringList(const QByteArray &data, int from, int to, QStringList &result) const
{
QByteArray value;
QList<QByteArray> valueList;
int i = from;
char ch;
while (i < to) {
ch = data.at(i++);
if (ch == '\\') {
value += ch;
if (i < to) {
value += data.at(i++);
continue;
}
else {
valueList << value;
break;
}
}
else if (ch == ';') {
valueList << value;
value = "";
}
else {
value += ch;
if (i == to) {
valueList << value;
}
}
}
foreach (value, valueList) {
QString str;
if (!unescapeString(value, 0, value.size(), str)) {
return false;
}
result << str;
}
return true;
}
QStringList KeyFile::Private::allGroups() const
{
return groups.keys();
}
QStringList KeyFile::Private::allKeys() const
{
QStringList keys;
QHash<QString, QHash<QString, QByteArray> >::const_iterator itrGroups = groups.begin();
while (itrGroups != groups.end()) {
keys << itrGroups.value().keys();
++itrGroups;
}
return keys;
}
QStringList KeyFile::Private::keys() const
{
QHash<QString, QByteArray> groupMap = groups[currentGroup];
return groupMap.keys();
}
bool KeyFile::Private::contains(const QString &key) const
{
QHash<QString, QByteArray> groupMap = groups[currentGroup];
return groupMap.contains(key);
}
QString KeyFile::Private::rawValue(const QString &key) const
{
QHash<QString, QByteArray> groupMap = groups[currentGroup];
QByteArray rawValue = groupMap.value(key);
return QLatin1String(rawValue);
}
QString KeyFile::Private::value(const QString &key) const
{
QHash<QString, QByteArray> groupMap = groups[currentGroup];
QString result;
QByteArray rawValue = groupMap.value(key);
if (unescapeString(rawValue, 0, rawValue.size(), result)) {
return result;
}
return QString();
}
QStringList KeyFile::Private::valueAsStringList(const QString &key) const
{
QHash<QString, QByteArray> groupMap = groups[currentGroup];
QStringList result;
QByteArray rawValue = groupMap.value(key);
if (unescapeStringList(rawValue, 0, rawValue.size(), result)) {
return result;
}
return QStringList();
}
/**
* \class KeyFile
* \headerfile TelepathyQt4/key-file.h <TelepathyQt4/KeyFile>
*
* \brief The KeyFile class provides an easy way to read key-pair files such as
* INI style files and .desktop files.
*
* It follows the rules regarding string escaping as defined in
* http://standards.freedesktop.org/desktop-entry-spec/latest/index.html
*/
/**
* Create a KeyFile object used to read (key-pair) compliant files.
*
* The status will be KeyFile::None
* \sa setFileName()
*/
KeyFile::KeyFile()
: mPriv(new Private())
{
}
/**
* Create a KeyFile object used to read (key-pair) compliant files.
*
* \param fileName Name of the file to be read.
*/
KeyFile::KeyFile(const QString &fileName)
: mPriv(new Private(fileName))
{
}
/**
* Class destructor.
*/
KeyFile::~KeyFile()
{
delete mPriv;
}
/**
* Set the name of the file to be read.
*
* \param fileName Name of the file to be read.
*/
void KeyFile::setFileName(const QString &fileName)
{
mPriv->setFileName(fileName);
}
/**
* Return the name of the file associated with this object.
*
* \return Name of the file associated with this object.
*/
QString KeyFile::fileName() const
{
return mPriv->fileName;
}
/**
* Return a status code indicating the first error that was met by #KeyFile,
* or KeyFile::NoError if no error occurred.
*
* Make sure to use this method if you set the filename to be read using
* setFileName().
*
* \return Status code.
* \sa setFileName()
*/
KeyFile::Status KeyFile::status() const
{
return mPriv->status;
}
/**
* Set the current group to be used while reading keys.
*
* Query functions such as keys(), contains() and value() are based on this
* group.
*
* By default a empty group is used as the group for global
* keys and is used as the default group if none is set.
*
* \param group Name of the group to be used.
* \sa group()
*/
void KeyFile::setGroup(const QString &group)
{
mPriv->currentGroup = group;
}
/**
* Return the current group.
*
* \return Name of the current group.
* \sa setGroup()
*/
QString KeyFile::group() const
{
return mPriv->currentGroup;
}
/**
* Return all groups in the desktop file.
*
* Global keys will be added to a empty group.
*
* \return List of all groups in the desktop file.
*/
QStringList KeyFile::allGroups() const
{
return mPriv->allGroups();
}
/**
* Return all keys described in the desktop file.
*
* \return List of all keys in the desktop file.
*/
QStringList KeyFile::allKeys() const
{
return mPriv->allKeys();
}
/**
* Return a list of keys in the current group.
*
* \return List of all keys in the current group.
* \sa group(), setGroup()
*/
QStringList KeyFile::keys() const
{
return mPriv->keys();
}
/**
* Check if the current group contains a key named \a key.
*
* \return true if \a key exists, false otherwise.
* \sa group(), setGroup()
*/
bool KeyFile::contains(const QString &key) const
{
return mPriv->contains(key);
}
/**
* Get the raw value for the key in the current group named \a key.
*
* The raw value is the value as is in the key file.
*
* \return Value of \a key, empty string if not found.
* \sa group(), setGroup()
*/
QString KeyFile::rawValue(const QString &key) const
{
return mPriv->rawValue(key);
}
/**
* Get the value for the key in the current group named \a key.
*
* Escape sequences in the value are interpreted as defined in:
* http://standards.freedesktop.org/desktop-entry-spec/latest/
*
* \return Value of \a key, empty string if not found or an error occurred.
* \sa group(), setGroup()
*/
QString KeyFile::value(const QString &key) const
{
return mPriv->value(key);
}
/**
* Get the value for the key in the current group named \a key as a list.
*
* Return a list containing all strings on this key separated by ';'.
* Escape sequences in the value are interpreted as defined in:
* http://standards.freedesktop.org/desktop-entry-spec/latest/
*
* \return Value of \a key as a list, empty string list if not found or an error occurred.
* \sa group(), setGroup()
*/
QStringList KeyFile::valueAsStringList(const QString &key) const
{
return mPriv->valueAsStringList(key);
}
} // Tp
<commit_msg>KeyFile: Remove methods now exported in utils.h.<commit_after>/*
* This file is part of TelepathyQt4
*
* Copyright (C) 2008-2009 Collabora Ltd. <http://www.collabora.co.uk/>
* Copyright (C) 2008-2009 Nokia Corporation
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.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
*/
#include <TelepathyQt4/KeyFile>
#include "TelepathyQt4/debug-internal.h"
#include <TelepathyQt4/Utils>
#include <QtCore/QByteArray>
#include <QtCore/QFile>
#include <QtCore/QHash>
#include <QtCore/QString>
#include <QtCore/QStringList>
namespace Tp
{
struct TELEPATHY_QT4_NO_EXPORT KeyFile::Private
{
QString fileName;
KeyFile::Status status;
QHash<QString, QHash<QString, QByteArray> > groups;
QString currentGroup;
Private();
Private(const QString &fName);
void setFileName(const QString &fName);
void setError(KeyFile::Status status, const QString &reason);
bool read();
bool validateKey(const QByteArray &data, int from, int to, QString &result);
QStringList allGroups() const;
QStringList allKeys() const;
QStringList keys() const;
bool contains(const QString &key) const;
QString rawValue(const QString &key) const;
QString value(const QString &key) const;
QStringList valueAsStringList(const QString &key) const;
};
KeyFile::Private::Private()
: status(KeyFile::None)
{
}
KeyFile::Private::Private(const QString &fName)
: fileName(fName),
status(KeyFile::NoError)
{
read();
}
void KeyFile::Private::setFileName(const QString &fName)
{
fileName = fName;
status = KeyFile::NoError;
currentGroup = QString();
groups.clear();
read();
}
void KeyFile::Private::setError(KeyFile::Status st, const QString &reason)
{
warning() << QString(QLatin1String("ERROR: filename(%1) reason(%2)"))
.arg(fileName).arg(reason);
status = st;
groups.clear();
}
bool KeyFile::Private::read()
{
QFile file(fileName);
if (!file.exists()) {
setError(KeyFile::NotFoundError,
QLatin1String("file does not exist"));
return false;
}
if (!file.open(QFile::ReadOnly)) {
setError(KeyFile::AccessError,
QLatin1String("cannot open file for readonly access"));
return false;
}
QByteArray data;
QByteArray group;
QString currentGroup;
QHash<QString, QByteArray> groupMap;
QByteArray rawValue;
int line = 0;
int idx;
while (!file.atEnd()) {
data = file.readLine().trimmed();
line++;
if (data.size() == 0) {
// skip empty lines
continue;
}
char ch = data.at(0);
if (ch == '#') {
// skip comments
continue;
}
else if (ch == '[') {
if (groupMap.size()) {
groups[currentGroup] = groupMap;
groupMap.clear();
}
idx = data.indexOf(']');
if (idx == -1) {
// line starts with [ and it's not a group
setError(KeyFile::FormatError,
QString(QLatin1String("invalid group at line %2 - missing ']'"))
.arg(line));
return false;
}
group = data.mid(1, idx - 1).trimmed();
if (groups.contains(QLatin1String(group))) {
setError(KeyFile::FormatError,
QString(QLatin1String("duplicated group '%1' at line %2"))
.arg(QLatin1String(group)).arg(line));
return false;
}
currentGroup = QLatin1String("");
if (!unescapeString(group, 0, group.size(), currentGroup)) {
setError(KeyFile::FormatError,
QString(QLatin1String("invalid group '%1' at line %2"))
.arg(currentGroup).arg(line));
return false;
}
}
else {
idx = data.indexOf('=');
if (idx == -1) {
setError(KeyFile::FormatError,
QString(QLatin1String("format error at line %1 - missing '='"))
.arg(line));
return false;
}
// remove trailing spaces
char ch;
int idxKeyEnd = idx;
while ((ch = data.at(idxKeyEnd - 1)) == ' ' || ch == '\t') {
--idxKeyEnd;
}
QString key;
if (!validateKey(data, 0, idxKeyEnd, key)) {
setError(KeyFile::FormatError,
QString(QLatin1String("invalid key '%1' at line %2"))
.arg(key).arg(line));
return false;
}
if (groupMap.contains(key)) {
setError(KeyFile::FormatError,
QString(QLatin1String("duplicated key '%1' on group '%2' at line %3"))
.arg(key).arg(currentGroup).arg(line));
return false;
}
data = data.mid(idx + 1).trimmed();
rawValue = data.mid(0, data.size());
groupMap[key] = rawValue;
}
}
if (groupMap.size()) {
groups[currentGroup] = groupMap;
groupMap.clear();
}
return true;
}
bool KeyFile::Private::validateKey(const QByteArray &data, int from, int to, QString &result)
{
int i = from;
bool ret = true;
while (i < to) {
uint ch = data.at(i++);
// as an extension to the Desktop Entry spec, we allow " ", "_", "." and "@"
// as valid key characters - "_" and "." are needed for keys that are
// D-Bus property names, and GKeyFile and KConfigIniBackend also accept
// all four of those characters.
if (!((ch >= 'a' && ch <= 'z') ||
(ch >= 'A' && ch <= 'Z') ||
(ch >= '0' && ch <= '9') ||
(ch == ' ') ||
(ch == '-') || (ch == '_') ||
(ch == '.') || (ch == '@'))) {
ret = false;
}
result += ch;
}
return ret;
}
QStringList KeyFile::Private::allGroups() const
{
return groups.keys();
}
QStringList KeyFile::Private::allKeys() const
{
QStringList keys;
QHash<QString, QHash<QString, QByteArray> >::const_iterator itrGroups = groups.begin();
while (itrGroups != groups.end()) {
keys << itrGroups.value().keys();
++itrGroups;
}
return keys;
}
QStringList KeyFile::Private::keys() const
{
QHash<QString, QByteArray> groupMap = groups[currentGroup];
return groupMap.keys();
}
bool KeyFile::Private::contains(const QString &key) const
{
QHash<QString, QByteArray> groupMap = groups[currentGroup];
return groupMap.contains(key);
}
QString KeyFile::Private::rawValue(const QString &key) const
{
QHash<QString, QByteArray> groupMap = groups[currentGroup];
QByteArray rawValue = groupMap.value(key);
return QLatin1String(rawValue);
}
QString KeyFile::Private::value(const QString &key) const
{
QHash<QString, QByteArray> groupMap = groups[currentGroup];
QString result;
QByteArray rawValue = groupMap.value(key);
if (unescapeString(rawValue, 0, rawValue.size(), result)) {
return result;
}
return QString();
}
QStringList KeyFile::Private::valueAsStringList(const QString &key) const
{
QHash<QString, QByteArray> groupMap = groups[currentGroup];
QStringList result;
QByteArray rawValue = groupMap.value(key);
if (unescapeStringList(rawValue, 0, rawValue.size(), result)) {
return result;
}
return QStringList();
}
/**
* \class KeyFile
* \headerfile TelepathyQt4/key-file.h <TelepathyQt4/KeyFile>
*
* \brief The KeyFile class provides an easy way to read key-pair files such as
* INI style files and .desktop files.
*
* It follows the rules regarding string escaping as defined in
* http://standards.freedesktop.org/desktop-entry-spec/latest/index.html
*/
/**
* Create a KeyFile object used to read (key-pair) compliant files.
*
* The status will be KeyFile::None
* \sa setFileName()
*/
KeyFile::KeyFile()
: mPriv(new Private())
{
}
/**
* Create a KeyFile object used to read (key-pair) compliant files.
*
* \param fileName Name of the file to be read.
*/
KeyFile::KeyFile(const QString &fileName)
: mPriv(new Private(fileName))
{
}
/**
* Class destructor.
*/
KeyFile::~KeyFile()
{
delete mPriv;
}
/**
* Set the name of the file to be read.
*
* \param fileName Name of the file to be read.
*/
void KeyFile::setFileName(const QString &fileName)
{
mPriv->setFileName(fileName);
}
/**
* Return the name of the file associated with this object.
*
* \return Name of the file associated with this object.
*/
QString KeyFile::fileName() const
{
return mPriv->fileName;
}
/**
* Return a status code indicating the first error that was met by #KeyFile,
* or KeyFile::NoError if no error occurred.
*
* Make sure to use this method if you set the filename to be read using
* setFileName().
*
* \return Status code.
* \sa setFileName()
*/
KeyFile::Status KeyFile::status() const
{
return mPriv->status;
}
/**
* Set the current group to be used while reading keys.
*
* Query functions such as keys(), contains() and value() are based on this
* group.
*
* By default a empty group is used as the group for global
* keys and is used as the default group if none is set.
*
* \param group Name of the group to be used.
* \sa group()
*/
void KeyFile::setGroup(const QString &group)
{
mPriv->currentGroup = group;
}
/**
* Return the current group.
*
* \return Name of the current group.
* \sa setGroup()
*/
QString KeyFile::group() const
{
return mPriv->currentGroup;
}
/**
* Return all groups in the desktop file.
*
* Global keys will be added to a empty group.
*
* \return List of all groups in the desktop file.
*/
QStringList KeyFile::allGroups() const
{
return mPriv->allGroups();
}
/**
* Return all keys described in the desktop file.
*
* \return List of all keys in the desktop file.
*/
QStringList KeyFile::allKeys() const
{
return mPriv->allKeys();
}
/**
* Return a list of keys in the current group.
*
* \return List of all keys in the current group.
* \sa group(), setGroup()
*/
QStringList KeyFile::keys() const
{
return mPriv->keys();
}
/**
* Check if the current group contains a key named \a key.
*
* \return true if \a key exists, false otherwise.
* \sa group(), setGroup()
*/
bool KeyFile::contains(const QString &key) const
{
return mPriv->contains(key);
}
/**
* Get the raw value for the key in the current group named \a key.
*
* The raw value is the value as is in the key file.
*
* \return Value of \a key, empty string if not found.
* \sa group(), setGroup()
*/
QString KeyFile::rawValue(const QString &key) const
{
return mPriv->rawValue(key);
}
/**
* Get the value for the key in the current group named \a key.
*
* Escape sequences in the value are interpreted as defined in:
* http://standards.freedesktop.org/desktop-entry-spec/latest/
*
* \return Value of \a key, empty string if not found or an error occurred.
* \sa group(), setGroup()
*/
QString KeyFile::value(const QString &key) const
{
return mPriv->value(key);
}
/**
* Get the value for the key in the current group named \a key as a list.
*
* Return a list containing all strings on this key separated by ';'.
* Escape sequences in the value are interpreted as defined in:
* http://standards.freedesktop.org/desktop-entry-spec/latest/
*
* \return Value of \a key as a list, empty string list if not found or an error occurred.
* \sa group(), setGroup()
*/
QStringList KeyFile::valueAsStringList(const QString &key) const
{
return mPriv->valueAsStringList(key);
}
} // Tp
<|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#include "modules/planning/tasks/dp_poly_path/trajectory_cost.h"
#include <algorithm>
#include <cmath>
#include <utility>
#include "modules/common/proto/pnc_point.pb.h"
#include "modules/common/configs/vehicle_config_helper.h"
#include "modules/common/math/vec2d.h"
#include "modules/common/util/util.h"
#include "modules/planning/common/planning_gflags.h"
namespace apollo {
namespace planning {
using apollo::common::math::Box2d;
using apollo::common::math::Vec2d;
using apollo::common::TrajectoryPoint;
TrajectoryCost::TrajectoryCost(
const DpPolyPathConfig &config, const ReferenceLine &reference_line,
const std::vector<const PathObstacle *> &obstacles,
const common::VehicleParam &vehicle_param,
const SpeedData &heuristic_speed_data, const common::SLPoint &init_sl_point)
: config_(config),
reference_line_(&reference_line),
vehicle_param_(vehicle_param),
heuristic_speed_data_(heuristic_speed_data),
init_sl_point_(init_sl_point) {
const double total_time =
std::min(heuristic_speed_data_.TotalTime(), FLAGS_prediction_total_time);
num_of_time_stamps_ = static_cast<uint32_t>(
std::floor(total_time / config.eval_time_interval()));
for (const auto ptr_path_obstacle : obstacles) {
if (ptr_path_obstacle->IsIgnore()) {
continue;
}
const auto ptr_obstacle = ptr_path_obstacle->obstacle();
if (Obstacle::IsVirtualObstacle(ptr_obstacle->Perception())) {
// Virtual obstacle
continue;
} else if (Obstacle::IsStaticObstacle(ptr_obstacle->Perception())) {
auto sl_boundary = ptr_path_obstacle->perception_sl_boundary();
const double kDefaultLaneWidth = 1.5;
const auto &vehicle_config =
common::VehicleConfigHelper::instance()->GetConfig();
const double width = vehicle_config.vehicle_param().width();
if (sl_boundary.start_l() + kDefaultLaneWidth < width &&
kDefaultLaneWidth - sl_boundary.end_l() < width) {
// lane blocking obstacle
continue;
}
const double length = vehicle_config.vehicle_param().length();
if (sl_boundary.start_s() - init_sl_point_.s() < 2.0 * length) {
// if too close, we treat the obstacle as non-nudgable
continue;
}
TrajectoryPoint trajectory_point = ptr_obstacle->GetPointAtTime(0.0);
constexpr double kBuff = 0.2;
Box2d obstacle_box = ptr_obstacle->GetBoundingBox(trajectory_point);
Box2d expanded_obstacle_box =
Box2d(obstacle_box.center(), obstacle_box.heading(),
obstacle_box.length() + kBuff, obstacle_box.width() + kBuff);
static_obstacle_boxes_.push_back(std::move(expanded_obstacle_box));
} else {
std::vector<Box2d> box_by_time;
for (uint32_t t = 0; t <= num_of_time_stamps_; ++t) {
TrajectoryPoint trajectory_point =
ptr_obstacle->GetPointAtTime(t * config.eval_time_interval());
Box2d obstacle_box = ptr_obstacle->GetBoundingBox(trajectory_point);
constexpr double kBuff = 0.5;
Box2d expanded_obstacle_box =
Box2d(obstacle_box.center(), obstacle_box.heading(),
obstacle_box.length() + kBuff, obstacle_box.width() + kBuff);
box_by_time.push_back(expanded_obstacle_box);
}
dynamic_obstacle_boxes_.push_back(std::move(box_by_time));
}
}
}
double TrajectoryCost::CalculatePathCost(const QuinticPolynomialCurve1d &curve,
const double start_s,
const double end_s) const {
double path_cost = 0.0;
for (double path_s = 0.0; path_s < (end_s - start_s);
path_s += config_.path_resolution()) {
const double l = curve.Evaluate(0, path_s);
std::function<double(const double)> quasi_softmax = [this](const double x) {
const double l0 = this->config_.path_l_cost_param_l0();
const double b = this->config_.path_l_cost_param_b();
const double k = this->config_.path_l_cost_param_k();
return (b + std::exp(-k * (x - l0))) / (1.0 + std::exp(-k * (x - l0)));
};
path_cost += l * l * config_.path_l_cost() * quasi_softmax(std::fabs(l));
double left_width = 0.0;
double right_width = 0.0;
reference_line_->GetLaneWidth(path_s, &left_width, &right_width);
const auto &vehicle_config =
common::VehicleConfigHelper::instance()->GetConfig();
const double width = vehicle_config.vehicle_param().width();
constexpr double kBuff = 0.2;
if (std::fabs(l) > std::fabs(init_sl_point_.l()) &&
(l + width + kBuff > left_width || l - width - kBuff < right_width)) {
path_cost += config_.path_out_lane_cost();
}
const double dl = std::fabs(curve.Evaluate(1, path_s));
path_cost += dl * dl * config_.path_dl_cost();
const double ddl = std::fabs(curve.Evaluate(2, path_s));
path_cost += ddl * ddl * config_.path_ddl_cost();
}
return path_cost * config_.path_resolution();
}
double TrajectoryCost::CalculateStaticObstacleCost(
const QuinticPolynomialCurve1d &curve, const double start_s,
const double end_s) const {
double obstacle_cost = 0.0;
for (double curr_s = start_s; curr_s <= end_s;
curr_s += config_.path_resolution()) {
const double s = curr_s - start_s; // spline curve s
const double l = curve.Evaluate(0, s);
const double dl = curve.Evaluate(1, s);
const common::SLPoint sl =
common::util::MakeSLPoint(curr_s, l); // ego vehicle sl point
const Box2d ego_box = GetBoxFromSLPoint(sl, dl);
for (const auto &obstacle_box : static_obstacle_boxes_) {
obstacle_cost += GetCostBetweenObsBoxes(ego_box, obstacle_box);
}
}
return obstacle_cost * config_.path_resolution();
}
double TrajectoryCost::CalculateDynamicObstacleCost(
const QuinticPolynomialCurve1d &curve, const double start_s,
const double end_s) const {
double obstacle_cost = 0.0;
double time_stamp = 0.0;
for (size_t index = 0; index < num_of_time_stamps_;
++index, time_stamp += config_.eval_time_interval()) {
common::SpeedPoint speed_point;
heuristic_speed_data_.EvaluateByTime(time_stamp, &speed_point);
if (speed_point.s() < start_s - init_sl_point_.s()) {
continue;
}
if (speed_point.s() > end_s - init_sl_point_.s()) {
break;
}
const double s =
init_sl_point_.s() + speed_point.s() - start_s; // s on spline curve
const double l = curve.Evaluate(0, s);
const double dl = curve.Evaluate(1, s);
const common::SLPoint sl =
common::util::MakeSLPoint(init_sl_point_.s() + speed_point.s(), l);
const Box2d ego_box = GetBoxFromSLPoint(sl, dl);
for (const auto &obstacle_trajectory : dynamic_obstacle_boxes_) {
obstacle_cost +=
GetCostBetweenObsBoxes(ego_box, obstacle_trajectory.at(index));
}
}
constexpr double kDynamicObsWeight = 1e-3;
return obstacle_cost * config_.eval_time_interval() * kDynamicObsWeight;
}
double TrajectoryCost::GetCostBetweenObsBoxes(const Box2d &ego_box,
const Box2d &obstacle_box) const {
// Simple version: calculate obstacle cost by distance
const double distance = obstacle_box.DistanceTo(ego_box);
if (distance > config_.obstacle_ignore_distance()) {
return 0.0;
}
std::function<double(const double, const double)> softmax = [](
const double x, const double x0) {
return std::exp(-(x - x0)) / (1.0 + std::exp(-(x - x0)));
};
double obstacle_cost = 0.0;
obstacle_cost += config_.obstacle_collision_cost() *
softmax(distance, config_.obstacle_collision_distance());
obstacle_cost += 20.0 * softmax(distance, config_.obstacle_risk_distance());
return obstacle_cost;
}
Box2d TrajectoryCost::GetBoxFromSLPoint(const common::SLPoint &sl,
const double dl) const {
Vec2d xy_point;
reference_line_->SLToXY(sl, &xy_point);
ReferencePoint reference_point = reference_line_->GetReferencePoint(sl.s());
const double one_minus_kappa_r_d = 1 - reference_point.kappa() * sl.l();
const double delta_theta = std::atan2(dl, one_minus_kappa_r_d);
const double theta =
common::math::NormalizeAngle(delta_theta + reference_point.heading());
return Box2d(xy_point, theta, vehicle_param_.length(),
vehicle_param_.width());
}
// TODO(All): optimize obstacle cost calculation time
double TrajectoryCost::Calculate(const QuinticPolynomialCurve1d &curve,
const double start_s,
const double end_s) const {
double total_cost = 0.0;
// path cost
total_cost += CalculatePathCost(curve, start_s, end_s);
// static obstacle cost
total_cost += CalculateStaticObstacleCost(curve, start_s, end_s);
// dynamic obstacle cost
total_cost += CalculateDynamicObstacleCost(curve, start_s, end_s);
return total_cost;
}
double TrajectoryCost::RiskDistanceCost(const double distance) const {
return (5.0 - distance) * ((5.0 - distance)) * 10;
}
double TrajectoryCost::RegularDistanceCost(const double distance) const {
return std::max(20.0 - distance, 0.0);
}
} // namespace planning
} // namespace apollo
<commit_msg>Update trajectory_cost.cc<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#include "modules/planning/tasks/dp_poly_path/trajectory_cost.h"
#include <algorithm>
#include <cmath>
#include <utility>
#include "modules/common/proto/pnc_point.pb.h"
#include "modules/common/configs/vehicle_config_helper.h"
#include "modules/common/math/vec2d.h"
#include "modules/common/util/util.h"
#include "modules/planning/common/planning_gflags.h"
namespace apollo {
namespace planning {
using apollo::common::math::Box2d;
using apollo::common::math::Vec2d;
using apollo::common::TrajectoryPoint;
TrajectoryCost::TrajectoryCost(
const DpPolyPathConfig &config, const ReferenceLine &reference_line,
const std::vector<const PathObstacle *> &obstacles,
const common::VehicleParam &vehicle_param,
const SpeedData &heuristic_speed_data, const common::SLPoint &init_sl_point)
: config_(config),
reference_line_(&reference_line),
vehicle_param_(vehicle_param),
heuristic_speed_data_(heuristic_speed_data),
init_sl_point_(init_sl_point) {
const double total_time =
std::min(heuristic_speed_data_.TotalTime(), FLAGS_prediction_total_time);
num_of_time_stamps_ = static_cast<uint32_t>(
std::floor(total_time / config.eval_time_interval()));
for (const auto ptr_path_obstacle : obstacles) {
if (ptr_path_obstacle->IsIgnore()) {
continue;
}
const auto ptr_obstacle = ptr_path_obstacle->obstacle();
if (Obstacle::IsVirtualObstacle(ptr_obstacle->Perception())) {
// Virtual obstacle
continue;
} else if (Obstacle::IsStaticObstacle(ptr_obstacle->Perception())) {
auto sl_boundary = ptr_path_obstacle->perception_sl_boundary();
const double kDefaultLaneWidth = 1.5;
const auto &vehicle_config =
common::VehicleConfigHelper::instance()->GetConfig();
const double width = vehicle_config.vehicle_param().width();
if (sl_boundary.start_l() + kDefaultLaneWidth < width &&
kDefaultLaneWidth - sl_boundary.end_l() < width) {
// lane blocking obstacle
continue;
}
const double length = vehicle_config.vehicle_param().length();
if (sl_boundary.start_s() - init_sl_point_.s() < 2.0 * length) {
// if too close, we treat the obstacle as non-nudgable
continue;
}
TrajectoryPoint trajectory_point = ptr_obstacle->GetPointAtTime(0.0);
constexpr double kBuff = 0.2;
Box2d obstacle_box = ptr_obstacle->GetBoundingBox(trajectory_point);
Box2d expanded_obstacle_box =
Box2d(obstacle_box.center(), obstacle_box.heading(),
obstacle_box.length() + kBuff, obstacle_box.width() + kBuff);
static_obstacle_boxes_.push_back(std::move(expanded_obstacle_box));
} else {
std::vector<Box2d> box_by_time;
for (uint32_t t = 0; t <= num_of_time_stamps_; ++t) {
TrajectoryPoint trajectory_point =
ptr_obstacle->GetPointAtTime(t * config.eval_time_interval());
Box2d obstacle_box = ptr_obstacle->GetBoundingBox(trajectory_point);
constexpr double kBuff = 0.5;
Box2d expanded_obstacle_box =
Box2d(obstacle_box.center(), obstacle_box.heading(),
obstacle_box.length() + kBuff, obstacle_box.width() + kBuff);
box_by_time.push_back(expanded_obstacle_box);
}
dynamic_obstacle_boxes_.push_back(std::move(box_by_time));
}
}
}
double TrajectoryCost::CalculatePathCost(const QuinticPolynomialCurve1d &curve,
const double start_s,
const double end_s) const {
double path_cost = 0.0;
for (double path_s = 0.0; path_s < (end_s - start_s);
path_s += config_.path_resolution()) {
const double l = curve.Evaluate(0, path_s);
std::function<double(const double)> quasi_softmax = [this](const double x) {
const double l0 = this->config_.path_l_cost_param_l0();
const double b = this->config_.path_l_cost_param_b();
const double k = this->config_.path_l_cost_param_k();
return (b + std::exp(-k * (x - l0))) / (1.0 + std::exp(-k * (x - l0)));
};
path_cost += l * l * config_.path_l_cost() * quasi_softmax(std::fabs(l));
double left_width = 0.0;
double right_width = 0.0;
reference_line_->GetLaneWidth(path_s, &left_width, &right_width);
const auto &vehicle_config =
common::VehicleConfigHelper::instance()->GetConfig();
const double width = vehicle_config.vehicle_param().width();
constexpr double kBuff = 0.2;
if (std::fabs(l) > std::fabs(init_sl_point_.l()) &&
(l + width / 2.0 + kBuff > left_width || l - width / 2.0 - kBuff < right_width)) {
path_cost += config_.path_out_lane_cost();
}
const double dl = std::fabs(curve.Evaluate(1, path_s));
path_cost += dl * dl * config_.path_dl_cost();
const double ddl = std::fabs(curve.Evaluate(2, path_s));
path_cost += ddl * ddl * config_.path_ddl_cost();
}
return path_cost * config_.path_resolution();
}
double TrajectoryCost::CalculateStaticObstacleCost(
const QuinticPolynomialCurve1d &curve, const double start_s,
const double end_s) const {
double obstacle_cost = 0.0;
for (double curr_s = start_s; curr_s <= end_s;
curr_s += config_.path_resolution()) {
const double s = curr_s - start_s; // spline curve s
const double l = curve.Evaluate(0, s);
const double dl = curve.Evaluate(1, s);
const common::SLPoint sl =
common::util::MakeSLPoint(curr_s, l); // ego vehicle sl point
const Box2d ego_box = GetBoxFromSLPoint(sl, dl);
for (const auto &obstacle_box : static_obstacle_boxes_) {
obstacle_cost += GetCostBetweenObsBoxes(ego_box, obstacle_box);
}
}
return obstacle_cost * config_.path_resolution();
}
double TrajectoryCost::CalculateDynamicObstacleCost(
const QuinticPolynomialCurve1d &curve, const double start_s,
const double end_s) const {
double obstacle_cost = 0.0;
double time_stamp = 0.0;
for (size_t index = 0; index < num_of_time_stamps_;
++index, time_stamp += config_.eval_time_interval()) {
common::SpeedPoint speed_point;
heuristic_speed_data_.EvaluateByTime(time_stamp, &speed_point);
if (speed_point.s() < start_s - init_sl_point_.s()) {
continue;
}
if (speed_point.s() > end_s - init_sl_point_.s()) {
break;
}
const double s =
init_sl_point_.s() + speed_point.s() - start_s; // s on spline curve
const double l = curve.Evaluate(0, s);
const double dl = curve.Evaluate(1, s);
const common::SLPoint sl =
common::util::MakeSLPoint(init_sl_point_.s() + speed_point.s(), l);
const Box2d ego_box = GetBoxFromSLPoint(sl, dl);
for (const auto &obstacle_trajectory : dynamic_obstacle_boxes_) {
obstacle_cost +=
GetCostBetweenObsBoxes(ego_box, obstacle_trajectory.at(index));
}
}
constexpr double kDynamicObsWeight = 1e-3;
return obstacle_cost * config_.eval_time_interval() * kDynamicObsWeight;
}
double TrajectoryCost::GetCostBetweenObsBoxes(const Box2d &ego_box,
const Box2d &obstacle_box) const {
// Simple version: calculate obstacle cost by distance
const double distance = obstacle_box.DistanceTo(ego_box);
if (distance > config_.obstacle_ignore_distance()) {
return 0.0;
}
std::function<double(const double, const double)> softmax = [](
const double x, const double x0) {
return std::exp(-(x - x0)) / (1.0 + std::exp(-(x - x0)));
};
double obstacle_cost = 0.0;
obstacle_cost += config_.obstacle_collision_cost() *
softmax(distance, config_.obstacle_collision_distance());
obstacle_cost += 20.0 * softmax(distance, config_.obstacle_risk_distance());
return obstacle_cost;
}
Box2d TrajectoryCost::GetBoxFromSLPoint(const common::SLPoint &sl,
const double dl) const {
Vec2d xy_point;
reference_line_->SLToXY(sl, &xy_point);
ReferencePoint reference_point = reference_line_->GetReferencePoint(sl.s());
const double one_minus_kappa_r_d = 1 - reference_point.kappa() * sl.l();
const double delta_theta = std::atan2(dl, one_minus_kappa_r_d);
const double theta =
common::math::NormalizeAngle(delta_theta + reference_point.heading());
return Box2d(xy_point, theta, vehicle_param_.length(),
vehicle_param_.width());
}
// TODO(All): optimize obstacle cost calculation time
double TrajectoryCost::Calculate(const QuinticPolynomialCurve1d &curve,
const double start_s,
const double end_s) const {
double total_cost = 0.0;
// path cost
total_cost += CalculatePathCost(curve, start_s, end_s);
// static obstacle cost
total_cost += CalculateStaticObstacleCost(curve, start_s, end_s);
// dynamic obstacle cost
total_cost += CalculateDynamicObstacleCost(curve, start_s, end_s);
return total_cost;
}
double TrajectoryCost::RiskDistanceCost(const double distance) const {
return (5.0 - distance) * ((5.0 - distance)) * 10;
}
double TrajectoryCost::RegularDistanceCost(const double distance) const {
return std::max(20.0 - distance, 0.0);
}
} // namespace planning
} // namespace apollo
<|endoftext|>
|
<commit_before>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2010 Belledonne Communications SARL.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "agent.hh"
class NatHelper : public Module, protected ModuleToolbox{
public:
NatHelper(Agent *ag) : Module(ag){
}
void onRequest(SipEvent *ev) {
sip_request_t *rq=ev->mSip->sip_request;
/* if we receive a request whose first via is wrong (received or rport parameters are present),
fix any possible Contact headers with the same wrong ip address and ports */
fixContactFromVia(ev->getHome(),ev->mSip,ev->mSip->sip_via);
if (rq->rq_method==sip_method_invite || rq->rq_method==sip_method_subscribe){
//be in the record route for all requests that can estabish a dialog
addRecordRoute (ev->getHome(),getAgent(),ev->mSip);
}
}
void onResponse(SipEvent *ev){
sip_via_t *via,*lastvia=NULL;
for(via=ev->mSip->sip_via;via!=NULL;via=via->v_next){
lastvia=via;
}
if (lastvia)
fixContactFromVia(ev->getHome(),ev->mSip,lastvia);
}
private:
bool empty(const char *value){
return value==NULL || value[0]=='\0';
}
void fixContactFromVia(su_home_t *home, sip_t *msg, const sip_via_t *via){
sip_contact_t *ctt=msg->sip_contact;
const char *received=via->v_received;
const char *rport=via->v_rport;
if (empty(received) && empty(rport))
return; /*nothing to do*/
if (empty(received)){
/*case where the rport is not empty but received is empty (because the host was correct)*/
received=via->v_host;
}
for (;ctt!=NULL;ctt=ctt->m_next){
const char *host=ctt->m_url->url_host;
if (host && strcmp(host,via->v_host)==0
&& sipPortEquals(ctt->m_url->url_port,via->v_port) ){
/*we have found a ip:port in a contact that seems incorrect, so fix it*/
LOGD("Fixing contact header with %s:%s to %s:%s",
ctt->m_url->url_host, ctt->m_url->url_port ? ctt->m_url->url_port :"" ,
received, rport ? rport : "");
ctt->m_url->url_host=received;
ctt->m_url->url_port=rport;
}
}
}
static ModuleInfo<NatHelper> sInfo;
};
ModuleInfo<NatHelper> NatHelper::sInfo("NatHelper");
<commit_msg>sip responses: fix contact only for INVITE and SUBCSRIBE<commit_after>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2010 Belledonne Communications SARL.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "agent.hh"
class NatHelper : public Module, protected ModuleToolbox{
public:
NatHelper(Agent *ag) : Module(ag){
}
void onRequest(SipEvent *ev) {
sip_request_t *rq=ev->mSip->sip_request;
/* if we receive a request whose first via is wrong (received or rport parameters are present),
fix any possible Contact headers with the same wrong ip address and ports */
fixContactFromVia(ev->getHome(),ev->mSip,ev->mSip->sip_via);
if (rq->rq_method==sip_method_invite || rq->rq_method==sip_method_subscribe){
//be in the record route for all requests that can estabish a dialog
addRecordRoute (ev->getHome(),getAgent(),ev->mSip);
}
}
void onResponse(SipEvent *ev){
sip_cseq_t *cseq=ev->mSip->sip_cseq;
// fix contact for answers to INVITE and SUBSCRIBES
if (cseq->cs_method==sip_method_invite || cseq->cs_method==sip_method_subscribe){
sip_via_t *via,*lastvia=NULL;
for(via=ev->mSip->sip_via;via!=NULL;via=via->v_next){
lastvia=via;
}
if (lastvia)
fixContactFromVia(ev->getHome(),ev->mSip,lastvia);
}
}
private:
bool empty(const char *value){
return value==NULL || value[0]=='\0';
}
void fixContactFromVia(su_home_t *home, sip_t *msg, const sip_via_t *via){
sip_contact_t *ctt=msg->sip_contact;
const char *received=via->v_received;
const char *rport=via->v_rport;
if (empty(received) && empty(rport))
return; /*nothing to do*/
if (empty(received)){
/*case where the rport is not empty but received is empty (because the host was correct)*/
received=via->v_host;
}
for (;ctt!=NULL;ctt=ctt->m_next){
const char *host=ctt->m_url->url_host;
if (host && strcmp(host,via->v_host)==0
&& sipPortEquals(ctt->m_url->url_port,via->v_port) ){
/*we have found a ip:port in a contact that seems incorrect, so fix it*/
LOGD("Fixing contact header with %s:%s to %s:%s",
ctt->m_url->url_host, ctt->m_url->url_port ? ctt->m_url->url_port :"" ,
received, rport ? rport : "");
ctt->m_url->url_host=received;
ctt->m_url->url_port=rport;
}
}
}
static ModuleInfo<NatHelper> sInfo;
};
ModuleInfo<NatHelper> NatHelper::sInfo("NatHelper");
<|endoftext|>
|
<commit_before>/*
* ngtcp2
*
* Copyright (c) 2017 ngtcp2 contributors
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "debug.h"
#include <random>
#include "util.h"
namespace ngtcp2 {
namespace debug {
namespace {
auto randgen = util::make_mt19937();
} // namespace
namespace {
std::chrono::steady_clock::time_point ts_base;
} // namespace
void reset_timestamp() { ts_base = std::chrono::steady_clock::now(); }
std::chrono::microseconds timestamp() {
return std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::steady_clock::now() - ts_base);
}
namespace {
auto color_output = false;
} // namespace
void set_color_output(bool f) { color_output = f; }
namespace {
auto *outfile = stderr;
} // namespace
namespace {
const char *ansi_esc(const char *code) { return color_output ? code : ""; }
} // namespace
namespace {
const char *ansi_escend() { return color_output ? "\033[0m" : ""; }
} // namespace
enum ngtcp2_dir {
NGTCP2_DIR_SEND,
NGTCP2_DIR_RECV,
};
namespace {
std::string strpkttype_long(uint8_t type) {
switch (type) {
case NGTCP2_PKT_VERSION_NEGOTIATION:
return "Version Negotiation";
case NGTCP2_PKT_CLIENT_INITIAL:
return "Client Initial";
case NGTCP2_PKT_SERVER_STATELESS_RETRY:
return "Server Stateless Retry";
case NGTCP2_PKT_SERVER_CLEARTEXT:
return "Server Cleartext";
case NGTCP2_PKT_CLIENT_CLEARTEXT:
return "Client Cleartext";
case NGTCP2_PKT_0RTT_PROTECTED:
return "0-RTT Protected";
case NGTCP2_PKT_1RTT_PROTECTED_K0:
return "1-RTT Protected (key phase 0)";
case NGTCP2_PKT_1RTT_PROTECTED_K1:
return "1-RTT Protected (key phase 1)";
case NGTCP2_PKT_PUBLIC_RESET:
return "Public Reset";
default:
return "UNKNOWN (0x" + util::format_hex(type) + ")";
}
}
} // namespace
namespace {
std::string strpkttype_short(uint8_t type) {
switch (type) {
case NGTCP2_PKT_01:
return "Short 01";
case NGTCP2_PKT_02:
return "Short 02";
case NGTCP2_PKT_03:
return "Short 03";
default:
return "UNKNOWN (0x" + util::format_hex(type) + ")";
}
}
} // namespace
namespace {
std::string strframetype(uint8_t type) {
switch (type) {
case NGTCP2_FRAME_PADDING:
return "PADDING";
case NGTCP2_FRAME_RST_STREAM:
return "RST_STREAM";
case NGTCP2_FRAME_CONNECTION_CLOSE:
return "CONNECTION_CLOSE";
case NGTCP2_FRAME_GOAWAY:
return "GOAWAY";
case NGTCP2_FRAME_MAX_DATA:
return "MAX_DATA";
case NGTCP2_FRAME_MAX_STREAM_DATA:
return "MAX_STREAM_DATA";
case NGTCP2_FRAME_MAX_STREAM_ID:
return "MAX_STREAM_ID";
case NGTCP2_FRAME_PING:
return "PING";
case NGTCP2_FRAME_BLOCKED:
return "BLOCKED";
case NGTCP2_FRAME_STREAM_BLOCKED:
return "STREAM_BLOCKED";
case NGTCP2_FRAME_STREAM_ID_NEEDED:
return "STREAM_ID_NEEDED";
case NGTCP2_FRAME_NEW_CONNECTION_ID:
return "NEW_CONNECTION_ID";
case NGTCP2_FRAME_ACK:
return "ACK";
case NGTCP2_FRAME_STREAM:
return "STREAM";
default:
return "UNKNOWN (0x" + util::format_hex(type) + ")";
}
}
} // namespace
void print_timestamp() {
auto t = timestamp().count();
fprintf(outfile, "%st=%d.%06d%s ", ansi_esc("\033[33m"),
static_cast<int32_t>(t / 1000000), static_cast<int32_t>(t % 1000000),
ansi_escend());
}
namespace {
const char *pkt_ansi_esc(ngtcp2_dir dir) {
return ansi_esc(dir == NGTCP2_DIR_SEND ? "\033[1;35m" : "\033[1;36m");
}
} // namespace
namespace {
const char *frame_ansi_esc(ngtcp2_dir dir) {
return ansi_esc(dir == NGTCP2_DIR_SEND ? "\033[1;35m" : "\033[1;36m");
}
} // namespace
namespace {
void print_indent() { fprintf(outfile, " "); }
} // namespace
namespace {
void print_pkt_long(ngtcp2_dir dir, const ngtcp2_pkt_hd *hd) {
fprintf(outfile, "%s%s%s CID=%016lx PKN=%lu V=%08x\n", pkt_ansi_esc(dir),
strpkttype_long(hd->type).c_str(), ansi_escend(), hd->conn_id,
hd->pkt_num, hd->version);
}
} // namespace
namespace {
void print_pkt_short(ngtcp2_dir dir, const ngtcp2_pkt_hd *hd) {
fprintf(outfile, "%s%s%s CID=%016lx PKN=%lu\n", pkt_ansi_esc(dir),
strpkttype_short(hd->type).c_str(), ansi_escend(), hd->conn_id,
hd->pkt_num);
}
} // namespace
namespace {
void print_pkt(ngtcp2_dir dir, const ngtcp2_pkt_hd *hd) {
if (hd->flags & NGTCP2_PKT_FLAG_LONG_FORM) {
print_pkt_long(dir, hd);
} else {
print_pkt_short(dir, hd);
}
}
} // namespace
namespace {
void print_frame(ngtcp2_dir dir, const ngtcp2_frame *fr) {
fprintf(outfile, "%s%s%s\n", frame_ansi_esc(dir),
strframetype(fr->type).c_str(), ansi_escend());
switch (fr->type) {
case NGTCP2_FRAME_STREAM:
print_indent();
fprintf(outfile, "stream_id=%08x fin=%u offset=%lu data_length=%zu\n",
fr->stream.stream_id, fr->stream.fin, fr->stream.offset,
fr->stream.datalen);
break;
case NGTCP2_FRAME_PADDING:
print_indent();
fprintf(outfile, "length=%zu\n", fr->padding.len);
break;
case NGTCP2_FRAME_ACK:
print_indent();
fprintf(outfile, "num_blks=%zu num_ts=%zu largest_ack=%lu ack_delay=%u\n",
fr->ack.num_blks, fr->ack.num_ts, fr->ack.largest_ack,
fr->ack.ack_delay);
print_indent();
fprintf(outfile, "first_ack_block_length=%lu\n", fr->ack.first_ack_blklen);
for (size_t i = 0; i < fr->ack.num_blks; ++i) {
auto blk = &fr->ack.blks[i];
print_indent();
fprintf(outfile, "gap=%u ack_block_length=%lu\n", blk->gap, blk->blklen);
}
break;
case NGTCP2_FRAME_RST_STREAM:
print_indent();
fprintf(outfile, "stream_id=%08x error_code=%08x final_offset=%lu\n",
fr->rst_stream.stream_id, fr->rst_stream.error_code,
fr->rst_stream.final_offset);
break;
case NGTCP2_FRAME_CONNECTION_CLOSE:
print_indent();
fprintf(outfile, "error_code=%08x reason_length=%zu\n",
fr->connection_close.error_code, fr->connection_close.reasonlen);
break;
case NGTCP2_FRAME_GOAWAY:
print_indent();
fprintf(outfile,
"largest_client_stream_id=%08x largest_server_stream_id=%08x\n",
fr->goaway.largest_client_stream_id,
fr->goaway.largest_server_stream_id);
break;
case NGTCP2_FRAME_MAX_DATA:
print_indent();
fprintf(outfile, "max_data=%lu\n", fr->max_data.max_data);
break;
case NGTCP2_FRAME_MAX_STREAM_DATA:
print_indent();
fprintf(outfile, "stream_id=%08x max_stream_data=%lu\n",
fr->max_stream_data.stream_id, fr->max_stream_data.max_stream_data);
break;
case NGTCP2_FRAME_MAX_STREAM_ID:
print_indent();
fprintf(outfile, "max_stream_id=%08x\n", fr->max_stream_id.max_stream_id);
break;
case NGTCP2_FRAME_PING:
break;
case NGTCP2_FRAME_BLOCKED:
break;
case NGTCP2_FRAME_STREAM_BLOCKED:
print_indent();
fprintf(outfile, "stream_id=%08x\n", fr->stream_blocked.stream_id);
break;
case NGTCP2_FRAME_STREAM_ID_NEEDED:
break;
case NGTCP2_FRAME_NEW_CONNECTION_ID:
print_indent();
fprintf(outfile, "seq=%u conn_id=%016lx\n", fr->new_connection_id.seq,
fr->new_connection_id.conn_id);
break;
}
}
} // namespace
int send_pkt(ngtcp2_conn *conn, const ngtcp2_pkt_hd *hd, void *user_data) {
print_timestamp();
fprintf(outfile, "TX ");
print_pkt(NGTCP2_DIR_SEND, hd);
return 0;
}
int send_frame(ngtcp2_conn *conn, const ngtcp2_pkt_hd *hd,
const ngtcp2_frame *fr, void *user_data) {
print_indent();
print_frame(NGTCP2_DIR_SEND, fr);
return 0;
}
int recv_pkt(ngtcp2_conn *conn, const ngtcp2_pkt_hd *hd, void *user_data) {
print_timestamp();
fprintf(outfile, "RX ");
print_pkt(NGTCP2_DIR_RECV, hd);
return 0;
}
int recv_frame(ngtcp2_conn *conn, const ngtcp2_pkt_hd *hd,
const ngtcp2_frame *fr, void *user_data) {
print_indent();
print_frame(NGTCP2_DIR_RECV, fr);
return 0;
}
int handshake_completed(ngtcp2_conn *conn, void *user_data) {
print_timestamp();
fprintf(outfile, "QUIC handshake has completed\n");
return 0;
}
int recv_version_negotiation(ngtcp2_conn *conn, const ngtcp2_pkt_hd *hd,
const uint32_t *sv, size_t nsv, void *user_data) {
for (size_t i = 0; i < nsv; ++i) {
print_indent();
fprintf(outfile, "version=%08x\n", sv[i]);
}
return 0;
}
bool packet_lost(double prob) {
auto p = std::uniform_real_distribution<>(0, 1)(randgen);
return p < prob;
}
void print_transport_params(const ngtcp2_transport_params *params, int type) {
switch (type) {
case NGTCP2_TRANSPORT_PARAMS_TYPE_CLIENT_HELLO:
print_indent();
fprintf(outfile, "negotiated_version=%08x\n",
params->v.ch.negotiated_version);
print_indent();
fprintf(outfile, "initial_version=%08x\n", params->v.ch.initial_version);
break;
case NGTCP2_TRANSPORT_PARAMS_TYPE_ENCRYPTED_EXTENSIONS:
for (size_t i = 0; i < params->v.ee.len; ++i) {
print_indent();
fprintf(outfile, "supported_version[%zu]=%08x\n", i,
params->v.ee.supported_versions[i]);
}
break;
}
print_indent();
fprintf(outfile, "initial_max_stream_data=%u\n",
params->initial_max_stream_data);
print_indent();
fprintf(outfile, "initial_max_data=%u\n", params->initial_max_data);
print_indent();
fprintf(outfile, "initial_max_stream_id=%u\n", params->initial_max_stream_id);
print_indent();
fprintf(outfile, "idle_timeout=%u\n", params->idle_timeout);
print_indent();
fprintf(outfile, "omit_connection_id=%u\n", params->omit_connection_id);
print_indent();
fprintf(outfile, "max_packet_size=%u\n", params->max_packet_size);
}
void print_stream_data(uint32_t stream_id, const uint8_t *data,
size_t datalen) {
print_timestamp();
fprintf(outfile, "%sSTREAM%s data stream_id=%08x\n",
frame_ansi_esc(NGTCP2_DIR_RECV), ansi_escend(), stream_id);
util::hexdump(outfile, data, datalen);
}
} // namespace debug
} // namespace ngtcp2
<commit_msg>Use PRIu64 instead of lu for uint64_t<commit_after>/*
* ngtcp2
*
* Copyright (c) 2017 ngtcp2 contributors
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "debug.h"
#include <cinttypes>
#include <random>
#include "util.h"
namespace ngtcp2 {
namespace debug {
namespace {
auto randgen = util::make_mt19937();
} // namespace
namespace {
std::chrono::steady_clock::time_point ts_base;
} // namespace
void reset_timestamp() { ts_base = std::chrono::steady_clock::now(); }
std::chrono::microseconds timestamp() {
return std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::steady_clock::now() - ts_base);
}
namespace {
auto color_output = false;
} // namespace
void set_color_output(bool f) { color_output = f; }
namespace {
auto *outfile = stderr;
} // namespace
namespace {
const char *ansi_esc(const char *code) { return color_output ? code : ""; }
} // namespace
namespace {
const char *ansi_escend() { return color_output ? "\033[0m" : ""; }
} // namespace
enum ngtcp2_dir {
NGTCP2_DIR_SEND,
NGTCP2_DIR_RECV,
};
namespace {
std::string strpkttype_long(uint8_t type) {
switch (type) {
case NGTCP2_PKT_VERSION_NEGOTIATION:
return "Version Negotiation";
case NGTCP2_PKT_CLIENT_INITIAL:
return "Client Initial";
case NGTCP2_PKT_SERVER_STATELESS_RETRY:
return "Server Stateless Retry";
case NGTCP2_PKT_SERVER_CLEARTEXT:
return "Server Cleartext";
case NGTCP2_PKT_CLIENT_CLEARTEXT:
return "Client Cleartext";
case NGTCP2_PKT_0RTT_PROTECTED:
return "0-RTT Protected";
case NGTCP2_PKT_1RTT_PROTECTED_K0:
return "1-RTT Protected (key phase 0)";
case NGTCP2_PKT_1RTT_PROTECTED_K1:
return "1-RTT Protected (key phase 1)";
case NGTCP2_PKT_PUBLIC_RESET:
return "Public Reset";
default:
return "UNKNOWN (0x" + util::format_hex(type) + ")";
}
}
} // namespace
namespace {
std::string strpkttype_short(uint8_t type) {
switch (type) {
case NGTCP2_PKT_01:
return "Short 01";
case NGTCP2_PKT_02:
return "Short 02";
case NGTCP2_PKT_03:
return "Short 03";
default:
return "UNKNOWN (0x" + util::format_hex(type) + ")";
}
}
} // namespace
namespace {
std::string strframetype(uint8_t type) {
switch (type) {
case NGTCP2_FRAME_PADDING:
return "PADDING";
case NGTCP2_FRAME_RST_STREAM:
return "RST_STREAM";
case NGTCP2_FRAME_CONNECTION_CLOSE:
return "CONNECTION_CLOSE";
case NGTCP2_FRAME_GOAWAY:
return "GOAWAY";
case NGTCP2_FRAME_MAX_DATA:
return "MAX_DATA";
case NGTCP2_FRAME_MAX_STREAM_DATA:
return "MAX_STREAM_DATA";
case NGTCP2_FRAME_MAX_STREAM_ID:
return "MAX_STREAM_ID";
case NGTCP2_FRAME_PING:
return "PING";
case NGTCP2_FRAME_BLOCKED:
return "BLOCKED";
case NGTCP2_FRAME_STREAM_BLOCKED:
return "STREAM_BLOCKED";
case NGTCP2_FRAME_STREAM_ID_NEEDED:
return "STREAM_ID_NEEDED";
case NGTCP2_FRAME_NEW_CONNECTION_ID:
return "NEW_CONNECTION_ID";
case NGTCP2_FRAME_ACK:
return "ACK";
case NGTCP2_FRAME_STREAM:
return "STREAM";
default:
return "UNKNOWN (0x" + util::format_hex(type) + ")";
}
}
} // namespace
void print_timestamp() {
auto t = timestamp().count();
fprintf(outfile, "%st=%d.%06d%s ", ansi_esc("\033[33m"),
static_cast<int32_t>(t / 1000000), static_cast<int32_t>(t % 1000000),
ansi_escend());
}
namespace {
const char *pkt_ansi_esc(ngtcp2_dir dir) {
return ansi_esc(dir == NGTCP2_DIR_SEND ? "\033[1;35m" : "\033[1;36m");
}
} // namespace
namespace {
const char *frame_ansi_esc(ngtcp2_dir dir) {
return ansi_esc(dir == NGTCP2_DIR_SEND ? "\033[1;35m" : "\033[1;36m");
}
} // namespace
namespace {
void print_indent() { fprintf(outfile, " "); }
} // namespace
namespace {
void print_pkt_long(ngtcp2_dir dir, const ngtcp2_pkt_hd *hd) {
fprintf(outfile, "%s%s%s CID=%016lx PKN=%" PRIu64 " V=%08x\n",
pkt_ansi_esc(dir), strpkttype_long(hd->type).c_str(), ansi_escend(),
hd->conn_id, hd->pkt_num, hd->version);
}
} // namespace
namespace {
void print_pkt_short(ngtcp2_dir dir, const ngtcp2_pkt_hd *hd) {
fprintf(outfile, "%s%s%s CID=%016lx PKN=%" PRIu64 "\n", pkt_ansi_esc(dir),
strpkttype_short(hd->type).c_str(), ansi_escend(), hd->conn_id,
hd->pkt_num);
}
} // namespace
namespace {
void print_pkt(ngtcp2_dir dir, const ngtcp2_pkt_hd *hd) {
if (hd->flags & NGTCP2_PKT_FLAG_LONG_FORM) {
print_pkt_long(dir, hd);
} else {
print_pkt_short(dir, hd);
}
}
} // namespace
namespace {
void print_frame(ngtcp2_dir dir, const ngtcp2_frame *fr) {
fprintf(outfile, "%s%s%s\n", frame_ansi_esc(dir),
strframetype(fr->type).c_str(), ansi_escend());
switch (fr->type) {
case NGTCP2_FRAME_STREAM:
print_indent();
fprintf(outfile,
"stream_id=%08x fin=%u offset=%" PRIu64 " data_length=%zu\n",
fr->stream.stream_id, fr->stream.fin, fr->stream.offset,
fr->stream.datalen);
break;
case NGTCP2_FRAME_PADDING:
print_indent();
fprintf(outfile, "length=%zu\n", fr->padding.len);
break;
case NGTCP2_FRAME_ACK:
print_indent();
fprintf(outfile,
"num_blks=%zu num_ts=%zu largest_ack=%" PRIu64 " ack_delay=%u\n",
fr->ack.num_blks, fr->ack.num_ts, fr->ack.largest_ack,
fr->ack.ack_delay);
print_indent();
fprintf(outfile, "first_ack_block_length=%" PRIu64 "\n",
fr->ack.first_ack_blklen);
for (size_t i = 0; i < fr->ack.num_blks; ++i) {
auto blk = &fr->ack.blks[i];
print_indent();
fprintf(outfile, "gap=%u ack_block_length=%" PRIu64 "\n", blk->gap,
blk->blklen);
}
break;
case NGTCP2_FRAME_RST_STREAM:
print_indent();
fprintf(outfile,
"stream_id=%08x error_code=%08x final_offset=%" PRIu64 "\n",
fr->rst_stream.stream_id, fr->rst_stream.error_code,
fr->rst_stream.final_offset);
break;
case NGTCP2_FRAME_CONNECTION_CLOSE:
print_indent();
fprintf(outfile, "error_code=%08x reason_length=%zu\n",
fr->connection_close.error_code, fr->connection_close.reasonlen);
break;
case NGTCP2_FRAME_GOAWAY:
print_indent();
fprintf(outfile,
"largest_client_stream_id=%08x largest_server_stream_id=%08x\n",
fr->goaway.largest_client_stream_id,
fr->goaway.largest_server_stream_id);
break;
case NGTCP2_FRAME_MAX_DATA:
print_indent();
fprintf(outfile, "max_data=%" PRIu64 "\n", fr->max_data.max_data);
break;
case NGTCP2_FRAME_MAX_STREAM_DATA:
print_indent();
fprintf(outfile, "stream_id=%08x max_stream_data=%" PRIu64 "\n",
fr->max_stream_data.stream_id, fr->max_stream_data.max_stream_data);
break;
case NGTCP2_FRAME_MAX_STREAM_ID:
print_indent();
fprintf(outfile, "max_stream_id=%08x\n", fr->max_stream_id.max_stream_id);
break;
case NGTCP2_FRAME_PING:
break;
case NGTCP2_FRAME_BLOCKED:
break;
case NGTCP2_FRAME_STREAM_BLOCKED:
print_indent();
fprintf(outfile, "stream_id=%08x\n", fr->stream_blocked.stream_id);
break;
case NGTCP2_FRAME_STREAM_ID_NEEDED:
break;
case NGTCP2_FRAME_NEW_CONNECTION_ID:
print_indent();
fprintf(outfile, "seq=%u conn_id=%016lx\n", fr->new_connection_id.seq,
fr->new_connection_id.conn_id);
break;
}
}
} // namespace
int send_pkt(ngtcp2_conn *conn, const ngtcp2_pkt_hd *hd, void *user_data) {
print_timestamp();
fprintf(outfile, "TX ");
print_pkt(NGTCP2_DIR_SEND, hd);
return 0;
}
int send_frame(ngtcp2_conn *conn, const ngtcp2_pkt_hd *hd,
const ngtcp2_frame *fr, void *user_data) {
print_indent();
print_frame(NGTCP2_DIR_SEND, fr);
return 0;
}
int recv_pkt(ngtcp2_conn *conn, const ngtcp2_pkt_hd *hd, void *user_data) {
print_timestamp();
fprintf(outfile, "RX ");
print_pkt(NGTCP2_DIR_RECV, hd);
return 0;
}
int recv_frame(ngtcp2_conn *conn, const ngtcp2_pkt_hd *hd,
const ngtcp2_frame *fr, void *user_data) {
print_indent();
print_frame(NGTCP2_DIR_RECV, fr);
return 0;
}
int handshake_completed(ngtcp2_conn *conn, void *user_data) {
print_timestamp();
fprintf(outfile, "QUIC handshake has completed\n");
return 0;
}
int recv_version_negotiation(ngtcp2_conn *conn, const ngtcp2_pkt_hd *hd,
const uint32_t *sv, size_t nsv, void *user_data) {
for (size_t i = 0; i < nsv; ++i) {
print_indent();
fprintf(outfile, "version=%08x\n", sv[i]);
}
return 0;
}
bool packet_lost(double prob) {
auto p = std::uniform_real_distribution<>(0, 1)(randgen);
return p < prob;
}
void print_transport_params(const ngtcp2_transport_params *params, int type) {
switch (type) {
case NGTCP2_TRANSPORT_PARAMS_TYPE_CLIENT_HELLO:
print_indent();
fprintf(outfile, "negotiated_version=%08x\n",
params->v.ch.negotiated_version);
print_indent();
fprintf(outfile, "initial_version=%08x\n", params->v.ch.initial_version);
break;
case NGTCP2_TRANSPORT_PARAMS_TYPE_ENCRYPTED_EXTENSIONS:
for (size_t i = 0; i < params->v.ee.len; ++i) {
print_indent();
fprintf(outfile, "supported_version[%zu]=%08x\n", i,
params->v.ee.supported_versions[i]);
}
break;
}
print_indent();
fprintf(outfile, "initial_max_stream_data=%u\n",
params->initial_max_stream_data);
print_indent();
fprintf(outfile, "initial_max_data=%u\n", params->initial_max_data);
print_indent();
fprintf(outfile, "initial_max_stream_id=%u\n", params->initial_max_stream_id);
print_indent();
fprintf(outfile, "idle_timeout=%u\n", params->idle_timeout);
print_indent();
fprintf(outfile, "omit_connection_id=%u\n", params->omit_connection_id);
print_indent();
fprintf(outfile, "max_packet_size=%u\n", params->max_packet_size);
}
void print_stream_data(uint32_t stream_id, const uint8_t *data,
size_t datalen) {
print_timestamp();
fprintf(outfile, "%sSTREAM%s data stream_id=%08x\n",
frame_ansi_esc(NGTCP2_DIR_RECV), ansi_escend(), stream_id);
util::hexdump(outfile, data, datalen);
}
} // namespace debug
} // namespace ngtcp2
<|endoftext|>
|
<commit_before>#include <cstdlib>
#include <cmath>
#include <fstream>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <algorithm>
#include <exception>
#include <sys/time.h>
#include "modules/htmTree.h"
#include "modules/kdTree.h"
#include "misc.h"
#include "feat.h"
#include "structs.h"
#include "collision.h"
#include "global.h"
//reduce redistributes, updates 07/02/15 rnc
int main(int argc, char **argv) {
//// Initializations ---------------------------------------------
srand48(1234); // Make sure we have reproducability
check_args(argc);
Time t, time; // t for global, time for local
init_time(t);
Feat F;
// Read parameters file //
F.readInputFile(argv[1]);
printFile(argv[1]);
std::cout/flush();
// Read galaxies
Gals G, Secret;
MTL Targ, SStars, SkyF;
if(F.Ascii){
G=read_galaxies_ascii(F);}
else{
G = read_galaxies(F);
}
F.Ngal = G.size();
printf("# Read %s galaxies from %s \n",f(F.Ngal).c_str(),F.galFile.c_str());
std::vector<int> count;
count=count_galaxies(G);
printf(" Number of galaxies by type, QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF\n");
for(int i=0;i<8;i++){printf (" type %d number %d \n",i, count[i]);}
// make MTL
//make_MTL(G,F,Secret,Targ);
//write_MTLfile(Secret,Targ,F);
make_MTL_SS_SF(G,Targ,SStars,SkyF,Secret,F);
write_MTL_SS_SFfile(Targ,SStars,SkyF,Secret,F);
return(0);
}
<commit_msg>add print statement<commit_after>#include <cstdlib>
#include <cmath>
#include <fstream>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <algorithm>
#include <exception>
#include <sys/time.h>
#include "modules/htmTree.h"
#include "modules/kdTree.h"
#include "misc.h"
#include "feat.h"
#include "structs.h"
#include "collision.h"
#include "global.h"
//reduce redistributes, updates 07/02/15 rnc
int main(int argc, char **argv) {
//// Initializations ---------------------------------------------
srand48(1234); // Make sure we have reproducability
check_args(argc);
Time t, time; // t for global, time for local
init_time(t);
Feat F;
// Read parameters file //
F.readInputFile(argv[1]);
printFile(argv[1]);
std::cout.flush();
// Read galaxies
Gals G, Secret;
MTL Targ, SStars, SkyF;
if(F.Ascii){
G=read_galaxies_ascii(F);}
else{
G = read_galaxies(F);
}
F.Ngal = G.size();
printf("# Read %s galaxies from %s \n",f(F.Ngal).c_str(),F.galFile.c_str());
std::vector<int> count;
count=count_galaxies(G);
printf(" Number of galaxies by type, QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF\n");
for(int i=0;i<8;i++){printf (" type %d number %d \n",i, count[i]);}
// make MTL
//make_MTL(G,F,Secret,Targ);
//write_MTLfile(Secret,Targ,F);
make_MTL_SS_SF(G,Targ,SStars,SkyF,Secret,F);
write_MTL_SS_SFfile(Targ,SStars,SkyF,Secret,F);
return(0);
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2015-2017 Advanced Micro Devices, Inc. All rights reserved.
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.
*/
// Simple test for memset.
// Also serves as a template for other tests.
/* HIT_START
* BUILD: %t %s ../../test_common.cpp NVCC_OPTIONS --std=c++11
* RUN: %t EXCLUDE_HIP_PLATFORM all
* HIT_END
*/
#include "hip/hip_runtime.h"
#include "test_common.h"
#ifdef __HIP_PLATFORM_HCC__
#include <hc_am.hpp>
#endif
#define USE_HCC_MEMTRACKER 0 /* Debug flag to show the memtracker periodically */
int elementSizes[] = {1, 16, 1024, 524288, 16*1000*1000};
int nSizes = sizeof(elementSizes) / sizeof(int);
int enablePeers(int dev0, int dev1)
{
int canAccessPeer01, canAccessPeer10;
HIPCHECK(hipDeviceCanAccessPeer(&canAccessPeer01, dev0, dev1));
HIPCHECK(hipDeviceCanAccessPeer(&canAccessPeer10, dev1, dev0));
if (!canAccessPeer01 || !canAccessPeer10) {
return -1;
}
HIPCHECK(hipSetDevice(dev0));
HIPCHECK(hipDeviceEnablePeerAccess(dev1, 0/*flags*/));
HIPCHECK(hipSetDevice(dev1));
HIPCHECK(hipDeviceEnablePeerAccess(dev0, 0/*flags*/));
return 0;
};
// Set value of array to specified 32-bit integer:
__global__ void
memsetIntKernel(int * ptr, const int val, size_t numElements)
{
int gid = (hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x);
int stride = hipBlockDim_x * hipGridDim_x ;
for (size_t i= gid; i< numElements; i+=stride){
ptr[i] = val;
}
};
__global__ void
memcpyIntKernel(const int * src, int* dst, size_t numElements)
{
int gid = (hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x);
int stride = hipBlockDim_x * hipGridDim_x ;
for (size_t i= gid; i< numElements; i+=stride){
dst[i] = src[i];
}
};
// CHeck arrays in reverse order, to more easily detect cases where
// the copy is "partially" done.
void checkReverse(const int *ptr, int numElements, int expected) {
for (int i=numElements-1; i>=0; i--) {
if (ptr[i] != expected) {
printf ("i=%d, ptr[](%d) != expected (%d)\n", i, ptr[i], expected);
assert (ptr[i] == expected);
}
}
printf ("test: OK\n");
}
void runTestImpl(bool stepAIsCopy, bool hostSync, hipStream_t gpu0Stream, hipStream_t gpu1Stream, int numElements,
int * dataGpu0_0, int * dataGpu0_1, int *dataGpu1, int *dataHost, int expected)
{
hipEvent_t e;
if(!hostSync) {
HIPCHECK(hipEventCreateWithFlags(&e,0));
}
const size_t sizeElements = numElements * sizeof(int);
printf ("test: runTestImpl with %zu bytes %s with hostSync %s\n", sizeElements, stepAIsCopy ? "copy" : "kernel", hostSync ? "enabled" : "disabled");
hipStream_t stepAStream = gpu0Stream;
if (stepAIsCopy) {
HIPCHECK(hipMemcpyAsync(dataGpu1, dataGpu0_0, sizeElements, hipMemcpyDeviceToDevice, stepAStream));
} else {
unsigned blocks = HipTest::setNumBlocks(blocksPerCU, threadsPerBlock, numElements);
hipLaunchKernelGGL(memcpyIntKernel, dim3(blocks), dim3(threadsPerBlock), 0, gpu0Stream,
dataGpu0_0, dataGpu1, numElements);
}
if(!hostSync) {
HIPCHECK(hipEventRecord(e, stepAStream));
HIPCHECK(hipStreamWaitEvent(gpu1Stream, e, 0));
} else {
HIPCHECK(hipStreamSynchronize(stepAStream));
}
HIPCHECK(hipMemcpyAsync(dataGpu0_1, dataGpu1, sizeElements, hipMemcpyDeviceToDevice, gpu1Stream));
if(!hostSync) {
HIPCHECK(hipEventRecord(e, gpu1Stream));
} else {
HIPCHECK(hipStreamSynchronize(gpu1Stream));
}
HIPCHECK(hipMemcpyAsync(dataHost, dataGpu0_1, sizeElements, hipMemcpyDeviceToHost, gpu0Stream));
HIPCHECK(hipStreamSynchronize(gpu0Stream));
checkReverse(dataHost, numElements, expected);
if(!hostSync) {
HIPCHECK(hipEventDestroy(e));
}
}
void testMultiGpu(int dev0, int dev1, int numElements, bool hostSync, bool useMemcpy)
{
const size_t sizeElements = numElements * sizeof(int);
int * dataGpu0_0, * dataGpu0_1, *dataGpu1, *dataHost;
hipStream_t gpu0Stream, gpu1Stream;
const int expected = 42;
unsigned blocks = HipTest::setNumBlocks(blocksPerCU, threadsPerBlock, numElements);
HIPCHECK(hipSetDevice(dev0));
HIPCHECK(hipMalloc(&dataGpu0_0, sizeElements));
HIPCHECK(hipMalloc(&dataGpu0_1, sizeElements));
HIPCHECK(hipStreamCreate(&gpu0Stream));
hipLaunchKernelGGL(memsetIntKernel, dim3(blocks), dim3(threadsPerBlock), 0, gpu0Stream,
dataGpu0_0, expected, numElements);
HIPCHECK(hipDeviceSynchronize());
HIPCHECK(hipSetDevice(dev1));
HIPCHECK(hipMalloc(&dataGpu1, sizeElements));
HIPCHECK(hipStreamCreate(&gpu1Stream));
hipLaunchKernelGGL(memsetIntKernel, dim3(blocks), dim3(threadsPerBlock), 0, gpu0Stream,
dataGpu1, 0x34, numElements);
HIPCHECK(hipDeviceSynchronize());
HIPCHECK(hipHostMalloc(&dataHost, sizeElements));
memset(dataHost, 13, sizeElements);
#if USE_HCC_MEMTRACKER
hc::am_memtracker_print(0x0);
#endif
printf (" test: init complete\n");
int stepAIsCopy = 0;
int stepBIsCopy = 1;
runTestImpl(true, hostSync, gpu0Stream, gpu1Stream, numElements, dataGpu0_0,dataGpu0_1, dataGpu1, dataHost, expected);
HIPCHECK(hipFree(dataGpu0_0));
HIPCHECK(hipFree(dataGpu0_1));
HIPCHECK(hipFree(dataGpu1));
HIPCHECK(hipHostFree(dataHost));
HIPCHECK(hipStreamDestroy(gpu0Stream));
HIPCHECK(hipStreamDestroy(gpu1Stream));
};
int main(int argc, char *argv[])
{
HipTest::parseStandardArguments(argc, argv, true);
int numElements = N;
int dev0 = 0;
int dev1 = 1;
int numDevices;
HIPCHECK(hipGetDeviceCount(&numDevices));
if (numDevices == 1) {
printf("warning : test requires atleast two gpus\n");
passed();
}
if (enablePeers(dev0,dev1) == -1) {
printf ("warning : could not find peer gpus\n");
return -1;
};
for(int index = 0;index < nSizes;index++) {
testMultiGpu(dev0, dev1, elementSizes[index] , false /* GPU Synchronization*/, true);
testMultiGpu(dev0, dev1, elementSizes[index] , true /*Host Synchronization*/, true);
testMultiGpu(dev0, dev1, elementSizes[index] , true /*Host Synchronization*/, false);
testMultiGpu(dev0, dev1, elementSizes[index] , false /*Host Synchronization*/, false);
}
passed();
};
<commit_msg>Clean up test to address review feedback.<commit_after>/*
Copyright (c) 2015-2017 Advanced Micro Devices, Inc. All rights reserved.
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.
*/
// Simple test for memset.
// Also serves as a template for other tests.
/* HIT_START
* BUILD: %t %s ../../test_common.cpp NVCC_OPTIONS --std=c++11
* RUN: %t EXCLUDE_HIP_PLATFORM all
* HIT_END
*/
#include "hip/hip_runtime.h"
#include "test_common.h"
#ifdef __HIP_PLATFORM_HCC__
#include <hc_am.hpp>
#endif
#define USE_HCC_MEMTRACKER 0 /* Debug flag to show the memtracker periodically */
int elementSizes[] = {1, 16, 1024, 524288, 16*1000*1000};
int nSizes = sizeof(elementSizes) / sizeof(int);
int enablePeers(int dev0, int dev1)
{
int canAccessPeer01, canAccessPeer10;
HIPCHECK(hipDeviceCanAccessPeer(&canAccessPeer01, dev0, dev1));
HIPCHECK(hipDeviceCanAccessPeer(&canAccessPeer10, dev1, dev0));
if (!canAccessPeer01 || !canAccessPeer10) {
return -1;
}
HIPCHECK(hipSetDevice(dev0));
HIPCHECK(hipDeviceEnablePeerAccess(dev1, 0/*flags*/));
HIPCHECK(hipSetDevice(dev1));
HIPCHECK(hipDeviceEnablePeerAccess(dev0, 0/*flags*/));
return 0;
};
// Set value of array to specified 32-bit integer:
__global__ void
memsetIntKernel(int * ptr, const int val, size_t numElements)
{
int gid = (hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x);
int stride = hipBlockDim_x * hipGridDim_x ;
for (size_t i= gid; i< numElements; i+=stride){
ptr[i] = val;
}
};
__global__ void
memcpyIntKernel(const int * src, int* dst, size_t numElements)
{
int gid = (hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x);
int stride = hipBlockDim_x * hipGridDim_x ;
for (size_t i= gid; i< numElements; i+=stride){
dst[i] = src[i];
}
};
// CHeck arrays in reverse order, to more easily detect cases where
// the copy is "partially" done.
void checkReverse(const int *ptr, int numElements, int expected) {
for (int i=numElements-1; i>=0; i--) {
if (ptr[i] != expected) {
printf ("i=%d, ptr[](%d) != expected (%d)\n", i, ptr[i], expected);
assert (ptr[i] == expected);
}
}
printf ("test: OK\n");
}
void runTestImpl(bool stepAIsCopy, bool hostSync, hipStream_t gpu0Stream, hipStream_t gpu1Stream, int numElements,
int * dataGpu0_0, int * dataGpu0_1, int *dataGpu1, int *dataHost, int expected)
{
hipEvent_t e;
if(!hostSync) {
HIPCHECK(hipEventCreateWithFlags(&e,0));
}
const size_t sizeElements = numElements * sizeof(int);
printf ("test: runTestImpl with %zu bytes %s with hostSync %s\n", sizeElements, stepAIsCopy ? "copy" : "kernel", hostSync ? "enabled" : "disabled");
hipStream_t stepAStream = gpu0Stream;
if (stepAIsCopy) {
HIPCHECK(hipMemcpyAsync(dataGpu1, dataGpu0_0, sizeElements, hipMemcpyDeviceToDevice, stepAStream));
} else {
unsigned blocks = HipTest::setNumBlocks(blocksPerCU, threadsPerBlock, numElements);
hipLaunchKernelGGL(memcpyIntKernel, dim3(blocks), dim3(threadsPerBlock), 0, gpu0Stream,
dataGpu0_0, dataGpu1, numElements);
}
if(!hostSync) {
HIPCHECK(hipEventRecord(e, stepAStream));
HIPCHECK(hipStreamWaitEvent(gpu1Stream, e, 0));
} else {
HIPCHECK(hipStreamSynchronize(stepAStream));
}
HIPCHECK(hipMemcpyAsync(dataGpu0_1, dataGpu1, sizeElements, hipMemcpyDeviceToDevice, gpu1Stream));
if(!hostSync) {
HIPCHECK(hipEventRecord(e, gpu1Stream));
} else {
HIPCHECK(hipStreamSynchronize(gpu1Stream));
}
HIPCHECK(hipMemcpyAsync(dataHost, dataGpu0_1, sizeElements, hipMemcpyDeviceToHost, gpu0Stream));
HIPCHECK(hipStreamSynchronize(gpu0Stream));
checkReverse(dataHost, numElements, expected);
if(!hostSync) {
HIPCHECK(hipEventDestroy(e));
}
}
void testMultiGpu(int dev0, int dev1, int numElements, bool hostSync)
{
const size_t sizeElements = numElements * sizeof(int);
int * dataGpu0_0, * dataGpu0_1, *dataGpu1, *dataHost;
hipStream_t gpu0Stream, gpu1Stream;
const int expected = 42;
unsigned blocks = HipTest::setNumBlocks(blocksPerCU, threadsPerBlock, numElements);
HIPCHECK(hipSetDevice(dev0));
HIPCHECK(hipMalloc(&dataGpu0_0, sizeElements));
HIPCHECK(hipMalloc(&dataGpu0_1, sizeElements));
HIPCHECK(hipStreamCreate(&gpu0Stream));
hipLaunchKernelGGL(memsetIntKernel, dim3(blocks), dim3(threadsPerBlock), 0, gpu0Stream,
dataGpu0_0, expected, numElements);
HIPCHECK(hipDeviceSynchronize());
HIPCHECK(hipSetDevice(dev1));
HIPCHECK(hipMalloc(&dataGpu1, sizeElements));
HIPCHECK(hipStreamCreate(&gpu1Stream));
hipLaunchKernelGGL(memsetIntKernel, dim3(blocks), dim3(threadsPerBlock), 0, gpu0Stream,
dataGpu1, 0x34, numElements);
HIPCHECK(hipDeviceSynchronize());
HIPCHECK(hipHostMalloc(&dataHost, sizeElements));
memset(dataHost, 13, sizeElements);
#if USE_HCC_MEMTRACKER
hc::am_memtracker_print(0x0);
#endif
printf (" test: init complete\n");
runTestImpl(true, hostSync, gpu0Stream, gpu1Stream, numElements, dataGpu0_0,dataGpu0_1, dataGpu1, dataHost, expected);
HIPCHECK(hipFree(dataGpu0_0));
HIPCHECK(hipFree(dataGpu0_1));
HIPCHECK(hipFree(dataGpu1));
HIPCHECK(hipHostFree(dataHost));
HIPCHECK(hipStreamDestroy(gpu0Stream));
HIPCHECK(hipStreamDestroy(gpu1Stream));
};
int main(int argc, char *argv[])
{
HipTest::parseStandardArguments(argc, argv, true);
int numElements = N;
int dev0 = 0;
int dev1 = 1;
int numDevices;
HIPCHECK(hipGetDeviceCount(&numDevices));
if (numDevices == 1) {
printf("warning : test requires atleast two gpus\n");
passed();
}
if (enablePeers(dev0,dev1) == -1) {
printf ("warning : could not find peer gpus\n");
return -1;
};
for(int index = 0;index < nSizes;index++) {
testMultiGpu(dev0, dev1, elementSizes[index] , false /*GPU Synchronization*/);
testMultiGpu(dev0, dev1, elementSizes[index] , true /*Host Synchronization*/);
}
passed();
};
<|endoftext|>
|
<commit_before>/**********************************************************************
* $Id$
*
* GEOS - Geometry Engine Open Source
* http://geos.refractions.net
*
* Copyright (C) 2009 Sandro Santilli <strk@keybit.net>
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
*
* Last port: original work
*
**********************************************************************/
#include "SingleSidedBufferResultMatcher.h"
#include <geos/geom/Geometry.h>
#include <geos/geom/BinaryOp.h>
#include <geos/operation/overlay/OverlayOp.h>
#include <geos/algorithm/distance/DiscreteHausdorffDistance.h>
#include <cmath>
namespace geos {
namespace xmltester {
double SingleSidedBufferResultMatcher::MIN_DISTANCE_TOLERANCE = 1.0e-8;
double SingleSidedBufferResultMatcher::MAX_HAUSDORFF_DISTANCE_FACTOR = 100;
bool
SingleSidedBufferResultMatcher::isBufferResultMatch(const geom::Geometry& actualBuffer,
const geom::Geometry& expectedBuffer,
double distance)
{
bool aEmpty = actualBuffer.isEmpty();
bool eEmpty = expectedBuffer.isEmpty();
// Both empty succeeds
if (aEmpty && eEmpty) return true;
// One empty and not the other is a failure
if (aEmpty || eEmpty)
{
std::cerr << "isBufferResultMatch failed (one empty and one not)" << std::endl;
return false;
}
if (! isBoundaryHausdorffDistanceInTolerance(actualBuffer,
expectedBuffer, distance))
{
std::cerr << "isBoundaryHasudorffDistanceInTolerance failed" << std::endl;
return false;
}
return true;
}
bool
SingleSidedBufferResultMatcher::isBoundaryHausdorffDistanceInTolerance(
const geom::Geometry& actualBuffer,
const geom::Geometry& expectedBuffer, double distance)
{
typedef std::auto_ptr<geom::Geometry> GeomPtr;
using geos::algorithm::distance::DiscreteHausdorffDistance;
GeomPtr actualBdy ( actualBuffer.clone() );
GeomPtr expectedBdy ( expectedBuffer.clone() );
DiscreteHausdorffDistance haus(*actualBdy, *expectedBdy);
haus.setDensifyFraction(0.25);
double maxDistanceFound = haus.orientedDistance();
double expectedDistanceTol = fabs(distance) / MAX_HAUSDORFF_DISTANCE_FACTOR;
if (expectedDistanceTol < MIN_DISTANCE_TOLERANCE)
{
expectedDistanceTol = MIN_DISTANCE_TOLERANCE;
}
if (maxDistanceFound > expectedDistanceTol)
{
std::cerr << "maxDistanceFound: " << maxDistanceFound << " tolerated " << expectedDistanceTol << std::endl;
return false;
}
return true;
}
} // namespace geos::xmltester
} // namespace geos
<commit_msg>Check hausdorff distance in both directions, or an expected output line longer than the obtained one would be found as correct<commit_after>/**********************************************************************
* $Id$
*
* GEOS - Geometry Engine Open Source
* http://geos.refractions.net
*
* Copyright (C) 2009 Sandro Santilli <strk@keybit.net>
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
*
* Last port: original work
*
**********************************************************************/
#include "SingleSidedBufferResultMatcher.h"
#include <geos/geom/Geometry.h>
#include <geos/geom/BinaryOp.h>
#include <geos/operation/overlay/OverlayOp.h>
#include <geos/algorithm/distance/DiscreteHausdorffDistance.h>
#include <cmath>
namespace geos {
namespace xmltester {
double SingleSidedBufferResultMatcher::MIN_DISTANCE_TOLERANCE = 1.0e-8;
double SingleSidedBufferResultMatcher::MAX_HAUSDORFF_DISTANCE_FACTOR = 100;
bool
SingleSidedBufferResultMatcher::isBufferResultMatch(const geom::Geometry& actualBuffer,
const geom::Geometry& expectedBuffer,
double distance)
{
bool aEmpty = actualBuffer.isEmpty();
bool eEmpty = expectedBuffer.isEmpty();
// Both empty succeeds
if (aEmpty && eEmpty) return true;
// One empty and not the other is a failure
if (aEmpty || eEmpty)
{
std::cerr << "isBufferResultMatch failed (one empty and one not)" << std::endl;
return false;
}
// NOTE: we need to test hausdorff distance in both directions
if (! isBoundaryHausdorffDistanceInTolerance(actualBuffer,
expectedBuffer, distance))
{
std::cerr << "isBoundaryHasudorffDistanceInTolerance failed (actual,expected)" << std::endl;
return false;
}
if (! isBoundaryHausdorffDistanceInTolerance(expectedBuffer,
actualBuffer, distance))
{
std::cerr << "isBoundaryHasudorffDistanceInTolerance failed (expected,actual)" << std::endl;
return false;
}
return true;
}
bool
SingleSidedBufferResultMatcher::isBoundaryHausdorffDistanceInTolerance(
const geom::Geometry& actualBuffer,
const geom::Geometry& expectedBuffer, double distance)
{
typedef std::auto_ptr<geom::Geometry> GeomPtr;
using geos::algorithm::distance::DiscreteHausdorffDistance;
GeomPtr actualBdy ( actualBuffer.clone() );
GeomPtr expectedBdy ( expectedBuffer.clone() );
DiscreteHausdorffDistance haus(*actualBdy, *expectedBdy);
haus.setDensifyFraction(0.25);
double maxDistanceFound = haus.orientedDistance();
double expectedDistanceTol = fabs(distance) / MAX_HAUSDORFF_DISTANCE_FACTOR;
if (expectedDistanceTol < MIN_DISTANCE_TOLERANCE)
{
expectedDistanceTol = MIN_DISTANCE_TOLERANCE;
}
if (maxDistanceFound > expectedDistanceTol)
{
std::cerr << "maxDistanceFound: " << maxDistanceFound << " tolerated " << expectedDistanceTol << std::endl;
return false;
}
return true;
}
} // namespace geos::xmltester
} // namespace geos
<|endoftext|>
|
<commit_before>/******************************************************************************
Copyright (c) Dmitri Dolzhenko
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.
*******************************************************************************/
#pragma once
//------------------------------------------------------------------------------
// include local:
// include std:
#include <vector>
#include <list>
#include <set>
#include <cassert>
#include <string>
#include <map> // Tests
#include <algorithm> // std::find
#include <functional> // std::fucntion
#include <iostream>
#include <iomanip>
// forward declarations:
//------------------------------------------------------------------------------
namespace limo {
class TestContext;
typedef std::string Name;
typedef std::function<TestContext*(void)> TestContextGetter;
typedef std::function<void (TestContextGetter&)> TestFunction;
typedef std::function<void(void)> PrepareFunction;
typedef std::map<Name, TestFunction> Tests;
struct TestSettings {
TestSettings(Name name, TestContext* suite): m_name(name), m_context(suite) {}
TestSettings& operator<<(TestFunction test) {
m_test = test;
return *this;
}
Name m_name;
TestContext* m_context;
TestFunction m_test;
};
struct Result
{
const char* expected;
const char* recieved;
const char* file;
const int line;
const bool ok;
};
inline std::ostream& operator<<(std::ostream& o, const Result& result)
{
return o << result.file << ":" << result.line << ":: "
<< (result.ok ? "ok" : "failed") << ": "
<< result.expected << std::endl;
};
struct Statistics
{
Statistics() { reset(); }
size_t total, passed, failured, crashed;
void reset() { total = passed = failured = crashed = 0; }
bool is_valid() const { return total == passed + failured + crashed; }
Statistics& operator+=(const Statistics& rhs)
{
total += rhs.total;
passed += rhs.passed;
failured += rhs.failured;
crashed += rhs.crashed;
return *this;
};
};
inline std::ostream& operator<<(std::ostream& o, const Statistics& stats)
{
assert(stats.is_valid());
return o << " crashed " << stats.crashed
<< ", failured " << stats.failured
<< ", passed " << stats.passed
<< ", total " << stats.total
<< ".";
};
class TestContextBase {
public:
Statistics stats;
void expect_true(const char* file, int line, const char* expected, bool ok)
{
stats.total++;
Result result = {expected, ok ? "true" : "false", file, line, ok};
// db.push_back(run);
if(ok)
{
stats.passed++;
}
else
{
stats.failured++;
std::cout << result;
}
}
};
class TestContext : public TestContextBase {
public:
static const bool m_verbose = true;
PrepareFunction m_before;
PrepareFunction m_after;
Name m_name;
Tests m_tests;
public:
TestContext(Name name)
: m_name(name)
, m_before([](){})
, m_after([](){})
{
if(m_verbose) std::cout << m_name << std::endl;
}
virtual void test(Name name, TestFunction test)
{
run_test(name, test, m_name+".");
}
void run_test(Name name, TestFunction test, Name basename)
{
m_before();
TestContext context(basename + name);
TestContextGetter getter = [&context]() { return &context; };
test(getter);
m_after();
stats += context.stats;
}
private:
};
class GlobalTestContext : public TestContext {
public:
GlobalTestContext(): TestContext("root") {}
bool run()
{
for(const auto& test : m_tests)
{
run_test(test.first, test.second, "");
}
std::cout << stats << std::endl;
return true;
}
virtual void test(Name name, TestFunction test) {
m_tests[name] = test;
}
};
struct Registrator {
Registrator(const TestSettings& w) {
w.m_context->test(w.m_name, w.m_test);
}
};
struct To { template <class T> To(const T&) {} };
// #define LTEST(test_name, ...) \
// To doreg##test_name = \
// get_ltest_context()->add(#test_name)
// limo::TestSettings(#test_name, get_ltest_context()) << \
// [__VA_ARGS__](limo::TestContextGetter& get_ltest_context) mutable -> void
#define LTEST(test_name, ...) \
limo::Registrator ltest_ ## test_name = \
limo::TestSettings(#test_name, get_ltest_context()) << \
[__VA_ARGS__](limo::TestContextGetter& get_ltest_context) mutable -> void
#define LBEFORE limo_context__.m_before = [&]()
#define LAFTER limo_context__.m_after = [&]()
// Unary
#define EXPECT_TRUE(expr) get_ltest_context()->expect_true(__FILE__, __LINE__, #expr, expr)
#define EXPECT_FALSE(expr) EXPECT_TRUE(!(expr))
// Binary
#define EXPECT_EQ(expr1, expr2) EXPECT_TRUE((expr1) == (expr2))
#define EXPECT_NE(expr1, expr2) EXPECT_TRUE((expr1) != (expr2))
#define EXPECT_LT(expr1, expr2) EXPECT_TRUE((expr1) < (expr2))
#define EXPECT_LE(expr1, expr2) EXPECT_TRUE((expr1) <= (expr2))
#define EXPECT_GT(expr1, expr2) EXPECT_TRUE((expr1) > (expr2))
#define EXPECT_GE(expr1, expr2) EXPECT_TRUE((expr1) >= (expr2))
// Complex
template <class T1, class T2>
bool in(const std::initializer_list<T1>& s, const T2& x) {
return std::find(s.begin(), s.end(), x) != s.end();
}
////////////////////////////////////////////////////////////////////////////////////////
} // namespace limo
//------------------------------------------------------------------------------
// globals
inline limo::GlobalTestContext* get_ltest_context() {
static limo::GlobalTestContext context;
return &context;
}
//------------------------------------------------------------------------------
<commit_msg>localized printers, cleanup statistics<commit_after>/******************************************************************************
Copyright (c) Dmitri Dolzhenko
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.
*******************************************************************************/
#pragma once
//------------------------------------------------------------------------------
// include local:
// include std:
#include <vector>
#include <list>
#include <set>
#include <cassert>
#include <string>
#include <map> // Tests
#include <algorithm> // std::find
#include <functional> // std::fucntion
#include <iostream>
#include <iomanip>
// forward declarations:
//------------------------------------------------------------------------------
namespace limo {
class TestContext;
typedef std::string Name;
typedef std::function<TestContext*(void)> TestContextGetter;
typedef std::function<void (TestContextGetter&)> TestFunction;
typedef std::function<void(void)> PrepareFunction;
typedef std::map<Name, TestFunction> Tests;
struct TestSettings {
TestSettings(Name name, TestContext* suite): m_name(name), m_context(suite) {}
TestSettings& operator<<(TestFunction test) {
m_test = test;
return *this;
}
Name m_name;
TestContext* m_context;
TestFunction m_test;
};
struct Result
{
const char* expected;
const char* recieved;
const char* file;
const int line;
const bool ok;
friend std::ostream& operator<<(std::ostream& o, const Result& result)
{
return o << result.file << ":" << result.line << ":: "
<< (result.ok ? "ok" : "failed") << ": "
<< result.expected << std::endl;
};
};
struct Statistics {
size_t total, passed, failured, crashed;
Statistics(): total(0), passed(0), failured(0), crashed(0) {}
bool is_valid() const { return total == passed + failured + crashed; }
Statistics& operator+=(const Statistics& rhs) {
total += rhs.total;
passed += rhs.passed;
failured += rhs.failured;
crashed += rhs.crashed;
return *this;
}
friend std::ostream& operator<<(std::ostream& o, const Statistics& stats) {
assert(stats.is_valid());
return o << " crashed " << stats.crashed
<< ", failured " << stats.failured
<< ", passed " << stats.passed
<< ", total " << stats.total
<< ".";
}
};
class TestContextBase {
public:
Statistics stats;
void expect_true(const char* file, int line, const char* expected, bool ok)
{
stats.total++;
Result result = {expected, ok ? "true" : "false", file, line, ok};
if(ok)
{
stats.passed++;
}
else
{
stats.failured++;
std::cout << result;
}
}
};
class TestContext : public TestContextBase {
public:
static const bool m_verbose = true;
PrepareFunction m_before;
PrepareFunction m_after;
Name m_name;
Tests m_tests;
public:
TestContext(Name name)
: m_name(name)
, m_before([](){})
, m_after([](){})
{
if(m_verbose) std::cout << m_name << std::endl;
}
virtual void test(Name name, TestFunction test)
{
run_test(name, test, m_name+".");
}
void run_test(Name name, TestFunction test, Name basename)
{
m_before();
TestContext context(basename + name);
TestContextGetter getter = [&context]() { return &context; };
test(getter);
m_after();
stats += context.stats;
}
private:
};
class GlobalTestContext : public TestContext {
public:
GlobalTestContext(): TestContext("root") {}
bool run()
{
for(const auto& test : m_tests)
{
run_test(test.first, test.second, "");
}
std::cout << stats << std::endl;
return true;
}
virtual void test(Name name, TestFunction test) {
m_tests[name] = test;
}
};
struct Registrator {
Registrator(const TestSettings& w) {
w.m_context->test(w.m_name, w.m_test);
}
};
struct To { template <class T> To(const T&) {} };
// #define LTEST(test_name, ...) \
// To doreg##test_name = \
// get_ltest_context()->add(#test_name)
// limo::TestSettings(#test_name, get_ltest_context()) << \
// [__VA_ARGS__](limo::TestContextGetter& get_ltest_context) mutable -> void
#define LTEST(test_name, ...) \
limo::Registrator ltest_ ## test_name = \
limo::TestSettings(#test_name, get_ltest_context()) << \
[__VA_ARGS__](limo::TestContextGetter& get_ltest_context) mutable -> void
#define LBEFORE limo_context__.m_before = [&]()
#define LAFTER limo_context__.m_after = [&]()
// Unary
#define EXPECT_TRUE(expr) get_ltest_context()->expect_true(__FILE__, __LINE__, #expr, expr)
#define EXPECT_FALSE(expr) EXPECT_TRUE(!(expr))
// Binary
#define EXPECT_EQ(expr1, expr2) EXPECT_TRUE((expr1) == (expr2))
#define EXPECT_NE(expr1, expr2) EXPECT_TRUE((expr1) != (expr2))
#define EXPECT_LT(expr1, expr2) EXPECT_TRUE((expr1) < (expr2))
#define EXPECT_LE(expr1, expr2) EXPECT_TRUE((expr1) <= (expr2))
#define EXPECT_GT(expr1, expr2) EXPECT_TRUE((expr1) > (expr2))
#define EXPECT_GE(expr1, expr2) EXPECT_TRUE((expr1) >= (expr2))
// Complex
template <class T1, class T2>
bool in(const std::initializer_list<T1>& s, const T2& x) {
return std::find(s.begin(), s.end(), x) != s.end();
}
////////////////////////////////////////////////////////////////////////////////////////
} // namespace limo
//------------------------------------------------------------------------------
// globals
inline limo::GlobalTestContext* get_ltest_context() {
static limo::GlobalTestContext context;
return &context;
}
//------------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>#include "neo.h"
#include "protocol.h"
#include "serial.h"
#include <chrono>
#include <thread>
int32_t neo_get_version(void) { return NEO_VERSION; }
bool neo_is_abi_compatible(void) { return neo_get_version() >> 16u == NEO_VERSION_MAJOR; }
typedef struct neo_error {
const char* what; // always literal, do not deallocate
} neo_error;
typedef struct neo_device {
neo::serial::device_s serial; // serial port communication
bool is_scanning;
} neo_device;
#define NEO_MAX_SAMPLES 4096
typedef struct neo_scan {
int32_t angle[NEO_MAX_SAMPLES]; // in millidegrees
int32_t distance[NEO_MAX_SAMPLES]; // in cm
int32_t signal_strength[NEO_MAX_SAMPLES]; // range 0:255
int32_t count;
} neo_scan;
// Constructor hidden from users
static neo_error_s neo_error_construct(const char* what) {
NEO_ASSERT(what);
auto out = new neo_error{what};
return out;
}
const char* neo_error_message(neo_error_s error) {
NEO_ASSERT(error);
return error->what;
}
void neo_error_destruct(neo_error_s error) {
NEO_ASSERT(error);
delete error;
}
neo_device_s neo_device_construct_simple(const char* port, neo_error_s* error) {
NEO_ASSERT(error);
return neo_device_construct(port, 115200, error);
}
neo_device_s neo_device_construct(const char* port, int32_t bitrate, neo_error_s* error) {
NEO_ASSERT(port);
NEO_ASSERT(bitrate > 0);
NEO_ASSERT(error);
neo::serial::error_s serialerror = nullptr;
neo::serial::device_s serial = neo::serial::device_construct(port, bitrate, &serialerror);
if (serialerror) {
*error = neo_error_construct(neo::serial::error_message(serialerror));
neo::serial::error_destruct(serialerror);
return nullptr;
}
auto out = new neo_device{serial, /*is_scanning=*/true};
neo_error_s stoperror = nullptr;
neo_device_stop_scanning(out, &stoperror);
if (stoperror) {
*error = stoperror;
neo_device_destruct(out);
return nullptr;
}
return out;
}
void neo_device_destruct(neo_device_s device) {
NEO_ASSERT(device);
neo_error_s ignore = nullptr;
neo_device_stop_scanning(device, &ignore);
(void)ignore; // nothing we can do here
neo::serial::device_destruct(device->serial);
delete device;
}
void neo_device_start_scanning(neo_device_s device, neo_error_s* error) {
NEO_ASSERT(device);
NEO_ASSERT(error);
NEO_ASSERT(!device->is_scanning);
if (device->is_scanning)
return;
neo::protocol::error_s protocolerror = nullptr;
neo::protocol::write_command(device->serial, neo::protocol::DATA_ACQUISITION_START, &protocolerror);
if (protocolerror) {
*error = neo_error_construct("unable to send start scanning command");
neo::protocol::error_destruct(protocolerror);
return;
}
neo::protocol::response_header_s response;
neo::protocol::read_response_header(device->serial, neo::protocol::DATA_ACQUISITION_START, &response, &protocolerror);
if (protocolerror) {
*error = neo_error_construct("unable to receive start scanning command response");
neo::protocol::error_destruct(protocolerror);
return;
}
device->is_scanning = true;
}
void neo_device_stop_scanning(neo_device_s device, neo_error_s* error) {
NEO_ASSERT(device);
NEO_ASSERT(error);
if (!device->is_scanning)
return;
neo::protocol::error_s protocolerror = nullptr;
neo::protocol::write_command(device->serial, neo::protocol::DATA_ACQUISITION_STOP, &protocolerror);
if (protocolerror) {
*error = neo_error_construct("unable to send stop scanning command");
neo::protocol::error_destruct(protocolerror);
return;
}
// Wait until device stopped sending
std::this_thread::sleep_for(std::chrono::milliseconds(20));
neo::serial::error_s serialerror = nullptr;
neo::serial::device_flush(device->serial, &serialerror);
if (serialerror) {
*error = neo_error_construct("unable to flush serial device for stopping scanning command");
neo::serial::error_destruct(serialerror);
return;
}
neo::protocol::write_command(device->serial, neo::protocol::DATA_ACQUISITION_STOP, &protocolerror);
if (protocolerror) {
*error = neo_error_construct("unable to send stop scanning command");
neo::protocol::error_destruct(protocolerror);
return;
}
neo::protocol::response_header_s response;
neo::protocol::read_response_header(device->serial, neo::protocol::DATA_ACQUISITION_STOP, &response, &protocolerror);
if (protocolerror) {
*error = neo_error_construct("unable to receive stop scanning command response");
neo::protocol::error_destruct(protocolerror);
return;
}
device->is_scanning = false;
}
neo_scan_s neo_device_get_scan(neo_device_s device, neo_error_s* error) {
NEO_ASSERT(device);
NEO_ASSERT(error);
NEO_ASSERT(device->is_scanning);
neo::protocol::error_s protocolerror = nullptr;
neo::protocol::response_scan_packet_s responses[NEO_MAX_SAMPLES];
int32_t received = 1;
while (received < NEO_MAX_SAMPLES) {
neo::protocol::read_response_scan(device->serial, &responses[received], &protocolerror);
if (protocolerror) {
*error = neo_error_construct("unable to receive neo scan response");
neo::protocol::error_destruct(protocolerror);
return nullptr;
}
const bool is_sync = responses[received].sync_error & neo::protocol::response_scan_packet_sync::sync;
const bool has_error = (responses[received].sync_error >> 1) != 0; // shift out sync bit, others are errors
if (!has_error) {
received++;
}
if (is_sync) {
responses[0] = responses[received];
break;
}
}
auto out = new neo_scan;
out->count = received - 1;
for (int32_t it = 0; it < received; ++it) {
// Convert angle from compact serial format to float (in degrees).
// In addition convert from degrees to milli-degrees.
out->angle[it] = static_cast<int32_t>(neo::protocol::u16_to_f32(responses[it].angle) * 1000.f);
out->distance[it] = responses[it].distance;
out->signal_strength[it] = responses[it].signal_strength;
}
return out;
}
int32_t neo_scan_get_number_of_samples(neo_scan_s scan) {
NEO_ASSERT(scan);
NEO_ASSERT(scan->count >= 0);
return scan->count;
}
int32_t neo_scan_get_angle(neo_scan_s scan, int32_t sample) {
NEO_ASSERT(scan);
NEO_ASSERT(sample >= 0 && sample < scan->count && "sample index out of bounds");
return scan->angle[sample];
}
int32_t neo_scan_get_distance(neo_scan_s scan, int32_t sample) {
NEO_ASSERT(scan);
NEO_ASSERT(sample >= 0 && sample < scan->count && "sample index out of bounds");
return scan->distance[sample];
}
int32_t neo_scan_get_signal_strength(neo_scan_s scan, int32_t sample) {
NEO_ASSERT(scan);
NEO_ASSERT(sample >= 0 && sample < scan->count && "sample index out of bounds");
return scan->signal_strength[sample];
}
void neo_scan_destruct(neo_scan_s scan) {
NEO_ASSERT(scan);
delete scan;
}
int32_t neo_device_get_motor_speed(neo_device_s device, neo_error_s* error) {
NEO_ASSERT(device);
NEO_ASSERT(error);
NEO_ASSERT(!device->is_scanning);
neo::protocol::error_s protocolerror = nullptr;
neo::protocol::write_command(device->serial, neo::protocol::MOTOR_INFORMATION, &protocolerror);
if (protocolerror) {
*error = neo_error_construct("unable to send motor speed command");
neo::protocol::error_destruct(protocolerror);
return 0;
}
neo::protocol::response_info_motor_s response;
neo::protocol::read_response_info_motor(device->serial, neo::protocol::MOTOR_INFORMATION, &response, &protocolerror);
if (protocolerror) {
*error = neo_error_construct("unable to receive motor speed command response");
neo::protocol::error_destruct(protocolerror);
return 0;
}
int32_t speed = neo::protocol::ascii_bytes_to_integral(response.motor_speed);
NEO_ASSERT(speed >= 0);
return speed;
}
void neo_device_set_motor_speed(neo_device_s device, int32_t hz, neo_error_s* error) {
NEO_ASSERT(device);
NEO_ASSERT(hz >= 0 && hz <= 10);
NEO_ASSERT(error);
NEO_ASSERT(!device->is_scanning);
uint8_t args[2] = {0};
neo::protocol::integral_to_ascii_bytes(hz, args);
neo::protocol::error_s protocolerror = nullptr;
neo::protocol::write_command_with_arguments(device->serial, neo::protocol::MOTOR_SPEED_ADJUST, args, &protocolerror);
if (protocolerror) {
*error = neo_error_construct("unable to send motor speed command");
neo::protocol::error_destruct(protocolerror);
return;
}
neo::protocol::response_param_s response;
neo::protocol::read_response_param(device->serial, neo::protocol::MOTOR_SPEED_ADJUST, &response, &protocolerror);
if (protocolerror) {
*error = neo_error_construct("unable to receive motor speed command response");
neo::protocol::error_destruct(protocolerror);
return;
}
}
int32_t neo_device_get_sample_rate(neo_device_s device, neo_error_s* error) {
NEO_ASSERT(device);
NEO_ASSERT(error);
NEO_ASSERT(!device->is_scanning);
neo::protocol::error_s protocolerror = nullptr;
neo::protocol::write_command(device->serial, neo::protocol::SAMPLE_RATE_INFORMATION, &protocolerror);
if (protocolerror) {
*error = neo_error_construct("unable to send sample rate command");
neo::protocol::error_destruct(protocolerror);
return 0;
}
neo::protocol::response_info_sample_rate_s response;
neo::protocol::read_response_info_sample_rate(device->serial, neo::protocol::SAMPLE_RATE_INFORMATION, &response,
&protocolerror);
if (protocolerror) {
*error = neo_error_construct("unable to receive sample rate command response");
neo::protocol::error_destruct(protocolerror);
return 0;
}
// 01: 500-600Hz, 02: 750-800Hz, 03: 1000-1050Hz
int32_t code = neo::protocol::ascii_bytes_to_integral(response.sample_rate);
int32_t rate = 0;
switch (code) {
case 1:
rate = 500;
break;
case 2:
rate = 750;
break;
case 3:
rate = 1000;
break;
default:
NEO_ASSERT(false && "sample rate code unknown");
}
return rate;
}
void neo_device_set_sample_rate(neo_device_s device, int32_t hz, neo_error_s* error) {
NEO_ASSERT(device);
NEO_ASSERT(hz == 500 || hz == 750 || hz == 1000);
NEO_ASSERT(error);
NEO_ASSERT(!device->is_scanning);
// 01: 500-600Hz, 02: 750-800Hz, 03: 1000-1050Hz
int32_t code = 1;
switch (hz) {
case 500:
code = 1;
break;
case 750:
code = 2;
break;
case 1000:
code = 3;
break;
default:
NEO_ASSERT(false && "sample rate unknown");
}
uint8_t args[2] = {0};
neo::protocol::integral_to_ascii_bytes(code, args);
neo::protocol::error_s protocolerror = nullptr;
neo::protocol::write_command_with_arguments(device->serial, neo::protocol::SAMPLE_RATE_ADJUST, args, &protocolerror);
if (protocolerror) {
*error = neo_error_construct("unable to send sample rate command");
neo::protocol::error_destruct(protocolerror);
return;
}
neo::protocol::response_param_s response;
neo::protocol::read_response_param(device->serial, neo::protocol::SAMPLE_RATE_ADJUST, &response, &protocolerror);
if (protocolerror) {
*error = neo_error_construct("unable to receive sample rate command response");
neo::protocol::error_destruct(protocolerror);
return;
}
}
void neo_device_reset(neo_device_s device, neo_error_s* error) {
NEO_ASSERT(device);
NEO_ASSERT(error);
NEO_ASSERT(!device->is_scanning);
neo::protocol::error_s protocolerror = nullptr;
neo::protocol::write_command(device->serial, neo::protocol::RESET_DEVICE, &protocolerror);
if (protocolerror) {
*error = neo_error_construct("unable to send device reset command");
neo::protocol::error_destruct(protocolerror);
return;
}
}
<commit_msg>Revert "fix(the angle of the last one is large than the first one)."<commit_after>#include "neo.h"
#include "protocol.h"
#include "serial.h"
#include <chrono>
#include <thread>
int32_t neo_get_version(void) { return NEO_VERSION; }
bool neo_is_abi_compatible(void) { return neo_get_version() >> 16u == NEO_VERSION_MAJOR; }
typedef struct neo_error {
const char* what; // always literal, do not deallocate
} neo_error;
typedef struct neo_device {
neo::serial::device_s serial; // serial port communication
bool is_scanning;
} neo_device;
#define NEO_MAX_SAMPLES 4096
typedef struct neo_scan {
int32_t angle[NEO_MAX_SAMPLES]; // in millidegrees
int32_t distance[NEO_MAX_SAMPLES]; // in cm
int32_t signal_strength[NEO_MAX_SAMPLES]; // range 0:255
int32_t count;
} neo_scan;
// Constructor hidden from users
static neo_error_s neo_error_construct(const char* what) {
NEO_ASSERT(what);
auto out = new neo_error{what};
return out;
}
const char* neo_error_message(neo_error_s error) {
NEO_ASSERT(error);
return error->what;
}
void neo_error_destruct(neo_error_s error) {
NEO_ASSERT(error);
delete error;
}
neo_device_s neo_device_construct_simple(const char* port, neo_error_s* error) {
NEO_ASSERT(error);
return neo_device_construct(port, 115200, error);
}
neo_device_s neo_device_construct(const char* port, int32_t bitrate, neo_error_s* error) {
NEO_ASSERT(port);
NEO_ASSERT(bitrate > 0);
NEO_ASSERT(error);
neo::serial::error_s serialerror = nullptr;
neo::serial::device_s serial = neo::serial::device_construct(port, bitrate, &serialerror);
if (serialerror) {
*error = neo_error_construct(neo::serial::error_message(serialerror));
neo::serial::error_destruct(serialerror);
return nullptr;
}
auto out = new neo_device{serial, /*is_scanning=*/true};
neo_error_s stoperror = nullptr;
neo_device_stop_scanning(out, &stoperror);
if (stoperror) {
*error = stoperror;
neo_device_destruct(out);
return nullptr;
}
return out;
}
void neo_device_destruct(neo_device_s device) {
NEO_ASSERT(device);
neo_error_s ignore = nullptr;
neo_device_stop_scanning(device, &ignore);
(void)ignore; // nothing we can do here
neo::serial::device_destruct(device->serial);
delete device;
}
void neo_device_start_scanning(neo_device_s device, neo_error_s* error) {
NEO_ASSERT(device);
NEO_ASSERT(error);
NEO_ASSERT(!device->is_scanning);
if (device->is_scanning)
return;
neo::protocol::error_s protocolerror = nullptr;
neo::protocol::write_command(device->serial, neo::protocol::DATA_ACQUISITION_START, &protocolerror);
if (protocolerror) {
*error = neo_error_construct("unable to send start scanning command");
neo::protocol::error_destruct(protocolerror);
return;
}
neo::protocol::response_header_s response;
neo::protocol::read_response_header(device->serial, neo::protocol::DATA_ACQUISITION_START, &response, &protocolerror);
if (protocolerror) {
*error = neo_error_construct("unable to receive start scanning command response");
neo::protocol::error_destruct(protocolerror);
return;
}
device->is_scanning = true;
}
void neo_device_stop_scanning(neo_device_s device, neo_error_s* error) {
NEO_ASSERT(device);
NEO_ASSERT(error);
if (!device->is_scanning)
return;
neo::protocol::error_s protocolerror = nullptr;
neo::protocol::write_command(device->serial, neo::protocol::DATA_ACQUISITION_STOP, &protocolerror);
if (protocolerror) {
*error = neo_error_construct("unable to send stop scanning command");
neo::protocol::error_destruct(protocolerror);
return;
}
// Wait until device stopped sending
std::this_thread::sleep_for(std::chrono::milliseconds(20));
neo::serial::error_s serialerror = nullptr;
neo::serial::device_flush(device->serial, &serialerror);
if (serialerror) {
*error = neo_error_construct("unable to flush serial device for stopping scanning command");
neo::serial::error_destruct(serialerror);
return;
}
neo::protocol::write_command(device->serial, neo::protocol::DATA_ACQUISITION_STOP, &protocolerror);
if (protocolerror) {
*error = neo_error_construct("unable to send stop scanning command");
neo::protocol::error_destruct(protocolerror);
return;
}
neo::protocol::response_header_s response;
neo::protocol::read_response_header(device->serial, neo::protocol::DATA_ACQUISITION_STOP, &response, &protocolerror);
if (protocolerror) {
*error = neo_error_construct("unable to receive stop scanning command response");
neo::protocol::error_destruct(protocolerror);
return;
}
device->is_scanning = false;
}
neo_scan_s neo_device_get_scan(neo_device_s device, neo_error_s* error) {
NEO_ASSERT(device);
NEO_ASSERT(error);
NEO_ASSERT(device->is_scanning);
neo::protocol::error_s protocolerror = nullptr;
neo::protocol::response_scan_packet_s responses[NEO_MAX_SAMPLES];
int32_t received = 0;
while (received < NEO_MAX_SAMPLES) {
neo::protocol::read_response_scan(device->serial, &responses[received], &protocolerror);
if (protocolerror) {
*error = neo_error_construct("unable to receive neo scan response");
neo::protocol::error_destruct(protocolerror);
return nullptr;
}
const bool is_sync = responses[received].sync_error & neo::protocol::response_scan_packet_sync::sync;
const bool has_error = (responses[received].sync_error >> 1) != 0; // shift out sync bit, others are errors
if (!has_error) {
received++;
}
if (is_sync) {
break;
}
}
auto out = new neo_scan;
out->count = received;
for (int32_t it = 0; it < received; ++it) {
// Convert angle from compact serial format to float (in degrees).
// In addition convert from degrees to milli-degrees.
out->angle[it] = static_cast<int32_t>(neo::protocol::u16_to_f32(responses[it].angle) * 1000.f);
out->distance[it] = responses[it].distance;
out->signal_strength[it] = responses[it].signal_strength;
}
return out;
}
int32_t neo_scan_get_number_of_samples(neo_scan_s scan) {
NEO_ASSERT(scan);
NEO_ASSERT(scan->count >= 0);
return scan->count;
}
int32_t neo_scan_get_angle(neo_scan_s scan, int32_t sample) {
NEO_ASSERT(scan);
NEO_ASSERT(sample >= 0 && sample < scan->count && "sample index out of bounds");
return scan->angle[sample];
}
int32_t neo_scan_get_distance(neo_scan_s scan, int32_t sample) {
NEO_ASSERT(scan);
NEO_ASSERT(sample >= 0 && sample < scan->count && "sample index out of bounds");
return scan->distance[sample];
}
int32_t neo_scan_get_signal_strength(neo_scan_s scan, int32_t sample) {
NEO_ASSERT(scan);
NEO_ASSERT(sample >= 0 && sample < scan->count && "sample index out of bounds");
return scan->signal_strength[sample];
}
void neo_scan_destruct(neo_scan_s scan) {
NEO_ASSERT(scan);
delete scan;
}
int32_t neo_device_get_motor_speed(neo_device_s device, neo_error_s* error) {
NEO_ASSERT(device);
NEO_ASSERT(error);
NEO_ASSERT(!device->is_scanning);
neo::protocol::error_s protocolerror = nullptr;
neo::protocol::write_command(device->serial, neo::protocol::MOTOR_INFORMATION, &protocolerror);
if (protocolerror) {
*error = neo_error_construct("unable to send motor speed command");
neo::protocol::error_destruct(protocolerror);
return 0;
}
neo::protocol::response_info_motor_s response;
neo::protocol::read_response_info_motor(device->serial, neo::protocol::MOTOR_INFORMATION, &response, &protocolerror);
if (protocolerror) {
*error = neo_error_construct("unable to receive motor speed command response");
neo::protocol::error_destruct(protocolerror);
return 0;
}
int32_t speed = neo::protocol::ascii_bytes_to_integral(response.motor_speed);
NEO_ASSERT(speed >= 0);
return speed;
}
void neo_device_set_motor_speed(neo_device_s device, int32_t hz, neo_error_s* error) {
NEO_ASSERT(device);
NEO_ASSERT(hz >= 0 && hz <= 10);
NEO_ASSERT(error);
NEO_ASSERT(!device->is_scanning);
uint8_t args[2] = {0};
neo::protocol::integral_to_ascii_bytes(hz, args);
neo::protocol::error_s protocolerror = nullptr;
neo::protocol::write_command_with_arguments(device->serial, neo::protocol::MOTOR_SPEED_ADJUST, args, &protocolerror);
if (protocolerror) {
*error = neo_error_construct("unable to send motor speed command");
neo::protocol::error_destruct(protocolerror);
return;
}
neo::protocol::response_param_s response;
neo::protocol::read_response_param(device->serial, neo::protocol::MOTOR_SPEED_ADJUST, &response, &protocolerror);
if (protocolerror) {
*error = neo_error_construct("unable to receive motor speed command response");
neo::protocol::error_destruct(protocolerror);
return;
}
}
int32_t neo_device_get_sample_rate(neo_device_s device, neo_error_s* error) {
NEO_ASSERT(device);
NEO_ASSERT(error);
NEO_ASSERT(!device->is_scanning);
neo::protocol::error_s protocolerror = nullptr;
neo::protocol::write_command(device->serial, neo::protocol::SAMPLE_RATE_INFORMATION, &protocolerror);
if (protocolerror) {
*error = neo_error_construct("unable to send sample rate command");
neo::protocol::error_destruct(protocolerror);
return 0;
}
neo::protocol::response_info_sample_rate_s response;
neo::protocol::read_response_info_sample_rate(device->serial, neo::protocol::SAMPLE_RATE_INFORMATION, &response,
&protocolerror);
if (protocolerror) {
*error = neo_error_construct("unable to receive sample rate command response");
neo::protocol::error_destruct(protocolerror);
return 0;
}
// 01: 500-600Hz, 02: 750-800Hz, 03: 1000-1050Hz
int32_t code = neo::protocol::ascii_bytes_to_integral(response.sample_rate);
int32_t rate = 0;
switch (code) {
case 1:
rate = 500;
break;
case 2:
rate = 750;
break;
case 3:
rate = 1000;
break;
default:
NEO_ASSERT(false && "sample rate code unknown");
}
return rate;
}
void neo_device_set_sample_rate(neo_device_s device, int32_t hz, neo_error_s* error) {
NEO_ASSERT(device);
NEO_ASSERT(hz == 500 || hz == 750 || hz == 1000);
NEO_ASSERT(error);
NEO_ASSERT(!device->is_scanning);
// 01: 500-600Hz, 02: 750-800Hz, 03: 1000-1050Hz
int32_t code = 1;
switch (hz) {
case 500:
code = 1;
break;
case 750:
code = 2;
break;
case 1000:
code = 3;
break;
default:
NEO_ASSERT(false && "sample rate unknown");
}
uint8_t args[2] = {0};
neo::protocol::integral_to_ascii_bytes(code, args);
neo::protocol::error_s protocolerror = nullptr;
neo::protocol::write_command_with_arguments(device->serial, neo::protocol::SAMPLE_RATE_ADJUST, args, &protocolerror);
if (protocolerror) {
*error = neo_error_construct("unable to send sample rate command");
neo::protocol::error_destruct(protocolerror);
return;
}
neo::protocol::response_param_s response;
neo::protocol::read_response_param(device->serial, neo::protocol::SAMPLE_RATE_ADJUST, &response, &protocolerror);
if (protocolerror) {
*error = neo_error_construct("unable to receive sample rate command response");
neo::protocol::error_destruct(protocolerror);
return;
}
}
void neo_device_reset(neo_device_s device, neo_error_s* error) {
NEO_ASSERT(device);
NEO_ASSERT(error);
NEO_ASSERT(!device->is_scanning);
neo::protocol::error_s protocolerror = nullptr;
neo::protocol::write_command(device->serial, neo::protocol::RESET_DEVICE, &protocolerror);
if (protocolerror) {
*error = neo_error_construct("unable to send device reset command");
neo::protocol::error_destruct(protocolerror);
return;
}
}
<|endoftext|>
|
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2020 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <gtest/gtest.h>
#include <Graphics/Widgets/BasicBoundingBoxWidget.h>
#include <Graphics/Widgets/Tests/WidgetTestingUtility.h>
using namespace SCIRun::Graphics::Datatypes;
using namespace SCIRun::Core::Geometry;
TEST(BasicBoundingBoxWidgetTest, CanCreateSingleBoxReal)
{
StubGeometryIDGenerator idGen;
BasicBoundingBoxWidget box({{idGen, "testSphere1"}, boost::make_shared<RealGlyphFactory>()},
{
{10.0, "", {1,2,3}, {{0,0,0}, {1,1,1}}, 10},
{{0,2,1},{{1,1,1},{1,0,1},{0,1,1}}}
});
EXPECT_EQ(Point(0,2,1), box.position());
EXPECT_EQ("bounding_box_cylinders102-21201021041001021-241-261", box.name());
//FAIL() << "todo";
}
TEST(BasicBoundingBoxWidgetTest, CanCreateSingleBoxStubbed)
{
StubGeometryIDGenerator idGen;
BasicBoundingBoxWidget box({{idGen, "testSphere1"}, boost::make_shared<StubGlyphFactory>()},
{
{10.0, "", {1,2,3}, {{0,0,0}, {1,1,1}}, 10},
{{0,2,1},{{1,1,1},{1,0,1},{0,1,1}}}
});
EXPECT_EQ(Point(0,2,1), box.position());
EXPECT_EQ("__basicBox__0", box.name());
//FAIL() << "todo";
}
<commit_msg>Update BasicBoundingBoxWidgetTest.cc<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2020 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <gtest/gtest.h>
#include <Graphics/Widgets/BasicBoundingBoxWidget.h>
#include <Graphics/Widgets/Tests/WidgetTestingUtility.h>
using namespace SCIRun::Graphics::Datatypes;
using namespace SCIRun::Core::Geometry;
TEST(BasicBoundingBoxWidgetTest, DISABLED_CanCreateSingleBoxReal)
{
StubGeometryIDGenerator idGen;
BasicBoundingBoxWidget box({{idGen, "testSphere1"}, boost::make_shared<RealGlyphFactory>()},
{
{10.0, "", {1,2,3}, {{0,0,0}, {1,1,1}}, 10},
{{0,2,1},{{1,1,1},{1,0,1},{0,1,1}}}
});
EXPECT_EQ(Point(0,2,1), box.position());
EXPECT_EQ("bounding_box_cylinders102-21201021041001021-241-261", box.name());
//FAIL() << "todo";
}
TEST(BasicBoundingBoxWidgetTest, DISABLED_CanCreateSingleBoxStubbed)
{
StubGeometryIDGenerator idGen;
BasicBoundingBoxWidget box({{idGen, "testSphere1"}, boost::make_shared<StubGlyphFactory>()},
{
{10.0, "", {1,2,3}, {{0,0,0}, {1,1,1}}, 10},
{{0,2,1},{{1,1,1},{1,0,1},{0,1,1}}}
});
EXPECT_EQ(Point(0,2,1), box.position());
EXPECT_EQ("__basicBox__0", box.name());
//FAIL() << "todo";
}
<|endoftext|>
|
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2008-2009, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "boost/python.hpp"
#include "IECore/MeshPrimitiveShrinkWrapOp.h"
#include "IECore/Parameter.h"
#include "IECore/Object.h"
#include "IECore/CompoundObject.h"
#include "IECore/bindings/RunTimeTypedBinding.h"
#include "IECore/bindings/MeshPrimitiveShrinkWrapOpBinding.h"
using namespace boost;
using namespace boost::python;
namespace IECore
{
void bindMeshPrimitiveShrinkWrapOp()
{
typedef class_< MeshPrimitiveShrinkWrapOp, MeshPrimitiveShrinkWrapOpPtr, boost::noncopyable, bases<MeshPrimitiveOp> > MeshPrimitiveShrinkWrapOpPyClass;
scope opScope = MeshPrimitiveShrinkWrapOpPyClass( "MeshPrimitiveShrinkWrapOp", no_init )
.def( init< >() )
;
enum_< MeshPrimitiveShrinkWrapOp::Direction >( "Direction" )
.value( "Both", MeshPrimitiveShrinkWrapOp::Both )
.value( "Inside", MeshPrimitiveShrinkWrapOp::Inside )
.value( "Outside", MeshPrimitiveShrinkWrapOp::Outside )
;
enum_< MeshPrimitiveShrinkWrapOp::Method >( "Method" )
.value( "Normal", MeshPrimitiveShrinkWrapOp::Normal )
.value( "XAxis", MeshPrimitiveShrinkWrapOp::XAxis )
.value( "YAxis", MeshPrimitiveShrinkWrapOp::YAxis )
.value( "ZAxis", MeshPrimitiveShrinkWrapOp::ZAxis )
;
}
} // namespace IECore
<commit_msg>Updated binding to use new RunTimeTypedClass template<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2008-2009, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "boost/python.hpp"
#include "IECore/MeshPrimitiveShrinkWrapOp.h"
#include "IECore/Parameter.h"
#include "IECore/Object.h"
#include "IECore/CompoundObject.h"
#include "IECore/bindings/RunTimeTypedBinding.h"
#include "IECore/bindings/MeshPrimitiveShrinkWrapOpBinding.h"
using namespace boost;
using namespace boost::python;
namespace IECore
{
void bindMeshPrimitiveShrinkWrapOp()
{
scope opScope = RunTimeTypedClass<MeshPrimitiveShrinkWrapOp>()
.def( init<>() )
;
enum_< MeshPrimitiveShrinkWrapOp::Direction >( "Direction" )
.value( "Both", MeshPrimitiveShrinkWrapOp::Both )
.value( "Inside", MeshPrimitiveShrinkWrapOp::Inside )
.value( "Outside", MeshPrimitiveShrinkWrapOp::Outside )
;
enum_< MeshPrimitiveShrinkWrapOp::Method >( "Method" )
.value( "Normal", MeshPrimitiveShrinkWrapOp::Normal )
.value( "XAxis", MeshPrimitiveShrinkWrapOp::XAxis )
.value( "YAxis", MeshPrimitiveShrinkWrapOp::YAxis )
.value( "ZAxis", MeshPrimitiveShrinkWrapOp::ZAxis )
;
}
} // namespace IECore
<|endoftext|>
|
<commit_before>#include "OnlinePlanExpansionExecution.h"
#include "CaseBasedReasonerEx.h"
#include "WinGameGoal.h"
#include "CaseEx.h"
#include "RtsGame.h"
#include "Action.h"
#include "MessagePump.h"
#include "Message.h"
#include <crtdbg.h>
#include "AbstractReviser.h"
#include "AbstractRetriever.h"
#include "GamePlayer.h"
#include "Toolbox.h"
#include "Logger.h"
#include "RetainerEx.h"
#include "DataMessage.h"
#include "GoalFactory.h"
using namespace std;
using namespace IStrategizer;
//////////////////////////////////////////////////////////////////////////
void OnlinePlanExpansionExecution::Update(_In_ const WorldClock& clock)
{
m_pOlcbpPlan->Lock();
// We have exhausted all possible plans. We have surrendered, nothing to do
if (m_pOlcbpPlan->Size() > 0)
{
IOlcbpPlan::NodeQueue actionQ;
IOlcbpPlan::NodeQueue goalQ;
typedef unsigned GoalKey;
map<GoalKey, IOlcbpPlan::NodeID> goalTable;
// 1st pass: get ready nodes only
GetReachableReadyNodes(actionQ, goalQ);
// 2nd pass: prioritize and filter goal updates
while (!goalQ.empty())
{
GoalEx* pCurrGoal = (GoalEx*)m_pOlcbpPlan->GetNode(goalQ.front());
GoalKey typeKey = pCurrGoal->Key();
if (!IsNodeDone(goalQ.front()))
{
goalTable[typeKey] = goalQ.front();
}
goalQ.pop();
}
// 3rd pass: actual node update
for (auto goalEntry : goalTable)
{
// Only update a goal node if it still exist
// It is normal that a previous updated goal node during this pass
// failed and its snippet was destroyed, and as a result a node that
// was considered for update does not exist anymore
if (m_pOlcbpPlan->Contains(goalEntry.second))
UpdateGoalNode(goalEntry.second, clock);
}
while (!actionQ.empty())
{
// Only update an action node if it still exist
// What applies to a goal in the 3rd pass apply here
if (m_pOlcbpPlan->Contains(actionQ.front()))
UpdateActionNode(actionQ.front(), clock);
actionQ.pop();
}
}
m_pOlcbpPlan->Unlock();
if (m_planStructureChangedThisFrame)
{
g_MessagePump.Send(new DataMessage<IOlcbpPlan>(0, MSG_PlanStructureChange, nullptr));
m_planStructureChangedThisFrame = false;
}
}
//////////////////////////////////////////////////////////////////////////
void OnlinePlanExpansionExecution::GetReachableReadyNodes(_Out_ IOlcbpPlan::NodeQueue& actionQ, _Out_ IOlcbpPlan::NodeQueue& goalQ)
{
IOlcbpPlan::NodeQueue Q;
IOlcbpPlan::NodeID currNodeId;
IOlcbpPlan::NodeSerializedSet planRoots;
IOlcbpPlan::NodeSet visitedNodes;
_ASSERTE(m_planRootNodeId != IOlcbpPlan::NullNodeID);
Q.push(m_planRootNodeId);
visitedNodes.insert(m_planRootNodeId);
goalQ.push(m_planRootNodeId);
// Do a BFS on the plan an collect only ready nodes (i.e nodes with WaitOnParentsCount = 0)
// Add ready action nodes to the action Q
// Add ready goal nodes to the goal Q
while(!Q.empty())
{
currNodeId = Q.front();
Q.pop();
if (!m_pOlcbpPlan->Contains(currNodeId))
{
LogWarning("A non existing node was there in the update queue, skipping it");
continue;
}
for (auto childNodeId : m_pOlcbpPlan->GetAdjacentNodes(currNodeId))
{
if (visitedNodes.count(childNodeId) == 0)
{
if (IsNodeReady(childNodeId))
{
if (IsGoalNode(childNodeId))
{
goalQ.push(childNodeId);
}
else if (IsActionNode(childNodeId))
{
actionQ.push(childNodeId);
}
Q.push(childNodeId);
}
visitedNodes.insert(childNodeId);
}
}
}
}
//////////////////////////////////////////////////////////////////////////
void OnlinePlanExpansionExecution::UpdateGoalNode(_In_ IOlcbpPlan::NodeID currentNode, _In_ const WorldClock& clock)
{
GoalEx* pCurrentGoalNode = (GoalEx*)m_pOlcbpPlan->GetNode(currentNode);
// fast return if node state reached a final state (i.e succeeded or failed)
_ASSERTE(!IsNodeDone(currentNode));
#pragma region Node Open
if (IsNodeOpen(currentNode))
{
_ASSERTE(pCurrentGoalNode->State() == ESTATE_NotPrepared);
_ASSERTE(IsNodeDone(currentNode) == false);
bool hasPreviousPlan = DestroyGoalSnippetIfExist(currentNode);
// The goal was previously expanded with a plan, but it somehow failed
// Thats why it is now open
// Revise the node belonging case as failed case
if (hasPreviousPlan)
{
LogInfo("Node with plan-step '%s' is open and has children nodes, case is sent for revision and children have been destroyed", pCurrentGoalNode->ToString().c_str());
CaseEx* currentCase = GetLastCaseForGoalNode(currentNode);
m_pCbReasoner->Reviser()->Revise(currentCase, false);
UpdateHistory(currentCase);
m_pCbReasoner->Retainer()->Retain(currentCase);
}
if (pCurrentGoalNode->SuccessConditionsSatisfied(*g_Game))
{
LogInfo("Goal %s already satisfied, no need to expand it, closing the node", pCurrentGoalNode->ToString().c_str());
pCurrentGoalNode->State(ESTATE_Succeeded, *g_Game, clock);
CloseNode(currentNode);
OnGoalNodeSucceeded(currentNode);
}
else
{
CaseSet exclusions = GetNodeData(currentNode).TriedCases;
IOlcbpPlan::NodeID satisfyingGoalNode = GetNodeData(currentNode).SatisfyingGoal;
if (satisfyingGoalNode != IOlcbpPlan::NullNodeID)
{
LogInfo("Excluding satisfying goal node %s to avoid recursive plan expansion", m_pOlcbpPlan->GetNode(satisfyingGoalNode)->ToString().c_str());
// Add belonging case to exclusion to avoid recursive expansion of plans
_ASSERTE(GetNodeData(satisfyingGoalNode).BelongingCase != nullptr);
exclusions.insert(GetNodeData(satisfyingGoalNode).BelongingCase);
}
pCurrentGoalNode->AdaptParameters(*g_Game);
AbstractRetriever::RetrieveOptions options;
options.GoalTypeId = (GoalType)pCurrentGoalNode->StepTypeId();
options.pGameState = g_Game;
options.ExcludedCases = exclusions;
for (auto pCase : exclusions)
options.ExcludedGoalHashes.insert(pCase->Goal()->Hash());
options.Parameters = pCurrentGoalNode->Parameters();
CaseEx* pCandidateCase = m_pCbReasoner->Retriever()->Retrieve(options);
// We found a matching case and it was not tried for that goal before
if (pCandidateCase != nullptr)
{
// Retriever should always retrieve a non tried case for that specific node
_ASSERTE(!IsCaseTried(currentNode, pCandidateCase));
LogInfo("Retrieved case '%s' has not been tried before, and its goal is being sent for expansion",
pCandidateCase->Goal()->ToString().c_str());
MarkCaseAsTried(currentNode, pCandidateCase);
ExpandGoal(currentNode, pCandidateCase);
}
else
{
// The current failed goal node is the root goal and the planner exhausted all possible
// plans form the case-base for that goal node and nothing succeeded so far
//
// WE SURRENDER!!
//
if (m_planRootNodeId == currentNode)
{
LogWarning("Planner has exhausted all possible cases, WE SURRENDER!!");
m_planRootNodeId = IOlcbpPlan::NullNodeID;
}
else
{
LogInfo("Goal=%s exhausted all possible cases, failing it", pCurrentGoalNode->ToString().c_str());
pCurrentGoalNode->State(ESTATE_Failed, *g_Game, clock);
CloseNode(currentNode);
OnGoalNodeFailed(currentNode);
}
}
}
}
#pragma endregion
#pragma region Node Closed
else
{
_ASSERTE(pCurrentGoalNode->State() == ESTATE_NotPrepared);
if (pCurrentGoalNode->SuccessConditionsSatisfied(*g_Game))
{
pCurrentGoalNode->State(ESTATE_Succeeded, *g_Game, clock);
OnGoalNodeSucceeded(currentNode);
}
else
{
// The goal is not done yet, and all of its children are done and
// finished execution. It does not make sense for the goal to continue
// this goal should fail, it has no future
if (GetNodeData(currentNode).WaitOnChildrenCount == 0)
{
LogInfo("Goal '%s' is still not done and all of its children are done execution, failing it",
pCurrentGoalNode->ToString().c_str());
OpenNode(currentNode);
}
}
}
#pragma endregion
}
//////////////////////////////////////////////////////////////////////////
void IStrategizer::OnlinePlanExpansionExecution::UpdateActionNode(_In_ IOlcbpPlan::NodeID currentNode, _In_ const WorldClock& clock)
{
PlanStepEx *pCurrentPlanStep = m_pOlcbpPlan->GetNode(currentNode);
_ASSERTE(IsNodeReady(currentNode));
if (!IsNodeDone(currentNode))
{
_ASSERTE(pCurrentPlanStep->State() == ESTATE_NotPrepared ||
pCurrentPlanStep->State() == ESTATE_Executing ||
pCurrentPlanStep->State() == ESTATE_END);
pCurrentPlanStep->Update(*g_Game, clock);
if (pCurrentPlanStep->State() == ESTATE_Succeeded)
{
OnActionNodeSucceeded(currentNode);
}
else if (pCurrentPlanStep->State() == ESTATE_Failed)
{
OnActionNodeFailed(currentNode);
}
}
}<commit_msg>Planner exclude only goal direct parent by hash instead of all excluded cases goals<commit_after>#include "OnlinePlanExpansionExecution.h"
#include "CaseBasedReasonerEx.h"
#include "WinGameGoal.h"
#include "CaseEx.h"
#include "RtsGame.h"
#include "Action.h"
#include "MessagePump.h"
#include "Message.h"
#include <crtdbg.h>
#include "AbstractReviser.h"
#include "AbstractRetriever.h"
#include "GamePlayer.h"
#include "Toolbox.h"
#include "Logger.h"
#include "RetainerEx.h"
#include "DataMessage.h"
#include "GoalFactory.h"
using namespace std;
using namespace IStrategizer;
//////////////////////////////////////////////////////////////////////////
void OnlinePlanExpansionExecution::Update(_In_ const WorldClock& clock)
{
m_pOlcbpPlan->Lock();
// We have exhausted all possible plans. We have surrendered, nothing to do
if (m_pOlcbpPlan->Size() > 0)
{
IOlcbpPlan::NodeQueue actionQ;
IOlcbpPlan::NodeQueue goalQ;
typedef unsigned GoalKey;
map<GoalKey, IOlcbpPlan::NodeID> goalTable;
// 1st pass: get ready nodes only
GetReachableReadyNodes(actionQ, goalQ);
// 2nd pass: prioritize and filter goal updates
while (!goalQ.empty())
{
GoalEx* pCurrGoal = (GoalEx*)m_pOlcbpPlan->GetNode(goalQ.front());
GoalKey typeKey = pCurrGoal->Key();
if (!IsNodeDone(goalQ.front()))
{
goalTable[typeKey] = goalQ.front();
}
goalQ.pop();
}
// 3rd pass: actual node update
for (auto goalEntry : goalTable)
{
// Only update a goal node if it still exist
// It is normal that a previous updated goal node during this pass
// failed and its snippet was destroyed, and as a result a node that
// was considered for update does not exist anymore
if (m_pOlcbpPlan->Contains(goalEntry.second))
UpdateGoalNode(goalEntry.second, clock);
}
while (!actionQ.empty())
{
// Only update an action node if it still exist
// What applies to a goal in the 3rd pass apply here
if (m_pOlcbpPlan->Contains(actionQ.front()))
UpdateActionNode(actionQ.front(), clock);
actionQ.pop();
}
}
m_pOlcbpPlan->Unlock();
if (m_planStructureChangedThisFrame)
{
g_MessagePump.Send(new DataMessage<IOlcbpPlan>(0, MSG_PlanStructureChange, nullptr));
m_planStructureChangedThisFrame = false;
}
}
//////////////////////////////////////////////////////////////////////////
void OnlinePlanExpansionExecution::GetReachableReadyNodes(_Out_ IOlcbpPlan::NodeQueue& actionQ, _Out_ IOlcbpPlan::NodeQueue& goalQ)
{
IOlcbpPlan::NodeQueue Q;
IOlcbpPlan::NodeID currNodeId;
IOlcbpPlan::NodeSerializedSet planRoots;
IOlcbpPlan::NodeSet visitedNodes;
_ASSERTE(m_planRootNodeId != IOlcbpPlan::NullNodeID);
Q.push(m_planRootNodeId);
visitedNodes.insert(m_planRootNodeId);
goalQ.push(m_planRootNodeId);
// Do a BFS on the plan an collect only ready nodes (i.e nodes with WaitOnParentsCount = 0)
// Add ready action nodes to the action Q
// Add ready goal nodes to the goal Q
while(!Q.empty())
{
currNodeId = Q.front();
Q.pop();
if (!m_pOlcbpPlan->Contains(currNodeId))
{
LogWarning("A non existing node was there in the update queue, skipping it");
continue;
}
for (auto childNodeId : m_pOlcbpPlan->GetAdjacentNodes(currNodeId))
{
if (visitedNodes.count(childNodeId) == 0)
{
if (IsNodeReady(childNodeId))
{
if (IsGoalNode(childNodeId))
{
goalQ.push(childNodeId);
}
else if (IsActionNode(childNodeId))
{
actionQ.push(childNodeId);
}
Q.push(childNodeId);
}
visitedNodes.insert(childNodeId);
}
}
}
}
//////////////////////////////////////////////////////////////////////////
void OnlinePlanExpansionExecution::UpdateGoalNode(_In_ IOlcbpPlan::NodeID currentNode, _In_ const WorldClock& clock)
{
GoalEx* pCurrentGoalNode = (GoalEx*)m_pOlcbpPlan->GetNode(currentNode);
// fast return if node state reached a final state (i.e succeeded or failed)
_ASSERTE(!IsNodeDone(currentNode));
#pragma region Node Open
if (IsNodeOpen(currentNode))
{
_ASSERTE(pCurrentGoalNode->State() == ESTATE_NotPrepared);
_ASSERTE(IsNodeDone(currentNode) == false);
bool hasPreviousPlan = DestroyGoalSnippetIfExist(currentNode);
// The goal was previously expanded with a plan, but it somehow failed
// Thats why it is now open
// Revise the node belonging case as failed case
if (hasPreviousPlan)
{
LogInfo("Node with plan-step '%s' is open and has children nodes, case is sent for revision and children have been destroyed", pCurrentGoalNode->ToString().c_str());
CaseEx* currentCase = GetLastCaseForGoalNode(currentNode);
m_pCbReasoner->Reviser()->Revise(currentCase, false);
UpdateHistory(currentCase);
m_pCbReasoner->Retainer()->Retain(currentCase);
}
if (pCurrentGoalNode->SuccessConditionsSatisfied(*g_Game))
{
LogInfo("Goal %s already satisfied, no need to expand it, closing the node", pCurrentGoalNode->ToString().c_str());
pCurrentGoalNode->State(ESTATE_Succeeded, *g_Game, clock);
CloseNode(currentNode);
OnGoalNodeSucceeded(currentNode);
}
else
{
IOlcbpPlan::NodeID satisfyingGoalNode = GetNodeData(currentNode).SatisfyingGoal;
AbstractRetriever::RetrieveOptions options;
options.ExcludedCases = GetNodeData(currentNode).TriedCases;
if (satisfyingGoalNode != IOlcbpPlan::NullNodeID)
{
LogInfo("Excluding satisfying goal node %s to avoid recursive plan expansion", m_pOlcbpPlan->GetNode(satisfyingGoalNode)->ToString().c_str());
// Add belonging case to exclusion to avoid recursive expansion of plans
_ASSERTE(GetNodeData(satisfyingGoalNode).BelongingCase != nullptr);
options.ExcludedGoalHashes.insert(GetNodeData(satisfyingGoalNode).BelongingCase->Goal()->Hash());
}
pCurrentGoalNode->AdaptParameters(*g_Game);
options.GoalTypeId = (GoalType)pCurrentGoalNode->StepTypeId();
options.pGameState = g_Game;
options.Parameters = pCurrentGoalNode->Parameters();
CaseEx* pCandidateCase = m_pCbReasoner->Retriever()->Retrieve(options);
// We found a matching case and it was not tried for that goal before
if (pCandidateCase != nullptr)
{
// Retriever should always retrieve a non tried case for that specific node
_ASSERTE(!IsCaseTried(currentNode, pCandidateCase));
LogInfo("Retrieved case '%s' has not been tried before, and its goal is being sent for expansion",
pCandidateCase->Goal()->ToString().c_str());
MarkCaseAsTried(currentNode, pCandidateCase);
ExpandGoal(currentNode, pCandidateCase);
}
else
{
// The current failed goal node is the root goal and the planner exhausted all possible
// plans form the case-base for that goal node and nothing succeeded so far
//
// WE SURRENDER!!
//
if (m_planRootNodeId == currentNode)
{
LogWarning("Planner has exhausted all possible cases, WE SURRENDER!!");
m_planRootNodeId = IOlcbpPlan::NullNodeID;
}
else
{
LogInfo("Goal=%s exhausted all possible cases, failing it", pCurrentGoalNode->ToString().c_str());
pCurrentGoalNode->State(ESTATE_Failed, *g_Game, clock);
CloseNode(currentNode);
OnGoalNodeFailed(currentNode);
}
}
}
}
#pragma endregion
#pragma region Node Closed
else
{
_ASSERTE(pCurrentGoalNode->State() == ESTATE_NotPrepared);
if (pCurrentGoalNode->SuccessConditionsSatisfied(*g_Game))
{
pCurrentGoalNode->State(ESTATE_Succeeded, *g_Game, clock);
OnGoalNodeSucceeded(currentNode);
}
else
{
// The goal is not done yet, and all of its children are done and
// finished execution. It does not make sense for the goal to continue
// this goal should fail, it has no future
if (GetNodeData(currentNode).WaitOnChildrenCount == 0)
{
LogInfo("Goal '%s' is still not done and all of its children are done execution, failing it",
pCurrentGoalNode->ToString().c_str());
OpenNode(currentNode);
}
}
}
#pragma endregion
}
//////////////////////////////////////////////////////////////////////////
void IStrategizer::OnlinePlanExpansionExecution::UpdateActionNode(_In_ IOlcbpPlan::NodeID currentNode, _In_ const WorldClock& clock)
{
PlanStepEx *pCurrentPlanStep = m_pOlcbpPlan->GetNode(currentNode);
_ASSERTE(IsNodeReady(currentNode));
if (!IsNodeDone(currentNode))
{
_ASSERTE(pCurrentPlanStep->State() == ESTATE_NotPrepared ||
pCurrentPlanStep->State() == ESTATE_Executing ||
pCurrentPlanStep->State() == ESTATE_END);
pCurrentPlanStep->Update(*g_Game, clock);
if (pCurrentPlanStep->State() == ESTATE_Succeeded)
{
OnActionNodeSucceeded(currentNode);
}
else if (pCurrentPlanStep->State() == ESTATE_Failed)
{
OnActionNodeFailed(currentNode);
}
}
}<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dp_resource.cxx,v $
*
* $Revision: 1.17 $
*
* last change: $Author: ihi $ $Date: 2007-11-22 15:04:37 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_desktop.hxx"
#include "dp_misc.h"
#include "dp_resource.h"
#include "osl/module.hxx"
#include "osl/mutex.hxx"
#include "rtl/ustring.h"
#include "cppuhelper/implbase1.hxx"
#include "unotools/configmgr.hxx"
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using ::rtl::OUString;
namespace dp_misc {
namespace {
struct OfficeLocale :
public rtl::StaticWithInit<const OUString, OfficeLocale> {
const OUString operator () () {
OUString slang;
if (! (::utl::ConfigManager::GetDirectConfigProperty(
::utl::ConfigManager::LOCALE ) >>= slang))
throw RuntimeException( OUSTR("Cannot determine language!"), 0 );
//fallback, the locale is currently only set when the user starts the
//office for the first time.
if (slang.getLength() == 0)
slang = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("en-US"));
return slang;
}
};
struct DeploymentResMgr : public rtl::StaticWithInit<
ResMgr *, DeploymentResMgr> {
ResMgr * operator () () {
return ResMgr::CreateResMgr( "deployment" LIBRARY_SOLARUPD(),
getOfficeLocale() );
}
};
osl::Mutex s_mutex;
} // anon namespace
//==============================================================================
ResId getResId( USHORT id )
{
const osl::MutexGuard guard( s_mutex );
return ResId( id, *DeploymentResMgr::get() );
}
//==============================================================================
String getResourceString( USHORT id )
{
const osl::MutexGuard guard( s_mutex );
String ret( ResId( id, *DeploymentResMgr::get() ) );
if (ret.SearchAscii( "%PRODUCTNAME" ) != STRING_NOTFOUND) {
static String s_brandName;
if (s_brandName.Len() == 0) {
OUString brandName(
::utl::ConfigManager::GetDirectConfigProperty(
::utl::ConfigManager::PRODUCTNAME ).get<OUString>() );
s_brandName = brandName;
}
ret.SearchAndReplaceAllAscii( "%PRODUCTNAME", s_brandName );
}
return ret;
}
//throws an Exception on failure
//primary subtag 2 or three letters(A-Z, a-z), i or x
void checkPrimarySubtag(::rtl::OUString const & tag)
{
sal_Int32 len = tag.getLength();
sal_Unicode const * arLang = tag.getStr();
if (len < 1 || len > 3)
throw Exception(OUSTR("Invalid language string."), 0);
if (len == 1
&& (arLang[0] != 'i' && arLang[0] != 'x'))
throw Exception(OUSTR("Invalid language string."), 0);
if (len == 2 || len == 3)
{
for (sal_Int32 i = 0; i < len; i++)
{
if ( !((arLang[i] >= 'A' && arLang[i] <= 'Z')
|| (arLang[i] >= 'a' && arLang[i] <= 'z')))
{
throw Exception(OUSTR("Invalid language string."), 0);
}
}
}
}
//throws an Exception on failure
//second subtag 2 letter country code or 3-8 letter other code(A-Z, a-z, 0-9)
void checkSecondSubtag(::rtl::OUString const & tag, bool & bIsCountry)
{
sal_Int32 len = tag.getLength();
sal_Unicode const * arLang = tag.getStr();
if (len < 2 || len > 8)
throw Exception(OUSTR("Invalid language string."), 0);
//country code
bIsCountry = false;
if (len == 2)
{
for (sal_Int32 i = 0; i < 2; i++)
{
if (!( (arLang[i] >= 'A' && arLang[i] <= 'Z')
|| (arLang[i] >= 'a' && arLang[i] <= 'z')))
{
throw Exception(OUSTR("Invalid language string."), 0);
}
}
bIsCountry = true;
}
if (len > 2)
{
for (sal_Int32 i = 0; i < len; i++)
{
if (!( (arLang[i] >= 'A' && arLang[i] <= 'Z')
|| (arLang[i] >= 'a' && arLang[i] <= 'z')
|| (arLang[i] >= '0' && arLang[i] <= '9') ))
{
throw Exception(OUSTR("Invalid language string."), 0);
}
}
}
}
void checkThirdSubtag(::rtl::OUString const & tag)
{
sal_Int32 len = tag.getLength();
sal_Unicode const * arLang = tag.getStr();
if (len < 1 || len > 8)
throw Exception(OUSTR("Invalid language string."), 0);
for (sal_Int32 i = 0; i < len; i++)
{
if (!( (arLang[i] >= 'A' && arLang[i] <= 'Z')
|| (arLang[i] >= 'a' && arLang[i] <= 'z')
|| (arLang[i] >= '0' && arLang[i] <= '9') ))
{
throw Exception(OUSTR("Invalid language string."), 0);
}
}
}
//=============================================================================
//We parse the string acording to RFC 3066
//We only use the primary sub-tag and two subtags. That is lang-country-variant
//We do some simple tests if the string is correct. Actually this should do a
//validating parser
//We may have the case that there is no country tag, for example en-welsh
::com::sun::star::lang::Locale toLocale( ::rtl::OUString const & slang )
{
OUString _sLang = slang.trim();
::com::sun::star::lang::Locale locale;
sal_Int32 nIndex = 0;
OUString lang = _sLang.getToken( 0, '-', nIndex );
checkPrimarySubtag(lang);
locale.Language = lang;
OUString country = _sLang.getToken( 0, '-', nIndex );
if (country.getLength() > 0)
{
bool bIsCountry = false;
checkSecondSubtag(country, bIsCountry);
if (bIsCountry)
{
locale.Country = country;
}
else
{
locale.Variant = country;
}
}
if (locale.Variant.getLength() == 0)
{
OUString variant = _sLang.getToken( 0, '-', nIndex );
if (variant.getLength() > 0)
{
checkThirdSubtag(variant);
locale.Variant = variant;
}
}
return locale;
}
//==============================================================================
lang::Locale getOfficeLocale()
{
return toLocale(OfficeLocale::get());
}
::rtl::OUString getOfficeLocaleString()
{
return OfficeLocale::get();
}
}
<commit_msg>INTEGRATION: CWS supdremove02 (1.17.54); FILE MERGED 2008/01/31 13:50:06 rt 1.17.54.1: #i85482# Remove UPD from resource name.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dp_resource.cxx,v $
*
* $Revision: 1.18 $
*
* last change: $Author: obo $ $Date: 2008-02-25 16:48:39 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_desktop.hxx"
#include "dp_misc.h"
#include "dp_resource.h"
#include "osl/module.hxx"
#include "osl/mutex.hxx"
#include "rtl/ustring.h"
#include "cppuhelper/implbase1.hxx"
#include "unotools/configmgr.hxx"
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using ::rtl::OUString;
namespace dp_misc {
namespace {
struct OfficeLocale :
public rtl::StaticWithInit<const OUString, OfficeLocale> {
const OUString operator () () {
OUString slang;
if (! (::utl::ConfigManager::GetDirectConfigProperty(
::utl::ConfigManager::LOCALE ) >>= slang))
throw RuntimeException( OUSTR("Cannot determine language!"), 0 );
//fallback, the locale is currently only set when the user starts the
//office for the first time.
if (slang.getLength() == 0)
slang = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("en-US"));
return slang;
}
};
struct DeploymentResMgr : public rtl::StaticWithInit<
ResMgr *, DeploymentResMgr> {
ResMgr * operator () () {
return ResMgr::CreateResMgr( "deployment", getOfficeLocale() );
}
};
osl::Mutex s_mutex;
} // anon namespace
//==============================================================================
ResId getResId( USHORT id )
{
const osl::MutexGuard guard( s_mutex );
return ResId( id, *DeploymentResMgr::get() );
}
//==============================================================================
String getResourceString( USHORT id )
{
const osl::MutexGuard guard( s_mutex );
String ret( ResId( id, *DeploymentResMgr::get() ) );
if (ret.SearchAscii( "%PRODUCTNAME" ) != STRING_NOTFOUND) {
static String s_brandName;
if (s_brandName.Len() == 0) {
OUString brandName(
::utl::ConfigManager::GetDirectConfigProperty(
::utl::ConfigManager::PRODUCTNAME ).get<OUString>() );
s_brandName = brandName;
}
ret.SearchAndReplaceAllAscii( "%PRODUCTNAME", s_brandName );
}
return ret;
}
//throws an Exception on failure
//primary subtag 2 or three letters(A-Z, a-z), i or x
void checkPrimarySubtag(::rtl::OUString const & tag)
{
sal_Int32 len = tag.getLength();
sal_Unicode const * arLang = tag.getStr();
if (len < 1 || len > 3)
throw Exception(OUSTR("Invalid language string."), 0);
if (len == 1
&& (arLang[0] != 'i' && arLang[0] != 'x'))
throw Exception(OUSTR("Invalid language string."), 0);
if (len == 2 || len == 3)
{
for (sal_Int32 i = 0; i < len; i++)
{
if ( !((arLang[i] >= 'A' && arLang[i] <= 'Z')
|| (arLang[i] >= 'a' && arLang[i] <= 'z')))
{
throw Exception(OUSTR("Invalid language string."), 0);
}
}
}
}
//throws an Exception on failure
//second subtag 2 letter country code or 3-8 letter other code(A-Z, a-z, 0-9)
void checkSecondSubtag(::rtl::OUString const & tag, bool & bIsCountry)
{
sal_Int32 len = tag.getLength();
sal_Unicode const * arLang = tag.getStr();
if (len < 2 || len > 8)
throw Exception(OUSTR("Invalid language string."), 0);
//country code
bIsCountry = false;
if (len == 2)
{
for (sal_Int32 i = 0; i < 2; i++)
{
if (!( (arLang[i] >= 'A' && arLang[i] <= 'Z')
|| (arLang[i] >= 'a' && arLang[i] <= 'z')))
{
throw Exception(OUSTR("Invalid language string."), 0);
}
}
bIsCountry = true;
}
if (len > 2)
{
for (sal_Int32 i = 0; i < len; i++)
{
if (!( (arLang[i] >= 'A' && arLang[i] <= 'Z')
|| (arLang[i] >= 'a' && arLang[i] <= 'z')
|| (arLang[i] >= '0' && arLang[i] <= '9') ))
{
throw Exception(OUSTR("Invalid language string."), 0);
}
}
}
}
void checkThirdSubtag(::rtl::OUString const & tag)
{
sal_Int32 len = tag.getLength();
sal_Unicode const * arLang = tag.getStr();
if (len < 1 || len > 8)
throw Exception(OUSTR("Invalid language string."), 0);
for (sal_Int32 i = 0; i < len; i++)
{
if (!( (arLang[i] >= 'A' && arLang[i] <= 'Z')
|| (arLang[i] >= 'a' && arLang[i] <= 'z')
|| (arLang[i] >= '0' && arLang[i] <= '9') ))
{
throw Exception(OUSTR("Invalid language string."), 0);
}
}
}
//=============================================================================
//We parse the string acording to RFC 3066
//We only use the primary sub-tag and two subtags. That is lang-country-variant
//We do some simple tests if the string is correct. Actually this should do a
//validating parser
//We may have the case that there is no country tag, for example en-welsh
::com::sun::star::lang::Locale toLocale( ::rtl::OUString const & slang )
{
OUString _sLang = slang.trim();
::com::sun::star::lang::Locale locale;
sal_Int32 nIndex = 0;
OUString lang = _sLang.getToken( 0, '-', nIndex );
checkPrimarySubtag(lang);
locale.Language = lang;
OUString country = _sLang.getToken( 0, '-', nIndex );
if (country.getLength() > 0)
{
bool bIsCountry = false;
checkSecondSubtag(country, bIsCountry);
if (bIsCountry)
{
locale.Country = country;
}
else
{
locale.Variant = country;
}
}
if (locale.Variant.getLength() == 0)
{
OUString variant = _sLang.getToken( 0, '-', nIndex );
if (variant.getLength() > 0)
{
checkThirdSubtag(variant);
locale.Variant = variant;
}
}
return locale;
}
//==============================================================================
lang::Locale getOfficeLocale()
{
return toLocale(OfficeLocale::get());
}
::rtl::OUString getOfficeLocaleString()
{
return OfficeLocale::get();
}
}
<|endoftext|>
|
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/*
$Log$
Revision 1.2 2001/08/30 09:48:12 hristov
The operator[] is replaced by At() or AddAt() in case of TObjArray.
Revision 1.1 2001/07/25 17:28:32 morsch
LHC related code. First commit.
*/
#include "AliLHC.h"
#include "AliLhcIRegion.h"
#include "AliLhcProcess.h"
#include "AliLhcBeam.h"
ClassImp(AliLHC)
AliLHC::AliLHC()
{
// Constructor
fIRegions = new TList;
fProcesses = new TList;
fNRegions = 0;
fNProcesses = 0;
fBeams = new TObjArray(2);
//PH (*fBeams)[0] = 0;
//PH (*fBeams)[1] = 0;
fBeams->AddAt(0,0);
fBeams->AddAt(0,1);
fTime = 0;
fTimeMax = 0;
fTimeA = 0;
}
AliLHC::AliLHC(const AliLHC& lhc)
{
// copy constructor
}
AliLHC::~AliLHC()
{
// Destructor
delete fIRegions;
delete fProcesses;
delete fBeams;
}
void AliLHC::AddIRegion(AliLhcIRegion *region)
{
//
// Add region to list
fIRegions->Add(region);
fNRegions++;
}
void AliLHC::AddProcess(AliLhcProcess *process)
{
//
// Add process to list
fProcesses->Add(process);
fNProcesses++;
}
void AliLHC::SetBeams(AliLhcBeam *beam1, AliLhcBeam *beam2 )
{
//
// Set the beams
(*fBeams)[0] = beam1;
(*fBeams)[1] = beam2;
}
void AliLHC::Init()
{
// Initialisation
fNt = 0;
fNmax = Int_t(fTimeMax/fTimeStep);
fTimeA = new Float_t[fNmax];
//
Beam(0)->Init();
Beam(1)->Init();
TIter next(fIRegions);
AliLhcIRegion *region;
//
// Loop over generators and initialize
while((region = (AliLhcIRegion*)next())) {
region->Init();
region->SetMonitor(fNmax);
}
Beam(0)->SetMonitor(fNmax);
Beam(1)->SetMonitor(fNmax);
TIter nextp(fProcesses);
AliLhcProcess *process;
//
// Loop over generators and initialize
while((process = (AliLhcProcess*)nextp())) {
process->Init();
process->SetMonitor(fNmax);
}
}
void AliLHC::EvolveTime()
{
//
// Simulate Time Evolution
//
while (fTime <= fTimeMax) {
printf("\n Time: %f %f", fTime, fTimeStep);
//
// Processes
//
TIter next(fProcesses);
AliLhcProcess *process;
//
// Evolve for each process
while((process = (AliLhcProcess*)next())) {
process->Evolve(fTimeStep);
process->Record();
}
//
// Update and Monitoring
//
TIter nextregion(fIRegions);
AliLhcIRegion *region;
//
while((region = (AliLhcIRegion*)nextregion())) {
printf("\n Region: %s, Luminosity %10.3e",
region->GetName(), region->Luminosity());
region->Update();
region->Record();
}
Beam(0)->Record();
fTimeA[fNt] = fTime/3600.;
fTime+=fTimeStep;
fNt++;
}
}
void AliLHC::Evaluate()
{
// Evaluation of the results
TIter nextregion(fIRegions);
AliLhcIRegion *region;
//
// Loop over generators and initialize
while((region = (AliLhcIRegion*)nextregion())) {
region->Draw();
}
TIter next(fProcesses);
AliLhcProcess *process;
//
// Evolve for each process
while((process = (AliLhcProcess*)next())) {
process->Draw();
}
Beam(0)->Draw();
}
AliLHC& AliLHC::operator=(const AliLHC & rhs)
{
// Assignment operator
return *this;
}
<commit_msg>DrawPlots() instead of Draw().<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/*
$Log$
Revision 1.3 2001/10/21 18:35:19 hristov
A pointer was set to zero in the default constructor to avoid memory management problems
Revision 1.2 2001/08/30 09:48:12 hristov
The operator[] is replaced by At() or AddAt() in case of TObjArray.
Revision 1.1 2001/07/25 17:28:32 morsch
LHC related code. First commit.
*/
#include "AliLHC.h"
#include "AliLhcIRegion.h"
#include "AliLhcProcess.h"
#include "AliLhcBeam.h"
ClassImp(AliLHC)
AliLHC::AliLHC()
{
// Constructor
fIRegions = new TList;
fProcesses = new TList;
fNRegions = 0;
fNProcesses = 0;
fBeams = new TObjArray(2);
//PH (*fBeams)[0] = 0;
//PH (*fBeams)[1] = 0;
fBeams->AddAt(0,0);
fBeams->AddAt(0,1);
fTime = 0;
fTimeMax = 0;
fTimeA = 0;
}
AliLHC::AliLHC(const AliLHC& lhc)
{
// copy constructor
}
AliLHC::~AliLHC()
{
// Destructor
delete fIRegions;
delete fProcesses;
delete fBeams;
}
void AliLHC::AddIRegion(AliLhcIRegion *region)
{
//
// Add region to list
fIRegions->Add(region);
fNRegions++;
}
void AliLHC::AddProcess(AliLhcProcess *process)
{
//
// Add process to list
fProcesses->Add(process);
fNProcesses++;
}
void AliLHC::SetBeams(AliLhcBeam *beam1, AliLhcBeam *beam2 )
{
//
// Set the beams
(*fBeams)[0] = beam1;
(*fBeams)[1] = beam2;
}
void AliLHC::Init()
{
// Initialisation
fNt = 0;
fNmax = Int_t(fTimeMax/fTimeStep);
fTimeA = new Float_t[fNmax];
//
Beam(0)->Init();
Beam(1)->Init();
TIter next(fIRegions);
AliLhcIRegion *region;
//
// Loop over generators and initialize
while((region = (AliLhcIRegion*)next())) {
region->Init();
region->SetMonitor(fNmax);
}
Beam(0)->SetMonitor(fNmax);
Beam(1)->SetMonitor(fNmax);
TIter nextp(fProcesses);
AliLhcProcess *process;
//
// Loop over generators and initialize
while((process = (AliLhcProcess*)nextp())) {
process->Init();
process->SetMonitor(fNmax);
}
}
void AliLHC::EvolveTime()
{
//
// Simulate Time Evolution
//
while (fTime <= fTimeMax) {
printf("\n Time: %f %f", fTime, fTimeStep);
//
// Processes
//
TIter next(fProcesses);
AliLhcProcess *process;
//
// Evolve for each process
while((process = (AliLhcProcess*)next())) {
process->Evolve(fTimeStep);
process->Record();
}
//
// Update and Monitoring
//
TIter nextregion(fIRegions);
AliLhcIRegion *region;
//
while((region = (AliLhcIRegion*)nextregion())) {
printf("\n Region: %s, Luminosity %10.3e",
region->GetName(), region->Luminosity());
region->Update();
region->Record();
}
Beam(0)->Record();
fTimeA[fNt] = fTime/3600.;
fTime+=fTimeStep;
fNt++;
}
}
void AliLHC::Evaluate()
{
// Evaluation of the results
TIter nextregion(fIRegions);
AliLhcIRegion *region;
//
// Loop over generators and initialize
while((region = (AliLhcIRegion*)nextregion())) {
region->DrawPlots();
}
TIter next(fProcesses);
AliLhcProcess *process;
//
// Evolve for each process
while((process = (AliLhcProcess*)next())) {
process->DrawPlots();
}
Beam(0)->DrawPlots();
}
AliLHC& AliLHC::operator=(const AliLHC & rhs)
{
// Assignment operator
return *this;
}
<|endoftext|>
|
<commit_before>/* CalendarAkonadiProxy.cc KPilot
**
** Copyright (C) 2008 by Bertjan Broeksema <b.broeksema@kdemail.net>
*/
/*
** This program 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 program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public License
** along with this program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
** MA 02110-1301, USA.
*/
/*
** Bug reports and questions can be sent to kde-pim@kde.org
*/
#include "calendarakonadiproxy.h"
#include "calendarakonadirecord.h"
CalendarAkonadiProxy::CalendarAkonadiProxy( const IDMapping& mapping )
: AkonadiDataProxy( mapping )
{
}
void CalendarAkonadiProxy::addCategory( Record* rec, const QString& category )
{
CalendarAkonadiRecord* tar = static_cast<CalendarAkonadiRecord*>( rec );
tar->addCategory( category );
}
void CalendarAkonadiProxy::setCategory( Record* rec, const QString& category )
{
CalendarAkonadiRecord* tar = static_cast<CalendarAkonadiRecord*>( rec );
tar->addCategory( category );
}
/* ***** Protected methods ***** */
AkonadiRecord* CalendarAkonadiProxy::createAkonadiRecord( const Akonadi::Item& i
, const QDateTime& dt ) const
{
return new CalendarAkonadiRecord( i, dt );
}
AkonadiRecord* CalendarAkonadiProxy::createDeletedAkonadiRecord( const QString& id ) const
{
return new CalendarAkonadiRecord( id );
}
bool CalendarAkonadiProxy::hasValidPayload( const Akonadi::Item& i ) const
{
if( i.hasPayload<IncidencePtr>() )
{
const KCal::Todo* todo = dynamic_cast<const KCal::Todo*>( i.payload<IncidencePtr>().get() );
if( todo )
{
return true;
}
}
return false;
}
<commit_msg>Implemented CalendarAkonadiProxy.<commit_after>/* CalendarAkonadiProxy.cc KPilot
**
** Copyright (C) 2008 by Bertjan Broeksema <b.broeksema@kdemail.net>
*/
/*
** This program 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 program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public License
** along with this program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
** MA 02110-1301, USA.
*/
/*
** Bug reports and questions can be sent to kde-pim@kde.org
*/
#include "calendarakonadiproxy.h"
#include <kcal/event.h>
#include "calendarakonadirecord.h"
CalendarAkonadiProxy::CalendarAkonadiProxy( const IDMapping& mapping )
: AkonadiDataProxy( mapping )
{
}
void CalendarAkonadiProxy::addCategory( Record* rec, const QString& category )
{
CalendarAkonadiRecord* tar = static_cast<CalendarAkonadiRecord*>( rec );
tar->addCategory( category );
}
void CalendarAkonadiProxy::setCategory( Record* rec, const QString& category )
{
CalendarAkonadiRecord* tar = static_cast<CalendarAkonadiRecord*>( rec );
tar->addCategory( category );
}
/* ***** Protected methods ***** */
AkonadiRecord* CalendarAkonadiProxy::createAkonadiRecord( const Akonadi::Item& i
, const QDateTime& dt ) const
{
return new CalendarAkonadiRecord( i, dt );
}
AkonadiRecord* CalendarAkonadiProxy::createDeletedAkonadiRecord( const QString& id ) const
{
return new CalendarAkonadiRecord( id );
}
bool CalendarAkonadiProxy::hasValidPayload( const Akonadi::Item& i ) const
{
if( i.hasPayload<IncidencePtr>() )
{
boost::shared_ptr<KCal::Event> event
= boost::dynamic_pointer_cast<KCal::Event, KCal::Incidence>
(
i.payload<IncidencePtr>()
);
if( event )
{
return true;
}
}
return false;
}
<|endoftext|>
|
<commit_before>#include "UTIL.h"
#include "Cutter.h"
//OXSX libaries
// #include <BinnedPdf.h>
// #include <Rand.h>
// #include <ROOTNtuple.h>
// #include <BinnedNLLH.h>
// #include <GridSearch.h>
// #include <MetropolisHastings.h>
// #include <Minuit.h>
// #include <Histogram.h>
// #include <PdfConverter.h>
// #include <CompositePdf.h>
// #include <Convolution.h>
// #include <Gaussian.h>
// #include <DataSetGenerator.h>
// #include <OXSXDataSet.h>
// #include <BoolCut.h>
// #include <BoxCut.h>
//ROOT libaries
#include <TString.h>
#include <TH1D.h>
#include <TH2D.h>
#include <TStyle.h>
#include <TPaveStats.h>
#include <TAttFill.h>
#include <TGraph2D.h>
#include <TMath.h>
#include <TMultiGraph.h>
#include <TFrame.h>
#include <TGraph.h>
#include <TGraphErrors.h>
#include <TPaveText.h>
#include <TCanvas.h>
#include <TSystemDirectory.h>
#include <TList.h>
#include <THStack.h>
#include <TLegend.h>
#include <TLine.h>
#include <TFile.h>
#include <TNtuple.h>
#include <TPad.h>
//Standard libaries
#include <iomanip>
#include <sstream>
#include <vector>
#include <string>
#include <math.h>
#include <cmath>
#include <iostream>
#include <fstream>
#include <sstream>
#include <numeric>
void Cutter::FillHist(TFile* file,ofstream& outputfile)
{
TTree* Tree = (TTree*) file->Get("output");
Double_t berkeleyAlphaBeta, mcEdepQuenched,posr,mcPosr;
Bool_t Qfit;
Int_t pdg1, pdg2, evIndex;
Int_t parentpdg1,parentpdg2;
Tree->SetBranchAddress("pdg1",&pdg1);
Tree->SetBranchAddress("pdg2",&pdg2);
Tree->SetBranchAddress("parentpdg1",&parentpdg1);
Tree->SetBranchAddress("parentpdg2",&parentpdg2);
Tree->SetBranchAddress("berkeleyAlphaBeta",&berkeleyAlphaBeta);
Tree->SetBranchAddress("mcEdepQuenched",&mcEdepQuenched);
Tree->SetBranchAddress("posr",&posr);
Tree->SetBranchAddress("mcPosr",&mcPosr);
Tree->SetBranchAddress("fitValid",&Qfit);
Tree->SetBranchAddress("evIndex",&evIndex);
Int_t n = (Int_t)Tree->GetEntries();
for( Int_t i =0;i<n;i++){
Tree->GetEntry(i);
if( Qfit && evIndex==0 && mcPosr<radialCut ){
// if( Qfit && evIndex==0 && mcPosr<4000 ){
// if( Qfit && evIndex==0 && mcPosr<6000 ){
BabVsEnergy->Fill(mcEdepQuenched,berkeleyAlphaBeta);
numberOfEntries++;
outputfile<< mcEdepQuenched<<","<<posr<<","<< berkeleyAlphaBeta << std::endl;
}
}
file->Close();
}
void Cutter::FindNEntries(std::string folder, std::string fileStart){
UTIL* util = new UTIL();
std::vector<std::string> FileList= util->glob(folder ,fileStart);
for( int i=0; i<FileList.size(); i++ ){
TFile * file= TFile::Open(FileList[i].c_str());
// std::cout<<"Loaded file "<<FileList[i]<<std::endl;
TTree* Tree = (TTree*) file->Get("output");
Double_t berkeleyAlphaBeta, mcEdepQuenched,posr,mcPosr;
Bool_t Qfit;
Int_t pdg1, pdg2, evIndex;
Int_t parentpdg1,parentpdg2;
Tree->SetBranchAddress("pdg1",&pdg1);
Tree->SetBranchAddress("pdg2",&pdg2);
Tree->SetBranchAddress("parentpdg1",&parentpdg1);
Tree->SetBranchAddress("parentpdg2",&parentpdg2);
Tree->SetBranchAddress("berkeleyAlphaBeta",&berkeleyAlphaBeta);
Tree->SetBranchAddress("mcEdepQuenched",&mcEdepQuenched);
Tree->SetBranchAddress("posr",&posr);
Tree->SetBranchAddress("mcPosr",&mcPosr);
Tree->SetBranchAddress("fitValid",&Qfit);
Tree->SetBranchAddress("evIndex",&evIndex);
Int_t n = (Int_t)Tree->GetEntries();
for( Int_t i =0;i<n;i++){
Tree->GetEntry(i);
if( Qfit && evIndex==0 && mcPosr<radialCut ){
numberOfEntries++;
}
}
file->Close();
}
}
void Cutter::FillHist(TFile* file)
{
TTree* Tree = (TTree*) file->Get("output");
Double_t berkeleyAlphaBeta, mcEdepQuenched,posr,mcPosr;
Bool_t Qfit;
Int_t pdg1, pdg2, evIndex;
Int_t parentpdg1,parentpdg2;
Tree->SetBranchAddress("pdg1",&pdg1);
Tree->SetBranchAddress("pdg2",&pdg2);
Tree->SetBranchAddress("parentpdg1",&parentpdg1);
Tree->SetBranchAddress("parentpdg2",&parentpdg2);
Tree->SetBranchAddress("berkeleyAlphaBeta",&berkeleyAlphaBeta);
Tree->SetBranchAddress("mcEdepQuenched",&mcEdepQuenched);
Tree->SetBranchAddress("posr",&posr);
Tree->SetBranchAddress("mcPosr",&mcPosr);
Tree->SetBranchAddress("fitValid",&Qfit);
Tree->SetBranchAddress("evIndex",&evIndex);
Int_t n = (Int_t)Tree->GetEntries();
for( Int_t i =0;i<n;i++){
Tree->GetEntry(i);
if( Qfit && evIndex==0 && mcPosr<4000 ){
// if( Qfit && evIndex==0 && mcPosr<6000 ){
BabVsEnergy->Fill(mcEdepQuenched,berkeleyAlphaBeta);
numberOfEntries++;
}
}
file->Close();
}
void Cutter::SetHistLimits(double Ebins,double ELow,double EHigh,double BabBins, double BabLow, double BabHigh){
BabVsEnergy = new TH2D("BabVsEnergy","berkeleyAlphaBeta",Ebins,ELow,EHigh,BabBins,BabLow,BabHigh);
if(PID=="alpha"){
BabVsEnergy->SetLineColorAlpha(kRed,0.2);
BabVsEnergy->SetLineWidth(3);
BabVsEnergy->SetMarkerColorAlpha(kRed,0.2);
BabVsEnergy->SetFillColorAlpha(kRed,0.2);
}else if (PID=="beta"){
BabVsEnergy->SetLineColorAlpha(kBlue,0.2);
BabVsEnergy->SetLineWidth(3);
BabVsEnergy->SetMarkerColorAlpha(kBlue,0.2);
BabVsEnergy->SetFillColorAlpha(kBlue,0.2);
}else{
std::cout<<"You need to supply a PID"<<std::endl;
}
BabVsEnergy->SetTitle("BerekelyAlphaBeta across energy");
BabVsEnergy->GetXaxis()->SetTitle("mcEdepQuenched (Mev)");
}
void Cutter::SetHist(){
BabVsEnergy = new TH2D("BabVsEnergy","berkeleyAlphaBeta",25,0,2.5,260,-60,40);
if(PID=="alpha"){
BabVsEnergy->SetLineColorAlpha(kRed,0.2);
BabVsEnergy->SetLineWidth(3);
BabVsEnergy->SetMarkerColorAlpha(kRed,0.2);
BabVsEnergy->SetFillColorAlpha(kRed,0.2);
}else if (PID=="beta"){
BabVsEnergy->SetLineColorAlpha(kBlue,0.2);
BabVsEnergy->SetLineWidth(3);
BabVsEnergy->SetMarkerColorAlpha(kBlue,0.2);
BabVsEnergy->SetFillColorAlpha(kBlue,0.2);
}else{
std::cout<<"You need to supply a PID"<<std::endl;
}
BabVsEnergy->SetTitle("BerekelyAlphaBeta across energy");
BabVsEnergy->GetXaxis()->SetTitle("mcEdepQuenched (Mev)");
}
void Cutter::PrintHist(){
TCanvas * c1= new TCanvas();
c1->cd();
BabVsEnergy->Draw();
c1->Print(Form("plots/BabVsMCEdepQuenched_%s.png",PID.c_str()));
}
TH2D* Cutter::GetHist(){
return BabVsEnergy;
}
void Cutter::ApplyCut(TFile * file){
// numberOfEntries=0;
TTree* Tree = (TTree*) file->Get("output");
Double_t berkeleyAlphaBeta, mcEdepQuenched,posr,mcPosr;
Bool_t Qfit;
Int_t pdg1, pdg2, evIndex;
Int_t parentpdg1,parentpdg2;
Tree->SetBranchAddress("pdg1",&pdg1);
Tree->SetBranchAddress("pdg2",&pdg2);
Tree->SetBranchAddress("parentpdg1",&parentpdg1);
Tree->SetBranchAddress("parentpdg2",&parentpdg2);
Tree->SetBranchAddress("berkeleyAlphaBeta",&berkeleyAlphaBeta);
Tree->SetBranchAddress("mcEdepQuenched",&mcEdepQuenched);
Tree->SetBranchAddress("posr",&posr);
Tree->SetBranchAddress("mcPosr",&mcPosr);
Tree->SetBranchAddress("fitValid",&Qfit);
Tree->SetBranchAddress("evIndex",&evIndex);
Int_t n = (Int_t)Tree->GetEntries();
for( Int_t i =0;i<n;i++){
Tree->GetEntry(i);
if( Qfit && evIndex==0 && mcPosr<radialCut){
// if( Qfit && evIndex==0 && mcPosr<4000 ){
// if( Qfit && evIndex==0 && mcPosr<6000 ){
// numberOfEntries is given in the FillHist method.
if(berkeleyAlphaBeta<(gradient*mcEdepQuenched+intercept)) remainingAfterCut++;
}
}
file->Close();
}
void Cutter::FillCutter(std::string folder, std::string fileStart){
UTIL* util = new UTIL();
// std::vector<std::string> FileList= util->glob("/data/snoplus/liggins/year1/fitting/fitting/alphaSims/output_electron/ntuple","electron");
std::vector<std::string> FileList= util->glob(folder ,fileStart);
for( int i=0; i<FileList.size(); i++ ){
TFile * file= TFile::Open(FileList[i].c_str());
// std::cout<<"Loaded file "<<FileList[i]<<std::endl;
this->FillHist(file);
file->Close();
}
}
void Cutter::FillCutter(std::string folder, std::string fileStart,ofstream& File_bi){
UTIL* util = new UTIL();
std::vector<std::string> FileList= util->glob(folder ,fileStart);
for( int i=0; i<FileList.size(); i++ ){
TFile * file= TFile::Open(FileList[i].c_str());
// std::cout<<"Loaded file "<<FileList[i]<<std::endl;
this->FillHist(file,File_bi);
file->Close();
}
}
void Cutter::ApplyBoundary(std::string folder,std::string fileStart){
UTIL* util = new UTIL();
std::vector<std::string> FileList= util->glob(folder,fileStart);
// remainingAfterCut=0;
for( int i=0; i<FileList.size(); i++ ){
TFile * file= TFile::Open(FileList[i].c_str());
this->ApplyCut(file);
file->Close();
}
}
void Cutter::FindRejection(std::string folder,std::string fileStart){
UTIL* util = new UTIL();
std::vector<std::string> FileList= util->glob(folder,fileStart);
// remainingAfterCut=0;
double minBin=this->GetHist()->GetXaxis()->GetXmin();
double maxBin=this->GetHist()->GetXaxis()->GetXmax();
double sliceWidth=this->GetHist()->GetXaxis()->GetBinWidth(1);
for (double energy = minBin; i <maxBin; energy+=sliceWidth) {
double N=0;
double N_remain=0;
for( int i=0; i<FileList.size(); i++ ){
TFile * file= TFile::Open(FileList[i].c_str());
// this->ApplyCut(file);
TTree* Tree = (TTree*) file->Get("output");
Double_t berkeleyAlphaBeta, mcEdepQuenched,posr,mcPosr;
Bool_t Qfit;
Int_t pdg1, pdg2, evIndex;
Int_t parentpdg1,parentpdg2;
Tree->SetBranchAddress("berkeleyAlphaBeta",&berkeleyAlphaBeta);
Tree->SetBranchAddress("mcEdepQuenched",&mcEdepQuenched);
Tree->SetBranchAddress("posr",&posr);
Tree->SetBranchAddress("mcPosr",&mcPosr);
Tree->SetBranchAddress("fitValid",&Qfit);
Tree->SetBranchAddress("evIndex",&evIndex);
Int_t n = (Int_t)Tree->GetEntries();
for( Int_t i =0;i<n;i++){
Tree->GetEntry(i);
if( Qfit && evIndex==0 && mcPosr<radialCut){
if(energy<mcEdepQuenched && mcEdepQuenched<energy+sliceWidth){
N++;
if(berkeleyAlphaBeta<(gradient*mcEdepQuenched+intercept)) N_remain++;
}
}
}
}//end of file n loop.
file->Close();
rejection->push_back(N/N_remain);
rejection_errors->push_back(N/N_remain*sqrt((N+N_remain)/(N*N_remain)));
}//energy of filelist loop.
for (int i = 0; i < rejection.size(); ++i) {
std::cout<<"rejection = "<<rejection[i]<<" +/- "<<rejection_errors[i]<<std::endl;
}
}
<commit_msg>another Update.<commit_after>#include "UTIL.h"
#include "Cutter.h"
//OXSX libaries
// #include <BinnedPdf.h>
// #include <Rand.h>
// #include <ROOTNtuple.h>
// #include <BinnedNLLH.h>
// #include <GridSearch.h>
// #include <MetropolisHastings.h>
// #include <Minuit.h>
// #include <Histogram.h>
// #include <PdfConverter.h>
// #include <CompositePdf.h>
// #include <Convolution.h>
// #include <Gaussian.h>
// #include <DataSetGenerator.h>
// #include <OXSXDataSet.h>
// #include <BoolCut.h>
// #include <BoxCut.h>
//ROOT libaries
#include <TString.h>
#include <TH1D.h>
#include <TH2D.h>
#include <TStyle.h>
#include <TPaveStats.h>
#include <TAttFill.h>
#include <TGraph2D.h>
#include <TMath.h>
#include <TMultiGraph.h>
#include <TFrame.h>
#include <TGraph.h>
#include <TGraphErrors.h>
#include <TPaveText.h>
#include <TCanvas.h>
#include <TSystemDirectory.h>
#include <TList.h>
#include <THStack.h>
#include <TLegend.h>
#include <TLine.h>
#include <TFile.h>
#include <TNtuple.h>
#include <TPad.h>
//Standard libaries
#include <iomanip>
#include <sstream>
#include <vector>
#include <string>
#include <math.h>
#include <cmath>
#include <iostream>
#include <fstream>
#include <sstream>
#include <numeric>
void Cutter::FillHist(TFile* file,ofstream& outputfile)
{
TTree* Tree = (TTree*) file->Get("output");
Double_t berkeleyAlphaBeta, mcEdepQuenched,posr,mcPosr;
Bool_t Qfit;
Int_t pdg1, pdg2, evIndex;
Int_t parentpdg1,parentpdg2;
Tree->SetBranchAddress("pdg1",&pdg1);
Tree->SetBranchAddress("pdg2",&pdg2);
Tree->SetBranchAddress("parentpdg1",&parentpdg1);
Tree->SetBranchAddress("parentpdg2",&parentpdg2);
Tree->SetBranchAddress("berkeleyAlphaBeta",&berkeleyAlphaBeta);
Tree->SetBranchAddress("mcEdepQuenched",&mcEdepQuenched);
Tree->SetBranchAddress("posr",&posr);
Tree->SetBranchAddress("mcPosr",&mcPosr);
Tree->SetBranchAddress("fitValid",&Qfit);
Tree->SetBranchAddress("evIndex",&evIndex);
Int_t n = (Int_t)Tree->GetEntries();
for( Int_t i =0;i<n;i++){
Tree->GetEntry(i);
if( Qfit && evIndex==0 && mcPosr<radialCut ){
// if( Qfit && evIndex==0 && mcPosr<4000 ){
// if( Qfit && evIndex==0 && mcPosr<6000 ){
BabVsEnergy->Fill(mcEdepQuenched,berkeleyAlphaBeta);
numberOfEntries++;
outputfile<< mcEdepQuenched<<","<<posr<<","<< berkeleyAlphaBeta << std::endl;
}
}
file->Close();
}
void Cutter::FindNEntries(std::string folder, std::string fileStart){
UTIL* util = new UTIL();
std::vector<std::string> FileList= util->glob(folder ,fileStart);
for( int i=0; i<FileList.size(); i++ ){
TFile * file= TFile::Open(FileList[i].c_str());
// std::cout<<"Loaded file "<<FileList[i]<<std::endl;
TTree* Tree = (TTree*) file->Get("output");
Double_t berkeleyAlphaBeta, mcEdepQuenched,posr,mcPosr;
Bool_t Qfit;
Int_t pdg1, pdg2, evIndex;
Int_t parentpdg1,parentpdg2;
Tree->SetBranchAddress("pdg1",&pdg1);
Tree->SetBranchAddress("pdg2",&pdg2);
Tree->SetBranchAddress("parentpdg1",&parentpdg1);
Tree->SetBranchAddress("parentpdg2",&parentpdg2);
Tree->SetBranchAddress("berkeleyAlphaBeta",&berkeleyAlphaBeta);
Tree->SetBranchAddress("mcEdepQuenched",&mcEdepQuenched);
Tree->SetBranchAddress("posr",&posr);
Tree->SetBranchAddress("mcPosr",&mcPosr);
Tree->SetBranchAddress("fitValid",&Qfit);
Tree->SetBranchAddress("evIndex",&evIndex);
Int_t n = (Int_t)Tree->GetEntries();
for( Int_t i =0;i<n;i++){
Tree->GetEntry(i);
if( Qfit && evIndex==0 && mcPosr<radialCut ){
numberOfEntries++;
}
}
file->Close();
}
}
void Cutter::FillHist(TFile* file)
{
TTree* Tree = (TTree*) file->Get("output");
Double_t berkeleyAlphaBeta, mcEdepQuenched,posr,mcPosr;
Bool_t Qfit;
Int_t pdg1, pdg2, evIndex;
Int_t parentpdg1,parentpdg2;
Tree->SetBranchAddress("pdg1",&pdg1);
Tree->SetBranchAddress("pdg2",&pdg2);
Tree->SetBranchAddress("parentpdg1",&parentpdg1);
Tree->SetBranchAddress("parentpdg2",&parentpdg2);
Tree->SetBranchAddress("berkeleyAlphaBeta",&berkeleyAlphaBeta);
Tree->SetBranchAddress("mcEdepQuenched",&mcEdepQuenched);
Tree->SetBranchAddress("posr",&posr);
Tree->SetBranchAddress("mcPosr",&mcPosr);
Tree->SetBranchAddress("fitValid",&Qfit);
Tree->SetBranchAddress("evIndex",&evIndex);
Int_t n = (Int_t)Tree->GetEntries();
for( Int_t i =0;i<n;i++){
Tree->GetEntry(i);
if( Qfit && evIndex==0 && mcPosr<4000 ){
// if( Qfit && evIndex==0 && mcPosr<6000 ){
BabVsEnergy->Fill(mcEdepQuenched,berkeleyAlphaBeta);
numberOfEntries++;
}
}
file->Close();
}
void Cutter::SetHistLimits(double Ebins,double ELow,double EHigh,double BabBins, double BabLow, double BabHigh){
BabVsEnergy = new TH2D("BabVsEnergy","berkeleyAlphaBeta",Ebins,ELow,EHigh,BabBins,BabLow,BabHigh);
if(PID=="alpha"){
BabVsEnergy->SetLineColorAlpha(kRed,0.2);
BabVsEnergy->SetLineWidth(3);
BabVsEnergy->SetMarkerColorAlpha(kRed,0.2);
BabVsEnergy->SetFillColorAlpha(kRed,0.2);
}else if (PID=="beta"){
BabVsEnergy->SetLineColorAlpha(kBlue,0.2);
BabVsEnergy->SetLineWidth(3);
BabVsEnergy->SetMarkerColorAlpha(kBlue,0.2);
BabVsEnergy->SetFillColorAlpha(kBlue,0.2);
}else{
std::cout<<"You need to supply a PID"<<std::endl;
}
BabVsEnergy->SetTitle("BerekelyAlphaBeta across energy");
BabVsEnergy->GetXaxis()->SetTitle("mcEdepQuenched (Mev)");
}
void Cutter::SetHist(){
BabVsEnergy = new TH2D("BabVsEnergy","berkeleyAlphaBeta",25,0,2.5,260,-60,40);
if(PID=="alpha"){
BabVsEnergy->SetLineColorAlpha(kRed,0.2);
BabVsEnergy->SetLineWidth(3);
BabVsEnergy->SetMarkerColorAlpha(kRed,0.2);
BabVsEnergy->SetFillColorAlpha(kRed,0.2);
}else if (PID=="beta"){
BabVsEnergy->SetLineColorAlpha(kBlue,0.2);
BabVsEnergy->SetLineWidth(3);
BabVsEnergy->SetMarkerColorAlpha(kBlue,0.2);
BabVsEnergy->SetFillColorAlpha(kBlue,0.2);
}else{
std::cout<<"You need to supply a PID"<<std::endl;
}
BabVsEnergy->SetTitle("BerekelyAlphaBeta across energy");
BabVsEnergy->GetXaxis()->SetTitle("mcEdepQuenched (Mev)");
}
void Cutter::PrintHist(){
TCanvas * c1= new TCanvas();
c1->cd();
BabVsEnergy->Draw();
c1->Print(Form("plots/BabVsMCEdepQuenched_%s.png",PID.c_str()));
}
TH2D* Cutter::GetHist(){
return BabVsEnergy;
}
void Cutter::ApplyCut(TFile * file){
// numberOfEntries=0;
TTree* Tree = (TTree*) file->Get("output");
Double_t berkeleyAlphaBeta, mcEdepQuenched,posr,mcPosr;
Bool_t Qfit;
Int_t pdg1, pdg2, evIndex;
Int_t parentpdg1,parentpdg2;
Tree->SetBranchAddress("pdg1",&pdg1);
Tree->SetBranchAddress("pdg2",&pdg2);
Tree->SetBranchAddress("parentpdg1",&parentpdg1);
Tree->SetBranchAddress("parentpdg2",&parentpdg2);
Tree->SetBranchAddress("berkeleyAlphaBeta",&berkeleyAlphaBeta);
Tree->SetBranchAddress("mcEdepQuenched",&mcEdepQuenched);
Tree->SetBranchAddress("posr",&posr);
Tree->SetBranchAddress("mcPosr",&mcPosr);
Tree->SetBranchAddress("fitValid",&Qfit);
Tree->SetBranchAddress("evIndex",&evIndex);
Int_t n = (Int_t)Tree->GetEntries();
for( Int_t i =0;i<n;i++){
Tree->GetEntry(i);
if( Qfit && evIndex==0 && mcPosr<radialCut){
// if( Qfit && evIndex==0 && mcPosr<4000 ){
// if( Qfit && evIndex==0 && mcPosr<6000 ){
// numberOfEntries is given in the FillHist method.
if(berkeleyAlphaBeta<(gradient*mcEdepQuenched+intercept)) remainingAfterCut++;
}
}
file->Close();
}
void Cutter::FillCutter(std::string folder, std::string fileStart){
UTIL* util = new UTIL();
// std::vector<std::string> FileList= util->glob("/data/snoplus/liggins/year1/fitting/fitting/alphaSims/output_electron/ntuple","electron");
std::vector<std::string> FileList= util->glob(folder ,fileStart);
for( int i=0; i<FileList.size(); i++ ){
TFile * file= TFile::Open(FileList[i].c_str());
// std::cout<<"Loaded file "<<FileList[i]<<std::endl;
this->FillHist(file);
file->Close();
}
}
void Cutter::FillCutter(std::string folder, std::string fileStart,ofstream& File_bi){
UTIL* util = new UTIL();
std::vector<std::string> FileList= util->glob(folder ,fileStart);
for( int i=0; i<FileList.size(); i++ ){
TFile * file= TFile::Open(FileList[i].c_str());
// std::cout<<"Loaded file "<<FileList[i]<<std::endl;
this->FillHist(file,File_bi);
file->Close();
}
}
void Cutter::ApplyBoundary(std::string folder,std::string fileStart){
UTIL* util = new UTIL();
std::vector<std::string> FileList= util->glob(folder,fileStart);
// remainingAfterCut=0;
for( int i=0; i<FileList.size(); i++ ){
TFile * file= TFile::Open(FileList[i].c_str());
this->ApplyCut(file);
file->Close();
}
}
void Cutter::FindRejection(std::string folder,std::string fileStart){
UTIL* util = new UTIL();
std::vector<std::string> FileList= util->glob(folder,fileStart);
// remainingAfterCut=0;
double minBin=this->GetHist()->GetXaxis()->GetXmin();
double maxBin=this->GetHist()->GetXaxis()->GetXmax();
double sliceWidth=this->GetHist()->GetXaxis()->GetBinWidth(1);
for (double energy = minBin; energy <maxBin; energy+=sliceWidth) {
double N=0;
double N_remain=0;
for( int i=0; i<FileList.size(); i++ ){
TFile * file= TFile::Open(FileList[i].c_str());
// this->ApplyCut(file);
TTree* Tree = (TTree*) file->Get("output");
Double_t berkeleyAlphaBeta, mcEdepQuenched,posr,mcPosr;
Bool_t Qfit;
Int_t pdg1, pdg2, evIndex;
Int_t parentpdg1,parentpdg2;
Tree->SetBranchAddress("berkeleyAlphaBeta",&berkeleyAlphaBeta);
Tree->SetBranchAddress("mcEdepQuenched",&mcEdepQuenched);
Tree->SetBranchAddress("posr",&posr);
Tree->SetBranchAddress("mcPosr",&mcPosr);
Tree->SetBranchAddress("fitValid",&Qfit);
Tree->SetBranchAddress("evIndex",&evIndex);
Int_t n = (Int_t)Tree->GetEntries();
for( Int_t i =0;i<n;i++){
Tree->GetEntry(i);
if( Qfit && evIndex==0 && mcPosr<radialCut){
if(energy<mcEdepQuenched && mcEdepQuenched<energy+sliceWidth){
N++;
if(berkeleyAlphaBeta<(gradient*mcEdepQuenched+intercept)) N_remain++;
}
}
}
file->Close();
}//end of file n loop.
rejection->push_back(N/N_remain);
rejection_errors->push_back(N/N_remain*sqrt((N+N_remain)/(N*N_remain)));
}//energy of filelist loop.
for (int i = 0; i < rejection.size(); ++i) {
std::cout<<"rejection = "<<rejection[i]<<" +/- "<<rejection_errors[i]<<std::endl;
}
}
<|endoftext|>
|
<commit_before>// ================================================================================
// == This file is a part of TinkerBell UI Toolkit. (C) 2011-2012, Emil Segers ==
// == See tinkerbell.h for more information. ==
// ================================================================================
#include "addons/tbimage/tb_image_manager.h"
#include "tb_system.h"
namespace tinkerbell {
TB_ADDON_FACTORY(TBImageManager);
// == TBImageRep ========================================================================
TBImageRep::TBImageRep(TBImageManager *image_manager, TBBitmapFragment *fragment, uint32 hash_key)
: ref_count(0), hash_key(hash_key), image_manager(image_manager), fragment(fragment)
{
}
void TBImageRep::IncRef()
{
ref_count++;
}
void TBImageRep::DecRef()
{
ref_count--;
if (ref_count == 0)
{
if (image_manager)
image_manager->RemoveImageRep(this);
delete this;
}
}
// == TBImage ===========================================================================
TBImage::TBImage(TBImageRep *rep)
: m_image_rep(rep)
{
if (m_image_rep)
m_image_rep->IncRef();
}
TBImage::TBImage(const TBImage &image)
: m_image_rep(image.m_image_rep)
{
if (m_image_rep)
m_image_rep->IncRef();
}
TBImage::~TBImage()
{
if (m_image_rep)
m_image_rep->DecRef();
}
bool TBImage::IsEmpty() const
{
return m_image_rep && m_image_rep->fragment;
}
int TBImage::Width() const
{
if (m_image_rep && m_image_rep->fragment)
return m_image_rep->fragment->Width();
return 0;
}
int TBImage::Height() const
{
if (m_image_rep && m_image_rep->fragment)
return m_image_rep->fragment->Height();
return 0;
}
TBBitmapFragment *TBImage::GetBitmap() const
{
return m_image_rep ? m_image_rep->fragment : nullptr;
}
void TBImage::SetImageRep(TBImageRep *image_rep)
{
if (m_image_rep == image_rep)
return;
if (m_image_rep)
m_image_rep->DecRef();
m_image_rep = image_rep;
if (m_image_rep)
m_image_rep->IncRef();
}
// == TBImageManager ====================================================================
TBImageManager *g_image_manager = nullptr;
bool TBImageManager::Init()
{
g_image_manager = this;
g_renderer->AddListener(this);
return true;
}
void TBImageManager::Shutdown()
{
g_renderer->RemoveListener(this);
// If there is TBImageRep objects live, we must unset the fragment pointer
// since the m_frag_manager is going to be destroyed very soon.
TBHashTableIteratorOf<TBImageRep> it(&m_image_rep_hash);
while (TBImageRep *image_rep = it.GetNextContent())
{
image_rep->fragment = nullptr;
image_rep->image_manager = nullptr;
}
g_image_manager = nullptr;
}
TBImage TBImageManager::GetImage(const char *filename)
{
uint32 hash_key = TBGetHash(filename);
TBImageRep *image_rep = m_image_rep_hash.Get(hash_key);
if (!image_rep)
{
TBBitmapFragment *fragment = m_frag_manager.GetFragmentFromFile(filename, false);
image_rep = new TBImageRep(this, fragment, hash_key);
if (!image_rep || !fragment || !m_image_rep_hash.Add(hash_key, image_rep))
{
delete image_rep;
m_frag_manager.FreeFragment(fragment);
image_rep = nullptr;
}
TBDebugOut(image_rep ? "TBImageManager - Loaded new image.\n" : "TBImageManager - Loading image failed.\n");
}
return TBImage(image_rep);
}
void TBImageManager::RemoveImageRep(TBImageRep *image_rep)
{
assert(image_rep->ref_count == 0);
if (image_rep->fragment)
{
m_frag_manager.FreeFragment(image_rep->fragment);
image_rep->fragment = nullptr;
}
m_image_rep_hash.Remove(image_rep->hash_key);
image_rep->image_manager = nullptr;
TBDebugOut("TBImageManager - Removed image.\n");
}
void TBImageManager::OnContextLost()
{
m_frag_manager.DeleteBitmaps();
}
void TBImageManager::OnContextRestored()
{
// No need to do anything. The bitmaps will be created when drawing.
}
}; // namespace tinkerbell
<commit_msg>TBImage addon should also load bitmaps in destination DPI.<commit_after>// ================================================================================
// == This file is a part of TinkerBell UI Toolkit. (C) 2011-2012, Emil Segers ==
// == See tinkerbell.h for more information. ==
// ================================================================================
#include "addons/tbimage/tb_image_manager.h"
#include "tb_system.h"
#include "tb_tempbuffer.h"
namespace tinkerbell {
TB_ADDON_FACTORY(TBImageManager);
// == TBImageRep ========================================================================
TBImageRep::TBImageRep(TBImageManager *image_manager, TBBitmapFragment *fragment, uint32 hash_key)
: ref_count(0), hash_key(hash_key), image_manager(image_manager), fragment(fragment)
{
}
void TBImageRep::IncRef()
{
ref_count++;
}
void TBImageRep::DecRef()
{
ref_count--;
if (ref_count == 0)
{
if (image_manager)
image_manager->RemoveImageRep(this);
delete this;
}
}
// == TBImage ===========================================================================
TBImage::TBImage(TBImageRep *rep)
: m_image_rep(rep)
{
if (m_image_rep)
m_image_rep->IncRef();
}
TBImage::TBImage(const TBImage &image)
: m_image_rep(image.m_image_rep)
{
if (m_image_rep)
m_image_rep->IncRef();
}
TBImage::~TBImage()
{
if (m_image_rep)
m_image_rep->DecRef();
}
bool TBImage::IsEmpty() const
{
return m_image_rep && m_image_rep->fragment;
}
int TBImage::Width() const
{
if (m_image_rep && m_image_rep->fragment)
return m_image_rep->fragment->Width();
return 0;
}
int TBImage::Height() const
{
if (m_image_rep && m_image_rep->fragment)
return m_image_rep->fragment->Height();
return 0;
}
TBBitmapFragment *TBImage::GetBitmap() const
{
return m_image_rep ? m_image_rep->fragment : nullptr;
}
void TBImage::SetImageRep(TBImageRep *image_rep)
{
if (m_image_rep == image_rep)
return;
if (m_image_rep)
m_image_rep->DecRef();
m_image_rep = image_rep;
if (m_image_rep)
m_image_rep->IncRef();
}
// == TBImageManager ====================================================================
TBImageManager *g_image_manager = nullptr;
bool TBImageManager::Init()
{
g_image_manager = this;
g_renderer->AddListener(this);
return true;
}
void TBImageManager::Shutdown()
{
g_renderer->RemoveListener(this);
// If there is TBImageRep objects live, we must unset the fragment pointer
// since the m_frag_manager is going to be destroyed very soon.
TBHashTableIteratorOf<TBImageRep> it(&m_image_rep_hash);
while (TBImageRep *image_rep = it.GetNextContent())
{
image_rep->fragment = nullptr;
image_rep->image_manager = nullptr;
}
g_image_manager = nullptr;
}
TBImage TBImageManager::GetImage(const char *filename)
{
uint32 hash_key = TBGetHash(filename);
TBImageRep *image_rep = m_image_rep_hash.Get(hash_key);
if (!image_rep)
{
// Load a fragment. Load a destination DPI bitmap if available.
TBBitmapFragment *fragment = nullptr;
if (g_tb_skin->GetDimensionConverter()->NeedConversion())
{
TBTempBuffer filename_dst_DPI;
g_tb_skin->GetDimensionConverter()->GetDstDPIFilename(filename, &filename_dst_DPI);
fragment = m_frag_manager.GetFragmentFromFile(filename_dst_DPI.GetData(), false);
}
if (!fragment)
fragment = m_frag_manager.GetFragmentFromFile(filename, false);
image_rep = new TBImageRep(this, fragment, hash_key);
if (!image_rep || !fragment || !m_image_rep_hash.Add(hash_key, image_rep))
{
delete image_rep;
m_frag_manager.FreeFragment(fragment);
image_rep = nullptr;
}
TBDebugOut(image_rep ? "TBImageManager - Loaded new image.\n" : "TBImageManager - Loading image failed.\n");
}
return TBImage(image_rep);
}
void TBImageManager::RemoveImageRep(TBImageRep *image_rep)
{
assert(image_rep->ref_count == 0);
if (image_rep->fragment)
{
m_frag_manager.FreeFragment(image_rep->fragment);
image_rep->fragment = nullptr;
}
m_image_rep_hash.Remove(image_rep->hash_key);
image_rep->image_manager = nullptr;
TBDebugOut("TBImageManager - Removed image.\n");
}
void TBImageManager::OnContextLost()
{
m_frag_manager.DeleteBitmaps();
}
void TBImageManager::OnContextRestored()
{
// No need to do anything. The bitmaps will be created when drawing.
}
}; // namespace tinkerbell
<|endoftext|>
|
<commit_before>#ifndef MP_LINKEDLIST_HPP
#define MP_LINKEDLIST_HPP
#include <boost/smart_ptr/intrusive_ref_counter.hpp>
#include <boost/atomic.hpp>
#include <assert.h>
#include "IntrusivePtr.hpp"
// lockfree
template<typename T>
class LinkedList {
public:
struct Item;
typedef IntrusivePtr<Item> ItemPtr;
enum ItemState {
S_Uninitialized,
S_MainLink,
S_Data,
};
struct Item : public boost::intrusive_ref_counter< Item, boost::thread_safe_counter > {
ItemPtr prev, next;
boost::atomic<ItemState> state;
T value;
Item() : state(S_Uninitialized), value() {}
bool isEmpty() {
ItemPtr nextCpy(next);
if(!nextCpy) // can happen when clear() meanwhile
return true;
return nextCpy->state != S_Data;
}
bool insertBefore(ItemPtr& item) {
ItemPtr oldPrev = prev.exchange(item);
if(oldPrev) {
ItemPtr oldPrevNext = oldPrev->next.exchange(item);
// If pop_front() meanwhile and oldPrev was the first item,
// we might have reset oldPrev->next already or will soon.
// In the latter case, it will set item->prev = main, which is correct;
// we do the same here, it doesn't matter which comes first.
// Otherwise, we get here:
if(!oldPrevNext) {
// oldPrev is being returned by pop_front()
oldPrev->next = NULL;
}
else {
item->prev = oldPrev;
}
} else {
// oldPrev == NULL -> clear() or pop_front() item.
return false;
}
item->next = this;
return true;
}
};
private:
ItemPtr main; // prev = last, next = first
ItemPtr _newMain() {
ItemPtr m = new Item();
m->next = m;
m->prev = m;
m->state = S_MainLink;
return m;
}
void _releaseMain(const ItemPtr& m) {
ItemPtr ptr = m;
while(true) {
ptr = ptr->next.exchange(NULL);
if(!ptr) break;
}
ptr = m;
while(true) {
ptr = ptr->prev.exchange(NULL);
if(!ptr) break;
}
}
public:
LinkedList() {
main = _newMain();
}
~LinkedList() {
clear();
}
// The iterator is not thread-safe, i.e. you can't access
// a single iterator from multiple threads. However,
// the list can be accessed and modified from other threads.
struct Iterator {
ItemPtr ptr;
Iterator(const ItemPtr& _ptr) : ptr(_ptr) {}
T& operator*() {
return ptr->value;
}
Iterator& operator++() {
if(isEnd()) return *this;
ptr = ptr->next;
return *this;
}
bool operator==(const Iterator& other) const {
if(isEnd() && other.isEnd()) return true;
return ptr == other.ptr;
}
bool operator!=(const Iterator& other) const {
return !(*this == other);
}
bool isEnd() const {
if(ptr.get() == NULL) return true;
if(ptr->state != S_Data) return true;
return false;
}
};
Iterator begin() {
ItemPtr backup(main);
return Iterator(backup->next);
}
Iterator end() {
return Iterator(NULL);
}
// only single producer supported
ItemPtr push_back(ItemPtr item = NULL) {
ItemPtr mainCpy(main);
if(!item) item.reset(new Item());
item->state = S_Uninitialized;
mainCpy->insertBefore(item);
item->state = S_Data;
return item;
}
// only single consumer supported
ItemPtr pop_front() {
ItemPtr mainCpy(main);
ItemPtr first = mainCpy->next;
if(!first || first == mainCpy || first->state != S_Data)
return NULL;
first->prev = NULL;
ItemPtr firstNext = first->next.exchange(NULL);
if(firstNext) // can happen to be NULL when clear() meanwhile
// e.g. if firstNext==main and push_front() meanwhile,
// main->prev != first. in that case, don't change.
firstNext->prev.compare_exchange(first, mainCpy);
if(!mainCpy->next.compare_exchange(first, firstNext))
assert(false); // this can only happen if there was another consumer
return first;
}
void clear() {
ItemPtr oldMain = main.exchange(_newMain());
_releaseMain(oldMain);
}
bool empty() {
return ItemPtr(main)->isEmpty();
}
// be very careful! noone must use pop_front() or clear() meanwhile
T& front() { return main->next->value; }
T& back() { return main->prev->value; }
// not threading-safe!
size_t size() {
ItemPtr ptr = main;
size_t c = 0;
while(true) {
ptr = ptr->next;
if(ptr->state != S_Data) break;
c++;
}
return c;
}
// not threading-safe!
void _checkSanity() {
assert(main->state == S_MainLink);
ItemPtr ptr = main;
size_t c1 = 0;
while(true) {
assert(ptr->next->prev == ptr);
assert(ptr->prev->next == ptr);
ptr = ptr->next;
if(ptr->state == S_MainLink) break;
else if(ptr->state == S_Data) {} // ok
else if(ptr->state == S_Uninitialized) assert(false);
else assert(false);
c1++;
}
assert(ptr->state == S_MainLink);
size_t c2 = 0;
ptr = main;
while(true) {
assert(ptr->next->prev == ptr);
assert(ptr->prev->next == ptr);
ptr = ptr->prev;
if(ptr->state == S_MainLink) break;
else if(ptr->state == S_Data) {} // ok
else if(ptr->state == S_Uninitialized) assert(false);
else assert(false);
c2++;
}
assert(ptr->state == S_MainLink);
assert(c1 == c2);
if(c1 == 0) {
assert(main->next == main);
assert(main->prev == main);
}
}
};
#endif // LINKEDLIST_HPP
<commit_msg>better<commit_after>#ifndef MP_LINKEDLIST_HPP
#define MP_LINKEDLIST_HPP
#include <boost/smart_ptr/intrusive_ref_counter.hpp>
#include <boost/atomic.hpp>
#include <assert.h>
#include "IntrusivePtr.hpp"
// lockfree
template<typename T>
class LinkedList {
public:
struct Item;
typedef IntrusivePtr<Item> ItemPtr;
enum ItemState {
S_Uninitialized,
S_MainLink,
S_Data,
};
struct Item : public boost::intrusive_ref_counter< Item, boost::thread_safe_counter > {
ItemPtr prev, next;
boost::atomic<ItemState> state;
T value;
Item() : state(S_Uninitialized), value() {}
bool isEmpty() {
ItemPtr nextCpy(next);
if(!nextCpy) // can happen when clear() meanwhile
return true;
return nextCpy->state != S_Data;
}
bool insertBefore(ItemPtr item) {
ItemPtr oldPrev = prev.exchange(item);
if(oldPrev) {
bool success = oldPrev->next.compare_exchange(this, item);
// If pop_front() meanwhile and oldPrev was the first item,
// we might have reset oldPrev->next already or will soon.
// In the latter case, it will set item->prev = main, which is correct;
// we do the same here, it doesn't matter which comes first.
if(success)
item->prev = oldPrev;
} else {
// oldPrev == NULL -> clear() or pop_front() item.
return false;
}
item->next = this;
return true;
}
};
private:
ItemPtr main; // prev = last, next = first
ItemPtr _newMain() {
ItemPtr m = new Item();
m->next = m;
m->prev = m;
m->state = S_MainLink;
return m;
}
void _releaseMain(const ItemPtr& m) {
ItemPtr ptr = m;
while(true) {
ptr = ptr->next.exchange(NULL);
if(!ptr) break;
}
ptr = m;
while(true) {
ptr = ptr->prev.exchange(NULL);
if(!ptr) break;
}
}
public:
LinkedList() {
main = _newMain();
}
~LinkedList() {
clear();
}
// The iterator is not thread-safe, i.e. you can't access
// a single iterator from multiple threads. However,
// the list can be accessed and modified from other threads.
struct Iterator {
ItemPtr ptr;
Iterator(const ItemPtr& _ptr) : ptr(_ptr) {}
T& operator*() {
return ptr->value;
}
Iterator& operator++() {
if(isEnd()) return *this;
ptr = ptr->next;
return *this;
}
bool operator==(const Iterator& other) const {
if(isEnd() && other.isEnd()) return true;
return ptr == other.ptr;
}
bool operator!=(const Iterator& other) const {
return !(*this == other);
}
bool isEnd() const {
if(ptr.get() == NULL) return true;
if(ptr->state != S_Data) return true;
return false;
}
};
Iterator begin() {
ItemPtr backup(main);
return Iterator(backup->next);
}
Iterator end() {
return Iterator(NULL);
}
// only single producer supported
ItemPtr push_back(ItemPtr item = NULL) {
ItemPtr mainCpy(main);
if(!item) item.reset(new Item());
item->state = S_Uninitialized;
mainCpy->insertBefore(item);
item->state = S_Data;
return item;
}
// only single consumer supported
ItemPtr pop_front() {
ItemPtr mainCpy(main);
ItemPtr first = mainCpy->next;
if(!first || first == mainCpy || first->state != S_Data)
return NULL;
first->prev = NULL;
ItemPtr firstNext = first->next.exchange(NULL);
if(firstNext) // can happen to be NULL when clear() meanwhile
// e.g. if firstNext==main and push_front() meanwhile,
// main->prev != first. in that case, don't change.
firstNext->prev.compare_exchange(first, mainCpy);
if(!mainCpy->next.compare_exchange(first, firstNext))
assert(false); // this can only happen if there was another consumer
return first;
}
void clear() {
ItemPtr oldMain = main.exchange(_newMain());
_releaseMain(oldMain);
}
bool empty() {
return ItemPtr(main)->isEmpty();
}
// be very careful! noone must use pop_front() or clear() meanwhile
T& front() { return main->next->value; }
T& back() { return main->prev->value; }
// not threading-safe!
size_t size() {
ItemPtr ptr = main;
size_t c = 0;
while(true) {
ptr = ptr->next;
if(ptr->state != S_Data) break;
c++;
}
return c;
}
// not threading-safe!
void _checkSanity() {
assert(main->state == S_MainLink);
ItemPtr ptr = main;
size_t c1 = 0;
while(true) {
assert(ptr->next->prev == ptr);
assert(ptr->prev->next == ptr);
ptr = ptr->next;
if(ptr->state == S_MainLink) break;
else if(ptr->state == S_Data) {} // ok
else if(ptr->state == S_Uninitialized) assert(false);
else assert(false);
c1++;
}
assert(ptr->state == S_MainLink);
size_t c2 = 0;
ptr = main;
while(true) {
assert(ptr->next->prev == ptr);
assert(ptr->prev->next == ptr);
ptr = ptr->prev;
if(ptr->state == S_MainLink) break;
else if(ptr->state == S_Data) {} // ok
else if(ptr->state == S_Uninitialized) assert(false);
else assert(false);
c2++;
}
assert(ptr->state == S_MainLink);
assert(c1 == c2);
if(c1 == 0) {
assert(main->next == main);
assert(main->prev == main);
}
}
};
#endif // LINKEDLIST_HPP
<|endoftext|>
|
<commit_before>//
// 257.cpp
// LeetCode
//
// Created by Narikbi on 18.03.17.
// Copyright © 2017 app.leetcode.kz. All rights reserved.
//
#include <stdio.h>
<commit_msg>257 task bugfix.<commit_after>//
// 257.cpp
// LeetCode
//
// Created by Narikbi on 18.03.17.
// Copyright © 2017 app.leetcode.kz. All rights reserved.
//
#include <stdio.h>
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <deque>
#include <queue>
#include <set>
#include <map>
#include <stack>
#include <cmath>
#include <numeric>
#include <unordered_map>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
vector<string> res;
void rec(TreeNode *node, string path) {
if (node->left == NULL && node->right == NULL) {
res.push_back(path + to_string(node->val));
}
if (node->left != NULL) rec(node->left, path + to_string(node->val) + "->");
if (node->right != NULL) rec(node->right, path + to_string(node->val) + "->");
}
vector<string> binaryTreePaths(TreeNode* root) {
if (root != NULL) rec(root, {});
return res;
}
<|endoftext|>
|
<commit_before>#include "stdafx.h"
#ifndef _MSC_VER
static int GetKeyState(char) {
return 0x01;
}
#define VK_RETURN 0x0D
#endif
static float CalcRadius(const Mesh* m)
{
const Block& b = m->GetRawDatas();
float maxSq = 0;
for (auto& it : b.vertices) {
float sq = lengthSq(it.xyz);
maxSq = std::max(maxSq, sq);
}
return sqrt(maxSq);
}
App::App() : radius(1), animationNumber(0), trackTime(0), meshTiny(nullptr)
{
memset(mesh, 0, sizeof(mesh));
lastTime = GetTime();
}
App::~App()
{
}
void App::ApplySky()
{
switch(skyNum) {
case 0:
//skyMan.Create("C:\\Program Files (x86)\\Microsoft DirectX SDK (August 2009)\\Samples\\C++\\Direct3D\\StateManager\\Media\\skybox02.dds", "sky_cubemap_high");
skyMan.Create("C:\\Program Files (x86)\\Microsoft DirectX SDK (August 2009)\\Samples\\Media\\Lobby\\LobbyCube.dds", "sky_cubemap");
break;
case 1:
skyMan.Create("resource\\OutputCube2.dds", "projection_equirectangular");
//skyMan.Create("C:\\Program Files (x86)\\Microsoft DirectX SDK (August 2009)\\Samples\\C++\\Direct3D\\StateManager\\Media\\skybox02.dds", "projection_equirectangular");
break;
case 2:
skyMan.Create("C:\\Program Files (x86)\\Microsoft DirectX SDK (August 2009)\\Samples\\C++\\Direct3D\\StateManager\\Media\\skybox02.dds", "projection_little_planet");
break;
case 3:
skyMan.Create("C:\\Program Files (x86)\\Microsoft DirectX SDK (August 2009)\\Samples\\Media\\trees\\tree35S.dds", "sky_spheremap");
//skyMan.Create("C:\\Program Files (x86)\\Microsoft DirectX SDK (August 2009)\\Samples\\Media\\SubD10\\msd_MicrosoftCharacterMaya100_heroChr_mechanicalCM_tga_001.dds", "sky_spheremap");
//skyMan.Create("resource\\sphere_map.dds", "sky_spheremap");
break;
case 4:
skyMan.Create("resource\\PANO_20141115_141959.dds", "sky_photosphere");
break;
case 5:
skyMan.Create("resource\\Equirectangular-projection.jpg", "sky_photosphere");
break;
case 6:
skyMan.Create("resource\\warcraft.dds", "sky_photosphere");
break;
case 7:
skyMan.Create("resource\\PANO_20141115_141959.dds", "projection_equirectangular_to_stereographic");
break;
}
}
void App::Init(const char* fileName)
{
Destroy();
for (auto& it : rt) {
it.Init(ivec2(SCR_W, SCR_H), AFDT_R8G8B8A8_UINT, AFDT_INVALID);
}
fontMan.Init();
debugRenderer.Init();
gridRenderer.Init();
waterSurface.Init();
postEffectMan.Create("post_effect_mono");
computeShaderMan.Create("fx\\post_effect_cs.fx");
computeShaderSkinning.Create("fx\\skin_cs.fx");
g_type = "mesh";
const char* meshFileName = "resource\\tiny.x";
const char* ext = fileName ? strrchr(fileName, '.') : nullptr;
if (ext && !_stricmp(ext, ".x")) {
meshFileName = fileName;
}
#if 1
meshTiny = new MeshX(meshFileName);
if (ext && !_stricmp(ext, ".bvh")) {
Bvh* bvh = new Bvh(fileName);
mesh[0] = bvh;
bvh->ResetAnim();
meshTiny->SyncLocalAxisWithBvh(bvh, bind[0]);
} else {
const char* bvhNames[] = {
"D:\\github\\aachan.bvh",
"D:\\github\\kashiyuka.bvh",
"D:\\github\\nocchi.bvh",
};
for (int i = 0; i < (int)dimof(bvhNames); i++) {
Bvh* bvh = new Bvh(bvhNames[i]);
mesh[i] = bvh;
bvh->ResetAnim();
meshTiny->SyncLocalAxisWithBvh(bvh, bind[i]);
}
}
if (mesh[0]) {
radius = CalcRadius(mesh[0]);
}
#endif
float scale = std::max(0.00001f, radius);
devCamera.SetDistance(scale * 3);
devCamera.SetHeight(radius / 2);
lastTime = GetTime();
ApplySky();
}
inline Vec2 GetScreenPos(const Mat& mLocal)
{
Mat mW, mV, mP, mViewport;
matrixMan.Get(MatrixMan::WORLD, mW);
matrixMan.Get(MatrixMan::VIEW, mV);
matrixMan.Get(MatrixMan::PROJ, mP);
mViewport._11 = SCR_W / 2;
mViewport._22 = -SCR_H / 2;
mViewport._41 = SCR_W / 2;
mViewport._42 = SCR_H / 2;
Mat m = mLocal * mW * mV * mP * mViewport;
Vec2 p;
p.x = m._41 / m._44;
p.y = m._42 / m._44;
return p;
}
void App::DrawBoneNames(Bvh* bvh)
{
const std::vector<BvhFrame>& frames = bvh->GetFrames();
for (auto& it : frames) {
if (it.childId < 0) {
continue;
}
Vec2 size = fontMan.MeasureString(12, it.name);
Vec2 pos = GetScreenPos(it.result);
pos -= size / 2;
fontMan.DrawString(floor(pos), 12, it.name);
}
}
void App::DrawBoneNames(const MeshX* meshX, const MeshXAnimResult& result)
{
const std::vector<Frame>& frames = meshX->GetFrames();
for (BONE_ID id = 0; id < (BONE_ID)frames.size(); id++) {
const Frame& f = frames[id];
Vec2 pos = floor(GetScreenPos(result.boneMat[id]));
fontMan.DrawString(pos, 12, f.name[0] == '\0' ? "[NO NAME]" : f.name);
}
}
void App::DrawCameraParams()
{
Mat v;
matrixMan.Get(MatrixMan::VIEW, v);
Mat mInv = inv(v);
char buf[128];
Vec2 pos = { 5, 105 };
auto draw = [&]() {
fontMan.DrawString(pos, 20, buf);
pos.y += 22;
};
// snprintf(buf, sizeof(buf), "cam pos(via inv view):%f, %f, %f dir:%f, %f, %f", mInv._41, mInv._42, mInv._43, mInv._31, mInv._32, mInv._33);
// draw();
// mInv = fastInv(v);
// snprintf(buf, sizeof(buf), "cam pos(by fastInv):%f, %f, %f dir:%f, %f, %f", mInv._41, mInv._42, mInv._43, mInv._31, mInv._32, mInv._33);
// draw();
// snprintf(buf, sizeof(buf), "cam dir(view mtx direct): %f, %f, %f", v._13, v._23, v._33);
// draw();
snprintf(buf, sizeof(buf), "cam dir: %f, %f, %f", v._13, v._23, v._33);
draw();
float longitude = atan2(v._13, v._33) * (180.0f / 3.14159265f);
float latitude = asin(v._23) * (180.0f / 3.14159265f);
snprintf(buf, sizeof(buf), "longitude: %f, latitude: %f", longitude, latitude);
draw();
}
void App::Update()
{
if (GetKeyState(VK_F1) & 0x80) {
skyNum = 0;
ApplySky();
}
if (GetKeyState(VK_F2) & 0x80) {
skyNum = 1;
ApplySky();
}
if (GetKeyState(VK_F3) & 0x80) {
skyNum = 2;
ApplySky();
}
if (GetKeyState(VK_F4) & 0x80) {
skyNum = 3;
ApplySky();
}
if (GetKeyState(VK_F5) & 0x80) {
skyNum = 4;
ApplySky();
}
if (GetKeyState(VK_F6) & 0x80) {
skyNum = 5;
ApplySky();
}
if (GetKeyState(VK_F7) & 0x80) {
skyNum = 6;
ApplySky();
}
if (GetKeyState(VK_F8) & 0x80) {
skyNum = 7;
ApplySky();
}
if (GetKeyState('P') & 0x80) {
g_type = "pivot";
}
if (GetKeyState('M') & 0x80) {
g_type = "mesh";
}
if (GetKeyState('B') & 0x80) {
g_type = "bone";
}
static char v[] = "012349";
for (auto& i : v) {
if (i && GetKeyState(i) & 0x80) {
animationNumber = i - '0';
}
}
}
void App::Draw()
{
// fontMan.DrawString(Vec2(0, 110), 16, "TEXT SPRITE TEST!!!!!!!!!!!!!text sprite 1234567890");
// fontMan.DrawString(Vec2(10, 130), 32, "@#$%^&*()");
// fontMan.DrawString(Vec2(10, 170), 40, L"あいうえお한글漢字");
ID3D11DeviceContext* context = deviceMan11.GetContext();
// rt[0].BeginRenderToThis();
AFRenderTarget defaultTarget;
defaultTarget.InitForDefaultRenderTarget();
defaultTarget.BeginRenderToThis();
double currentTime = GetTime();
double deltaTime = currentTime - lastTime;
lastTime = currentTime;
if (GetKeyState(VK_RETURN) & 0x01) {
trackTime += deltaTime;
}
matrixMan.Set(MatrixMan::WORLD, Mat());
matrixMan.Set(MatrixMan::VIEW, devCamera.GetViewMatrix());
matrixMan.Set(MatrixMan::PROJ, devCamera.GetProjMatrix());
skyMan.Draw();
// gridRenderer.Draw();
// waterSurface.Draw();
for (int i = 0; i < (int)dimof(mesh); i++) {
Mesh* it = mesh[i];
MeshX* meshX = meshTiny;
MeshXAnimResult meshXAnimResult;
if (it && meshX) {
Bvh* bvh = dynamic_cast<Bvh*>(it);
if (bvh) {
bvh->Draw(animationNumber == 9 ? 0 : animationNumber, trackTime);
if (animationNumber == 9) {
meshX->CalcAnimationFromBvh(bvh, bind[i], trackTime, meshXAnimResult, 270 / radius);
} else {
meshX->CalcAnimation(animationNumber, trackTime, meshXAnimResult);
}
meshX->Draw(meshXAnimResult);
if (GetKeyState('T') & 0x01) {
DrawBoneNames(bvh);
}
}
}
if (meshX && (GetKeyState('T') & 0x01)) {
DrawBoneNames(meshX, meshXAnimResult);
}
}
if (GetKeyState('T') & 0x01) {
DrawCameraParams();
char buf[20];
sprintf(buf, "FPS: %f", fps.Get());
Vec2 pos = { 5, 15 };
fontMan.DrawString(pos, 16, buf);
}
fontMan.Render();
// computeShaderMan.Draw(rt[0].GetTexture(), rt[1].GetUnorderedAccessView());
// postEffectMan.Draw(rt[1].GetTexture());
deviceMan11.Present();
fps.Update();
}
void App::Destroy()
{
for (auto& it : mesh) {
SAFE_DELETE(it);
}
SAFE_DELETE(meshTiny);
for (auto& it : rt) {
it.Destroy();
}
fontMan.Destroy();
debugRenderer.Destroy();
gridRenderer.Destroy();
waterSurface.Destroy();
postEffectMan.Destroy();
computeShaderMan.Destroy();
computeShaderSkinning.Destroy();
}
std::string g_type;
<commit_msg>activate post effects<commit_after>#include "stdafx.h"
#ifndef _MSC_VER
static int GetKeyState(char) {
return 0x01;
}
#define VK_RETURN 0x0D
#endif
static float CalcRadius(const Mesh* m)
{
const Block& b = m->GetRawDatas();
float maxSq = 0;
for (auto& it : b.vertices) {
float sq = lengthSq(it.xyz);
maxSq = std::max(maxSq, sq);
}
return sqrt(maxSq);
}
App::App() : radius(1), animationNumber(0), trackTime(0), meshTiny(nullptr)
{
memset(mesh, 0, sizeof(mesh));
lastTime = GetTime();
}
App::~App()
{
}
void App::ApplySky()
{
switch(skyNum) {
case 0:
//skyMan.Create("C:\\Program Files (x86)\\Microsoft DirectX SDK (August 2009)\\Samples\\C++\\Direct3D\\StateManager\\Media\\skybox02.dds", "sky_cubemap_high");
skyMan.Create("C:\\Program Files (x86)\\Microsoft DirectX SDK (August 2009)\\Samples\\Media\\Lobby\\LobbyCube.dds", "sky_cubemap");
break;
case 1:
skyMan.Create("resource\\OutputCube2.dds", "projection_equirectangular");
//skyMan.Create("C:\\Program Files (x86)\\Microsoft DirectX SDK (August 2009)\\Samples\\C++\\Direct3D\\StateManager\\Media\\skybox02.dds", "projection_equirectangular");
break;
case 2:
skyMan.Create("C:\\Program Files (x86)\\Microsoft DirectX SDK (August 2009)\\Samples\\C++\\Direct3D\\StateManager\\Media\\skybox02.dds", "projection_little_planet");
break;
case 3:
skyMan.Create("C:\\Program Files (x86)\\Microsoft DirectX SDK (August 2009)\\Samples\\Media\\trees\\tree35S.dds", "sky_spheremap");
//skyMan.Create("C:\\Program Files (x86)\\Microsoft DirectX SDK (August 2009)\\Samples\\Media\\SubD10\\msd_MicrosoftCharacterMaya100_heroChr_mechanicalCM_tga_001.dds", "sky_spheremap");
//skyMan.Create("resource\\sphere_map.dds", "sky_spheremap");
break;
case 4:
skyMan.Create("resource\\PANO_20141115_141959.dds", "sky_photosphere");
break;
case 5:
skyMan.Create("resource\\Equirectangular-projection.jpg", "sky_photosphere");
break;
case 6:
skyMan.Create("resource\\warcraft.dds", "sky_photosphere");
break;
case 7:
skyMan.Create("resource\\PANO_20141115_141959.dds", "projection_equirectangular_to_stereographic");
break;
}
}
void App::Init(const char* fileName)
{
Destroy();
for (auto& it : rt) {
it.Init(ivec2(SCR_W, SCR_H), AFDT_R8G8B8A8_UINT, AFDT_INVALID);
}
fontMan.Init();
debugRenderer.Init();
gridRenderer.Init();
waterSurface.Init();
postEffectMan.Create("post_effect_mono");
computeShaderMan.Create("fx\\post_effect_cs.fx");
computeShaderSkinning.Create("fx\\skin_cs.fx");
g_type = "mesh";
const char* meshFileName = "resource\\tiny.x";
const char* ext = fileName ? strrchr(fileName, '.') : nullptr;
if (ext && !_stricmp(ext, ".x")) {
meshFileName = fileName;
}
#if 1
meshTiny = new MeshX(meshFileName);
if (ext && !_stricmp(ext, ".bvh")) {
Bvh* bvh = new Bvh(fileName);
mesh[0] = bvh;
bvh->ResetAnim();
meshTiny->SyncLocalAxisWithBvh(bvh, bind[0]);
} else {
const char* bvhNames[] = {
"D:\\github\\aachan.bvh",
"D:\\github\\kashiyuka.bvh",
"D:\\github\\nocchi.bvh",
};
for (int i = 0; i < (int)dimof(bvhNames); i++) {
Bvh* bvh = new Bvh(bvhNames[i]);
mesh[i] = bvh;
bvh->ResetAnim();
meshTiny->SyncLocalAxisWithBvh(bvh, bind[i]);
}
}
if (mesh[0]) {
radius = CalcRadius(mesh[0]);
}
#endif
float scale = std::max(0.00001f, radius);
devCamera.SetDistance(scale * 3);
devCamera.SetHeight(radius / 2);
lastTime = GetTime();
ApplySky();
}
inline Vec2 GetScreenPos(const Mat& mLocal)
{
Mat mW, mV, mP, mViewport;
matrixMan.Get(MatrixMan::WORLD, mW);
matrixMan.Get(MatrixMan::VIEW, mV);
matrixMan.Get(MatrixMan::PROJ, mP);
mViewport._11 = SCR_W / 2;
mViewport._22 = -SCR_H / 2;
mViewport._41 = SCR_W / 2;
mViewport._42 = SCR_H / 2;
Mat m = mLocal * mW * mV * mP * mViewport;
Vec2 p;
p.x = m._41 / m._44;
p.y = m._42 / m._44;
return p;
}
void App::DrawBoneNames(Bvh* bvh)
{
const std::vector<BvhFrame>& frames = bvh->GetFrames();
for (auto& it : frames) {
if (it.childId < 0) {
continue;
}
Vec2 size = fontMan.MeasureString(12, it.name);
Vec2 pos = GetScreenPos(it.result);
pos -= size / 2;
fontMan.DrawString(floor(pos), 12, it.name);
}
}
void App::DrawBoneNames(const MeshX* meshX, const MeshXAnimResult& result)
{
const std::vector<Frame>& frames = meshX->GetFrames();
for (BONE_ID id = 0; id < (BONE_ID)frames.size(); id++) {
const Frame& f = frames[id];
Vec2 pos = floor(GetScreenPos(result.boneMat[id]));
fontMan.DrawString(pos, 12, f.name[0] == '\0' ? "[NO NAME]" : f.name);
}
}
void App::DrawCameraParams()
{
Mat v;
matrixMan.Get(MatrixMan::VIEW, v);
Mat mInv = inv(v);
char buf[128];
Vec2 pos = { 5, 105 };
auto draw = [&]() {
fontMan.DrawString(pos, 20, buf);
pos.y += 22;
};
// snprintf(buf, sizeof(buf), "cam pos(via inv view):%f, %f, %f dir:%f, %f, %f", mInv._41, mInv._42, mInv._43, mInv._31, mInv._32, mInv._33);
// draw();
// mInv = fastInv(v);
// snprintf(buf, sizeof(buf), "cam pos(by fastInv):%f, %f, %f dir:%f, %f, %f", mInv._41, mInv._42, mInv._43, mInv._31, mInv._32, mInv._33);
// draw();
// snprintf(buf, sizeof(buf), "cam dir(view mtx direct): %f, %f, %f", v._13, v._23, v._33);
// draw();
snprintf(buf, sizeof(buf), "cam dir: %f, %f, %f", v._13, v._23, v._33);
draw();
float longitude = atan2(v._13, v._33) * (180.0f / 3.14159265f);
float latitude = asin(v._23) * (180.0f / 3.14159265f);
snprintf(buf, sizeof(buf), "longitude: %f, latitude: %f", longitude, latitude);
draw();
}
void App::Update()
{
if (GetKeyState(VK_F1) & 0x80) {
skyNum = 0;
ApplySky();
}
if (GetKeyState(VK_F2) & 0x80) {
skyNum = 1;
ApplySky();
}
if (GetKeyState(VK_F3) & 0x80) {
skyNum = 2;
ApplySky();
}
if (GetKeyState(VK_F4) & 0x80) {
skyNum = 3;
ApplySky();
}
if (GetKeyState(VK_F5) & 0x80) {
skyNum = 4;
ApplySky();
}
if (GetKeyState(VK_F6) & 0x80) {
skyNum = 5;
ApplySky();
}
if (GetKeyState(VK_F7) & 0x80) {
skyNum = 6;
ApplySky();
}
if (GetKeyState(VK_F8) & 0x80) {
skyNum = 7;
ApplySky();
}
if (GetKeyState('P') & 0x80) {
g_type = "pivot";
}
if (GetKeyState('M') & 0x80) {
g_type = "mesh";
}
if (GetKeyState('B') & 0x80) {
g_type = "bone";
}
static char v[] = "012349";
for (auto& i : v) {
if (i && GetKeyState(i) & 0x80) {
animationNumber = i - '0';
}
}
}
void App::Draw()
{
// fontMan.DrawString(Vec2(0, 110), 16, "TEXT SPRITE TEST!!!!!!!!!!!!!text sprite 1234567890");
// fontMan.DrawString(Vec2(10, 130), 32, "@#$%^&*()");
// fontMan.DrawString(Vec2(10, 170), 40, L"あいうえお한글漢字");
ID3D11DeviceContext* context = deviceMan11.GetContext();
rt[0].BeginRenderToThis();
double currentTime = GetTime();
double deltaTime = currentTime - lastTime;
lastTime = currentTime;
if (GetKeyState(VK_RETURN) & 0x01) {
trackTime += deltaTime;
}
matrixMan.Set(MatrixMan::WORLD, Mat());
matrixMan.Set(MatrixMan::VIEW, devCamera.GetViewMatrix());
matrixMan.Set(MatrixMan::PROJ, devCamera.GetProjMatrix());
skyMan.Draw();
// gridRenderer.Draw();
// waterSurface.Draw();
for (int i = 0; i < (int)dimof(mesh); i++) {
Mesh* it = mesh[i];
MeshX* meshX = meshTiny;
MeshXAnimResult meshXAnimResult;
if (it && meshX) {
Bvh* bvh = dynamic_cast<Bvh*>(it);
if (bvh) {
bvh->Draw(animationNumber == 9 ? 0 : animationNumber, trackTime);
if (animationNumber == 9) {
meshX->CalcAnimationFromBvh(bvh, bind[i], trackTime, meshXAnimResult, 270 / radius);
} else {
meshX->CalcAnimation(animationNumber, trackTime, meshXAnimResult);
}
meshX->Draw(meshXAnimResult);
if (GetKeyState('T') & 0x01) {
DrawBoneNames(bvh);
}
}
}
if (meshX && (GetKeyState('T') & 0x01)) {
DrawBoneNames(meshX, meshXAnimResult);
}
}
if (GetKeyState('T') & 0x01) {
DrawCameraParams();
char buf[20];
sprintf(buf, "FPS: %f", fps.Get());
Vec2 pos = { 5, 15 };
fontMan.DrawString(pos, 16, buf);
}
fontMan.Render();
deviceMan11.GetContext()->OMSetRenderTargets(0, nullptr, nullptr); // unbind RT to prevent warnings in debug layer
computeShaderMan.Draw(rt[0].GetTexture(), rt[1].GetUnorderedAccessView());
AFRenderTarget defaultTarget;
defaultTarget.InitForDefaultRenderTarget();
defaultTarget.BeginRenderToThis();
postEffectMan.Draw(rt[1].GetTexture());
deviceMan11.Present();
fps.Update();
}
void App::Destroy()
{
for (auto& it : mesh) {
SAFE_DELETE(it);
}
SAFE_DELETE(meshTiny);
for (auto& it : rt) {
it.Destroy();
}
fontMan.Destroy();
debugRenderer.Destroy();
gridRenderer.Destroy();
waterSurface.Destroy();
postEffectMan.Destroy();
computeShaderMan.Destroy();
computeShaderSkinning.Destroy();
}
std::string g_type;
<|endoftext|>
|
<commit_before>#include <SmurffCpp/Utils/StringUtils.h>
#include <algorithm>
#include <functional>
#include <cctype>
#include <locale>
#include <sstream>
template<>
std::string smurff::_util::convert<std::string>(const std::string& value)
{
return value;
}
template<>
int smurff::_util::convert<int>(const std::string& value)
{
return std::stoi(value);
}
template<>
double smurff::_util::convert<double>(const std::string& value)
{
return std::stod(value);
}
std::string& smurff::ltrim(std::string& s)
{
s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
return s;
}
std::string& smurff::rtrim(std::string& s)
{
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
std::string& smurff::trim(std::string& s)
{
return ltrim(rtrim(s));
}
bool smurff::startsWith(const std::string& str, const std::string& prefix)
{
//protection from out of range exception
if (str.length() < prefix.length())
return false;
return std::equal(prefix.begin(), prefix.end(), str.begin());
}
std::string smurff::stripPrefix(const std::string& str, const std::string& prefix)
{
//protection from out of range exception
if (str.length() < prefix.length())
return str;
if (str.substr(0, prefix.size()) != prefix)
return str;
return fileName(str);
}
std::string smurff::fileName(const std::string& str)
{
auto pos = str.find_last_of("/");
if (std::string::npos == pos)
return str;
return str.substr(pos+1);
}
std::string smurff::dirName(const std::string& str)
{
auto pos = str.find_last_of("/");
if (std::string::npos == pos)
return str;
return str.substr(0, pos+1);
}
std::string smurff::addDirName(const std::string& str, const std::string& dirname)
{
if (str.size() >0 && str[0] == '/')
return str;
return dirname + str;
}
<commit_msg>FIX: return empty string when no dirname in path<commit_after>#include <SmurffCpp/Utils/StringUtils.h>
#include <algorithm>
#include <functional>
#include <cctype>
#include <locale>
#include <sstream>
template<>
std::string smurff::_util::convert<std::string>(const std::string& value)
{
return value;
}
template<>
int smurff::_util::convert<int>(const std::string& value)
{
return std::stoi(value);
}
template<>
double smurff::_util::convert<double>(const std::string& value)
{
return std::stod(value);
}
std::string& smurff::ltrim(std::string& s)
{
s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
return s;
}
std::string& smurff::rtrim(std::string& s)
{
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
std::string& smurff::trim(std::string& s)
{
return ltrim(rtrim(s));
}
bool smurff::startsWith(const std::string& str, const std::string& prefix)
{
//protection from out of range exception
if (str.length() < prefix.length())
return false;
return std::equal(prefix.begin(), prefix.end(), str.begin());
}
std::string smurff::stripPrefix(const std::string& str, const std::string& prefix)
{
//protection from out of range exception
if (str.length() < prefix.length())
return str;
if (str.substr(0, prefix.size()) != prefix)
return str;
return fileName(str);
}
std::string smurff::fileName(const std::string& str)
{
auto pos = str.find_last_of("/");
if (std::string::npos == pos)
return str;
return str.substr(pos+1);
}
std::string smurff::dirName(const std::string& str)
{
auto pos = str.find_last_of("/");
if (std::string::npos == pos)
return std::string();
return str.substr(0, pos+1);
}
std::string smurff::addDirName(const std::string& str, const std::string& dirname)
{
if (str.size() >0 && str[0] == '/')
return str;
return dirname + str;
}
<|endoftext|>
|
<commit_before>// Copyright (C) 2017 - 2018 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and University of
// of Connecticut School of Medicine.
// All rights reserved.
// Copyright (C) 2016 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
#include <QSortFilterProxyModel>
#include "copasi/UI/CQParameterGroupView.h"
#include "copasi/UI/CQComboDelegate.h"
#include "copasi/UI/CQPushButtonDelegate.h"
#include "copasi/UI/CCopasiSelectionDialog.h"
#include "copasi/resourcesUI/CQIconResource.h"
#include "copasi/UI/copasiui3window.h"
#include "copasi/copasi.h"
#include "copasi/UI/qtUtilities.h"
#include "copasi/utilities/CCopasiParameterGroup.h"
#include "copasi/CopasiDataModel/CDataModel.h"
#include "copasi/UI/CQParameterGroupDM.h"
#include "copasi/model/CObjectLists.h"
#include "copasi/utilities/utility.h"
#include "copasi/core/CRootContainer.h"
#include "copasi/commandline/CConfigurationFile.h"
CQParameterGroupView::CQParameterGroupView(QWidget* parent):
QTreeView(parent),
mpParameterGroupDM(NULL),
mpSortFilterDM(NULL),
mpComboBoxDelegate(NULL),
mpPushButtonDelegate(NULL)
{
// create a new QListview to be displayed on the screen..and set its property
mpParameterGroupDM = new CQParameterGroupDM(this);
mpSortFilterDM = new QSortFilterProxyModel(this);
mpSortFilterDM->setFilterKeyColumn(0);
mpSortFilterDM->setFilterRole(Qt::UserRole + 1);
mpSortFilterDM->setFilterRegExp(CRootContainer::getConfiguration()->enableAdditionalOptimizationParameters() ? "" : "basic");
mpSortFilterDM->setSourceModel(mpParameterGroupDM);
mpSortFilterDM->setSortRole(Qt::UserRole + 2);
mpSortFilterDM->sort(0, Qt::DescendingOrder);
setSortingEnabled(true);
setModel(mpSortFilterDM);
mpComboBoxDelegate = new CQComboDelegate(this);
mpPushButtonDelegate = new CQPushButtonDelegate(CQIconResource::icon(CQIconResource::copasi), QString(),
CQPushButtonDelegate::ToolButton, this);
connect(mpParameterGroupDM, SIGNAL(signalCreateComboBox(const QModelIndex &)), this, SLOT(slotCreateComboBox(const QModelIndex &)));
connect(mpParameterGroupDM, SIGNAL(signalCreatePushButton(const QModelIndex &)), this, SLOT(slotCreatePushButton(const QModelIndex &)));
connect(mpParameterGroupDM, SIGNAL(signalCloseEditor(const QModelIndex &)), this, SLOT(slotCloseEditor(const QModelIndex &)));
connect(mpPushButtonDelegate, SIGNAL(clicked(const QModelIndex &)), this, SLOT(slotPushButtonClicked(const QModelIndex &)));
connect(dynamic_cast<CopasiUI3Window *>(CopasiUI3Window::getMainWindow()), SIGNAL(signalPreferenceUpdated()), this, SLOT(slotPreferenceUpdated()));
}
CQParameterGroupView::~CQParameterGroupView()
{}
void CQParameterGroupView::setAdvanced(const bool & advanced)
{
mpParameterGroupDM->setAdvanced(advanced);
}
void CQParameterGroupView::pushGroup(CCopasiParameterGroup * pGroup)
{
mpParameterGroupDM->pushGroup(pGroup);
this->expandAll();
this->resizeColumnToContents(0);
}
void CQParameterGroupView::popGroup(CCopasiParameterGroup * pGroup)
{
mpParameterGroupDM->popGroup(pGroup);
this->expandAll();
this->resizeColumnToContents(0);
}
void CQParameterGroupView::clearGroups()
{
mpParameterGroupDM->clearGroups();
}
void CQParameterGroupView::slotPreferenceUpdated()
{
mpSortFilterDM->setFilterRegExp(CRootContainer::getConfiguration()->enableAdditionalOptimizationParameters() ? "" : "basic");
}
void CQParameterGroupView::slotCreateComboBox(const QModelIndex & index)
{
QModelIndex Source = index;
while (Source.model()->inherits("QSortFilterProxyModel"))
{
Source = static_cast< const QSortFilterProxyModel *>(Source.model())->mapToSource(index);
}
this->setItemDelegateForRow(Source.row(), mpComboBoxDelegate);
this->openPersistentEditor(Source);
this->expandAll();
}
void CQParameterGroupView::slotCreatePushButton(const QModelIndex & index)
{
QModelIndex Source = index;
while (Source.model()->inherits("QSortFilterProxyModel"))
{
Source = static_cast< const QSortFilterProxyModel *>(Source.model())->mapToSource(index);
}
this->setItemDelegateForRow(Source.row(), mpPushButtonDelegate);
this->openPersistentEditor(Source);
this->expandAll();
}
void CQParameterGroupView::slotCloseEditor(const QModelIndex & index)
{
QModelIndex Source = index;
while (Source.model()->inherits("QSortFilterProxyModel"))
{
Source = static_cast< const QSortFilterProxyModel *>(Source.model())->mapToSource(index);
}
if (this->itemDelegateForRow(Source.row()) != mpComboBoxDelegate) return;
this->setItemDelegateForRow(Source.row(), this->itemDelegate());
this->expandAll();
}
void CQParameterGroupView::slotPushButtonClicked(const QModelIndex & index)
{
QModelIndex Source = index;
while (Source.model()->inherits("QSortFilterProxyModel"))
{
Source = static_cast< const QSortFilterProxyModel *>(Source.model())->mapToSource(index);
}
if (this->itemDelegateForRow(Source.row()) != mpPushButtonDelegate) return;
CCopasiParameter * pParameter = CQParameterGroupDM::nodeFromIndex(Source);
if (pParameter->getType() != CCopasiParameter::Type::GROUP) return;
CCopasiParameterGroup * pGroup = static_cast< CCopasiParameterGroup * >(pParameter);
CCopasiParameterGroup::elements::const_iterator it = pGroup->getElementTemplates().beginIndex();
CCopasiParameterGroup::elements::const_iterator end = pGroup->getElementTemplates().endIndex();
for (; it != end; ++it)
{
switch ((*it)->getType())
{
case CCopasiParameter::Type::CN:
modifySelectCNs(*pGroup, **it);
break;
default:
break;
}
}
}
void CQParameterGroupView::modifySelectCNs(CCopasiParameterGroup & group, const CCopasiParameter & cnTemplate)
{
// OpenSelectionDialog
std::vector< const CDataObject * > Selection;
CObjectInterface::ContainerList ContainerList;
ContainerList.push_back(group.getObjectDataModel());
// Create the current selection
CCopasiParameterGroup::elements::iterator it = group.beginIndex();
CCopasiParameterGroup::elements::iterator end = group.endIndex();
for (; it != end; ++it)
{
const CDataObject * pObject = CObjectInterface::DataObject(CObjectInterface::GetObjectFromCN(ContainerList, (*it)->getValue< CCommonName >()));
if (pObject != NULL)
{
Selection.push_back(pObject);
}
}
CModel * pModel = group.getObjectDataModel()->getModel();
std::vector<const CDataObject * > ValidObjects;
const std::vector< std::pair < CCommonName, CCommonName > > & ValidValues = cnTemplate.getValidValues< CCommonName >();
std::vector< std::pair < CCommonName, CCommonName > >::const_iterator itValidValues = ValidValues.begin();
std::vector< std::pair < CCommonName, CCommonName > >::const_iterator endValidValues = ValidValues.end();
for (; itValidValues != endValidValues; ++itValidValues)
{
CObjectLists::ListType ListType = toEnum(itValidValues->first, CObjectLists::ListTypeName, CObjectLists::EMPTY_LIST);
std::vector<const CDataObject * > Tmp = CObjectLists::getListOfConstObjects(ListType, pModel);
ValidObjects.insert(ValidObjects.end(), Tmp.begin(), Tmp.end());
}
std::vector< const CDataObject * > NewSelection = CCopasiSelectionDialog::getObjectVector(this, ValidObjects, &Selection);
// Modify group parameters;
mpParameterGroupDM->beginResetModel();
group.clear();
std::vector< const CDataObject * >::const_iterator itNew = NewSelection.begin();
std::vector< const CDataObject * >::const_iterator endNew = NewSelection.end();
for (; itNew != endNew; ++itNew)
{
group.addParameter("Reaction", CCopasiParameter::Type::CN, (*itNew)->getCN());
}
mpParameterGroupDM->endResetModel();
}
<commit_msg>Bug 2922: The item delegates are reset to default on method change.<commit_after>// Copyright (C) 2019 - 2020 by Pedro Mendes, Rector and Visitors of the
// University of Virginia, University of Heidelberg, and University
// of Connecticut School of Medicine.
// All rights reserved.
// Copyright (C) 2017 - 2018 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and University of
// of Connecticut School of Medicine.
// All rights reserved.
// Copyright (C) 2016 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
#include <QSortFilterProxyModel>
#include "copasi/UI/CQParameterGroupView.h"
#include "copasi/UI/CQComboDelegate.h"
#include "copasi/UI/CQPushButtonDelegate.h"
#include "copasi/UI/CCopasiSelectionDialog.h"
#include "copasi/resourcesUI/CQIconResource.h"
#include "copasi/UI/copasiui3window.h"
#include "copasi/copasi.h"
#include "copasi/UI/qtUtilities.h"
#include "copasi/utilities/CCopasiParameterGroup.h"
#include "copasi/CopasiDataModel/CDataModel.h"
#include "copasi/UI/CQParameterGroupDM.h"
#include "copasi/model/CObjectLists.h"
#include "copasi/utilities/utility.h"
#include "copasi/core/CRootContainer.h"
#include "copasi/commandline/CConfigurationFile.h"
CQParameterGroupView::CQParameterGroupView(QWidget* parent):
QTreeView(parent),
mpParameterGroupDM(NULL),
mpSortFilterDM(NULL),
mpComboBoxDelegate(NULL),
mpPushButtonDelegate(NULL)
{
// create a new QListview to be displayed on the screen..and set its property
mpParameterGroupDM = new CQParameterGroupDM(this);
mpSortFilterDM = new QSortFilterProxyModel(this);
mpSortFilterDM->setFilterKeyColumn(0);
mpSortFilterDM->setFilterRole(Qt::UserRole + 1);
mpSortFilterDM->setFilterRegExp(CRootContainer::getConfiguration()->enableAdditionalOptimizationParameters() ? "" : "basic");
mpSortFilterDM->setSourceModel(mpParameterGroupDM);
mpSortFilterDM->setSortRole(Qt::UserRole + 2);
mpSortFilterDM->sort(0, Qt::DescendingOrder);
setSortingEnabled(true);
setModel(mpSortFilterDM);
mpComboBoxDelegate = new CQComboDelegate(this);
mpPushButtonDelegate = new CQPushButtonDelegate(CQIconResource::icon(CQIconResource::copasi), QString(),
CQPushButtonDelegate::ToolButton, this);
connect(mpParameterGroupDM, SIGNAL(signalCreateComboBox(const QModelIndex &)), this, SLOT(slotCreateComboBox(const QModelIndex &)));
connect(mpParameterGroupDM, SIGNAL(signalCreatePushButton(const QModelIndex &)), this, SLOT(slotCreatePushButton(const QModelIndex &)));
connect(mpParameterGroupDM, SIGNAL(signalCloseEditor(const QModelIndex &)), this, SLOT(slotCloseEditor(const QModelIndex &)));
connect(mpPushButtonDelegate, SIGNAL(clicked(const QModelIndex &)), this, SLOT(slotPushButtonClicked(const QModelIndex &)));
connect(dynamic_cast<CopasiUI3Window *>(CopasiUI3Window::getMainWindow()), SIGNAL(signalPreferenceUpdated()), this, SLOT(slotPreferenceUpdated()));
}
CQParameterGroupView::~CQParameterGroupView()
{}
void CQParameterGroupView::setAdvanced(const bool & advanced)
{
mpParameterGroupDM->setAdvanced(advanced);
}
void CQParameterGroupView::pushGroup(CCopasiParameterGroup * pGroup)
{
mpParameterGroupDM->pushGroup(pGroup);
this->expandAll();
this->resizeColumnToContents(0);
}
void CQParameterGroupView::popGroup(CCopasiParameterGroup * pGroup)
{
mpParameterGroupDM->popGroup(pGroup);
this->expandAll();
this->resizeColumnToContents(0);
}
void CQParameterGroupView::clearGroups()
{
// We need to remove/reset all custom delegates
QAbstractItemDelegate * pDefault = this->itemDelegate();
for (int i = 0; i < mpParameterGroupDM->rowCount(); ++i)
{
this->setItemDelegateForRow(i, pDefault);
}
mpParameterGroupDM->clearGroups();
}
void CQParameterGroupView::slotPreferenceUpdated()
{
mpSortFilterDM->setFilterRegExp(CRootContainer::getConfiguration()->enableAdditionalOptimizationParameters() ? "" : "basic");
}
void CQParameterGroupView::slotCreateComboBox(const QModelIndex & index)
{
QModelIndex Source = index;
while (Source.model()->inherits("QSortFilterProxyModel"))
{
Source = static_cast< const QSortFilterProxyModel *>(Source.model())->mapToSource(index);
}
this->setItemDelegateForRow(Source.row(), mpComboBoxDelegate);
this->openPersistentEditor(Source);
this->expandAll();
}
void CQParameterGroupView::slotCreatePushButton(const QModelIndex & index)
{
QModelIndex Source = index;
while (Source.model()->inherits("QSortFilterProxyModel"))
{
Source = static_cast< const QSortFilterProxyModel *>(Source.model())->mapToSource(index);
}
this->setItemDelegateForRow(Source.row(), mpPushButtonDelegate);
this->openPersistentEditor(Source);
this->expandAll();
}
void CQParameterGroupView::slotCloseEditor(const QModelIndex & index)
{
QModelIndex Source = index;
while (Source.model()->inherits("QSortFilterProxyModel"))
{
Source = static_cast< const QSortFilterProxyModel *>(Source.model())->mapToSource(index);
}
if (this->itemDelegateForRow(Source.row()) != mpComboBoxDelegate) return;
this->setItemDelegateForRow(Source.row(), this->itemDelegate());
this->expandAll();
}
void CQParameterGroupView::slotPushButtonClicked(const QModelIndex & index)
{
QModelIndex Source = index;
while (Source.model()->inherits("QSortFilterProxyModel"))
{
Source = static_cast< const QSortFilterProxyModel *>(Source.model())->mapToSource(index);
}
if (this->itemDelegateForRow(Source.row()) != mpPushButtonDelegate) return;
CCopasiParameter * pParameter = CQParameterGroupDM::nodeFromIndex(Source);
if (pParameter->getType() != CCopasiParameter::Type::GROUP) return;
CCopasiParameterGroup * pGroup = static_cast< CCopasiParameterGroup * >(pParameter);
CCopasiParameterGroup::elements::const_iterator it = pGroup->getElementTemplates().beginIndex();
CCopasiParameterGroup::elements::const_iterator end = pGroup->getElementTemplates().endIndex();
for (; it != end; ++it)
{
switch ((*it)->getType())
{
case CCopasiParameter::Type::CN:
modifySelectCNs(*pGroup, **it);
break;
default:
break;
}
}
}
void CQParameterGroupView::modifySelectCNs(CCopasiParameterGroup & group, const CCopasiParameter & cnTemplate)
{
// OpenSelectionDialog
std::vector< const CDataObject * > Selection;
CObjectInterface::ContainerList ContainerList;
ContainerList.push_back(group.getObjectDataModel());
// Create the current selection
CCopasiParameterGroup::elements::iterator it = group.beginIndex();
CCopasiParameterGroup::elements::iterator end = group.endIndex();
for (; it != end; ++it)
{
const CDataObject * pObject = CObjectInterface::DataObject(CObjectInterface::GetObjectFromCN(ContainerList, (*it)->getValue< CCommonName >()));
if (pObject != NULL)
{
Selection.push_back(pObject);
}
}
CModel * pModel = group.getObjectDataModel()->getModel();
std::vector<const CDataObject * > ValidObjects;
const std::vector< std::pair < CCommonName, CCommonName > > & ValidValues = cnTemplate.getValidValues< CCommonName >();
std::vector< std::pair < CCommonName, CCommonName > >::const_iterator itValidValues = ValidValues.begin();
std::vector< std::pair < CCommonName, CCommonName > >::const_iterator endValidValues = ValidValues.end();
for (; itValidValues != endValidValues; ++itValidValues)
{
CObjectLists::ListType ListType = toEnum(itValidValues->first, CObjectLists::ListTypeName, CObjectLists::EMPTY_LIST);
std::vector<const CDataObject * > Tmp = CObjectLists::getListOfConstObjects(ListType, pModel);
ValidObjects.insert(ValidObjects.end(), Tmp.begin(), Tmp.end());
}
std::vector< const CDataObject * > NewSelection = CCopasiSelectionDialog::getObjectVector(this, ValidObjects, &Selection);
// Modify group parameters;
mpParameterGroupDM->beginResetModel();
group.clear();
std::vector< const CDataObject * >::const_iterator itNew = NewSelection.begin();
std::vector< const CDataObject * >::const_iterator endNew = NewSelection.end();
for (; itNew != endNew; ++itNew)
{
group.addParameter("Reaction", CCopasiParameter::Type::CN, (*itNew)->getCN());
}
mpParameterGroupDM->endResetModel();
}
<|endoftext|>
|
<commit_before>#pragma once
#include <vector>
template<class T, typename S = double>
struct TopKHolder {
size_t k;
std::vector<std::pair<T, S>> data;
TopKHolder(const size_t k);
size_t size() const;
bool updatable(const S s) const;
bool update(T& m, const S s);
S lastScore() const;
};
template<class T, typename S>
TopKHolder<T, S>::TopKHolder(const size_t k)
:k(k)
{
data.reserve(k);
}
template<class T, typename S>
size_t TopKHolder<T, S>::size() const
{
return data.size();
}
template<class T, typename S>
bool TopKHolder<T, S>::updatable(const S s) const
{
return data.size() < k || s > lastScore();
}
template<class T, typename S>
bool TopKHolder<T, S>::update(T& m, const S s)
{
size_t p = find_if(data.rbegin(), data.rend(), [s](const pair<T, S>& p) {
return p.second >= s;
}) - data.rbegin();
p = data.size() - p; // p is the place to insert the new value
if(p < k) {
if(data.size() < k)
data.resize(data.size() + 1);
for(size_t i = data.size() - 1; i > p; --i)
data[i] = move(data[i - 1]);
data[p] = make_pair(move(m), s);
return true;
}
return false;
}
template<class T, typename S>
S TopKHolder<T, S>::lastScore() const
{
return data.empty() ? -numeric_limits<S>::min() : data.back().second;
}
<commit_msg>compile fix<commit_after>#pragma once
#include <vector>
template<class T, typename S = double>
struct TopKHolder {
size_t k;
std::vector<std::pair<T, S>> data;
TopKHolder(const size_t k);
size_t size() const;
bool updatable(const S s) const;
bool update(T& m, const S s);
S lastScore() const;
std::vector<T> getResult() const;
std::vector<T> getResultMove();
};
template<class T, typename S>
TopKHolder<T, S>::TopKHolder(const size_t k)
:k(k)
{
data.reserve(k);
}
template<class T, typename S>
size_t TopKHolder<T, S>::size() const
{
return data.size();
}
template<class T, typename S>
bool TopKHolder<T, S>::updatable(const S s) const
{
return data.size() < k || s > lastScore();
}
template<class T, typename S>
bool TopKHolder<T, S>::update(T& m, const S s)
{
size_t p = find_if(data.rbegin(), data.rend(), [s](const std::pair<T, S>& p) {
return p.second >= s;
}) - data.rbegin();
p = data.size() - p; // p is the place to insert the new value
if(p < k) {
if(data.size() < k)
data.resize(data.size() + 1);
for(size_t i = data.size() - 1; i > p; --i)
data[i] = move(data[i - 1]);
data[p] = make_pair(move(m), s);
return true;
}
return false;
}
template<class T, typename S>
S TopKHolder<T, S>::lastScore() const
{
return data.empty() ? - std::numeric_limits<S>::min() : data.back().second;
}
template<class T, typename S>
inline std::vector<T> TopKHolder<T, S>::getResult() const
{
std::vector<T> res;
res.reserve(data.size());
for(auto& p : data)
res.push_back(p.first);
return res;
}
template<class T, typename S>
inline std::vector<T> TopKHolder<T, S>::getResultMove()
{
std::vector<T> res;
res.reserve(data.size());
for(auto& p : data)
res.push_back(move(p.first));
return res;
}
<|endoftext|>
|
<commit_before>/*
* Tyrion
* Copyright 2010, Silas Sewell
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <csignal>
#include <pthread.h>
#include <txmpp/cryptstring.h>
#include <txmpp/thread.h>
#include <txmpp/xmppclientsettings.h>
#include "logging.h"
#include "node_loop.h"
#include "node_settings.h"
#include "node_utils.h"
#ifdef _DEBUG
#include <txmpp/logging.h>
#endif
int main(int argc, char* argv[]) {
#ifdef _DEBUG
txmpp::LogMessage::LogToDebug(txmpp::LS_SENSITIVE);
#endif
int code = 0;
int sig;
sigset_t set;
sigset_t set_waiting;
sigemptyset(&set);
sigaddset(&set, SIGHUP);
sigaddset(&set, SIGINT);
sigaddset(&set, SIGTERM);
pthread_sigmask(SIG_BLOCK, &set, NULL);
tyrion::Logging::Instance()->Debug(tyrion::Logging::DEBUG);
tyrion::NodeSetupConfig(argc, argv);
tyrion::NodeLoop* loop = tyrion::NodeLoop::Instance();
loop->Start();
loop->Login();
while (true) {
sigwait(&set, &sig);
if (sig == SIGHUP) {
loop->Restart();
break;
} else if (sig == SIGINT || sig == SIGTERM) {
if (loop->state() == tyrion::NodeLoop::ERROR) code = 1;
loop->Disconnect();
loop->Quit();
loop->Stop();
break;
}
}
return code;
}
<commit_msg>Remove unused variable<commit_after>/*
* Tyrion
* Copyright 2010, Silas Sewell
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <csignal>
#include <pthread.h>
#include <txmpp/cryptstring.h>
#include <txmpp/thread.h>
#include <txmpp/xmppclientsettings.h>
#include "logging.h"
#include "node_loop.h"
#include "node_settings.h"
#include "node_utils.h"
#ifdef _DEBUG
#include <txmpp/logging.h>
#endif
int main(int argc, char* argv[]) {
#ifdef _DEBUG
txmpp::LogMessage::LogToDebug(txmpp::LS_SENSITIVE);
#endif
int code = 0;
int sig;
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGHUP);
sigaddset(&set, SIGINT);
sigaddset(&set, SIGTERM);
pthread_sigmask(SIG_BLOCK, &set, NULL);
tyrion::Logging::Instance()->Debug(tyrion::Logging::DEBUG);
tyrion::NodeSetupConfig(argc, argv);
tyrion::NodeLoop* loop = tyrion::NodeLoop::Instance();
loop->Start();
loop->Login();
while (true) {
sigwait(&set, &sig);
if (sig == SIGHUP) {
loop->Restart();
break;
} else if (sig == SIGINT || sig == SIGTERM) {
if (loop->state() == tyrion::NodeLoop::ERROR) code = 1;
loop->Disconnect();
loop->Quit();
loop->Stop();
break;
}
}
return code;
}
<|endoftext|>
|
<commit_before>#include <stdexcept>
#include <string>
#include <ros/ros.h>
#include <actionlib/client/simple_action_client.h>
#include <geometry_msgs/Point.h>
#include <geometry_msgs/Quaternion.h>
#include <geometry_msgs/TransformStamped.h>
#include <goal_sender_msgs/ApplyGoals.h>
#include <goal_sender_msgs/GoalSequence.h>
#include <move_base_msgs/MoveBaseAction.h>
#include <move_base_msgs/MoveBaseGoal.h>
#include <tf2_geometry_msgs/tf2_geometry_msgs.h>
#include <tf2_ros/transform_listener.h>
inline double squaring_distance(const geometry_msgs::Point& a, const geometry_msgs::Point& b) {
const auto x {a.x - b.x};
const auto y {a.y - b.y};
return x*x + y*y;
}
/**
* Waypoint update service manager
*/
class WaypointManager
{
public:
bool operator()(goal_sender_msgs::ApplyGoals::Request& req,
goal_sender_msgs::ApplyGoals::Response& res){
sequence_ = req.goal_sequence;
now_goal_ = sequence_.waypoints.begin();
res.success = true;
res.message = "update waypoints";
return true;
}
const geometry_msgs::Point& point() const
{
if (is_end()) throw std::logic_error {"range error: Please check is_end() before point()"};
return now_goal_->position;
}
const geometry_msgs::Quaternion& quaternion() const
{
if (is_end()) throw std::logic_error {"range error: Please check is_end() before quaternion()"};
return now_goal_->orientation;
}
double radius() const
{
if (is_end()) throw std::logic_error {"range error: Please check is_end() before radius()"};
return now_goal_->radius;
}
bool next()
{
if (is_end()) throw std::logic_error {"range error: Please check is_end() before next()"}; // wrong way.
if (++now_goal_ == sequence_.waypoints.end())
return false; // correct way: this is last one.
return true;
}
bool is_end() const noexcept
{
return sequence_.waypoints.end() == now_goal_;
}
explicit operator bool() noexcept
{
return !is_end();
}
[[deprecated]]
const goal_sender_msgs::Waypoint& get() const
{
if (is_end()) throw std::logic_error {"range error: Please check is_end() before get()"};
return *now_goal_;
}
private:
goal_sender_msgs::GoalSequence sequence_;
decltype(sequence_.waypoints)::iterator now_goal_;
};
/**
* Tf lookup API
*/
class TfPositionManager
{
public:
explicit TfPositionManager(tf2_ros::Buffer& tfBuffer) // buffer is lvalue
: buffer_ {tfBuffer}
{
}
geometry_msgs::Point operator()(std::string parent, std::string child) const
{
const auto ts {buffer_.lookupTransform(parent, child, ros::Time(0))};
geometry_msgs::Point point;
point.x = ts.transform.translation.x;
point.y = ts.transform.translation.y;
return point;
}
private:
const tf2_ros::Buffer& buffer_;
};
class GoalSender
{
public:
using MoveBaseActionClient = actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction>;
GoalSender(WaypointManager& point_manager,
MoveBaseActionClient& move_base_client,
TfPositionManager lookupper)
: point_manager_ {point_manager},
move_base_client_ {move_base_client},
lookupper_ {lookupper}
{
}
void once()
{
if (!point_manager_)
return; // no work
if (is_reach()) {
point_manager_.next();
send_goal();
}
}
private:
bool is_reach() const
{
const auto robot_point {lookupper_("/map", "/base_link")};
const auto waypoint_point {point_manager_.point()};
const auto sqr_distance {squaring_distance(robot_point, waypoint_point)};
const auto radius {point_manager_.radius()};
const auto sqr_radius {radius * radius};
if (sqr_distance < sqr_radius) // into valid range
return true;
return false;
}
void send_goal() const
{
if (!point_manager_) { // finish waypoint
move_base_client_.cancelGoal(); // cancel moveing
ROS_INFO("Finish waypoints");
return;
}
move_base_msgs::MoveBaseGoal goal;
goal.target_pose.pose.position = point_manager_.point();
goal.target_pose.pose.orientation = point_manager_.quaternion();
goal.target_pose.header.frame_id = "/map";
goal.target_pose.header.stamp = ros::Time::now();
move_base_client_.sendGoal(goal); // send waypoint
}
WaypointManager& point_manager_;
MoveBaseActionClient& move_base_client_;
TfPositionManager lookupper_;
};
int main(int argc, char** argv)
{
ros::init(argc, argv, "goal_sender");
ros::NodeHandle nh {};
WaypointManager point_manager {};
ros::ServiceServer srv {
nh.advertiseService<goal_sender_msgs::ApplyGoals::Request,
goal_sender_msgs::ApplyGoals::Response>(
"apply_goals", point_manager)};
tf2_ros::Buffer tfBuffer;
tf2_ros::TransformListener tfListener {tfBuffer};
TfPositionManager lookupper {tfBuffer};
GoalSender::MoveBaseActionClient move_base_client {"move_base", true};
move_base_client.waitForServer();
GoalSender goal_sender {point_manager, move_base_client, lookupper};
ros::Rate rate {10};
while (ros::ok()) {
ros::spinOnce();
goal_sender.once();
}
}
<commit_msg>Add constructor for bugfix<commit_after>#include <stdexcept>
#include <string>
#include <ros/ros.h>
#include <actionlib/client/simple_action_client.h>
#include <geometry_msgs/Point.h>
#include <geometry_msgs/Quaternion.h>
#include <geometry_msgs/TransformStamped.h>
#include <goal_sender_msgs/ApplyGoals.h>
#include <goal_sender_msgs/GoalSequence.h>
#include <move_base_msgs/MoveBaseAction.h>
#include <move_base_msgs/MoveBaseGoal.h>
#include <tf2_geometry_msgs/tf2_geometry_msgs.h>
#include <tf2_ros/transform_listener.h>
inline double squaring_distance(const geometry_msgs::Point& a, const geometry_msgs::Point& b) {
const auto x {a.x - b.x};
const auto y {a.y - b.y};
return x*x + y*y;
}
/**
* Waypoint update service manager
*/
class WaypointManager
{
public:
WaypointManager()
: sequence_ {},
now_goal_ {sequence_.waypoints.end()}
{
}
bool operator()(goal_sender_msgs::ApplyGoals::Request& req,
goal_sender_msgs::ApplyGoals::Response& res){
sequence_ = req.goal_sequence;
now_goal_ = sequence_.waypoints.begin();
res.success = true;
res.message = "update waypoints";
return true;
}
const geometry_msgs::Point& point() const
{
if (is_end()) throw std::logic_error {"range error: Please check is_end() before point()"};
return now_goal_->position;
}
const geometry_msgs::Quaternion& quaternion() const
{
if (is_end()) throw std::logic_error {"range error: Please check is_end() before quaternion()"};
return now_goal_->orientation;
}
double radius() const
{
if (is_end()) throw std::logic_error {"range error: Please check is_end() before radius()"};
return now_goal_->radius;
}
bool next()
{
if (is_end()) throw std::logic_error {"range error: Please check is_end() before next()"}; // wrong way.
if (++now_goal_ == sequence_.waypoints.end())
return false; // correct way: this is last one.
return true;
}
bool is_end() const noexcept
{
return sequence_.waypoints.end() == now_goal_;
}
explicit operator bool() noexcept
{
return !is_end();
}
[[deprecated]]
const goal_sender_msgs::Waypoint& get() const
{
if (is_end()) throw std::logic_error {"range error: Please check is_end() before get()"};
return *now_goal_;
}
private:
goal_sender_msgs::GoalSequence sequence_;
decltype(sequence_.waypoints)::iterator now_goal_;
};
/**
* Tf lookup API
*/
class TfPositionManager
{
public:
explicit TfPositionManager(tf2_ros::Buffer& tfBuffer) // buffer is lvalue
: buffer_ {tfBuffer}
{
}
geometry_msgs::Point operator()(std::string parent, std::string child) const
{
const auto ts {buffer_.lookupTransform(parent, child, ros::Time(0))};
geometry_msgs::Point point;
point.x = ts.transform.translation.x;
point.y = ts.transform.translation.y;
return point;
}
private:
const tf2_ros::Buffer& buffer_;
};
class GoalSender
{
public:
using MoveBaseActionClient = actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction>;
GoalSender(WaypointManager& point_manager,
MoveBaseActionClient& move_base_client,
TfPositionManager lookupper)
: point_manager_ {point_manager},
move_base_client_ {move_base_client},
lookupper_ {lookupper}
{
}
void once()
{
if (!point_manager_)
return; // no work
if (is_reach()) {
point_manager_.next();
send_goal();
}
}
private:
bool is_reach() const
{
const auto robot_point {lookupper_("/map", "/base_link")};
const auto waypoint_point {point_manager_.point()};
const auto sqr_distance {squaring_distance(robot_point, waypoint_point)};
const auto radius {point_manager_.radius()};
const auto sqr_radius {radius * radius};
if (sqr_distance < sqr_radius) // into valid range
return true;
return false;
}
void send_goal() const
{
if (!point_manager_) { // finish waypoint
move_base_client_.cancelGoal(); // cancel moveing
ROS_INFO("Finish waypoints");
return;
}
move_base_msgs::MoveBaseGoal goal;
goal.target_pose.pose.position = point_manager_.point();
goal.target_pose.pose.orientation = point_manager_.quaternion();
goal.target_pose.header.frame_id = "/map";
goal.target_pose.header.stamp = ros::Time::now();
move_base_client_.sendGoal(goal); // send waypoint
}
WaypointManager& point_manager_;
MoveBaseActionClient& move_base_client_;
TfPositionManager lookupper_;
};
int main(int argc, char** argv)
{
ros::init(argc, argv, "goal_sender");
ros::NodeHandle nh {};
WaypointManager point_manager {};
ros::ServiceServer srv {
nh.advertiseService<goal_sender_msgs::ApplyGoals::Request,
goal_sender_msgs::ApplyGoals::Response>(
"apply_goals", point_manager)};
tf2_ros::Buffer tfBuffer;
tf2_ros::TransformListener tfListener {tfBuffer};
TfPositionManager lookupper {tfBuffer};
GoalSender::MoveBaseActionClient move_base_client {"move_base", true};
move_base_client.waitForServer();
GoalSender goal_sender {point_manager, move_base_client, lookupper};
ros::Rate rate {10};
while (ros::ok()) {
ros::spinOnce();
goal_sender.once();
}
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include "menuinterface.h"
#ifdef _WIN32
#include <windows.h>
#endif
using namespace std;
/*
bool systemCheck
{
#ifdef _APPLE_
return 0;
#elif _WIN32
return 1;
#else
return 2;
#endif
}
*/
MenuInterface::MenuInterface()
{
_firstTimeBooting = 0;
}
void MenuInterface::invalidInput()
{
cout << endl;
cout << "Your input was invalid, please try again." << endl;
cout << endl;
}
void MenuInterface::banner()
{
//if program is run on Windows then the banner is displayed in color
#ifdef _WIN32
//sets color of font to pink
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, 13);
//system("CLS");
if(_firstTimeBooting == constants::FIRST_TIME)
{
cout << endl;
cout << " ********************************************" << endl;
cout << " * WELCOME TO THE COMPUTER SCIENCE LIST *" << endl;
cout << " ********************************************" << endl;
cout << endl;
SetConsoleTextAttribute(hConsole, 15); //set back to black background and white text
_firstTimeBooting = 1; //just something else than 0
}
else
{
cout << endl;
cout << " ********************************************" << endl;
cout << " * COMPUTER SCIENCE LIST *" << endl;
cout << " ********************************************" << endl;
cout << endl;
SetConsoleTextAttribute(hConsole, 15); //set back to black background and white text
}
//if program is run on Apple the banner displays white as normal
#else
//system("CLS");
if(_firstTimeBooting == constants::FIRST_TIME)
{
cout << endl;
cout << " ********************************************" << endl;
cout << " * WELCOME TO THE COMPUTER SCIENCE LIST *" << endl;
cout << " ********************************************" << endl;
cout << endl;
_firstTimeBooting = 1; //just something else than 0
}
else
{
cout << endl;
cout << " ********************************************" << endl;
cout << " * COMPUTER SCIENCE LIST *" << endl;
cout << " ********************************************" << endl;
cout << endl;
}
#endif
}
void MenuInterface::DisplayMenu()
{
string choice;
while(choice != "Q" || choice != "q")
{
cout << "| 1 | Display either a computer or a scientist" << endl;
cout << "| 2 | Search the list" << endl;
cout << "| 3 | Add to the list" << endl;
cout << "| 4 | Remove from the list" << endl;
cout << "| Q | Exit the program" << endl;
cout << "Enter your choice here: ";
cin >> choice;
cout << endl;
if(choice == constants::DISPLAY_LIST || choice == constants::ADD || choice == constants::SEARCH || choice == constants::REMOVE)
{
processChoice(choice);
}
else if(choice == "Q" || choice == "q")
{
char choice;
cout << "Are you sure you want to quit the program?" << endl;
cout << "Enter y for yes, and n for no: ";
cin >> choice;
if(choice != 'y' && choice != 'Y')
{
cout << endl;
DisplayMenu();
}
else
{
cout << endl;
return;
}
}
else
{
invalidInput();
banner();
DisplayMenu();
}
}
}
void MenuInterface::processChoice(const string choice)
{
string subMenuChoice = "";
bool valid = false;
while(valid == false)
{
cout << endl;
cout << "Choose either:" << endl;
cout << "| 1 | Computer " << endl;
cout << "| 2 | Scientist " << endl;
cout << "| 0 | Go back" << endl;
cin >> subMenuChoice;
if(subMenuChoice == constants::GO_BACK)
{
return;
}
if(subMenuChoice == "1" || subMenuChoice == "2")
{
valid = true;
}
else
{
invalidInput();
}
}
int subMenuInt = stoi(subMenuChoice);
int choiceInt = stoi(choice);
banner();
// Computer operations
if(subMenuInt == constants::INT_COMPUTER)
{
switch (choiceInt)
{
case 1:
displayComputers();
break;
case 2:
_userLayer.searchForAComputer();
break;
case 3:
// User gets a choice between:
// 1. adding a computer
// 2. adding a computer type
_userLayer.computerChoice();
break;
case 4:
_userLayer.removeComputerFromList();
break;
default:
invalidInput();
break;
}
}
// Scientist operations
else if(subMenuInt == constants::INT_SCIENTIST)
{
switch (choiceInt)
{
case 1:
displayScientists();
break;
case 2:
_userLayer.searchForAPerson();
break;
case 3:
_userLayer.addPerson();
break;
case 4:
_userLayer.removePersonFromList();
break;
default:
// This should never run
invalidInput();
break;
}
}
else
{
// This should never run
cout << "Something went wrong" << endl;
}
}
void MenuInterface::displayComputers()
{
string sortOption;
_userLayer.printCompleteListOfComputers();
cout << "| 1 | Sort computers by alphabetical order" << endl;
cout << "| 2 | Sort computers by descending alphabetical order" << endl;
cout << "| 3 | Sort by year of build" << endl;
cout << "| 4 | Sort by year of design" << endl;
cout << "| 5 | Sort by type of computer" << endl;
cout << "| 6 | View more info on a computer" << endl;
cout << "| 0 | Go back" << endl;
cout << "Enter your choice here: ";
cin >> sortOption;
cout << endl;
if(sortOption == constants::SORT_ALPHABET)
{
banner();
_userLayer.sortComputerListAlphabetically();
}
else if(sortOption == constants::SORT_DESCENDING_ALPHABET)
{
banner();
_userLayer.sortComputerListAlphabeticallyDESC();
}
else if(sortOption == constants::SORT_BY_BUILDYEAR)
{
banner();
_userLayer.sortComputerListByBuildYear();
}
else if(sortOption == constants::SORT_BY_DESIGNYEAR)
{
banner();
_userLayer.sortComputerListByDesignYear();
}
else if(sortOption == constants::SORT_BY_TYPE)
{
banner();
_userLayer.sortComputerListByType();
}
else if(sortOption == constants::MORE_INFO)
{
_userLayer.printListMoreInfoComputer();
}
else if(sortOption == constants::GO_BACK)
{
banner();
}
else
{
banner();
invalidInput();
}
}
void MenuInterface::displayScientists()
{
string sortOption;
_userLayer.printCompleteList();
cout << "| 1 | Sort computer scientists by alphabetical order" << endl;
cout << "| 2 | Sort computer scientists by descending alphabetical order" << endl;
cout << "| 3 | Sort computer scientists by year of birth" << endl;
cout << "| 4 | Sort computer scientists by ascending year of birth" << endl;
cout << "| 5 | Sort computer scientists by year of death" << endl;
cout << "| 6 | Sort computer scientists by age" << endl;
cout << "| 7 | Sort computer scientists by gender" << endl;
cout << "| 0 | Go back" << endl;
cout << "Enter your choice here: ";
cin >> sortOption;
cout << endl;
if(sortOption == constants::SORT_ALPHABET)
{
banner();
_userLayer.sortScientistListAlphabetically();
}
else if(sortOption == constants::SORT_BY_YEAR_OF_BIRTH)
{
banner();
_userLayer.sortScientistListByBirthYear();
}
else if(sortOption == constants::SORT_BY_YEAR_OF_DEATH)
{
banner();
_userLayer.sortScientistListByDeathYear();
}
else if(sortOption == constants::SORT_BY_AGE)
{
banner();
_userLayer.sortScientistListByAge();
}
else if(sortOption == constants::SORT_DESCENDING_ALPHABET)
{
banner();
_userLayer.sortScientistListAlphabeticallyDESC();
}
else if(sortOption == constants::SORT_BY_ASCENDING_YEAR_OF_BIRTH)
{
banner();
_userLayer.sortScientistListByBirthYearASC();
}
else if(sortOption == constants::SORT_BY_GENDER)
{
banner();
_userLayer.sortScientistListByGender();
}
else if(sortOption == constants::GO_BACK)
{
banner();
}
else
{
banner();
invalidInput();
}
}
<commit_msg>tok ut ur menuinterface stuff<commit_after>#include <iostream>
#include "menuinterface.h"
#ifdef _WIN32
#include <windows.h>
#endif
using namespace std;
MenuInterface::MenuInterface()
{
_firstTimeBooting = 0;
}
void MenuInterface::invalidInput()
{
cout << endl;
cout << "Your input was invalid, please try again." << endl;
cout << endl;
}
void MenuInterface::banner()
{
//if program is run on Windows then the banner is displayed in color
#ifdef _WIN32
//sets color of font to pink
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, 13);
//system("CLS");
if(_firstTimeBooting == constants::FIRST_TIME)
{
cout << endl;
cout << " ********************************************" << endl;
cout << " * WELCOME TO THE COMPUTER SCIENCE LIST *" << endl;
cout << " ********************************************" << endl;
cout << endl;
SetConsoleTextAttribute(hConsole, 15); //set back to black background and white text
_firstTimeBooting = 1; //just something else than 0
}
else
{
cout << endl;
cout << " ********************************************" << endl;
cout << " * COMPUTER SCIENCE LIST *" << endl;
cout << " ********************************************" << endl;
cout << endl;
SetConsoleTextAttribute(hConsole, 15); //set back to black background and white text
}
//if program is run on Apple the banner displays white as normal
#else
//system("CLS");
if(_firstTimeBooting == constants::FIRST_TIME)
{
cout << endl;
cout << " ********************************************" << endl;
cout << " * WELCOME TO THE COMPUTER SCIENCE LIST *" << endl;
cout << " ********************************************" << endl;
cout << endl;
_firstTimeBooting = 1; //just something else than 0
}
else
{
cout << endl;
cout << " ********************************************" << endl;
cout << " * COMPUTER SCIENCE LIST *" << endl;
cout << " ********************************************" << endl;
cout << endl;
}
#endif
}
void MenuInterface::DisplayMenu()
{
string choice;
while(choice != "Q" || choice != "q")
{
cout << "| 1 | Display either a computer or a scientist" << endl;
cout << "| 2 | Search the list" << endl;
cout << "| 3 | Add to the list" << endl;
cout << "| 4 | Remove from the list" << endl;
cout << "| Q | Exit the program" << endl;
cout << "Enter your choice here: ";
cin >> choice;
cout << endl;
if(choice == constants::DISPLAY_LIST || choice == constants::ADD || choice == constants::SEARCH || choice == constants::REMOVE)
{
processChoice(choice);
}
else if(choice == "Q" || choice == "q")
{
char choice;
cout << "Are you sure you want to quit the program?" << endl;
cout << "Enter y for yes, and n for no: ";
cin >> choice;
if(choice != 'y' && choice != 'Y')
{
cout << endl;
DisplayMenu();
}
else
{
cout << endl;
return;
}
}
else
{
invalidInput();
banner();
DisplayMenu();
}
}
}
void MenuInterface::processChoice(const string choice)
{
string subMenuChoice = "";
bool valid = false;
while(valid == false)
{
cout << endl;
cout << "Choose either:" << endl;
cout << "| 1 | Computer " << endl;
cout << "| 2 | Scientist " << endl;
cout << "| 0 | Go back" << endl;
cin >> subMenuChoice;
if(subMenuChoice == constants::GO_BACK)
{
return;
}
if(subMenuChoice == "1" || subMenuChoice == "2")
{
valid = true;
}
else
{
invalidInput();
}
}
int subMenuInt = stoi(subMenuChoice);
int choiceInt = stoi(choice);
banner();
// Computer operations
if(subMenuInt == constants::INT_COMPUTER)
{
switch (choiceInt)
{
case 1:
displayComputers();
break;
case 2:
_userLayer.searchForAComputer();
break;
case 3:
// User gets a choice between:
// 1. adding a computer
// 2. adding a computer type
_userLayer.computerChoice();
break;
case 4:
_userLayer.removeComputerFromList();
break;
default:
invalidInput();
break;
}
}
// Scientist operations
else if(subMenuInt == constants::INT_SCIENTIST)
{
switch (choiceInt)
{
case 1:
displayScientists();
break;
case 2:
_userLayer.searchForAPerson();
break;
case 3:
_userLayer.addPerson();
break;
case 4:
_userLayer.removePersonFromList();
break;
default:
// This should never run
invalidInput();
break;
}
}
else
{
// This should never run
cout << "Something went wrong" << endl;
}
}
void MenuInterface::displayComputers()
{
string sortOption;
_userLayer.printCompleteListOfComputers();
cout << "| 1 | Sort computers by alphabetical order" << endl;
cout << "| 2 | Sort computers by descending alphabetical order" << endl;
cout << "| 3 | Sort by year of build" << endl;
cout << "| 4 | Sort by year of design" << endl;
cout << "| 5 | Sort by type of computer" << endl;
cout << "| 6 | View more info on a computer" << endl;
cout << "| 0 | Go back" << endl;
cout << "Enter your choice here: ";
cin >> sortOption;
cout << endl;
if(sortOption == constants::SORT_ALPHABET)
{
banner();
_userLayer.sortComputerListAlphabetically();
}
else if(sortOption == constants::SORT_DESCENDING_ALPHABET)
{
banner();
_userLayer.sortComputerListAlphabeticallyDESC();
}
else if(sortOption == constants::SORT_BY_BUILDYEAR)
{
banner();
_userLayer.sortComputerListByBuildYear();
}
else if(sortOption == constants::SORT_BY_DESIGNYEAR)
{
banner();
_userLayer.sortComputerListByDesignYear();
}
else if(sortOption == constants::SORT_BY_TYPE)
{
banner();
_userLayer.sortComputerListByType();
}
else if(sortOption == constants::MORE_INFO)
{
_userLayer.printListMoreInfoComputer();
}
else if(sortOption == constants::GO_BACK)
{
banner();
}
else
{
banner();
invalidInput();
}
}
void MenuInterface::displayScientists()
{
string sortOption;
_userLayer.printCompleteList();
cout << "| 1 | Sort computer scientists by alphabetical order" << endl;
cout << "| 2 | Sort computer scientists by descending alphabetical order" << endl;
cout << "| 3 | Sort computer scientists by year of birth" << endl;
cout << "| 4 | Sort computer scientists by ascending year of birth" << endl;
cout << "| 5 | Sort computer scientists by year of death" << endl;
cout << "| 6 | Sort computer scientists by age" << endl;
cout << "| 7 | Sort computer scientists by gender" << endl;
cout << "| 0 | Go back" << endl;
cout << "Enter your choice here: ";
cin >> sortOption;
cout << endl;
if(sortOption == constants::SORT_ALPHABET)
{
banner();
_userLayer.sortScientistListAlphabetically();
}
else if(sortOption == constants::SORT_BY_YEAR_OF_BIRTH)
{
banner();
_userLayer.sortScientistListByBirthYear();
}
else if(sortOption == constants::SORT_BY_YEAR_OF_DEATH)
{
banner();
_userLayer.sortScientistListByDeathYear();
}
else if(sortOption == constants::SORT_BY_AGE)
{
banner();
_userLayer.sortScientistListByAge();
}
else if(sortOption == constants::SORT_DESCENDING_ALPHABET)
{
banner();
_userLayer.sortScientistListAlphabeticallyDESC();
}
else if(sortOption == constants::SORT_BY_ASCENDING_YEAR_OF_BIRTH)
{
banner();
_userLayer.sortScientistListByBirthYearASC();
}
else if(sortOption == constants::SORT_BY_GENDER)
{
banner();
_userLayer.sortScientistListByGender();
}
else if(sortOption == constants::GO_BACK)
{
banner();
}
else
{
banner();
invalidInput();
}
}
<|endoftext|>
|
<commit_before>//============================================================================
// MCKL/include/mckl/random/uniform_int_distribution.hpp
//----------------------------------------------------------------------------
// MCKL: Monte Carlo Kernel Library
//----------------------------------------------------------------------------
// Copyright (c) 2013-2016, Yan Zhou
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//============================================================================
#ifndef MCKL_RANDOM_UNIFORM_INT_DISTRIBUTION_HPP
#define MCKL_RANDOM_UNIFORM_INT_DISTRIBUTION_HPP
#include <mckl/random/internal/common.hpp>
#include <mckl/random/u01_distribution.hpp>
namespace mckl
{
namespace internal
{
template <typename IntType>
inline bool uniform_int_distribution_use_double_big(
IntType a, IntType b, std::true_type)
{
static constexpr IntType imax = const_one<IntType>() << 32;
return a > -imax && b < imax;
}
template <typename IntType>
inline bool uniform_int_distribution_use_double_big(
IntType, IntType b, std::false_type)
{
static constexpr IntType imax = const_one<IntType>() << 32;
return b < imax;
}
template <typename IntType>
inline bool uniform_int_distribution_use_double(
IntType, IntType, std::true_type)
{
return true;
}
template <typename IntType>
inline bool uniform_int_distribution_use_double(
IntType a, IntType b, std::false_type)
{
return uniform_int_distribution_use_double_big(
a, b, std::is_signed<IntType>());
}
template <typename IntType>
inline bool uniform_int_distribution_use_double(IntType a, IntType b)
{
return uniform_int_distribution_use_double(
a, b, std::integral_constant<bool,
std::numeric_limits<IntType>::digits <= 32>());
}
template <typename IntType>
inline bool uniform_int_distribution_check_param(IntType a, IntType b)
{
return a <= b;
}
template <std::size_t K, typename IntType, typename RNGType>
inline void uniform_int_distribution_impl(RNGType &rng, std::size_t n,
IntType *r, IntType a, IntType b, std::true_type)
{
double ra = static_cast<double>(a);
double rb = static_cast<double>(b);
Array<double, K> s;
double *const u = s.data();
u01_co_distribution(rng, n, u);
fma(n, u, rb - ra + const_one<double>(), ra, u);
floor(n, u, u);
for (std::size_t i = 0; i != n; ++i)
r[i] = static_cast<IntType>(u[i]);
}
template <std::size_t, typename IntType, typename RNGType>
inline void uniform_int_distribution_impl(RNGType &rng, std::size_t n,
IntType *r, IntType a, IntType b, std::false_type)
{
std::uniform_int_distribution<IntType> uniform(a, b);
rand(rng, uniform, n, r);
}
template <std::size_t K, typename IntType, typename RNGType>
inline void uniform_int_distribution_impl(
RNGType &rng, std::size_t n, IntType *r, IntType a, IntType b)
{
using UIntType = typename std::make_unsigned<IntType>::type;
static constexpr IntType imin = std::numeric_limits<IntType>::min();
static constexpr IntType imax = std::numeric_limits<IntType>::max();
if (a == b) {
std::fill_n(r, n, a);
return;
}
if (a == imin && b == imax) {
uniform_bits_distribution(rng, n, reinterpret_cast<UIntType *>(r));
return;
}
uniform_int_distribution_use_double(a, b) ?
uniform_int_distribution_impl<K>(rng, n, r, a, b, std::true_type()) :
uniform_int_distribution_impl<K>(rng, n, r, a, b, std::false_type());
}
MCKL_DEFINE_RANDOM_DISTRIBUTION_IMPL_2(
UniformInt, uniform_int, IntType, IntType, a, IntType, b)
} // namespace mckl::internal
/// \brief Uniform integer distribution
/// \ingroup Distribution
template <typename IntType>
class UniformIntDistribution
{
MCKL_DEFINE_RANDOM_DISTRIBUTION_ASSERT_INT_TYPE(UniformInt, short)
MCKL_DEFINE_RANDOM_DISTRIBUTION_2(UniformInt, uniform_int, IntType,
result_type, a, 0, result_type, b,
std::numeric_limits<result_type>::max())
MCKL_DEFINE_RANDOM_DISTRIBUTION_MEMBER_0
public:
result_type min() const { return a(); }
result_type max() const { return b(); }
void reset() {}
private:
template <typename RNGType>
result_type generate(RNGType &rng, const param_type ¶m)
{
using UIntType = typename std::make_unsigned<result_type>::type;
static constexpr result_type imin =
std::numeric_limits<result_type>::min();
static constexpr result_type imax =
std::numeric_limits<result_type>::max();
if (param.a() == param.b())
return param.a();
UniformBitsDistribution<UIntType> ubits;
if (param.a() == imin && param.b() == imax)
return static_cast<result_type>(ubits(rng));
return internal::uniform_int_distribution_use_double(
param.a(), param.b()) ?
generate(rng, param, std::true_type()) :
generate(rng, param, std::false_type());
}
template <typename RNGType>
result_type generate(RNGType &rng, const param_type ¶m, std::true_type)
{
U01CODistribution<double> u01;
double ra = static_cast<double>(param.a());
double rb = static_cast<double>(param.b());
double u = ra + (rb - ra + const_one<double>()) * u01(rng);
return static_cast<result_type>(std::floor(u));
}
template <typename RNGType>
result_type generate(
RNGType &rng, const param_type ¶m, std::false_type)
{
std::uniform_int_distribution<result_type> uniform(
param.a(), param.b());
return uniform(rng);
}
}; // class UniformIntDistribution
MCKL_DEFINE_RANDOM_DISTRIBUTION_RAND(UniformInt, IntType)
} // namespace mckl
#endif // MCKL_RANDOM_UNIFORM_INT_DISTRIBUTION_HPP
<commit_msg>use union to preserve bits<commit_after>//============================================================================
// MCKL/include/mckl/random/uniform_int_distribution.hpp
//----------------------------------------------------------------------------
// MCKL: Monte Carlo Kernel Library
//----------------------------------------------------------------------------
// Copyright (c) 2013-2016, Yan Zhou
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//============================================================================
#ifndef MCKL_RANDOM_UNIFORM_INT_DISTRIBUTION_HPP
#define MCKL_RANDOM_UNIFORM_INT_DISTRIBUTION_HPP
#include <mckl/random/internal/common.hpp>
#include <mckl/random/u01_distribution.hpp>
namespace mckl
{
namespace internal
{
template <typename IntType>
inline bool uniform_int_distribution_use_double_big(
IntType a, IntType b, std::true_type)
{
static constexpr IntType imax = const_one<IntType>() << 32;
return a > -imax && b < imax;
}
template <typename IntType>
inline bool uniform_int_distribution_use_double_big(
IntType, IntType b, std::false_type)
{
static constexpr IntType imax = const_one<IntType>() << 32;
return b < imax;
}
template <typename IntType>
inline bool uniform_int_distribution_use_double(
IntType, IntType, std::true_type)
{
return true;
}
template <typename IntType>
inline bool uniform_int_distribution_use_double(
IntType a, IntType b, std::false_type)
{
return uniform_int_distribution_use_double_big(
a, b, std::is_signed<IntType>());
}
template <typename IntType>
inline bool uniform_int_distribution_use_double(IntType a, IntType b)
{
return uniform_int_distribution_use_double(
a, b, std::integral_constant<bool,
std::numeric_limits<IntType>::digits <= 32>());
}
template <typename IntType>
inline bool uniform_int_distribution_check_param(IntType a, IntType b)
{
return a <= b;
}
template <std::size_t K, typename IntType, typename RNGType>
inline void uniform_int_distribution_impl(RNGType &rng, std::size_t n,
IntType *r, IntType a, IntType b, std::true_type)
{
double ra = static_cast<double>(a);
double rb = static_cast<double>(b);
Array<double, K> s;
double *const u = s.data();
u01_co_distribution(rng, n, u);
fma(n, u, rb - ra + const_one<double>(), ra, u);
floor(n, u, u);
for (std::size_t i = 0; i != n; ++i)
r[i] = static_cast<IntType>(u[i]);
}
template <std::size_t, typename IntType, typename RNGType>
inline void uniform_int_distribution_impl(RNGType &rng, std::size_t n,
IntType *r, IntType a, IntType b, std::false_type)
{
std::uniform_int_distribution<IntType> uniform(a, b);
rand(rng, uniform, n, r);
}
template <std::size_t K, typename IntType, typename RNGType>
inline void uniform_int_distribution_impl(
RNGType &rng, std::size_t n, IntType *r, IntType a, IntType b)
{
using UIntType = typename std::make_unsigned<IntType>::type;
static constexpr IntType imin = std::numeric_limits<IntType>::min();
static constexpr IntType imax = std::numeric_limits<IntType>::max();
if (a == b) {
std::fill_n(r, n, a);
return;
}
if (a == imin && b == imax) {
uniform_bits_distribution(rng, n, reinterpret_cast<UIntType *>(r));
return;
}
uniform_int_distribution_use_double(a, b) ?
uniform_int_distribution_impl<K>(rng, n, r, a, b, std::true_type()) :
uniform_int_distribution_impl<K>(rng, n, r, a, b, std::false_type());
}
MCKL_DEFINE_RANDOM_DISTRIBUTION_IMPL_2(
UniformInt, uniform_int, IntType, IntType, a, IntType, b)
} // namespace mckl::internal
/// \brief Uniform integer distribution
/// \ingroup Distribution
template <typename IntType>
class UniformIntDistribution
{
MCKL_DEFINE_RANDOM_DISTRIBUTION_ASSERT_INT_TYPE(UniformInt, short)
MCKL_DEFINE_RANDOM_DISTRIBUTION_2(UniformInt, uniform_int, IntType,
result_type, a, 0, result_type, b,
std::numeric_limits<result_type>::max())
MCKL_DEFINE_RANDOM_DISTRIBUTION_MEMBER_0
public:
result_type min() const { return a(); }
result_type max() const { return b(); }
void reset() {}
private:
template <typename RNGType>
result_type generate(RNGType &rng, const param_type ¶m)
{
using UIntType = typename std::make_unsigned<result_type>::type;
static constexpr result_type imin =
std::numeric_limits<result_type>::min();
static constexpr result_type imax =
std::numeric_limits<result_type>::max();
if (param.a() == param.b())
return param.a();
if (param.a() == imin && param.b() == imax) {
UniformBitsDistribution<UIntType> ubits;
union {
UIntType u;
result_type r;
} buf;
buf.u = ubits(rng);
return buf.r;
}
return internal::uniform_int_distribution_use_double(
param.a(), param.b()) ?
generate(rng, param, std::true_type()) :
generate(rng, param, std::false_type());
}
template <typename RNGType>
result_type generate(RNGType &rng, const param_type ¶m, std::true_type)
{
U01CODistribution<double> u01;
double ra = static_cast<double>(param.a());
double rb = static_cast<double>(param.b());
double u = ra + (rb - ra + const_one<double>()) * u01(rng);
return static_cast<result_type>(std::floor(u));
}
template <typename RNGType>
result_type generate(
RNGType &rng, const param_type ¶m, std::false_type)
{
std::uniform_int_distribution<result_type> uniform(
param.a(), param.b());
return uniform(rng);
}
}; // class UniformIntDistribution
MCKL_DEFINE_RANDOM_DISTRIBUTION_RAND(UniformInt, IntType)
} // namespace mckl
#endif // MCKL_RANDOM_UNIFORM_INT_DISTRIBUTION_HPP
<|endoftext|>
|
<commit_before>#pragma once
#include <sse/schemes/tethys/details/tethys_utils.hpp>
#include <sse/schemes/tethys/types.hpp>
#include <sse/schemes/utils/rocksdb_wrapper.hpp>
#include <sse/crypto/key.hpp>
#include <sse/crypto/prf.hpp>
#include <array>
namespace sse {
namespace tethys {
template<class ValueDecoder>
class TethysClient
{
public:
static constexpr size_t kServerBucketSize = ValueDecoder::kPayloadSize;
using keyed_bucket_pair_type = KeyedBucketPair<kServerBucketSize>;
TethysClient(const std::string& counter_db_path,
const std::string& stash_path,
crypto::Key<kMasterPrfKeySize>&& master_key);
// we have to specificy templated constructors inside the class definition
// (they do not have a name that can be 'templated')
template<class StashDecoder = ValueDecoder>
TethysClient(const std::string& counter_db_path,
const std::string& stash_path,
StashDecoder& stash_decoder,
crypto::Key<kMasterPrfKeySize>&& master_key)
: counter_db(counter_db_path), master_prf(std::move(master_key))
{
load_stash(stash_path, stash_decoder);
std::cerr << "Tethys client initialization succeeded!\n";
std::cerr << "Stash size: " << stash.size() << "\n";
}
SearchRequest search_request(const std::string& keyword,
bool log_not_found = true) const;
std::vector<index_type> decode_search_results(
const SearchRequest& req,
std::vector<keyed_bucket_pair_type> bucket_pairs,
ValueDecoder& decoder);
private:
template<class StashDecoder>
void load_stash(const std::string& stash_path, StashDecoder& stash_decoder);
std::map<tethys_core_key_type, std::vector<index_type>> stash;
sophos::RocksDBCounter counter_db;
master_prf_type master_prf;
};
template<class ValueDecoder>
TethysClient<ValueDecoder>::TethysClient(
const std::string& counter_db_path,
const std::string& stash_path,
crypto::Key<kMasterPrfKeySize>&& master_key)
: counter_db(counter_db_path), master_prf(std::move(master_key))
{
ValueDecoder stash_decoder;
load_stash(stash_path, stash_decoder);
std::cerr << "Tethys client initialization succeeded!\n";
std::cerr << "Stash size: " << stash.size() << "\n";
}
template<class ValueDecoder>
template<class StashDecoder>
void TethysClient<ValueDecoder>::load_stash(const std::string& stash_path,
StashDecoder& stash_decoder)
{
if (utility::is_file(stash_path)) {
std::ifstream input_stream;
input_stream.open(stash_path);
stash = abstractio::deserialize_map<tethys_core_key_type,
std::vector<index_type>,
ValueDecoder>(input_stream,
stash_decoder);
input_stream.close();
}
}
template<class ValueDecoder>
std::vector<index_type> TethysClient<ValueDecoder>::decode_search_results(
const SearchRequest& req,
std::vector<keyed_bucket_pair_type> keyed_bucket_pairs,
ValueDecoder& decoder)
{
std::vector<index_type> results;
for (const keyed_bucket_pair_type& key_bucket : keyed_bucket_pairs) {
std::vector<index_type> bucket_res
= decoder.decode_buckets(key_bucket.key,
key_bucket.buckets.payload_0,
key_bucket.buckets.index_0,
key_bucket.buckets.payload_1,
key_bucket.buckets.index_1);
results.reserve(results.size() + bucket_res.size());
results.insert(results.end(), bucket_res.begin(), bucket_res.end());
auto stash_it = stash.find(key_bucket.key);
if (stash_it != stash.end()) {
const std::vector<index_type>& stash_res = stash_it->second;
results.reserve(results.size() + stash_res.size());
results.insert(results.end(), stash_res.begin(), stash_res.end());
}
}
return results;
}
} // namespace tethys
} // namespace sse<commit_msg>Use a decrypt decoder in the Tethys client. This is at the cost of genericity. Meh ...<commit_after>#pragma once
#include <sse/schemes/tethys/details/tethys_utils.hpp>
#include <sse/schemes/tethys/types.hpp>
#include <sse/schemes/utils/rocksdb_wrapper.hpp>
#include <sse/crypto/key.hpp>
#include <sse/crypto/prf.hpp>
#include <array>
namespace sse {
namespace tethys {
template<class ValueDecoder>
class TethysClient
{
public:
static constexpr size_t kServerBucketSize = ValueDecoder::kPayloadSize;
using keyed_bucket_pair_type = KeyedBucketPair<kServerBucketSize>;
using decrypt_decoder_type
= encoders::DecryptDecoder<ValueDecoder, kServerBucketSize>;
static constexpr size_t kDecryptionKeySize = decrypt_decoder_type::kKeySize;
TethysClient(const std::string& counter_db_path,
const std::string& stash_path,
crypto::Key<kMasterPrfKeySize>&& master_key,
crypto::Key<kDecryptionKeySize>&& decryption_key);
// we have to specificy templated constructors inside the class definition
// (they do not have a name that can be 'templated')
template<class StashDecoder = ValueDecoder>
TethysClient(const std::string& counter_db_path,
const std::string& stash_path,
StashDecoder& stash_decoder,
crypto::Key<kMasterPrfKeySize>&& master_key,
crypto::Key<kDecryptionKeySize>&& decryption_key)
: counter_db(counter_db_path), master_prf(master_key),
decrypt_decoder(decryption_key)
{
load_stash(stash_path, stash_decoder);
std::cerr << "Tethys client initialization succeeded!\n";
std::cerr << "Stash size: " << stash.size() << "\n";
}
SearchRequest search_request(const std::string& keyword,
bool log_not_found = true) const;
std::vector<index_type> decode_search_results(
const SearchRequest& req,
std::vector<keyed_bucket_pair_type> bucket_pairs);
private:
template<class StashDecoder>
void load_stash(const std::string& stash_path, StashDecoder& stash_decoder);
std::map<tethys_core_key_type, std::vector<index_type>> stash;
sophos::RocksDBCounter counter_db;
master_prf_type master_prf;
decrypt_decoder_type decrypt_decoder;
};
template<class ValueDecoder>
TethysClient<ValueDecoder>::TethysClient(
const std::string& counter_db_path,
const std::string& stash_path,
crypto::Key<kMasterPrfKeySize>&& master_key,
crypto::Key<kDecryptionKeySize>&& decryption_key)
: counter_db(counter_db_path), master_prf(master_key),
decrypt_decoder(decryption_key)
{
ValueDecoder stash_decoder;
load_stash(stash_path, stash_decoder);
std::cerr << "Tethys client initialization succeeded!\n";
std::cerr << "Stash size: " << stash.size() << "\n";
}
template<class ValueDecoder>
template<class StashDecoder>
void TethysClient<ValueDecoder>::load_stash(const std::string& stash_path,
StashDecoder& stash_decoder)
{
if (utility::is_file(stash_path)) {
std::ifstream input_stream;
input_stream.open(stash_path);
stash = abstractio::deserialize_map<tethys_core_key_type,
std::vector<index_type>,
ValueDecoder>(input_stream,
stash_decoder);
input_stream.close();
}
}
template<class ValueDecoder>
std::vector<index_type> TethysClient<ValueDecoder>::decode_search_results(
const SearchRequest& req,
std::vector<keyed_bucket_pair_type> keyed_bucket_pairs)
{
std::vector<index_type> results;
for (const keyed_bucket_pair_type& key_bucket : keyed_bucket_pairs) {
std::vector<index_type> bucket_res
= decrypt_decoder.decode_buckets(key_bucket.key,
key_bucket.buckets.payload_0,
key_bucket.buckets.index_0,
key_bucket.buckets.payload_1,
key_bucket.buckets.index_1);
results.reserve(results.size() + bucket_res.size());
results.insert(results.end(), bucket_res.begin(), bucket_res.end());
auto stash_it = stash.find(key_bucket.key);
if (stash_it != stash.end()) {
const std::vector<index_type>& stash_res = stash_it->second;
results.reserve(results.size() + stash_res.size());
results.insert(results.end(), stash_res.begin(), stash_res.end());
}
}
return results;
}
} // namespace tethys
} // namespace sse<|endoftext|>
|
<commit_before>#include "builtin/array.hpp"
#include "builtin/class.hpp"
#include "builtin/exception.hpp"
#include "builtin/integer.hpp"
#include "builtin/string.hpp"
#include "builtin/time.hpp"
#include "objectmemory.hpp"
#include "object_utils.hpp"
#include "ontology.hpp"
#include "util/time64.h"
#include "util/strftime.h"
namespace rubinius {
void Time::init(STATE) {
GO(time_class).set(ontology::new_class(state, "Time", G(object)));
G(time_class)->set_object_type(state, TimeType);
}
Time* Time::now(STATE, Object* self) {
Time* tm = state->new_object_dirty<Time>(as<Class>(self));
#ifdef HAVE_CLOCK_GETTIME
struct timespec ts;
::clock_gettime(CLOCK_REALTIME, &ts);
tm->seconds_ = ts.tv_sec;
tm->nanoseconds_ = ts.tv_nsec;
#else
struct timeval tv;
/* don't fill in the 2nd argument here. getting the timezone here
* this way is not portable and broken anyway.
*/
::gettimeofday(&tv, NULL);
tm->seconds_ = tv.tv_sec;
tm->nanoseconds_ = tv.tv_usec * 1000;
#endif
tm->decomposed(state, nil<Array>());
tm->is_gmt(state, cFalse);
tm->offset(state, nil<Fixnum>());
return tm;
}
Time* Time::at(STATE, time64_t seconds, long nanoseconds) {
Time* tm = state->new_object_dirty<Time>(G(time_class));
tm->seconds_ = seconds;
tm->nanoseconds_ = nanoseconds;
tm->decomposed(state, nil<Array>());
tm->is_gmt(state, cFalse);
tm->offset(state, nil<Fixnum>());
return tm;
}
// Taken from MRI
#define NDIV(x,y) (-(-((x)+1)/(y))-1)
#define NMOD(x,y) ((y)-(-((x)+1)%(y))-1)
Time* Time::specific(STATE, Object* self, Integer* sec, Integer* nsec,
Object* gmt, Object* offset)
{
Time* tm = state->new_object_dirty<Time>(as<Class>(self));
tm->seconds_ = sec->to_long_long();
tm->nanoseconds_ = nsec->to_native();
// Do a little overflow cleanup.
if(tm->nanoseconds_ >= 1000000000) {
tm->seconds_ += tm->nanoseconds_ / 1000000000;
tm->nanoseconds_ %= 1000000000;
}
if(tm->nanoseconds_ < 0) {
tm->seconds_ += NDIV(tm->nanoseconds_, 1000000000);
tm->nanoseconds_ = NMOD(tm->nanoseconds_, 1000000000);
}
tm->decomposed(state, nil<Array>());
tm->is_gmt(state, RBOOL(CBOOL(gmt)));
tm->offset(state, offset);
return tm;
}
Time* Time::from_array(STATE, Object* self,
Fixnum* sec, Fixnum* min, Fixnum* hour,
Fixnum* mday, Fixnum* mon, Fixnum* year, Fixnum* nsec,
Fixnum* isdst, Object* from_gmt, Object* offset,
Fixnum* offset_sec, Fixnum* offset_nsec) {
struct tm64 tm;
tm.tm_sec = sec->to_native();
if(tm.tm_sec < 0 || tm.tm_sec > 60) {
Exception::argument_error(state, "sec must be in 0..60");
}
tm.tm_min = min->to_native();
if(tm.tm_min < 0 || tm.tm_min > 60) {
Exception::argument_error(state, "min must be in 0..60");
}
tm.tm_hour = hour->to_native();
if(tm.tm_hour < 0 || tm.tm_hour > 24) {
Exception::argument_error(state, "hour must be in 0..24");
}
tm.tm_mday = mday->to_native();
if(tm.tm_mday < 1 || tm.tm_mday > 31) {
Exception::argument_error(state, "mday must be in 1..31");
}
tm.tm_mon = mon->to_native() - 1;
if(tm.tm_mon < 0 || tm.tm_mon > 11) {
Exception::argument_error(state, "mon must be in 0..11");
}
tm.tm_wday = -1;
tm.tm_gmtoff = 0;
tm.tm_zone = 0;
tm.tm_year = year->to_long_long();
tm.tm_isdst = isdst->to_native();
time64_t seconds = -1;
if(CBOOL(from_gmt) || !offset->nil_p()) {
seconds = ::timegm64(&tm);
} else {
tzset();
seconds = ::timelocal64(&tm);
}
Time* obj = state->new_object_dirty<Time>(as<Class>(self));
obj->seconds_ = seconds;
obj->nanoseconds_ = nsec->to_native();
obj->is_gmt(state, RBOOL(CBOOL(from_gmt)));
if(!offset->nil_p()) {
obj->seconds_ -= offset_sec->to_long_long();
obj->nanoseconds_ -= offset_nsec->to_native();
// Deal with underflow wrapping
if(obj->nanoseconds_ < 0) {
obj->seconds_ += NDIV(obj->nanoseconds_, 1000000000);
obj->nanoseconds_ = NMOD(obj->nanoseconds_, 1000000000);
}
obj->offset(state, offset);
} else {
obj->offset(state, nil<Fixnum>());
}
obj->decomposed(state, nil<Array>());
return obj;
}
Time* Time::dup(STATE, Object* self, Time* other) {
Time* tm = state->new_object_dirty<Time>(as<Class>(self));
tm->seconds_ = other->seconds_;
tm->nanoseconds_ = other->nanoseconds_;
tm->decomposed(state, other->decomposed_);
tm->is_gmt(state, other->is_gmt_);
tm->offset(state, other->offset_);
return tm;
}
struct tm64 Time::get_tm() {
time64_t seconds = seconds_;
struct tm64 tm = {0};
if(Fixnum* off = try_as<Fixnum>(offset_)) {
seconds += off->to_long_long();
gmtime64_r(&seconds, &tm);
} else if(CBOOL(is_gmt_)) {
gmtime64_r(&seconds, &tm);
} else {
tzset();
localtime64_r(&seconds, &tm);
}
return tm;
}
Object* Time::utc_offset(STATE) {
if(CBOOL(is_gmt_)) {
return Fixnum::from(0);
} else if(!offset_->nil_p()) {
return offset_;
}
native_int off;
#ifdef HAVE_TM_NAME
struct tm tm = get_tm();
off = -tm.tm_tzadj;
#else /* !HAVE_TM_NAME */
#ifdef HAVE_TM_ZONE
#ifdef HAVE_TM_GMTOFF
struct tm64 tm = get_tm();
off = tm.tm_gmtoff;
#else
off = _timezone;
#endif
#else /* !HAVE_TM_ZONE */
#if HAVE_VAR_TIMEZONE
#if HAVE_VAR_ALTZONE
off = -(daylight ? timezone : altzone);
#else
off = -timezone;
#endif
#else /* !HAVE_VAR_TIMEZONE */
#ifdef HAVE_GETTIMEOFDAY
gettimeofday(&tv, &zone);
off = -zone.tz_minuteswest * 60;
#else
/* no timezone info, then calc by myself */
{
struct tm utc;
time_t now;
time(&now);
gmtime_r(&now, &utc);
off = (now - mktime(&utc));
}
#endif
#endif /* !HAVE_VAR_TIMEZONE */
#endif /* !HAVE_TM_ZONE */
#endif /* !HAVE_TM_NAME */
return Fixnum::from(off);
}
Array* Time::calculate_decompose(STATE) {
if(!decomposed_->nil_p()) return decomposed_;
struct tm64 tm = get_tm();
/* update Time::TM_FIELDS when changing order of fields */
Array* ary = Array::create(state, 11);
ary->set(state, 0, Integer::from(state, tm.tm_sec));
ary->set(state, 1, Integer::from(state, tm.tm_min));
ary->set(state, 2, Integer::from(state, tm.tm_hour));
ary->set(state, 3, Integer::from(state, tm.tm_mday));
ary->set(state, 4, Integer::from(state, tm.tm_mon + 1));
ary->set(state, 5, Integer::from(state, tm.tm_year));
ary->set(state, 6, Integer::from(state, tm.tm_wday));
ary->set(state, 7, Integer::from(state, tm.tm_yday + 1));
ary->set(state, 8, RBOOL(tm.tm_isdst));
if(offset_->nil_p() && tm.tm_zone) {
ary->set(state, 9, String::create(state, tm.tm_zone));
} else {
ary->set(state, 9, cNil);
}
// Cache it.
decomposed(state, ary);
return ary;
}
#define STRFTIME_STACK_BUF 128
String* Time::strftime(STATE, String* format) {
struct tm64 tm = get_tm();
struct timespec64 ts;
ts.tv_sec = seconds_;
ts.tv_nsec = nanoseconds_;
int off = 0;
if(Fixnum* offset = try_as<Fixnum>(utc_offset(state))) {
off = offset->to_int();
}
char stack_str[STRFTIME_STACK_BUF];
size_t chars = ::strftime_extended(stack_str, STRFTIME_STACK_BUF,
format->c_str(state), &tm, &ts, CBOOL(is_gmt_) ? 1 : 0,
off);
size_t buf_size = format->byte_size() * 2;
String* result = 0;
if(chars == 0 && format->byte_size() > 0) {
char* malloc_str = (char*)malloc(buf_size);
chars = ::strftime_extended(malloc_str, buf_size,
format->c_str(state), &tm, &ts, CBOOL(is_gmt_) ? 1 : 0,
off);
while (chars == 0 && format->byte_size() > 0) {
buf_size *= 2;
char* new_malloc_str = (char*)realloc(malloc_str, buf_size);
if(!new_malloc_str) {
free(malloc_str);
Exception::memory_error(state);
return NULL;
}
malloc_str = new_malloc_str;
chars = ::strftime_extended(malloc_str, buf_size,
format->c_str(state), &tm, &ts, CBOOL(is_gmt_) ? 1 : 0,
off);
}
result = String::create(state, malloc_str, chars);
free(malloc_str);
} else {
result = String::create(state, stack_str, chars);
}
return result;
}
}
<commit_msg>Cleanup Time#strftime primitive<commit_after>#include "builtin/array.hpp"
#include "builtin/class.hpp"
#include "builtin/exception.hpp"
#include "builtin/integer.hpp"
#include "builtin/string.hpp"
#include "builtin/time.hpp"
#include "objectmemory.hpp"
#include "object_utils.hpp"
#include "ontology.hpp"
#include "util/time64.h"
#include "util/strftime.h"
namespace rubinius {
void Time::init(STATE) {
GO(time_class).set(ontology::new_class(state, "Time", G(object)));
G(time_class)->set_object_type(state, TimeType);
}
Time* Time::now(STATE, Object* self) {
Time* tm = state->new_object_dirty<Time>(as<Class>(self));
#ifdef HAVE_CLOCK_GETTIME
struct timespec ts;
::clock_gettime(CLOCK_REALTIME, &ts);
tm->seconds_ = ts.tv_sec;
tm->nanoseconds_ = ts.tv_nsec;
#else
struct timeval tv;
/* don't fill in the 2nd argument here. getting the timezone here
* this way is not portable and broken anyway.
*/
::gettimeofday(&tv, NULL);
tm->seconds_ = tv.tv_sec;
tm->nanoseconds_ = tv.tv_usec * 1000;
#endif
tm->decomposed(state, nil<Array>());
tm->is_gmt(state, cFalse);
tm->offset(state, nil<Fixnum>());
return tm;
}
Time* Time::at(STATE, time64_t seconds, long nanoseconds) {
Time* tm = state->new_object_dirty<Time>(G(time_class));
tm->seconds_ = seconds;
tm->nanoseconds_ = nanoseconds;
tm->decomposed(state, nil<Array>());
tm->is_gmt(state, cFalse);
tm->offset(state, nil<Fixnum>());
return tm;
}
// Taken from MRI
#define NDIV(x,y) (-(-((x)+1)/(y))-1)
#define NMOD(x,y) ((y)-(-((x)+1)%(y))-1)
Time* Time::specific(STATE, Object* self, Integer* sec, Integer* nsec,
Object* gmt, Object* offset)
{
Time* tm = state->new_object_dirty<Time>(as<Class>(self));
tm->seconds_ = sec->to_long_long();
tm->nanoseconds_ = nsec->to_native();
// Do a little overflow cleanup.
if(tm->nanoseconds_ >= 1000000000) {
tm->seconds_ += tm->nanoseconds_ / 1000000000;
tm->nanoseconds_ %= 1000000000;
}
if(tm->nanoseconds_ < 0) {
tm->seconds_ += NDIV(tm->nanoseconds_, 1000000000);
tm->nanoseconds_ = NMOD(tm->nanoseconds_, 1000000000);
}
tm->decomposed(state, nil<Array>());
tm->is_gmt(state, RBOOL(CBOOL(gmt)));
tm->offset(state, offset);
return tm;
}
Time* Time::from_array(STATE, Object* self,
Fixnum* sec, Fixnum* min, Fixnum* hour,
Fixnum* mday, Fixnum* mon, Fixnum* year, Fixnum* nsec,
Fixnum* isdst, Object* from_gmt, Object* offset,
Fixnum* offset_sec, Fixnum* offset_nsec) {
struct tm64 tm;
tm.tm_sec = sec->to_native();
if(tm.tm_sec < 0 || tm.tm_sec > 60) {
Exception::argument_error(state, "sec must be in 0..60");
}
tm.tm_min = min->to_native();
if(tm.tm_min < 0 || tm.tm_min > 60) {
Exception::argument_error(state, "min must be in 0..60");
}
tm.tm_hour = hour->to_native();
if(tm.tm_hour < 0 || tm.tm_hour > 24) {
Exception::argument_error(state, "hour must be in 0..24");
}
tm.tm_mday = mday->to_native();
if(tm.tm_mday < 1 || tm.tm_mday > 31) {
Exception::argument_error(state, "mday must be in 1..31");
}
tm.tm_mon = mon->to_native() - 1;
if(tm.tm_mon < 0 || tm.tm_mon > 11) {
Exception::argument_error(state, "mon must be in 0..11");
}
tm.tm_wday = -1;
tm.tm_gmtoff = 0;
tm.tm_zone = 0;
tm.tm_year = year->to_long_long();
tm.tm_isdst = isdst->to_native();
time64_t seconds = -1;
if(CBOOL(from_gmt) || !offset->nil_p()) {
seconds = ::timegm64(&tm);
} else {
tzset();
seconds = ::timelocal64(&tm);
}
Time* obj = state->new_object_dirty<Time>(as<Class>(self));
obj->seconds_ = seconds;
obj->nanoseconds_ = nsec->to_native();
obj->is_gmt(state, RBOOL(CBOOL(from_gmt)));
if(!offset->nil_p()) {
obj->seconds_ -= offset_sec->to_long_long();
obj->nanoseconds_ -= offset_nsec->to_native();
// Deal with underflow wrapping
if(obj->nanoseconds_ < 0) {
obj->seconds_ += NDIV(obj->nanoseconds_, 1000000000);
obj->nanoseconds_ = NMOD(obj->nanoseconds_, 1000000000);
}
obj->offset(state, offset);
} else {
obj->offset(state, nil<Fixnum>());
}
obj->decomposed(state, nil<Array>());
return obj;
}
Time* Time::dup(STATE, Object* self, Time* other) {
Time* tm = state->new_object_dirty<Time>(as<Class>(self));
tm->seconds_ = other->seconds_;
tm->nanoseconds_ = other->nanoseconds_;
tm->decomposed(state, other->decomposed_);
tm->is_gmt(state, other->is_gmt_);
tm->offset(state, other->offset_);
return tm;
}
struct tm64 Time::get_tm() {
time64_t seconds = seconds_;
struct tm64 tm = {0};
if(Fixnum* off = try_as<Fixnum>(offset_)) {
seconds += off->to_long_long();
gmtime64_r(&seconds, &tm);
} else if(CBOOL(is_gmt_)) {
gmtime64_r(&seconds, &tm);
} else {
tzset();
localtime64_r(&seconds, &tm);
}
return tm;
}
Object* Time::utc_offset(STATE) {
if(CBOOL(is_gmt_)) {
return Fixnum::from(0);
} else if(!offset_->nil_p()) {
return offset_;
}
native_int off;
#ifdef HAVE_TM_NAME
struct tm tm = get_tm();
off = -tm.tm_tzadj;
#else /* !HAVE_TM_NAME */
#ifdef HAVE_TM_ZONE
#ifdef HAVE_TM_GMTOFF
struct tm64 tm = get_tm();
off = tm.tm_gmtoff;
#else
off = _timezone;
#endif
#else /* !HAVE_TM_ZONE */
#if HAVE_VAR_TIMEZONE
#if HAVE_VAR_ALTZONE
off = -(daylight ? timezone : altzone);
#else
off = -timezone;
#endif
#else /* !HAVE_VAR_TIMEZONE */
#ifdef HAVE_GETTIMEOFDAY
gettimeofday(&tv, &zone);
off = -zone.tz_minuteswest * 60;
#else
/* no timezone info, then calc by myself */
{
struct tm utc;
time_t now;
time(&now);
gmtime_r(&now, &utc);
off = (now - mktime(&utc));
}
#endif
#endif /* !HAVE_VAR_TIMEZONE */
#endif /* !HAVE_TM_ZONE */
#endif /* !HAVE_TM_NAME */
return Fixnum::from(off);
}
Array* Time::calculate_decompose(STATE) {
if(!decomposed_->nil_p()) return decomposed_;
struct tm64 tm = get_tm();
/* update Time::TM_FIELDS when changing order of fields */
Array* ary = Array::create(state, 11);
ary->set(state, 0, Integer::from(state, tm.tm_sec));
ary->set(state, 1, Integer::from(state, tm.tm_min));
ary->set(state, 2, Integer::from(state, tm.tm_hour));
ary->set(state, 3, Integer::from(state, tm.tm_mday));
ary->set(state, 4, Integer::from(state, tm.tm_mon + 1));
ary->set(state, 5, Integer::from(state, tm.tm_year));
ary->set(state, 6, Integer::from(state, tm.tm_wday));
ary->set(state, 7, Integer::from(state, tm.tm_yday + 1));
ary->set(state, 8, RBOOL(tm.tm_isdst));
if(offset_->nil_p() && tm.tm_zone) {
ary->set(state, 9, String::create(state, tm.tm_zone));
} else {
ary->set(state, 9, cNil);
}
// Cache it.
decomposed(state, ary);
return ary;
}
#define STRFTIME_STACK_BUF 128
String* Time::strftime(STATE, String* format) {
struct tm64 tm = get_tm();
struct timespec64 ts;
ts.tv_sec = seconds_;
ts.tv_nsec = nanoseconds_;
int off = 0;
if(Fixnum* offset = try_as<Fixnum>(utc_offset(state))) {
off = offset->to_int();
}
if(format->byte_size() == 0) return String::create(state, NULL, 0);
char stack_str[STRFTIME_STACK_BUF];
size_t chars = ::strftime_extended(stack_str, STRFTIME_STACK_BUF,
format->c_str(state), &tm, &ts, CBOOL(is_gmt_) ? 1 : 0,
off);
size_t buf_size = format->byte_size();
String* result = 0;
if(chars == 0) {
buf_size *= 2;
char* malloc_str = (char*)malloc(buf_size);
chars = ::strftime_extended(malloc_str, buf_size,
format->c_str(state), &tm, &ts, CBOOL(is_gmt_) ? 1 : 0,
off);
if(chars) {
result = String::create(state, malloc_str, chars);
}
free(malloc_str);
} else {
result = String::create(state, stack_str, chars);
}
return result;
}
}
<|endoftext|>
|
<commit_before>#include "VoiceDB.h"
using namespace std;
VoiceDB::VoiceDB():path_singer(L"") {}
VoiceDB::VoiceDB(const wstring& path_singer)
{
setSingerPath(path_singer);
}
VoiceDB::~VoiceDB() {}
bool VoiceDB::initVoiceMap()
{
namespace fs = boost::filesystem;
const fs::path path(path_singer);
if (fs::is_directory(path)) {
BOOST_FOREACH(const fs::path& p, std::make_pair(fs::recursive_directory_iterator(path), fs::recursive_directory_iterator())) {
if (p.leaf().wstring() == L"oto.ini") {
wcout << L"loading " << p.wstring() << endl;
initVoiceMap(p.wstring());
}
}
if (voice_map.size() > 0)
return true;
}
cerr << "[VoiceDB::initVoiceMap] path_singer is invalid" << endl;
return false;
}
bool VoiceDB::initVoiceMap(const wstring& path_oto_ini)
{
boost::filesystem::wifstream ifs(path_oto_ini);
boost::filesystem::path path_ini(path_oto_ini);
wstring buf, wav_ext=L".wav";
while (ifs && getline(ifs, buf)) {
// read oto.ini
Voice tmp_voice(this);
vector<wstring> v1, v2;
boost::algorithm::split(v1, buf, boost::is_any_of("="));
boost::algorithm::split(v2, v1[1], boost::is_any_of(","));
short tmp;
tmp_voice.setWavPath((path_ini.parent_path()/v1[0]).wstring());
tmp_voice.offs = (((tmp=boost::lexical_cast<double>(v2[1]))>0))?tmp:0;
tmp_voice.cons = (((tmp=boost::lexical_cast<double>(v2[2]))>0))?tmp:0;
tmp_voice.blnk = boost::lexical_cast<double>(v2[3]);
tmp_voice.prec = boost::lexical_cast<double>(v2[4]);
tmp_voice.ovrl = boost::lexical_cast<double>(v2[5]);
tmp_voice.is_vcv = false;
// sanitize
if (tmp_voice.ovrl > tmp_voice.prec) {
tmp_voice.prec = tmp_voice.ovrl;
}
if (tmp_voice.prec > tmp_voice.cons) {
tmp_voice.cons = tmp_voice.prec;
}
if (tmp_voice.blnk<0 && tmp_voice.cons > -tmp_voice.blnk) {
tmp_voice.blnk = -tmp_voice.cons;
}
if (tmp_voice.offs < 0) {
short tmp = -tmp_voice.offs;
tmp_voice.offs = 0;
tmp_voice.ovrl += tmp;
tmp_voice.cons += tmp;
tmp_voice.prec += tmp;
if (tmp_voice.blnk < 0) {
tmp_voice.blnk -= tmp;
}
}
// get Voice pron
tmp_voice.setAlias((v2[0]==L"")?tmp_voice.path_wav.stem().wstring():v2[0]);
tmp_voice.is_vcv = (tmp_voice.alias.prefix!=L"- " && tmp_voice.alias.prefix!=L"* " && !tmp_voice.alias.prefix.empty());
// set vowel_map
if (!tmp_voice.is_vcv) {
map<wstring, wstring>::const_iterator it = nak::getVow2PronIt(tmp_voice.getPron());
if (it!=nak::vow2pron.end() && (tmp_voice.alias.prefix==L"- "||tmp_voice.alias.prefix.empty())) {
WavParser wav_parser(tmp_voice.path_wav.wstring());
wav_parser.addTargetTrack(0);
if (wav_parser.parse()) {
short win_size = wav_parser.getFormat().dwSamplesPerSec / tmp_voice.getFrq();
double tmp_max_rms = -1.0;
vector<double> tmp_win = nak::getWindow(win_size*2, nak::unit_waveform_lobe);
vector<double> tmp_wav = (*(wav_parser.getDataChunks().begin())).getData();
vector<double>::iterator it_tmp_wav_cons = tmp_wav.begin()+((tmp_voice.offs+tmp_voice.cons)/1000.0*wav_parser.getFormat().dwSamplesPerSec);
vector<double>::iterator it_tmp_wav_max = it_tmp_wav_cons;
for (size_t i=0; i<win_size*2; i++) {
vector<double> tmp_wav(it_tmp_wav_cons+i-win_size, it_tmp_wav_cons+i+win_size);
for (size_t j=0; j<tmp_wav.size(); j++) {
tmp_wav[j] *= tmp_win[j];
}
double tmp_rms = nak::getRMS(tmp_wav);
if (tmp_rms>tmp_max_rms) {
tmp_max_rms = tmp_rms;
it_tmp_wav_max = it_tmp_wav_cons+i;
}
}
vowel_map[nak::pron2vow[it->second]+tmp_voice.alias.suffix].assign(it_tmp_wav_max-win_size, it_tmp_wav_max+win_size);
}
}
}
voice_map[tmp_voice.getAliasString()] = tmp_voice;
}
return true;
}
/*
* accessor
*/
const Voice* VoiceDB::getVoice(const wstring& alias) const
{
if (!isAlias(alias)) {
return 0;
}
return &(voice_map.at(alias));
}
bool VoiceDB::isAlias(const wstring& alias) const
{
return !(voice_map.empty() || voice_map.count(alias)==0);
}
bool VoiceDB::isVowel(const wstring& subject) const
{
return vowel_map.count(subject)>0;
}
const vector<double>& VoiceDB::getVowel(const wstring& subject) const
{
return vowel_map.at(subject);
}
void VoiceDB::setSingerPath(const wstring& path_singer)
{
this->path_singer = path_singer;
}
const wstring& VoiceDB::getSingerPath() const
{
return this->path_singer;
}
<commit_msg>change search method of pitchmark start point<commit_after>#include "VoiceDB.h"
using namespace std;
VoiceDB::VoiceDB():path_singer(L"") {}
VoiceDB::VoiceDB(const wstring& path_singer)
{
setSingerPath(path_singer);
}
VoiceDB::~VoiceDB() {}
bool VoiceDB::initVoiceMap()
{
namespace fs = boost::filesystem;
const fs::path path(path_singer);
if (fs::is_directory(path)) {
BOOST_FOREACH(const fs::path& p, std::make_pair(fs::recursive_directory_iterator(path), fs::recursive_directory_iterator())) {
if (p.leaf().wstring() == L"oto.ini") {
wcout << L"loading " << p.wstring() << endl;
initVoiceMap(p.wstring());
}
}
if (voice_map.size() > 0)
return true;
}
cerr << "[VoiceDB::initVoiceMap] path_singer is invalid" << endl;
return false;
}
bool VoiceDB::initVoiceMap(const wstring& path_oto_ini)
{
boost::filesystem::wifstream ifs(path_oto_ini);
boost::filesystem::path path_ini(path_oto_ini);
wstring buf, wav_ext=L".wav";
while (ifs && getline(ifs, buf)) {
// read oto.ini
Voice tmp_voice(this);
vector<wstring> v1, v2;
boost::algorithm::split(v1, buf, boost::is_any_of("="));
boost::algorithm::split(v2, v1[1], boost::is_any_of(","));
short tmp;
tmp_voice.setWavPath((path_ini.parent_path()/v1[0]).wstring());
tmp_voice.offs = (((tmp=boost::lexical_cast<double>(v2[1]))>0))?tmp:0;
tmp_voice.cons = (((tmp=boost::lexical_cast<double>(v2[2]))>0))?tmp:0;
tmp_voice.blnk = boost::lexical_cast<double>(v2[3]);
tmp_voice.prec = boost::lexical_cast<double>(v2[4]);
tmp_voice.ovrl = boost::lexical_cast<double>(v2[5]);
tmp_voice.is_vcv = false;
// sanitize
if (tmp_voice.ovrl > tmp_voice.prec) {
tmp_voice.prec = tmp_voice.ovrl;
}
if (tmp_voice.prec > tmp_voice.cons) {
tmp_voice.cons = tmp_voice.prec;
}
if (tmp_voice.blnk<0 && tmp_voice.cons > -tmp_voice.blnk) {
tmp_voice.blnk = -tmp_voice.cons;
}
if (tmp_voice.offs < 0) {
short tmp = -tmp_voice.offs;
tmp_voice.offs = 0;
tmp_voice.ovrl += tmp;
tmp_voice.cons += tmp;
tmp_voice.prec += tmp;
if (tmp_voice.blnk < 0) {
tmp_voice.blnk -= tmp;
}
}
// get Voice pron
tmp_voice.setAlias((v2[0]==L"")?tmp_voice.path_wav.stem().wstring():v2[0]);
tmp_voice.is_vcv = (tmp_voice.alias.prefix!=L"- " && tmp_voice.alias.prefix!=L"* " && !tmp_voice.alias.prefix.empty());
// set vowel_map
if (!tmp_voice.is_vcv) {
map<wstring, wstring>::const_iterator it = nak::getVow2PronIt(tmp_voice.getPron());
if (it!=nak::vow2pron.end() && (tmp_voice.alias.prefix==L"- "||tmp_voice.alias.prefix.empty())) {
WavParser wav_parser(tmp_voice.path_wav.wstring());
wav_parser.addTargetTrack(0);
if (wav_parser.parse()) {
short win_size = wav_parser.getFormat().dwSamplesPerSec / tmp_voice.getFrq();
vector<double> tmp_win = nak::getWindow(win_size*2, nak::unit_waveform_lobe);
vector<double> tmp_wav = (*(wav_parser.getDataChunks().begin())).getData();
vector<double>::iterator it_tmp_wav_cons = tmp_wav.begin()+((tmp_voice.offs+tmp_voice.cons)/1000.0*wav_parser.getFormat().dwSamplesPerSec);
vector<double>::iterator it_tmp_wav_max = it_tmp_wav_cons;
double tmp_max_rms = -1.0, avr_wav = accumulate(it_tmp_wav_cons-win_size,it_tmp_wav_cons+(win_size*3),0)/tmp_wav.size();
for (size_t i=0; i<win_size*2; i++) {
if (*(it_tmp_wav_cons+i)<avr_wav) {
continue;
}
vector<double> tmp_wav(it_tmp_wav_cons+i-win_size, it_tmp_wav_cons+i+win_size);
for (size_t j=0; j<tmp_wav.size(); j++) {
tmp_wav[j] *= tmp_win[j];
}
double tmp_rms = nak::getRMS(tmp_wav);
if (tmp_rms>tmp_max_rms) {
tmp_max_rms = tmp_rms;
it_tmp_wav_max = it_tmp_wav_cons+i;
}
}
vowel_map[nak::pron2vow[it->second]+tmp_voice.alias.suffix].assign(it_tmp_wav_max-win_size, it_tmp_wav_max+win_size);
}
}
}
voice_map[tmp_voice.getAliasString()] = tmp_voice;
}
return true;
}
/*
* accessor
*/
const Voice* VoiceDB::getVoice(const wstring& alias) const
{
if (!isAlias(alias)) {
return 0;
}
return &(voice_map.at(alias));
}
bool VoiceDB::isAlias(const wstring& alias) const
{
return !(voice_map.empty() || voice_map.count(alias)==0);
}
bool VoiceDB::isVowel(const wstring& subject) const
{
return vowel_map.count(subject)>0;
}
const vector<double>& VoiceDB::getVowel(const wstring& subject) const
{
return vowel_map.at(subject);
}
void VoiceDB::setSingerPath(const wstring& path_singer)
{
this->path_singer = path_singer;
}
const wstring& VoiceDB::getSingerPath() const
{
return this->path_singer;
}
<|endoftext|>
|
<commit_before>/** $Id$
Important macro to get certain Aliroot parameters. They are stored
in a file "Init.cxx". Compare the contents of the class AliL3Transform
with the result of this macro to check that there are no differences.
*/
void Make_Init(char *file, char *tofile="Init.cxx"){
TFile * rootf = new TFile(file,"READ");
if(!rootf->IsOpen()){
cerr<<"no file: "<<file<<endl;
return;
}
AliTPCParam* par = (AliTPCParam*)rootf->Get("75x40_100x60");
if(!par){
cerr<<"no AliTPCParam 75x40_100x60 in file: "<<file<<endl;
return;
}
AliTPCParamSR *param=(AliTPCParamSR*)par;
AliTPCPRF2D * prfinner = new AliTPCPRF2D;
AliTPCPRF2D * prfouter = new AliTPCPRF2D;
AliTPCRF1D * rf = new AliTPCRF1D(kTRUE);
rf->SetGauss(param->GetZSigma(),param->GetZWidth(),1.);
rf->SetOffset(3*param->GetZSigma());
rf->Update();
TDirectory *savedir=gDirectory;
TFile *if=TFile::Open("$ALICE_ROOT/TPC/AliTPCprf2d.root");
if (!if->IsOpen()) {
cerr<<"Can't open $ALICE_ROOT/TPC/AliTPCprf2d.root !\n" ;
exit(3);
}
prfinner->Read("prf_07504_Gati_056068_d02");
prfouter->Read("prf_10006_Gati_047051_d03");
if->Close();
savedir->cd();
param->SetInnerPRF(prfinner);
param->SetOuterPRF(prfouter);
param->SetTimeRF(rf);
int fNTimeBins = par->GetMaxTBin()+1;
int fNRowLow = par->GetNRowLow();
int fNRowUp = par->GetNRowUp();
int fNRow= fNRowLow + fNRowUp;
int fNSectorLow = par->GetNInnerSector();
int fNSectorUp = par->GetNOuterSector();
int fNSector = fNSectorLow + fNSectorUp;
int fNSlice = fNSectorLow;
FILE *f = fopen(tofile,"w");
fprintf(f,"void AliL3Transform::Init(){\n");
fprintf(f," //sector:\n");
fprintf(f," fNTimeBins = %d ;\n",fNTimeBins);
fprintf(f," fNRowLow = %d ;\n",fNRowLow);
fprintf(f," fNRowUp = %d ;\n",fNRowUp);
fprintf(f," fNSectorLow = %d ;\n",fNSectorLow);
fprintf(f," fNSectorUp = %d ;\n",fNSectorUp);
fprintf(f," fNSector = %d ;\n",fNSector);
fprintf(f," fPadPitchWidthLow = %f ;\n",par->GetPadPitchWidth(0));
fprintf(f," fPadPitchWidthUp = %f ;\n",par->GetPadPitchWidth(fNSectorLow));
fprintf(f," fZWidth = %.20f ;\n",par->GetZWidth());
fprintf(f," fZSigma = %.20f ;\n",par->GetZSigma());
fprintf(f," fZOffset = %.20f\n",par->GetZOffset());
fprintf(f," fDiffT = %.20f ;\n",par->GetDiffT());
fprintf(f," fDiffL = %.20f ;\n",par->GetDiffL());
fprintf(f," fInnerPadLength = %f\n",par->GetInnerPadLength());
fprintf(f," fOuterPadLength = %f\n",par->GetOuterPadLength());
fprintf(f," fInnerPRFSigma = %.20f\n",param->GetInnerPRF()->GetSigmaX());
fprintf(f," fOuterPRFSigma = %.20f\n",param->GetOuterPRF()->GetSigmaX());
fprintf(f," fTimeSigma = %.20f\n",param->GetTimeRF()->GetSigma());
fprintf(f," fZLength = %f\n",par->GetZLength());
fprintf(f,"\n //slices:\n");
fprintf(f," fNSlice = %d ;\n",fNSectorLow);
fprintf(f," fNRow = %d ;\n",fNRow);
//rotation shift put in by hand -> Constantin
fprintf(f," fNRotShift = 0.5 ;\n");
fprintf(f," fPi = %.15f ;\n",TMath::Pi());
fprintf(f," for(Int_t i=0;i<36;i++){\n");
fprintf(f," fCos[i] = cos(2*fPi/9*(i+0.5));\n");
fprintf(f," fSin[i] = sin(2*fPi/9*(i+0.5));\n");
fprintf(f," }\n\n");
for(Int_t i=0;i<fNRow;i++){
int sec,row;
if( i < fNRowLow){sec =0;row =i;}
else{sec = fNSectorLow;row =i-fNRowLow;}
fprintf(f," fX[%d] = %3.15f ;\n",i,par->GetPadRowRadii(sec,row));
}
for(Int_t i=0;i<fNRow;i++){
int sec,row;
if( i < fNRowLow){sec =0;row =i;}
else{sec = fNSectorLow;row =i-fNRowLow;}
fprintf(f," fNPads[%d] = %d ;\n",i,par->GetNPads(sec,row));
}
fprintf(f,"}\n");
fclose(f);
}
void Make_Default(char *file,char *tofile)
{
/*
Macro to write out default values, which should be used to initialize
the static data members of the AliL3Transform class. Macro does more
or less the same as the above, only the output syntax is changed in order
to use it for static data member initialization.
*/
TFile * rootf = new TFile(file,"READ");
if(!rootf->IsOpen()){
cerr<<"no file: "<<file<<endl;
return;
}
AliTPCParam* par = (AliTPCParam*)rootf->Get("75x40_100x60");
if(!par){
cerr<<"no AliTPCParam 75x40_100x60 in file: "<<file<<endl;
return;
}
int fNTimeBins = par->GetMaxTBin()+1;
int fNRowLow = par->GetNRowLow();
int fNRowUp = par->GetNRowUp();
int fNRow= fNRowLow + fNRowUp;
int fNSectorLow = par->GetNInnerSector();
int fNSectorUp = par->GetNOuterSector();
int fNSector = fNSectorLow + fNSectorUp;
int fNSlice = fNSectorLow;
FILE *f = fopen(tofile,"w");
fprintf(f,"Int_t AliL3Transform::fNTimeBins = %d ;\n",fNTimeBins);
fprintf(f,"Int_t AliL3Transform::fNRowLow = %d ;\n",fNRowLow);
fprintf(f,"Int_t AliL3Transform::fNRowUp = %d ;\n",fNRowUp);
fprintf(f,"Int_t AliL3Transform::fNSectorLow = %d ;\n",fNSectorLow);
fprintf(f,"Int_t AliL3Transform::fNSectorUp = %d ;\n",fNSectorUp);
fprintf(f,"Int_t AliL3Transform::fNSector = %d ;\n",fNSector);
fprintf(f,"Double_t AliL3Transform::fPadPitchWidthLow = %f ;\n",par->GetPadPitchWidth(0));
fprintf(f,"Double_t AliL3Transform::fPadPitchWidthUp = %f ;\n",par->GetPadPitchWidth(fNSectorLow));
fprintf(f,"Double_t AliL3Transform::fZWidth = %.20f ;\n",par->GetZWidth());
fprintf(f,"Double_t AliL3Transform::fZSigma = %.20f ;\n",par->GetZSigma());
fprintf(f,"Int_t AliL3Transform::fNSlice = %d ;\n",fNSectorLow);
fprintf(f,"Int_t AliL3Transform::fNRow = %d ;\n",fNRow);
fprintf(f,"Double_t AliL3Transform::fNRotShift = 0.5 ;\n");
fprintf(f,"Double_t AliL3Transform::fPi = %.15f ;\n",TMath::Pi());
fprintf(f,"Double_t AliL3Transform::fX[176] = {\n");
for(Int_t i=0;i<fNRow;i++){
int sec,row;
if( i < fNRowLow){sec =0;row =i;}
else{sec = fNSectorLow;row =i-fNRowLow;}
fprintf(f," %3.15f,\n",par->GetPadRowRadii(sec,row));
}
fprintf(f,"};\n\n");
fprintf(f,"Int_t AliL3Transform::fNPads[176] = {\n");
for(Int_t i=0;i<fNRow;i++){
int sec,row;
if( i < fNRowLow){sec =0;row =i;}
else{sec = fNSectorLow;row =i-fNRowLow;}
fprintf(f," %d,\n",par->GetNPads(sec,row));
}
fprintf(f,"};\n");
fclose(f);
}
<commit_msg>Bugfix in previous checkin.<commit_after>/** $Id$
Important macro to get certain Aliroot parameters. They are stored
in a file "Init.cxx". Compare the contents of the class AliL3Transform
with the result of this macro to check that there are no differences.
*/
void Make_Init(char *file, char *tofile="Init.cxx"){
TFile * rootf = new TFile(file,"READ");
if(!rootf->IsOpen()){
cerr<<"no file: "<<file<<endl;
return;
}
AliTPCParam* par = (AliTPCParam*)rootf->Get("75x40_100x60");
if(!par){
cerr<<"no AliTPCParam 75x40_100x60 in file: "<<file<<endl;
return;
}
AliTPCParamSR *param=(AliTPCParamSR*)par;
AliTPCPRF2D * prfinner = new AliTPCPRF2D;
AliTPCPRF2D * prfouter = new AliTPCPRF2D;
AliTPCRF1D * rf = new AliTPCRF1D(kTRUE);
rf->SetGauss(param->GetZSigma(),param->GetZWidth(),1.);
rf->SetOffset(3*param->GetZSigma());
rf->Update();
TDirectory *savedir=gDirectory;
TFile *if=TFile::Open("$ALICE_ROOT/TPC/AliTPCprf2d.root");
if (!if->IsOpen()) {
cerr<<"Can't open $ALICE_ROOT/TPC/AliTPCprf2d.root !\n" ;
exit(3);
}
prfinner->Read("prf_07504_Gati_056068_d02");
prfouter->Read("prf_10006_Gati_047051_d03");
if->Close();
savedir->cd();
param->SetInnerPRF(prfinner);
param->SetOuterPRF(prfouter);
param->SetTimeRF(rf);
int fNTimeBins = par->GetMaxTBin()+1;
int fNRowLow = par->GetNRowLow();
int fNRowUp = par->GetNRowUp();
int fNRow= fNRowLow + fNRowUp;
int fNSectorLow = par->GetNInnerSector();
int fNSectorUp = par->GetNOuterSector();
int fNSector = fNSectorLow + fNSectorUp;
int fNSlice = fNSectorLow;
FILE *f = fopen(tofile,"w");
fprintf(f,"void AliL3Transform::Init(){\n");
fprintf(f," //sector:\n");
fprintf(f," fNTimeBins = %d ;\n",fNTimeBins);
fprintf(f," fNRowLow = %d ;\n",fNRowLow);
fprintf(f," fNRowUp = %d ;\n",fNRowUp);
fprintf(f," fNSectorLow = %d ;\n",fNSectorLow);
fprintf(f," fNSectorUp = %d ;\n",fNSectorUp);
fprintf(f," fNSector = %d ;\n",fNSector);
fprintf(f," fPadPitchWidthLow = %f ;\n",par->GetPadPitchWidth(0));
fprintf(f," fPadPitchWidthUp = %f ;\n",par->GetPadPitchWidth(fNSectorLow));
fprintf(f," fZWidth = %.20f ;\n",par->GetZWidth());
fprintf(f," fZSigma = %.20f ;\n",par->GetZSigma());
fprintf(f," fZOffset = %.20f ;\n",par->GetZOffset());
fprintf(f," fDiffT = %.20f ;\n",par->GetDiffT());
fprintf(f," fDiffL = %.20f ;\n",par->GetDiffL());
fprintf(f," fInnerPadLength = %f ;\n",par->GetInnerPadLength());
fprintf(f," fOuterPadLength = %f ;\n",par->GetOuterPadLength());
fprintf(f," fInnerPRFSigma = %.20f ;\n",param->GetInnerPRF()->GetSigmaX());
fprintf(f," fOuterPRFSigma = %.20f ;\n",param->GetOuterPRF()->GetSigmaX());
fprintf(f," fTimeSigma = %.20f ;\n",param->GetTimeRF()->GetSigma());
fprintf(f," fZLength = %f ;\n",par->GetZLength());
fprintf(f,"\n //slices:\n");
fprintf(f," fNSlice = %d ;\n",fNSectorLow);
fprintf(f," fNRow = %d ;\n",fNRow);
//rotation shift put in by hand -> Constantin
fprintf(f," fNRotShift = 0.5 ;\n");
fprintf(f," fPi = %.15f ;\n",TMath::Pi());
fprintf(f," for(Int_t i=0;i<36;i++){\n");
fprintf(f," fCos[i] = cos(2*fPi/9*(i+0.5));\n");
fprintf(f," fSin[i] = sin(2*fPi/9*(i+0.5));\n");
fprintf(f," }\n\n");
for(Int_t i=0;i<fNRow;i++){
int sec,row;
if( i < fNRowLow){sec =0;row =i;}
else{sec = fNSectorLow;row =i-fNRowLow;}
fprintf(f," fX[%d] = %3.15f ;\n",i,par->GetPadRowRadii(sec,row));
}
for(Int_t i=0;i<fNRow;i++){
int sec,row;
if( i < fNRowLow){sec =0;row =i;}
else{sec = fNSectorLow;row =i-fNRowLow;}
fprintf(f," fNPads[%d] = %d ;\n",i,par->GetNPads(sec,row));
}
fprintf(f,"}\n");
fclose(f);
}
void Make_Default(char *file,char *tofile)
{
/*
Macro to write out default values, which should be used to initialize
the static data members of the AliL3Transform class. Macro does more
or less the same as the above, only the output syntax is changed in order
to use it for static data member initialization.
*/
TFile * rootf = new TFile(file,"READ");
if(!rootf->IsOpen()){
cerr<<"no file: "<<file<<endl;
return;
}
AliTPCParam* par = (AliTPCParam*)rootf->Get("75x40_100x60");
if(!par){
cerr<<"no AliTPCParam 75x40_100x60 in file: "<<file<<endl;
return;
}
int fNTimeBins = par->GetMaxTBin()+1;
int fNRowLow = par->GetNRowLow();
int fNRowUp = par->GetNRowUp();
int fNRow= fNRowLow + fNRowUp;
int fNSectorLow = par->GetNInnerSector();
int fNSectorUp = par->GetNOuterSector();
int fNSector = fNSectorLow + fNSectorUp;
int fNSlice = fNSectorLow;
FILE *f = fopen(tofile,"w");
fprintf(f,"Int_t AliL3Transform::fNTimeBins = %d ;\n",fNTimeBins);
fprintf(f,"Int_t AliL3Transform::fNRowLow = %d ;\n",fNRowLow);
fprintf(f,"Int_t AliL3Transform::fNRowUp = %d ;\n",fNRowUp);
fprintf(f,"Int_t AliL3Transform::fNSectorLow = %d ;\n",fNSectorLow);
fprintf(f,"Int_t AliL3Transform::fNSectorUp = %d ;\n",fNSectorUp);
fprintf(f,"Int_t AliL3Transform::fNSector = %d ;\n",fNSector);
fprintf(f,"Double_t AliL3Transform::fPadPitchWidthLow = %f ;\n",par->GetPadPitchWidth(0));
fprintf(f,"Double_t AliL3Transform::fPadPitchWidthUp = %f ;\n",par->GetPadPitchWidth(fNSectorLow));
fprintf(f,"Double_t AliL3Transform::fZWidth = %.20f ;\n",par->GetZWidth());
fprintf(f,"Double_t AliL3Transform::fZSigma = %.20f ;\n",par->GetZSigma());
fprintf(f,"Int_t AliL3Transform::fNSlice = %d ;\n",fNSectorLow);
fprintf(f,"Int_t AliL3Transform::fNRow = %d ;\n",fNRow);
fprintf(f,"Double_t AliL3Transform::fNRotShift = 0.5 ;\n");
fprintf(f,"Double_t AliL3Transform::fPi = %.15f ;\n",TMath::Pi());
fprintf(f,"Double_t AliL3Transform::fX[176] = {\n");
for(Int_t i=0;i<fNRow;i++){
int sec,row;
if( i < fNRowLow){sec =0;row =i;}
else{sec = fNSectorLow;row =i-fNRowLow;}
fprintf(f," %3.15f,\n",par->GetPadRowRadii(sec,row));
}
fprintf(f,"};\n\n");
fprintf(f,"Int_t AliL3Transform::fNPads[176] = {\n");
for(Int_t i=0;i<fNRow;i++){
int sec,row;
if( i < fNRowLow){sec =0;row =i;}
else{sec = fNSectorLow;row =i-fNRowLow;}
fprintf(f," %d,\n",par->GetNPads(sec,row));
}
fprintf(f,"};\n");
fclose(f);
}
<|endoftext|>
|
<commit_before>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2019 Intel Corporation. All Rights Reserved.
#include "l500-color.h"
#include "l500-private.h"
#include "l500-motion.h"
#include "../backend.h"
namespace librealsense
{
#ifdef _WIN32
std::vector<std::pair<std::string, stream_profile>> l500_sensor_name_and_hid_profiles =
{{ "HID Sensor Class Device: Gyroscope", {RS2_STREAM_GYRO, 0, 1, 1, 100, RS2_FORMAT_MOTION_XYZ32F}},
{ "HID Sensor Class Device: Gyroscope", {RS2_STREAM_GYRO, 0, 1, 1, 200, RS2_FORMAT_MOTION_XYZ32F}},
{ "HID Sensor Class Device: Gyroscope", {RS2_STREAM_GYRO, 0, 1, 1, 400, RS2_FORMAT_MOTION_XYZ32F}},
{ "HID Sensor Class Device: Accelerometer", {RS2_STREAM_ACCEL, 0, 1, 1, 50, RS2_FORMAT_MOTION_XYZ32F}},
{ "HID Sensor Class Device: Accelerometer", {RS2_STREAM_ACCEL, 0, 1, 1, 100, RS2_FORMAT_MOTION_XYZ32F}},
{ "HID Sensor Class Device: Accelerometer", {RS2_STREAM_ACCEL, 0, 1, 1, 200, RS2_FORMAT_MOTION_XYZ32F}},
{ "HID Sensor Class Device: Accelerometer", {RS2_STREAM_ACCEL, 0, 1, 1, 400, RS2_FORMAT_MOTION_XYZ32F}} };
// Translate frequency to SENSOR_PROPERTY_CURRENT_REPORT_INTERVAL
std::map<rs2_stream, std::map<unsigned, unsigned>> l500_fps_and_sampling_frequency_per_rs2_stream =
{ {RS2_STREAM_ACCEL,{{50, 2000},
{100, 1000},
{200, 500},
{400, 250}}},
{RS2_STREAM_GYRO, {{100, 1000},
{200, 500},
{400, 250}}}};
#else
std::vector<std::pair<std::string, stream_profile>> l500_sensor_name_and_hid_profiles =
{{ "gyro_3d", {RS2_STREAM_GYRO, 0, 1, 1, 100, RS2_FORMAT_MOTION_XYZ32F}},
{ "gyro_3d", {RS2_STREAM_GYRO, 0, 1, 1, 200, RS2_FORMAT_MOTION_XYZ32F}},
{ "gyro_3d", {RS2_STREAM_GYRO, 0, 1, 1, 400, RS2_FORMAT_MOTION_XYZ32F}},
{ "accel_3d", {RS2_STREAM_ACCEL, 0, 1, 1, 50, RS2_FORMAT_MOTION_XYZ32F}},
{ "accel_3d", {RS2_STREAM_ACCEL, 0, 1, 1, 100, RS2_FORMAT_MOTION_XYZ32F}},
{ "accel_3d", {RS2_STREAM_ACCEL, 0, 1, 1, 200, RS2_FORMAT_MOTION_XYZ32F}},
{ "accel_3d", {RS2_STREAM_ACCEL, 0, 1, 1, 400, RS2_FORMAT_MOTION_XYZ32F}}};
// The frequency selector is vendor and model-specific
std::map<rs2_stream, std::map<unsigned, unsigned>> l500_fps_and_sampling_frequency_per_rs2_stream =
{ {RS2_STREAM_ACCEL,{{50, 1},
{100, 1},
{200, 2},
{400, 4}}},
{RS2_STREAM_GYRO, {{100, 1},
{200, 2},
{400, 4}}} };
#endif
class l500_hid_sensor : public hid_sensor
{
public:
explicit l500_hid_sensor(l500_motion* owner, std::shared_ptr<platform::hid_device> hid_device,
std::unique_ptr<frame_timestamp_reader> hid_iio_timestamp_reader,
std::unique_ptr<frame_timestamp_reader> custom_hid_timestamp_reader,
std::map<rs2_stream, std::map<unsigned, unsigned>> fps_and_sampling_frequency_per_rs2_stream,
std::vector<std::pair<std::string, stream_profile>> sensor_name_and_hid_profiles)
: hid_sensor(hid_device, move(hid_iio_timestamp_reader), move(custom_hid_timestamp_reader),
fps_and_sampling_frequency_per_rs2_stream, sensor_name_and_hid_profiles, owner), _owner(owner)
{
}
rs2_motion_device_intrinsic get_motion_intrinsics(rs2_stream stream) const
{
return _owner->get_motion_intrinsics(stream);
}
stream_profiles init_stream_profiles() override
{
auto lock = environment::get_instance().get_extrinsics_graph().lock();
auto results = hid_sensor::init_stream_profiles();
for (auto p : results)
{
// Register stream types
if (p->get_stream_type() == RS2_STREAM_ACCEL)
assign_stream(_owner->_accel_stream, p);
if (p->get_stream_type() == RS2_STREAM_GYRO)
assign_stream(_owner->_gyro_stream, p);
//set motion intrinsics
if (p->get_stream_type() == RS2_STREAM_ACCEL || p->get_stream_type() == RS2_STREAM_GYRO)
{
auto motion = dynamic_cast<motion_stream_profile_interface*>(p.get());
assert(motion); //Expecting to succeed for motion stream (since we are under the "if")
auto st = p->get_stream_type();
motion->set_intrinsics([this, st]() { return get_motion_intrinsics(st); });
}
}
return results;
}
private:
const l500_motion* _owner;
};
std::shared_ptr<hid_sensor> l500_motion::create_hid_device(std::shared_ptr<context> ctx, const std::vector<platform::hid_device_info>& all_hid_infos)
{
if (all_hid_infos.empty())
{
LOG_WARNING("No HID info provided, IMU is disabled");
return nullptr;
}
std::unique_ptr<frame_timestamp_reader> iio_hid_ts_reader(new iio_hid_timestamp_reader());
std::unique_ptr<frame_timestamp_reader> custom_hid_ts_reader(new iio_hid_timestamp_reader());
auto enable_global_time_option = std::shared_ptr<global_time_option>(new global_time_option());
auto hid_ep = std::make_shared<l500_hid_sensor>(this, ctx->get_backend().create_hid_device(all_hid_infos.front()),
std::unique_ptr<frame_timestamp_reader>(new global_timestamp_reader(std::move(iio_hid_ts_reader), _tf_keeper, enable_global_time_option)),
std::unique_ptr<frame_timestamp_reader>(new global_timestamp_reader(std::move(custom_hid_ts_reader), _tf_keeper, enable_global_time_option)),
l500_fps_and_sampling_frequency_per_rs2_stream,
l500_sensor_name_and_hid_profiles);
hid_ep->register_option(RS2_OPTION_GLOBAL_TIME_ENABLED, enable_global_time_option);
hid_ep->register_pixel_format(pf_accel_axes);
hid_ep->register_pixel_format(pf_gyro_axes);
return hid_ep;
}
l500_motion::l500_motion(std::shared_ptr<context> ctx, const platform::backend_device_group & group)
:device(ctx, group), l500_device(ctx, group),
_accel_stream(new stream(RS2_STREAM_ACCEL)),
_gyro_stream(new stream(RS2_STREAM_GYRO))
{
auto hid_ep = create_hid_device(ctx, group.hid_devices);
if (hid_ep)
{
_motion_module_device_idx = add_sensor(hid_ep);
}
// HID metadata attributes
hid_ep->register_metadata(RS2_FRAME_METADATA_FRAME_TIMESTAMP, make_hid_header_parser(&platform::hid_header::timestamp));
}
std::vector<tagged_profile> l500_motion::get_profiles_tags() const
{
std::vector<tagged_profile> tags;
tags.push_back({ RS2_STREAM_GYRO, -1, 0, 0, RS2_FORMAT_MOTION_XYZ32F, 200, profile_tag::PROFILE_TAG_SUPERSET | profile_tag::PROFILE_TAG_DEFAULT });
tags.push_back({ RS2_STREAM_ACCEL, -1, 0, 0, RS2_FORMAT_MOTION_XYZ32F, 200, profile_tag::PROFILE_TAG_SUPERSET | profile_tag::PROFILE_TAG_DEFAULT });
return tags;
}
rs2_motion_device_intrinsic l500_motion::get_motion_intrinsics(rs2_stream) const
{
return rs2_motion_device_intrinsic();
}
}
<commit_msg>l500 - fix access violation if no HID device found<commit_after>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2019 Intel Corporation. All Rights Reserved.
#include "l500-color.h"
#include "l500-private.h"
#include "l500-motion.h"
#include "../backend.h"
namespace librealsense
{
#ifdef _WIN32
std::vector<std::pair<std::string, stream_profile>> l500_sensor_name_and_hid_profiles =
{{ "HID Sensor Class Device: Gyroscope", {RS2_STREAM_GYRO, 0, 1, 1, 100, RS2_FORMAT_MOTION_XYZ32F}},
{ "HID Sensor Class Device: Gyroscope", {RS2_STREAM_GYRO, 0, 1, 1, 200, RS2_FORMAT_MOTION_XYZ32F}},
{ "HID Sensor Class Device: Gyroscope", {RS2_STREAM_GYRO, 0, 1, 1, 400, RS2_FORMAT_MOTION_XYZ32F}},
{ "HID Sensor Class Device: Accelerometer", {RS2_STREAM_ACCEL, 0, 1, 1, 50, RS2_FORMAT_MOTION_XYZ32F}},
{ "HID Sensor Class Device: Accelerometer", {RS2_STREAM_ACCEL, 0, 1, 1, 100, RS2_FORMAT_MOTION_XYZ32F}},
{ "HID Sensor Class Device: Accelerometer", {RS2_STREAM_ACCEL, 0, 1, 1, 200, RS2_FORMAT_MOTION_XYZ32F}},
{ "HID Sensor Class Device: Accelerometer", {RS2_STREAM_ACCEL, 0, 1, 1, 400, RS2_FORMAT_MOTION_XYZ32F}} };
// Translate frequency to SENSOR_PROPERTY_CURRENT_REPORT_INTERVAL
std::map<rs2_stream, std::map<unsigned, unsigned>> l500_fps_and_sampling_frequency_per_rs2_stream =
{ {RS2_STREAM_ACCEL,{{50, 2000},
{100, 1000},
{200, 500},
{400, 250}}},
{RS2_STREAM_GYRO, {{100, 1000},
{200, 500},
{400, 250}}}};
#else
std::vector<std::pair<std::string, stream_profile>> l500_sensor_name_and_hid_profiles =
{{ "gyro_3d", {RS2_STREAM_GYRO, 0, 1, 1, 100, RS2_FORMAT_MOTION_XYZ32F}},
{ "gyro_3d", {RS2_STREAM_GYRO, 0, 1, 1, 200, RS2_FORMAT_MOTION_XYZ32F}},
{ "gyro_3d", {RS2_STREAM_GYRO, 0, 1, 1, 400, RS2_FORMAT_MOTION_XYZ32F}},
{ "accel_3d", {RS2_STREAM_ACCEL, 0, 1, 1, 50, RS2_FORMAT_MOTION_XYZ32F}},
{ "accel_3d", {RS2_STREAM_ACCEL, 0, 1, 1, 100, RS2_FORMAT_MOTION_XYZ32F}},
{ "accel_3d", {RS2_STREAM_ACCEL, 0, 1, 1, 200, RS2_FORMAT_MOTION_XYZ32F}},
{ "accel_3d", {RS2_STREAM_ACCEL, 0, 1, 1, 400, RS2_FORMAT_MOTION_XYZ32F}}};
// The frequency selector is vendor and model-specific
std::map<rs2_stream, std::map<unsigned, unsigned>> l500_fps_and_sampling_frequency_per_rs2_stream =
{ {RS2_STREAM_ACCEL,{{50, 1},
{100, 1},
{200, 2},
{400, 4}}},
{RS2_STREAM_GYRO, {{100, 1},
{200, 2},
{400, 4}}} };
#endif
class l500_hid_sensor : public hid_sensor
{
public:
explicit l500_hid_sensor(l500_motion* owner, std::shared_ptr<platform::hid_device> hid_device,
std::unique_ptr<frame_timestamp_reader> hid_iio_timestamp_reader,
std::unique_ptr<frame_timestamp_reader> custom_hid_timestamp_reader,
std::map<rs2_stream, std::map<unsigned, unsigned>> fps_and_sampling_frequency_per_rs2_stream,
std::vector<std::pair<std::string, stream_profile>> sensor_name_and_hid_profiles)
: hid_sensor(hid_device, move(hid_iio_timestamp_reader), move(custom_hid_timestamp_reader),
fps_and_sampling_frequency_per_rs2_stream, sensor_name_and_hid_profiles, owner), _owner(owner)
{
}
rs2_motion_device_intrinsic get_motion_intrinsics(rs2_stream stream) const
{
return _owner->get_motion_intrinsics(stream);
}
stream_profiles init_stream_profiles() override
{
auto lock = environment::get_instance().get_extrinsics_graph().lock();
auto results = hid_sensor::init_stream_profiles();
for (auto p : results)
{
// Register stream types
if (p->get_stream_type() == RS2_STREAM_ACCEL)
assign_stream(_owner->_accel_stream, p);
if (p->get_stream_type() == RS2_STREAM_GYRO)
assign_stream(_owner->_gyro_stream, p);
//set motion intrinsics
if (p->get_stream_type() == RS2_STREAM_ACCEL || p->get_stream_type() == RS2_STREAM_GYRO)
{
auto motion = dynamic_cast<motion_stream_profile_interface*>(p.get());
assert(motion); //Expecting to succeed for motion stream (since we are under the "if")
auto st = p->get_stream_type();
motion->set_intrinsics([this, st]() { return get_motion_intrinsics(st); });
}
}
return results;
}
private:
const l500_motion* _owner;
};
std::shared_ptr<hid_sensor> l500_motion::create_hid_device(std::shared_ptr<context> ctx, const std::vector<platform::hid_device_info>& all_hid_infos)
{
if (all_hid_infos.empty())
{
LOG_WARNING("No HID info provided, IMU is disabled");
return nullptr;
}
std::unique_ptr<frame_timestamp_reader> iio_hid_ts_reader(new iio_hid_timestamp_reader());
std::unique_ptr<frame_timestamp_reader> custom_hid_ts_reader(new iio_hid_timestamp_reader());
auto enable_global_time_option = std::shared_ptr<global_time_option>(new global_time_option());
auto hid_ep = std::make_shared<l500_hid_sensor>(this, ctx->get_backend().create_hid_device(all_hid_infos.front()),
std::unique_ptr<frame_timestamp_reader>(new global_timestamp_reader(std::move(iio_hid_ts_reader), _tf_keeper, enable_global_time_option)),
std::unique_ptr<frame_timestamp_reader>(new global_timestamp_reader(std::move(custom_hid_ts_reader), _tf_keeper, enable_global_time_option)),
l500_fps_and_sampling_frequency_per_rs2_stream,
l500_sensor_name_and_hid_profiles);
hid_ep->register_option(RS2_OPTION_GLOBAL_TIME_ENABLED, enable_global_time_option);
hid_ep->register_pixel_format(pf_accel_axes);
hid_ep->register_pixel_format(pf_gyro_axes);
return hid_ep;
}
l500_motion::l500_motion(std::shared_ptr<context> ctx, const platform::backend_device_group & group)
:device(ctx, group), l500_device(ctx, group),
_accel_stream(new stream(RS2_STREAM_ACCEL)),
_gyro_stream(new stream(RS2_STREAM_GYRO))
{
auto hid_ep = create_hid_device(ctx, group.hid_devices);
if (hid_ep)
{
_motion_module_device_idx = add_sensor(hid_ep);
// HID metadata attributes
hid_ep->register_metadata(RS2_FRAME_METADATA_FRAME_TIMESTAMP, make_hid_header_parser(&platform::hid_header::timestamp));
}
}
std::vector<tagged_profile> l500_motion::get_profiles_tags() const
{
std::vector<tagged_profile> tags;
tags.push_back({ RS2_STREAM_GYRO, -1, 0, 0, RS2_FORMAT_MOTION_XYZ32F, 200, profile_tag::PROFILE_TAG_SUPERSET | profile_tag::PROFILE_TAG_DEFAULT });
tags.push_back({ RS2_STREAM_ACCEL, -1, 0, 0, RS2_FORMAT_MOTION_XYZ32F, 200, profile_tag::PROFILE_TAG_SUPERSET | profile_tag::PROFILE_TAG_DEFAULT });
return tags;
}
rs2_motion_device_intrinsic l500_motion::get_motion_intrinsics(rs2_stream) const
{
return rs2_motion_device_intrinsic();
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: PaneShells.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2007-04-03 15:41:01 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "precompiled_sd.hxx"
#ifndef SD_PANE_SHELLS_HXX
#include "PaneShells.hxx"
#endif
#include "PaneChildWindows.hxx"
#include "glob.hrc"
#include "sdresid.hxx"
#include <sfx2/msg.hxx>
#include <sfx2/objface.hxx>
namespace sd {
//===== LeftImpressPaneShell ==================================================
#define ShellClass LeftImpressPaneShell
SFX_SLOTMAP(LeftImpressPaneShell)
{
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};
SFX_IMPL_INTERFACE(LeftImpressPaneShell, SfxShell, SdResId(STR_LEFT_IMPRESS_PANE_SHELL))
{
SFX_CHILDWINDOW_REGISTRATION(
::sd::LeftPaneImpressChildWindow::GetChildWindowId());
}
TYPEINIT1(LeftImpressPaneShell, SfxShell);
LeftImpressPaneShell::LeftImpressPaneShell (void)
: SfxShell()
{
SetName(rtl::OUString::createFromAscii("LeftImpressPane"));
}
LeftImpressPaneShell::~LeftImpressPaneShell (void)
{
}
//===== LeftDrawPaneShell =====================================================
#undef ShellClass
#define ShellClass LeftDrawPaneShell
SFX_SLOTMAP(LeftDrawPaneShell)
{
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};
SFX_IMPL_INTERFACE(LeftDrawPaneShell, SfxShell, SdResId(STR_LEFT_DRAW_PANE_SHELL))
{
SFX_CHILDWINDOW_REGISTRATION(
::sd::LeftPaneDrawChildWindow::GetChildWindowId());
}
TYPEINIT1(LeftDrawPaneShell, SfxShell);
LeftDrawPaneShell::LeftDrawPaneShell (void)
: SfxShell()
{
SetName(rtl::OUString::createFromAscii("LeftDrawPane"));
}
LeftDrawPaneShell::~LeftDrawPaneShell (void)
{
}
//===== RightPaneShell ========================================================
#undef ShellClass
#define ShellClass RightPaneShell
SFX_SLOTMAP(RightPaneShell)
{
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};
SFX_IMPL_INTERFACE(RightPaneShell, SfxShell, SdResId(STR_RIGHT_PANE_SHELL))
{
SFX_CHILDWINDOW_REGISTRATION(
::sd::RightPaneChildWindow::GetChildWindowId());
}
TYPEINIT1(RightPaneShell, SfxShell);
RightPaneShell::RightPaneShell (void)
: SfxShell()
{
SetName(rtl::OUString::createFromAscii("RightPane"));
}
RightPaneShell::~RightPaneShell (void)
{
}
} // end of namespace ::sd
<commit_msg>INTEGRATION: CWS changefileheader (1.2.234); FILE MERGED 2008/04/01 12:38:39 thb 1.2.234.2: #i85898# Stripping all external header guards 2008/03/31 13:57:44 rt 1.2.234.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: PaneShells.cxx,v $
* $Revision: 1.3 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "precompiled_sd.hxx"
#include "PaneShells.hxx"
#include "PaneChildWindows.hxx"
#include "glob.hrc"
#include "sdresid.hxx"
#include <sfx2/msg.hxx>
#include <sfx2/objface.hxx>
namespace sd {
//===== LeftImpressPaneShell ==================================================
#define ShellClass LeftImpressPaneShell
SFX_SLOTMAP(LeftImpressPaneShell)
{
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};
SFX_IMPL_INTERFACE(LeftImpressPaneShell, SfxShell, SdResId(STR_LEFT_IMPRESS_PANE_SHELL))
{
SFX_CHILDWINDOW_REGISTRATION(
::sd::LeftPaneImpressChildWindow::GetChildWindowId());
}
TYPEINIT1(LeftImpressPaneShell, SfxShell);
LeftImpressPaneShell::LeftImpressPaneShell (void)
: SfxShell()
{
SetName(rtl::OUString::createFromAscii("LeftImpressPane"));
}
LeftImpressPaneShell::~LeftImpressPaneShell (void)
{
}
//===== LeftDrawPaneShell =====================================================
#undef ShellClass
#define ShellClass LeftDrawPaneShell
SFX_SLOTMAP(LeftDrawPaneShell)
{
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};
SFX_IMPL_INTERFACE(LeftDrawPaneShell, SfxShell, SdResId(STR_LEFT_DRAW_PANE_SHELL))
{
SFX_CHILDWINDOW_REGISTRATION(
::sd::LeftPaneDrawChildWindow::GetChildWindowId());
}
TYPEINIT1(LeftDrawPaneShell, SfxShell);
LeftDrawPaneShell::LeftDrawPaneShell (void)
: SfxShell()
{
SetName(rtl::OUString::createFromAscii("LeftDrawPane"));
}
LeftDrawPaneShell::~LeftDrawPaneShell (void)
{
}
//===== RightPaneShell ========================================================
#undef ShellClass
#define ShellClass RightPaneShell
SFX_SLOTMAP(RightPaneShell)
{
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};
SFX_IMPL_INTERFACE(RightPaneShell, SfxShell, SdResId(STR_RIGHT_PANE_SHELL))
{
SFX_CHILDWINDOW_REGISTRATION(
::sd::RightPaneChildWindow::GetChildWindowId());
}
TYPEINIT1(RightPaneShell, SfxShell);
RightPaneShell::RightPaneShell (void)
: SfxShell()
{
SetName(rtl::OUString::createFromAscii("RightPane"));
}
RightPaneShell::~RightPaneShell (void)
{
}
} // end of namespace ::sd
<|endoftext|>
|
<commit_before>#include "PhotonGame.h"
#include "HelloWorldScene.h"
#include "LevelSelectlayer.h"
#include "InfoLayer.h"
#include "SettingLayer.h"
USING_NS_CC;
USING_NS_CC_DEN;
Scene* HelloWorld::createScene() {
auto scene = Scene::create();
auto layer = HelloWorld::create();
scene->addChild(layer);
return scene;
}
bool HelloWorld::init() {
if (!Layer::init()) {
return false;
}
//auto pic = Sprite::create("menu/LoadAni/01.png");
//pic->setPosition(Vec2(100, 100));
//this->addChild(pic);
//auto circle = CSLoader::createNode("LoadAni/Node1.csb");
//circle->setPosition(Vec2::ZERO);
//auto circleAni = CSLoader::createTimeline("LoadAni/RotateCircle.csb");
//circleAni->gotoFrameAndPlay(0, 66, true);
//this->addChild(circle);
//circle->runAction(circleAni);
auto rootNode = CSLoader::createNode("Csbs/MainMenu.csb");
rootNode->setPosition(Vec2::ZERO);
this->addChild(rootNode, 0);
auto startButton = dynamic_cast<ui::Button *>(rootNode->getChildByName("StartButton"));
startButton->addTouchEventListener([&](Ref* pSender, ui::Widget::TouchEventType type) {
if (type == ui::Widget::TouchEventType::ENDED) {
auto scr = LevelSelect::createScene();
auto reScr = TransitionProgressInOut::create(0.5f, scr);
Director::getInstance()->pushScene(reScr);
if (UserDefault::getInstance()->getBoolForKey(SOUND_KEY)) {
SimpleAudioEngine::getInstance()->playEffect(FILE_SOUND_1);
}
}
});
auto optionButton = dynamic_cast<ui::Button *>(rootNode->getChildByName("OptionButton"));
optionButton->addTouchEventListener([&](Ref* pSender, ui::Widget::TouchEventType type) {
if (type == ui::Widget::TouchEventType::ENDED) {
auto scr = Setting::createScene();
auto reScr = TransitionFadeTR::create(0.4f, scr);
Director::getInstance()->pushScene(reScr);
if (UserDefault::getInstance()->getBoolForKey(SOUND_KEY)) {
SimpleAudioEngine::getInstance()->playEffect(FILE_SOUND_1);
}
}
});
auto infoButton = dynamic_cast<ui::Button *>(rootNode->getChildByName("InfoButton"));
infoButton->addTouchEventListener([&](Ref* pSender, ui::Widget::TouchEventType type) {
if (type == ui::Widget::TouchEventType::ENDED) {
auto scr = Info::createScene();
auto reScr = TransitionFadeBL::create(0.4f, scr);
Director::getInstance()->pushScene(reScr);
if (UserDefault::getInstance()->getBoolForKey(SOUND_KEY)) {
SimpleAudioEngine::getInstance()->playEffect(FILE_SOUND_1);
}
}
});
auto exitButton = dynamic_cast<ui::Button *>(rootNode->getChildByName("ExitButton"));
exitButton->addTouchEventListener([&](Ref* pSender, ui::Widget::TouchEventType type) {
if (type == ui::Widget::TouchEventType::ENDED) {
SimpleAudioEngine::getInstance()->stopAllEffects();
Director::getInstance()->end();
}
});
//circle->stopAction(circleAni);
return true;
}
void HelloWorld::onEnterTransitionDidFinish() {
Layer::onEnterTransitionDidFinish();
if (UserDefault::getInstance()->getBoolForKey(MUSIC_KEY)) {
if (!UserDefault::getInstance()->getBoolForKey(MUSIC_PLAYED_KEY)) {
SimpleAudioEngine::getInstance()->playBackgroundMusic(FILE_BGM, true);
UserDefault::getInstance()->setBoolForKey(MUSIC_PLAYED_KEY, true);
}
else {
SimpleAudioEngine::getInstance()->resumeBackgroundMusic();
}
}
}
void HelloWorld::cleanup() {
Layer::cleanup();
SimpleAudioEngine::getInstance()->stopBackgroundMusic();
}<commit_msg>Delete HelloWorldScene.cpp<commit_after><|endoftext|>
|
<commit_before>#include "HelperFunctions.hpp"
cl::size_t<3> oul::createRegion(
unsigned int x,
unsigned int y,
unsigned int z) {
cl::size_t<3> region;
region[0] = x;
region[1] = y;
region[2] = z;
return region;
}
cl::size_t<3> oul::createOrigoRegion() {
cl::size_t<3> region;
region[0] = 0;
region[1] = 0;
region[2] = 0;
return region;
}
std::string getCLErrorString(cl_int err) {
switch (err) {
case CL_SUCCESS: return std::string( "Success!");
case CL_DEVICE_NOT_FOUND: return std::string( "Device not found.");
case CL_DEVICE_NOT_AVAILABLE: return std::string( "Device not available");
case CL_COMPILER_NOT_AVAILABLE: return std::string( "Compiler not available");
case CL_MEM_OBJECT_ALLOCATION_FAILURE: return std::string( "Memory object allocation failure");
case CL_OUT_OF_RESOURCES: return std::string( "Out of resources");
case CL_OUT_OF_HOST_MEMORY: return std::string( "Out of host memory");
case CL_PROFILING_INFO_NOT_AVAILABLE: return std::string( "Profiling information not available");
case CL_MEM_COPY_OVERLAP: return std::string( "Memory copy overlap");
case CL_IMAGE_FORMAT_MISMATCH: return std::string( "Image format mismatch");
case CL_IMAGE_FORMAT_NOT_SUPPORTED: return std::string( "Image format not supported");
case CL_BUILD_PROGRAM_FAILURE: return std::string( "Program build failure");
case CL_MAP_FAILURE: return std::string( "Map failure");
case CL_INVALID_VALUE: return std::string( "Invalid value");
case CL_INVALID_DEVICE_TYPE: return std::string( "Invalid device type");
case CL_INVALID_PLATFORM: return std::string( "Invalid platform");
case CL_INVALID_DEVICE: return std::string( "Invalid device");
case CL_INVALID_CONTEXT: return std::string( "Invalid context");
case CL_INVALID_QUEUE_PROPERTIES: return std::string( "Invalid queue properties");
case CL_INVALID_COMMAND_QUEUE: return std::string( "Invalid command queue");
case CL_INVALID_HOST_PTR: return std::string( "Invalid host pointer");
case CL_INVALID_MEM_OBJECT: return std::string( "Invalid memory object");
case CL_INVALID_IMAGE_FORMAT_DESCRIPTOR: return std::string( "Invalid image format descriptor");
case CL_INVALID_IMAGE_SIZE: return std::string( "Invalid image size");
case CL_INVALID_SAMPLER: return std::string( "Invalid sampler");
case CL_INVALID_BINARY: return std::string( "Invalid binary");
case CL_INVALID_BUILD_OPTIONS: return std::string( "Invalid build options");
case CL_INVALID_PROGRAM: return std::string( "Invalid program");
case CL_INVALID_PROGRAM_EXECUTABLE: return std::string( "Invalid program executable");
case CL_INVALID_KERNEL_NAME: return std::string( "Invalid kernel name");
case CL_INVALID_KERNEL_DEFINITION: return std::string( "Invalid kernel definition");
case CL_INVALID_KERNEL: return std::string( "Invalid kernel");
case CL_INVALID_ARG_INDEX: return std::string( "Invalid argument index");
case CL_INVALID_ARG_VALUE: return std::string( "Invalid argument value");
case CL_INVALID_ARG_SIZE: return std::string( "Invalid argument size");
case CL_INVALID_KERNEL_ARGS: return std::string( "Invalid kernel arguments");
case CL_INVALID_WORK_DIMENSION: return std::string( "Invalid work dimension");
case CL_INVALID_WORK_GROUP_SIZE: return std::string( "Invalid work group size");
case CL_INVALID_WORK_ITEM_SIZE: return std::string( "Invalid work item size");
case CL_INVALID_GLOBAL_OFFSET: return std::string( "Invalid global offset");
case CL_INVALID_EVENT_WAIT_LIST: return std::string( "Invalid event wait list");
case CL_INVALID_EVENT: return std::string( "Invalid event");
case CL_INVALID_OPERATION: return std::string( "Invalid operation");
case CL_INVALID_GL_OBJECT: return std::string( "Invalid OpenGL object");
case CL_INVALID_BUFFER_SIZE: return std::string( "Invalid buffer size");
case CL_INVALID_MIP_LEVEL: return std::string( "Invalid mip-map level");
default: return std::string( "Unknown");
}
}
<commit_msg>added missing namespace<commit_after>#include "HelperFunctions.hpp"
cl::size_t<3> oul::createRegion(
unsigned int x,
unsigned int y,
unsigned int z) {
cl::size_t<3> region;
region[0] = x;
region[1] = y;
region[2] = z;
return region;
}
cl::size_t<3> oul::createOrigoRegion() {
cl::size_t<3> region;
region[0] = 0;
region[1] = 0;
region[2] = 0;
return region;
}
std::string oul::getCLErrorString(cl_int err) {
switch (err) {
case CL_SUCCESS: return std::string( "Success!");
case CL_DEVICE_NOT_FOUND: return std::string( "Device not found.");
case CL_DEVICE_NOT_AVAILABLE: return std::string( "Device not available");
case CL_COMPILER_NOT_AVAILABLE: return std::string( "Compiler not available");
case CL_MEM_OBJECT_ALLOCATION_FAILURE: return std::string( "Memory object allocation failure");
case CL_OUT_OF_RESOURCES: return std::string( "Out of resources");
case CL_OUT_OF_HOST_MEMORY: return std::string( "Out of host memory");
case CL_PROFILING_INFO_NOT_AVAILABLE: return std::string( "Profiling information not available");
case CL_MEM_COPY_OVERLAP: return std::string( "Memory copy overlap");
case CL_IMAGE_FORMAT_MISMATCH: return std::string( "Image format mismatch");
case CL_IMAGE_FORMAT_NOT_SUPPORTED: return std::string( "Image format not supported");
case CL_BUILD_PROGRAM_FAILURE: return std::string( "Program build failure");
case CL_MAP_FAILURE: return std::string( "Map failure");
case CL_INVALID_VALUE: return std::string( "Invalid value");
case CL_INVALID_DEVICE_TYPE: return std::string( "Invalid device type");
case CL_INVALID_PLATFORM: return std::string( "Invalid platform");
case CL_INVALID_DEVICE: return std::string( "Invalid device");
case CL_INVALID_CONTEXT: return std::string( "Invalid context");
case CL_INVALID_QUEUE_PROPERTIES: return std::string( "Invalid queue properties");
case CL_INVALID_COMMAND_QUEUE: return std::string( "Invalid command queue");
case CL_INVALID_HOST_PTR: return std::string( "Invalid host pointer");
case CL_INVALID_MEM_OBJECT: return std::string( "Invalid memory object");
case CL_INVALID_IMAGE_FORMAT_DESCRIPTOR: return std::string( "Invalid image format descriptor");
case CL_INVALID_IMAGE_SIZE: return std::string( "Invalid image size");
case CL_INVALID_SAMPLER: return std::string( "Invalid sampler");
case CL_INVALID_BINARY: return std::string( "Invalid binary");
case CL_INVALID_BUILD_OPTIONS: return std::string( "Invalid build options");
case CL_INVALID_PROGRAM: return std::string( "Invalid program");
case CL_INVALID_PROGRAM_EXECUTABLE: return std::string( "Invalid program executable");
case CL_INVALID_KERNEL_NAME: return std::string( "Invalid kernel name");
case CL_INVALID_KERNEL_DEFINITION: return std::string( "Invalid kernel definition");
case CL_INVALID_KERNEL: return std::string( "Invalid kernel");
case CL_INVALID_ARG_INDEX: return std::string( "Invalid argument index");
case CL_INVALID_ARG_VALUE: return std::string( "Invalid argument value");
case CL_INVALID_ARG_SIZE: return std::string( "Invalid argument size");
case CL_INVALID_KERNEL_ARGS: return std::string( "Invalid kernel arguments");
case CL_INVALID_WORK_DIMENSION: return std::string( "Invalid work dimension");
case CL_INVALID_WORK_GROUP_SIZE: return std::string( "Invalid work group size");
case CL_INVALID_WORK_ITEM_SIZE: return std::string( "Invalid work item size");
case CL_INVALID_GLOBAL_OFFSET: return std::string( "Invalid global offset");
case CL_INVALID_EVENT_WAIT_LIST: return std::string( "Invalid event wait list");
case CL_INVALID_EVENT: return std::string( "Invalid event");
case CL_INVALID_OPERATION: return std::string( "Invalid operation");
case CL_INVALID_GL_OBJECT: return std::string( "Invalid OpenGL object");
case CL_INVALID_BUFFER_SIZE: return std::string( "Invalid buffer size");
case CL_INVALID_MIP_LEVEL: return std::string( "Invalid mip-map level");
default: return std::string( "Unknown");
}
}
<|endoftext|>
|
<commit_before>/*
The MIT License (MIT)
Copyright (c) 2015 Benjamin "Nefarius" Hglinger
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.
*/
#pragma once
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <string>
#include <MinHook.h>
// MinHook helper function
template <typename T>
inline MH_STATUS MH_CreateHookApiEx(
LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour, T** ppOriginal)
{
return MH_CreateHookApi(
pszModule, pszProcName, pDetour, reinterpret_cast<LPVOID*>(ppOriginal));
}
// type definition of CreateFile(...) WinAPI
typedef HANDLE(WINAPI* tCreateFile)(
_In_ LPCWSTR lpFileName,
_In_ DWORD dwDesiredAccess,
_In_ DWORD dwShareMode,
_In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes,
_In_ DWORD dwCreationDisposition,
_In_ DWORD dwFlagsAndAttributes,
_In_opt_ HANDLE hTemplateFile
);
// pointer to original function
tCreateFile OriginalCreateFile = nullptr;
// declaration of hooked function
HANDLE WINAPI DetourCreateFile(
_In_ LPCWSTR lpFileName,
_In_ DWORD dwDesiredAccess,
_In_ DWORD dwShareMode,
_In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes,
_In_ DWORD dwCreationDisposition,
_In_ DWORD dwFlagsAndAttributes,
_In_opt_ HANDLE hTemplateFile
);
int init(void);
// called on DLL load
BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID)
{
DisableThreadLibraryCalls(static_cast<HMODULE>(hInstance));
if (dwReason != DLL_PROCESS_ATTACH)
return FALSE;
return CreateThread(nullptr, 0, reinterpret_cast<LPTHREAD_START_ROUTINE>(init), nullptr, 0, nullptr) > nullptr;
}
// main logic
int init()
{
// initialize hook engine
if (MH_Initialize() != MH_OK)
{
return -1;
}
// create kernel32!CreateFileW hook (unicode)
if (MH_CreateHookApiEx(L"kernel32", "CreateFileW", &DetourCreateFile, &OriginalCreateFile) != MH_OK)
{
return -2;
}
// enable hook
if (MH_EnableHook(GetProcAddress(GetModuleHandle(L"kernel32"), "CreateFileW")) != MH_OK)
{
return -3;
}
// block this thread infinitely to keep hooks active
return WaitForSingleObject(INVALID_HANDLE_VALUE, INFINITE);
}
// fake/hooked CreateFile function
HANDLE WINAPI DetourCreateFile(
_In_ LPCWSTR lpFileName,
_In_ DWORD dwDesiredAccess,
_In_ DWORD dwShareMode,
_In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes,
_In_ DWORD dwCreationDisposition,
_In_ DWORD dwFlagsAndAttributes,
_In_opt_ HANDLE hTemplateFile
)
{
// wrap file name in unicode string
std::wstring fileName(lpFileName);
// identify open call for DualShock 4 device
if (fileName.find(L"\\\\?\\hid#vid_054c&pid_05c4") != std::wstring::npos)
{
// fake open error
SetLastError(ERROR_FILE_NOT_FOUND);
// fake return value
return INVALID_HANDLE_VALUE;
}
// legit call, forward to original function
return OriginalCreateFile(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);
}
<commit_msg>Added more comments<commit_after>/*
The MIT License (MIT)
Copyright (c) 2015 Benjamin "Nefarius" Hglinger
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.
*/
#pragma once
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <string>
#include <MinHook.h>
// MinHook helper function
template <typename T>
inline MH_STATUS MH_CreateHookApiEx(
LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour, T** ppOriginal)
{
return MH_CreateHookApi(
pszModule, pszProcName, pDetour, reinterpret_cast<LPVOID*>(ppOriginal));
}
// type definition of CreateFile(...) WinAPI
typedef HANDLE(WINAPI* tCreateFile)(
_In_ LPCWSTR lpFileName,
_In_ DWORD dwDesiredAccess,
_In_ DWORD dwShareMode,
_In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes,
_In_ DWORD dwCreationDisposition,
_In_ DWORD dwFlagsAndAttributes,
_In_opt_ HANDLE hTemplateFile
);
// pointer to original function
tCreateFile OriginalCreateFile = nullptr;
// declaration of hooked function
HANDLE WINAPI DetourCreateFile(
_In_ LPCWSTR lpFileName,
_In_ DWORD dwDesiredAccess,
_In_ DWORD dwShareMode,
_In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes,
_In_ DWORD dwCreationDisposition,
_In_ DWORD dwFlagsAndAttributes,
_In_opt_ HANDLE hTemplateFile
);
int init(void);
// called on DLL load
BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID)
{
// we don't care about thread attachments/detachments
DisableThreadLibraryCalls(static_cast<HMODULE>(hInstance));
if (dwReason != DLL_PROCESS_ATTACH)
return FALSE;
// loader lock active; begin work in new thread
return CreateThread(nullptr, 0, reinterpret_cast<LPTHREAD_START_ROUTINE>(init), nullptr, 0, nullptr) > nullptr;
}
// main logic
int init()
{
// initialize hook engine
if (MH_Initialize() != MH_OK)
{
return -1;
}
// create kernel32!CreateFileW hook (unicode)
if (MH_CreateHookApiEx(L"kernel32", "CreateFileW", &DetourCreateFile, &OriginalCreateFile) != MH_OK)
{
return -2;
}
// enable hook
if (MH_EnableHook(GetProcAddress(GetModuleHandle(L"kernel32"), "CreateFileW")) != MH_OK)
{
return -3;
}
// block this thread infinitely to keep hooks active
return WaitForSingleObject(INVALID_HANDLE_VALUE, INFINITE);
}
// fake/hooked CreateFile function
HANDLE WINAPI DetourCreateFile(
_In_ LPCWSTR lpFileName,
_In_ DWORD dwDesiredAccess,
_In_ DWORD dwShareMode,
_In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes,
_In_ DWORD dwCreationDisposition,
_In_ DWORD dwFlagsAndAttributes,
_In_opt_ HANDLE hTemplateFile
)
{
// wrap file name in unicode string
std::wstring fileName(lpFileName);
// identify open call for DualShock 4 device
if (fileName.find(L"\\\\?\\hid#vid_054c&pid_05c4") != std::wstring::npos)
{
// fake open error
SetLastError(ERROR_FILE_NOT_FOUND);
// fake return value
return INVALID_HANDLE_VALUE;
}
// legit call, forward to original function
return OriginalCreateFile(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);
}
<|endoftext|>
|
<commit_before>/*
* Silly subclass of CTreeCtrl just to implement Drag&Drop.
*
* Based on MFC sample code from CMNCTRL1
*/
#include "stdafx.h"
#include "MyTreeCtrl.h"
#include "DboxMain.h"
#include "corelib/ItemData.h"
#include "corelib/MyString.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
static const TCHAR GROUP_SEP = TCHAR('.');
CMyTreeCtrl::CMyTreeCtrl() : m_bDragging(false), m_pimagelist(NULL)
{
}
CMyTreeCtrl::~CMyTreeCtrl()
{
delete m_pimagelist;
}
BEGIN_MESSAGE_MAP(CMyTreeCtrl, CTreeCtrl)
//{{AFX_MSG_MAP(CMyTreeCtrl)
ON_NOTIFY_REFLECT(TVN_BEGINLABELEDIT, OnBeginLabelEdit)
ON_NOTIFY_REFLECT(TVN_ENDLABELEDIT, OnEndLabelEdit)
ON_NOTIFY_REFLECT(TVN_BEGINDRAG, OnBeginDrag)
ON_WM_MOUSEMOVE()
ON_WM_DESTROY()
ON_WM_LBUTTONUP()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
void CMyTreeCtrl::OnDestroy()
{
CImageList *pimagelist;
pimagelist = GetImageList(TVSIL_NORMAL);
if (pimagelist != NULL) {
pimagelist->DeleteImageList();
delete pimagelist;
}
}
void CMyTreeCtrl::SetNewStyle(long lStyleMask, BOOL bSetBits)
{
long lStyleOld;
lStyleOld = GetWindowLong(m_hWnd, GWL_STYLE);
lStyleOld &= ~lStyleMask;
if (bSetBits)
lStyleOld |= lStyleMask;
SetWindowLong(m_hWnd, GWL_STYLE, lStyleOld);
SetWindowPos(NULL, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER);
}
void CMyTreeCtrl::UpdateLeafsGroup(HTREEITEM hItem, CString prefix)
{
// Starting with hItem, update the Group field of all of hItem's
// children. Called after a label has been edited.
if (IsLeafNode(hItem)) {
DWORD itemData = GetItemData(hItem);
ASSERT(itemData != NULL);
CItemData *ci = (CItemData *)itemData;
ci->SetGroup(CMyString(prefix));
} else { // update prefix with current group name and recurse
if (!prefix.IsEmpty())
prefix += GROUP_SEP;
prefix += GetItemText(hItem);
HTREEITEM child;
for(child = GetChildItem(hItem); child != NULL; child = GetNextSiblingItem(child)) {
UpdateLeafsGroup(child, prefix);
}
}
}
void CMyTreeCtrl::OnBeginLabelEdit(LPNMHDR pnmhdr, LRESULT *pLResult)
{
TV_DISPINFO *ptvinfo = (TV_DISPINFO *)pnmhdr;
// I thought m_BeginEditText was needed to restore text if desired,
// but setting *pLResult to FALSE in OnEndLabelEdit suffices
if (ptvinfo->item.pszText != NULL &&
ptvinfo->item.pszText[0] != '\0') {
m_BeginEditText = ptvinfo->item.pszText;
} else {
m_BeginEditText = _T("");
}
DboxMain *parent = (DboxMain *)GetParent();
parent->DisableOnEdit(true); // so that Enter doesn't invoke Edit dialog
*pLResult = FALSE; // TRUE cancels label editing
}
static void splitLeafText(const char *lt, CString &newTitle, CString &newUser)
{
CString leafText(lt);
int leftBraceIndex = leafText.Find('[');
if (leftBraceIndex == -1) {
newTitle = leafText;
newUser = _T("");
} else {
newTitle = leafText.Left(leftBraceIndex - 1);
int rightBraceIndex = leafText.Find(']');
if (rightBraceIndex == -1) {
newUser = leafText.Mid(leftBraceIndex + 1);
} else {
newUser = leafText.Mid(leftBraceIndex + 1, rightBraceIndex - leftBraceIndex - 1);
}
}
}
static void makeLeafText(CString &treeDispString, const CString &title, const CString &user)
{
treeDispString = title;
if (!user.IsEmpty()) {
treeDispString += _T(" [");
treeDispString += user;
treeDispString += _T("]");
}
}
void CMyTreeCtrl::OnEndLabelEdit(LPNMHDR pnmhdr, LRESULT *pLResult)
{
static bool inEdit = false;
if (inEdit) { // happens when edit control manipulated - see below
inEdit = false;
*pLResult = TRUE;
return;
}
TV_DISPINFO *ptvinfo = (TV_DISPINFO *)pnmhdr;
HTREEITEM ti = ptvinfo->item.hItem;
DboxMain *parent = (DboxMain *)GetParent();
parent->DisableOnEdit(false); // Allow Enter to invoke Edit dialog
if (ptvinfo->item.pszText != NULL && // NULL if edit cancelled,
ptvinfo->item.pszText[0] != '\0') { // empty if text deleted - not allowed
ptvinfo->item.mask = TVIF_TEXT;
SetItem(&ptvinfo->item);
if (IsLeafNode(ptvinfo->item.hItem)) {
/*
* Leaf text is of the form: title [user]
* If edited text contains '[', then the user is updated
* If not, then the user is retrieved and the leaf is updated
*/
// Update leaf's title
DWORD itemData = GetItemData(ti);
ASSERT(itemData != NULL);
CItemData *ci = (CItemData *)itemData;
CString newTitle, newUser;
splitLeafText(ptvinfo->item.pszText, newTitle, newUser);
if (newUser.IsEmpty())
newUser = CString(ci->GetUser());
CString treeDispString;
makeLeafText(treeDispString, newTitle, newUser);
// Following needed to force display to update at this stage.
inEdit = true; // hack to exit ugly recursion.
CEdit *ed = EditLabel(ti);
ASSERT(ed != NULL);
ed->SetWindowText(treeDispString);
SetItemText(ti, treeDispString);
ci->SetTitle(newTitle); ci->SetUser(newUser);
// update corresponding List text
DisplayInfo *di = (DisplayInfo *)ci->GetDisplayInfo();
ASSERT(di != NULL);
int lindex = di->list_index;
parent->UpdateListItemTitle(lindex, newTitle);
parent->UpdateListItemUser(lindex, newUser);
} else {
// Update all leaf children with new path element
// prefix is path up to and NOT including renamed node
CString prefix;
HTREEITEM parent, current = ti;
do {
parent = GetParentItem(current);
if (parent == NULL) {
break;
}
current = parent;
if (!prefix.IsEmpty())
prefix = GROUP_SEP + prefix;
prefix = GetItemText(current) + prefix;
} while (1);
UpdateLeafsGroup(ti, prefix);
}
// Mark database as modified
parent->SetChanged(true);
SortChildren(GetParentItem(ti));
*pLResult = TRUE;
} else {
// restore text
// (not that this is documented anywhere in MS's docs...)
*pLResult = FALSE;
}
}
void CMyTreeCtrl::OnMouseMove(UINT nFlags, CPoint point)
{
if (m_bDragging) {
UINT flags;
ASSERT(m_pimagelist != NULL);
m_pimagelist->DragMove(point);
HTREEITEM hitem = HitTest(point, &flags);
if (hitem != NULL) {
m_pimagelist->DragLeave(this);
SelectDropTarget(hitem);
m_hitemDrop = hitem;
m_pimagelist->DragEnter(this, point);
}
}
CTreeCtrl::OnMouseMove(nFlags, point);
}
bool CMyTreeCtrl::IsChildNodeOf(HTREEITEM hitemChild, HTREEITEM hitemSuspectedParent)
{
do {
if (hitemChild == hitemSuspectedParent)
break;
} while ((hitemChild = GetParentItem(hitemChild)) != NULL);
return (hitemChild != NULL);
}
bool CMyTreeCtrl::IsLeafNode(HTREEITEM hItem)
{
// ItemHasChildren() won't work in the general case
BOOL status;
int i, dummy;
status = GetItemImage(hItem, i, dummy);
ASSERT(status);
return (i == LEAF);
}
void CMyTreeCtrl::DeleteWithParents(HTREEITEM hItem)
{
// We don't want nodes that have no children to remain
HTREEITEM p;
do {
p = GetParentItem(hItem);
DeleteItem(hItem);
if (ItemHasChildren(p))
break;
hItem = p;
} while (p != TVI_ROOT && p != NULL);
}
CString CMyTreeCtrl::GetGroup(HTREEITEM hItem)
{
CString retval;
CString nodeText;
while (hItem != NULL) {
nodeText = GetItemText(hItem);
if (!retval.IsEmpty())
nodeText += GROUP_SEP;
retval = nodeText + retval;
hItem = GetParentItem(hItem);
}
return retval;
}
static CMyString GetPathElem(CMyString &path)
{
// Get first path element and chop it off, i.e., if
// path = "a.b.c.d"
// will return "a" and path will be "b.c.d"
// (assuming GROUP_SEP is '.')
CMyString retval;
int N = path.Find(GROUP_SEP);
if (N == -1) {
retval = path;
path = _T("");
} else {
const int Len = path.GetLength();
retval = CMyString(path.Left(N));
path = CMyString(path.Right(Len - N - 1));
}
return retval;
}
static bool ExistsInTree(CTreeCtrl &Tree, HTREEITEM node,
const CMyString &s, HTREEITEM &si)
{
// returns true iff s is a direct descendant of node
HTREEITEM ti = Tree.GetChildItem(node);
while (ti != NULL) {
const CMyString itemText = Tree.GetItemText(ti);
if (itemText == s) {
si = ti;
return true;
}
ti = Tree.GetNextItem(ti, TVGN_NEXT);
}
return false;
}
HTREEITEM CMyTreeCtrl::AddGroup(const CString &group)
{
// Add a group at the end of path
HTREEITEM ti = TVI_ROOT;
HTREEITEM si;
if (!group.IsEmpty()) {
CMyString path = group;
CMyString s;
do {
s = GetPathElem(path);
if (!ExistsInTree(*this, ti, s, si)) {
ti = InsertItem(s, ti, TVI_SORT);
SetItemImage(ti, CMyTreeCtrl::NODE, CMyTreeCtrl::NODE);
} else
ti = si;
} while (!path.IsEmpty());
}
return ti;
}
bool CMyTreeCtrl::TransferItem(HTREEITEM hitemDrag, HTREEITEM hitemDrop)
{
TV_INSERTSTRUCT tvstruct;
TCHAR sztBuffer[128];
HTREEITEM hNewItem, hFirstChild;
DWORD itemData = GetItemData(hitemDrag);
// avoid an infinite recursion
tvstruct.item.hItem = hitemDrag;
tvstruct.item.cchTextMax = sizeof(sztBuffer)/sizeof(TCHAR) - 1;
tvstruct.item.pszText = sztBuffer;
tvstruct.item.mask = (TVIF_CHILDREN | TVIF_HANDLE | TVIF_IMAGE
| TVIF_SELECTEDIMAGE | TVIF_TEXT);
GetItem(&tvstruct.item); // get information of the dragged element
tvstruct.hParent = hitemDrop;
tvstruct.hInsertAfter = TVI_SORT;
tvstruct.item.mask = TVIF_IMAGE | TVIF_SELECTEDIMAGE | TVIF_TEXT;
hNewItem = InsertItem(&tvstruct);
if (itemData != 0) { // Non-NULL itemData implies Leaf
CItemData *ci = (CItemData *)itemData;
// Update Group
CMyString path, elem;
HTREEITEM p, q = hNewItem;
do {
p = GetParentItem(q);
if (p != NULL) {
elem = CMyString(GetItemText(p));
if (!path.IsEmpty())
elem += GROUP_SEP;
path = elem + path;
q = p;
} else
break;
} while (1);
ci->SetGroup(path);
// Mark database as modified!
((DboxMain *)GetParent())->SetChanged(true);
// Update DisplayInfo record associated with ItemData
DisplayInfo *di = (DisplayInfo *)ci->GetDisplayInfo();
ASSERT(di != NULL);
di->tree_item = hNewItem;
}
SetItemData(hNewItem, itemData);
while ((hFirstChild = GetChildItem(hitemDrag)) != NULL) {
TransferItem(hFirstChild, hNewItem); // recursively transfer all the items
DeleteItem(hFirstChild);
}
return true;
}
void CMyTreeCtrl::OnButtonUp()
{
if (m_bDragging) {
ASSERT(m_pimagelist != NULL);
m_pimagelist->DragLeave(this);
m_pimagelist->EndDrag();
delete m_pimagelist;
m_pimagelist = NULL;
HTREEITEM parent = GetParentItem(m_hitemDrag);
if (m_hitemDrag != m_hitemDrop &&
!IsLeafNode(m_hitemDrop) &&
!IsChildNodeOf(m_hitemDrop, m_hitemDrag) &&
parent != m_hitemDrop) {
TransferItem(m_hitemDrag, m_hitemDrop);
DeleteItem(m_hitemDrag);
while (parent != NULL && !ItemHasChildren(parent)) {
HTREEITEM grandParent = GetParentItem(parent);
DeleteItem(parent);
parent = grandParent;
}
SelectItem(m_hitemDrop);
} else { // drag failed, revert to last selected
SelectItem(m_hitemDrag);
}
ReleaseCapture();
m_bDragging = FALSE;
SelectDropTarget(NULL);
}
}
void CMyTreeCtrl::OnLButtonUp(UINT nFlags, CPoint point)
{
OnButtonUp();
CTreeCtrl::OnLButtonUp(nFlags, point);
}
void CMyTreeCtrl::OnBeginDrag(LPNMHDR , LRESULT *)
{
CPoint ptAction;
UINT nFlags;
GetCursorPos(&ptAction);
ScreenToClient(&ptAction);
ASSERT(!m_bDragging);
m_bDragging = TRUE;
m_hitemDrag = HitTest(ptAction, &nFlags);
m_hitemDrop = NULL;
ASSERT(m_pimagelist == NULL);
m_pimagelist = CreateDragImage(m_hitemDrag);
m_pimagelist->DragShowNolock(TRUE);
m_pimagelist->SetDragCursorImage(0, CPoint(0, 0));
m_pimagelist->BeginDrag(0, CPoint(0,0));
m_pimagelist->DragMove(ptAction);
m_pimagelist->DragEnter(this, ptAction);
SetCapture();
}
<commit_msg>[916587] - can now invoke edit dialog after inline edit<commit_after>/*
* Silly subclass of CTreeCtrl just to implement Drag&Drop.
*
* Based on MFC sample code from CMNCTRL1
*/
#include "stdafx.h"
#include "MyTreeCtrl.h"
#include "DboxMain.h"
#include "corelib/ItemData.h"
#include "corelib/MyString.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
static const TCHAR GROUP_SEP = TCHAR('.');
CMyTreeCtrl::CMyTreeCtrl() : m_bDragging(false), m_pimagelist(NULL)
{
}
CMyTreeCtrl::~CMyTreeCtrl()
{
delete m_pimagelist;
}
BEGIN_MESSAGE_MAP(CMyTreeCtrl, CTreeCtrl)
//{{AFX_MSG_MAP(CMyTreeCtrl)
ON_NOTIFY_REFLECT(TVN_BEGINLABELEDIT, OnBeginLabelEdit)
ON_NOTIFY_REFLECT(TVN_ENDLABELEDIT, OnEndLabelEdit)
ON_NOTIFY_REFLECT(TVN_BEGINDRAG, OnBeginDrag)
ON_WM_MOUSEMOVE()
ON_WM_DESTROY()
ON_WM_LBUTTONUP()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
void CMyTreeCtrl::OnDestroy()
{
CImageList *pimagelist;
pimagelist = GetImageList(TVSIL_NORMAL);
if (pimagelist != NULL) {
pimagelist->DeleteImageList();
delete pimagelist;
}
}
void CMyTreeCtrl::SetNewStyle(long lStyleMask, BOOL bSetBits)
{
long lStyleOld;
lStyleOld = GetWindowLong(m_hWnd, GWL_STYLE);
lStyleOld &= ~lStyleMask;
if (bSetBits)
lStyleOld |= lStyleMask;
SetWindowLong(m_hWnd, GWL_STYLE, lStyleOld);
SetWindowPos(NULL, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER);
}
void CMyTreeCtrl::UpdateLeafsGroup(HTREEITEM hItem, CString prefix)
{
// Starting with hItem, update the Group field of all of hItem's
// children. Called after a label has been edited.
if (IsLeafNode(hItem)) {
DWORD itemData = GetItemData(hItem);
ASSERT(itemData != NULL);
CItemData *ci = (CItemData *)itemData;
ci->SetGroup(CMyString(prefix));
} else { // update prefix with current group name and recurse
if (!prefix.IsEmpty())
prefix += GROUP_SEP;
prefix += GetItemText(hItem);
HTREEITEM child;
for(child = GetChildItem(hItem); child != NULL; child = GetNextSiblingItem(child)) {
UpdateLeafsGroup(child, prefix);
}
}
}
void CMyTreeCtrl::OnBeginLabelEdit(LPNMHDR pnmhdr, LRESULT *pLResult)
{
TV_DISPINFO *ptvinfo = (TV_DISPINFO *)pnmhdr;
// I thought m_BeginEditText was needed to restore text if desired,
// but setting *pLResult to FALSE in OnEndLabelEdit suffices
if (ptvinfo->item.pszText != NULL &&
ptvinfo->item.pszText[0] != '\0') {
m_BeginEditText = ptvinfo->item.pszText;
} else {
m_BeginEditText = _T("");
}
DboxMain *parent = (DboxMain *)GetParent();
parent->DisableOnEdit(true); // so that Enter doesn't invoke Edit dialog
*pLResult = FALSE; // TRUE cancels label editing
}
static void splitLeafText(const char *lt, CString &newTitle, CString &newUser)
{
CString leafText(lt);
int leftBraceIndex = leafText.Find('[');
if (leftBraceIndex == -1) {
newTitle = leafText;
newUser = _T("");
} else {
newTitle = leafText.Left(leftBraceIndex - 1);
int rightBraceIndex = leafText.Find(']');
if (rightBraceIndex == -1) {
newUser = leafText.Mid(leftBraceIndex + 1);
} else {
newUser = leafText.Mid(leftBraceIndex + 1, rightBraceIndex - leftBraceIndex - 1);
}
}
}
static void makeLeafText(CString &treeDispString, const CString &title, const CString &user)
{
treeDispString = title;
if (!user.IsEmpty()) {
treeDispString += _T(" [");
treeDispString += user;
treeDispString += _T("]");
}
}
void CMyTreeCtrl::OnEndLabelEdit(LPNMHDR pnmhdr, LRESULT *pLResult)
{
static bool inEdit = false;
if (inEdit) { // happens when edit control manipulated - see below
inEdit = false;
*pLResult = TRUE;
return;
}
TV_DISPINFO *ptvinfo = (TV_DISPINFO *)pnmhdr;
HTREEITEM ti = ptvinfo->item.hItem;
DboxMain *parent = (DboxMain *)GetParent();
if (ptvinfo->item.pszText != NULL && // NULL if edit cancelled,
ptvinfo->item.pszText[0] != '\0') { // empty if text deleted - not allowed
ptvinfo->item.mask = TVIF_TEXT;
SetItem(&ptvinfo->item);
if (IsLeafNode(ptvinfo->item.hItem)) {
/*
* Leaf text is of the form: title [user]
* If edited text contains '[', then the user is updated
* If not, then the user is retrieved and the leaf is updated
*/
// Update leaf's title
DWORD itemData = GetItemData(ti);
ASSERT(itemData != NULL);
CItemData *ci = (CItemData *)itemData;
CString newTitle, newUser;
splitLeafText(ptvinfo->item.pszText, newTitle, newUser);
if (newUser.IsEmpty())
newUser = CString(ci->GetUser());
CString treeDispString;
makeLeafText(treeDispString, newTitle, newUser);
// Following needed to force display to update at this stage.
inEdit = true; // hack to exit ugly recursion.
CEdit *ed = EditLabel(ti);
ASSERT(ed != NULL);
ed->SetWindowText(treeDispString);
SetItemText(ti, treeDispString);
ci->SetTitle(newTitle); ci->SetUser(newUser);
// update corresponding List text
DisplayInfo *di = (DisplayInfo *)ci->GetDisplayInfo();
ASSERT(di != NULL);
int lindex = di->list_index;
parent->UpdateListItemTitle(lindex, newTitle);
parent->UpdateListItemUser(lindex, newUser);
} else {
// Update all leaf children with new path element
// prefix is path up to and NOT including renamed node
CString prefix;
HTREEITEM parent, current = ti;
do {
parent = GetParentItem(current);
if (parent == NULL) {
break;
}
current = parent;
if (!prefix.IsEmpty())
prefix = GROUP_SEP + prefix;
prefix = GetItemText(current) + prefix;
} while (1);
UpdateLeafsGroup(ti, prefix);
}
// Mark database as modified
parent->SetChanged(true);
SortChildren(GetParentItem(ti));
*pLResult = TRUE;
} else {
// restore text
// (not that this is documented anywhere in MS's docs...)
*pLResult = FALSE;
}
// following has to be done at end of function, since OnBeginLabelEdit
// may be called (indirectly) from this fuction
parent->DisableOnEdit(false); // Allow Enter to invoke Edit dialog
}
void CMyTreeCtrl::OnMouseMove(UINT nFlags, CPoint point)
{
if (m_bDragging) {
UINT flags;
ASSERT(m_pimagelist != NULL);
m_pimagelist->DragMove(point);
HTREEITEM hitem = HitTest(point, &flags);
if (hitem != NULL) {
m_pimagelist->DragLeave(this);
SelectDropTarget(hitem);
m_hitemDrop = hitem;
m_pimagelist->DragEnter(this, point);
}
}
CTreeCtrl::OnMouseMove(nFlags, point);
}
bool CMyTreeCtrl::IsChildNodeOf(HTREEITEM hitemChild, HTREEITEM hitemSuspectedParent)
{
do {
if (hitemChild == hitemSuspectedParent)
break;
} while ((hitemChild = GetParentItem(hitemChild)) != NULL);
return (hitemChild != NULL);
}
bool CMyTreeCtrl::IsLeafNode(HTREEITEM hItem)
{
// ItemHasChildren() won't work in the general case
BOOL status;
int i, dummy;
status = GetItemImage(hItem, i, dummy);
ASSERT(status);
return (i == LEAF);
}
void CMyTreeCtrl::DeleteWithParents(HTREEITEM hItem)
{
// We don't want nodes that have no children to remain
HTREEITEM p;
do {
p = GetParentItem(hItem);
DeleteItem(hItem);
if (ItemHasChildren(p))
break;
hItem = p;
} while (p != TVI_ROOT && p != NULL);
}
CString CMyTreeCtrl::GetGroup(HTREEITEM hItem)
{
CString retval;
CString nodeText;
while (hItem != NULL) {
nodeText = GetItemText(hItem);
if (!retval.IsEmpty())
nodeText += GROUP_SEP;
retval = nodeText + retval;
hItem = GetParentItem(hItem);
}
return retval;
}
static CMyString GetPathElem(CMyString &path)
{
// Get first path element and chop it off, i.e., if
// path = "a.b.c.d"
// will return "a" and path will be "b.c.d"
// (assuming GROUP_SEP is '.')
CMyString retval;
int N = path.Find(GROUP_SEP);
if (N == -1) {
retval = path;
path = _T("");
} else {
const int Len = path.GetLength();
retval = CMyString(path.Left(N));
path = CMyString(path.Right(Len - N - 1));
}
return retval;
}
static bool ExistsInTree(CTreeCtrl &Tree, HTREEITEM node,
const CMyString &s, HTREEITEM &si)
{
// returns true iff s is a direct descendant of node
HTREEITEM ti = Tree.GetChildItem(node);
while (ti != NULL) {
const CMyString itemText = Tree.GetItemText(ti);
if (itemText == s) {
si = ti;
return true;
}
ti = Tree.GetNextItem(ti, TVGN_NEXT);
}
return false;
}
HTREEITEM CMyTreeCtrl::AddGroup(const CString &group)
{
// Add a group at the end of path
HTREEITEM ti = TVI_ROOT;
HTREEITEM si;
if (!group.IsEmpty()) {
CMyString path = group;
CMyString s;
do {
s = GetPathElem(path);
if (!ExistsInTree(*this, ti, s, si)) {
ti = InsertItem(s, ti, TVI_SORT);
SetItemImage(ti, CMyTreeCtrl::NODE, CMyTreeCtrl::NODE);
} else
ti = si;
} while (!path.IsEmpty());
}
return ti;
}
bool CMyTreeCtrl::TransferItem(HTREEITEM hitemDrag, HTREEITEM hitemDrop)
{
TV_INSERTSTRUCT tvstruct;
TCHAR sztBuffer[128];
HTREEITEM hNewItem, hFirstChild;
DWORD itemData = GetItemData(hitemDrag);
// avoid an infinite recursion
tvstruct.item.hItem = hitemDrag;
tvstruct.item.cchTextMax = sizeof(sztBuffer)/sizeof(TCHAR) - 1;
tvstruct.item.pszText = sztBuffer;
tvstruct.item.mask = (TVIF_CHILDREN | TVIF_HANDLE | TVIF_IMAGE
| TVIF_SELECTEDIMAGE | TVIF_TEXT);
GetItem(&tvstruct.item); // get information of the dragged element
tvstruct.hParent = hitemDrop;
tvstruct.hInsertAfter = TVI_SORT;
tvstruct.item.mask = TVIF_IMAGE | TVIF_SELECTEDIMAGE | TVIF_TEXT;
hNewItem = InsertItem(&tvstruct);
if (itemData != 0) { // Non-NULL itemData implies Leaf
CItemData *ci = (CItemData *)itemData;
// Update Group
CMyString path, elem;
HTREEITEM p, q = hNewItem;
do {
p = GetParentItem(q);
if (p != NULL) {
elem = CMyString(GetItemText(p));
if (!path.IsEmpty())
elem += GROUP_SEP;
path = elem + path;
q = p;
} else
break;
} while (1);
ci->SetGroup(path);
// Mark database as modified!
((DboxMain *)GetParent())->SetChanged(true);
// Update DisplayInfo record associated with ItemData
DisplayInfo *di = (DisplayInfo *)ci->GetDisplayInfo();
ASSERT(di != NULL);
di->tree_item = hNewItem;
}
SetItemData(hNewItem, itemData);
while ((hFirstChild = GetChildItem(hitemDrag)) != NULL) {
TransferItem(hFirstChild, hNewItem); // recursively transfer all the items
DeleteItem(hFirstChild);
}
return true;
}
void CMyTreeCtrl::OnButtonUp()
{
if (m_bDragging) {
ASSERT(m_pimagelist != NULL);
m_pimagelist->DragLeave(this);
m_pimagelist->EndDrag();
delete m_pimagelist;
m_pimagelist = NULL;
HTREEITEM parent = GetParentItem(m_hitemDrag);
if (m_hitemDrag != m_hitemDrop &&
!IsLeafNode(m_hitemDrop) &&
!IsChildNodeOf(m_hitemDrop, m_hitemDrag) &&
parent != m_hitemDrop) {
TransferItem(m_hitemDrag, m_hitemDrop);
DeleteItem(m_hitemDrag);
while (parent != NULL && !ItemHasChildren(parent)) {
HTREEITEM grandParent = GetParentItem(parent);
DeleteItem(parent);
parent = grandParent;
}
SelectItem(m_hitemDrop);
} else { // drag failed, revert to last selected
SelectItem(m_hitemDrag);
}
ReleaseCapture();
m_bDragging = FALSE;
SelectDropTarget(NULL);
}
}
void CMyTreeCtrl::OnLButtonUp(UINT nFlags, CPoint point)
{
OnButtonUp();
CTreeCtrl::OnLButtonUp(nFlags, point);
}
void CMyTreeCtrl::OnBeginDrag(LPNMHDR , LRESULT *)
{
CPoint ptAction;
UINT nFlags;
GetCursorPos(&ptAction);
ScreenToClient(&ptAction);
ASSERT(!m_bDragging);
m_bDragging = TRUE;
m_hitemDrag = HitTest(ptAction, &nFlags);
m_hitemDrop = NULL;
ASSERT(m_pimagelist == NULL);
m_pimagelist = CreateDragImage(m_hitemDrag);
m_pimagelist->DragShowNolock(TRUE);
m_pimagelist->SetDragCursorImage(0, CPoint(0, 0));
m_pimagelist->BeginDrag(0, CPoint(0,0));
m_pimagelist->DragMove(ptAction);
m_pimagelist->DragEnter(this, ptAction);
SetCapture();
}
<|endoftext|>
|
<commit_before>/* Sirikata Kernel -- Task scheduling system
* Scheduler.hpp
*
* Copyright (c) 2008, Patrick Reiter Horn
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Sirikata 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.
*/
#ifndef SIRIKATA_Scheduler_HPP__
#define SIRIKATA_Scheduler_HPP__
#include "Time.hpp"
namespace Sirikata {
namespace Task {
/**
* TaskFunction represents a runnable task that will is a bound
* std::tr1::function to some class that needs to be run whenever it
* needs processing time. NOTE: Because this interface needs to be fast
* and should be kept simple,
*
* @param LocalTime When the task should aim to finish.
* @returns 'true' if the task should remain on the ready queue
* (if it needs more time), or false if it should sleep.
*/
typedef std::tr1::function1<bool(LocalTime)> TaskFunction;
/// Scheduler interface
class Scheduler {
public:
/** Create a task. */
SubscriptionId createTask(TaskFunction func) = 0;
/** Put the task in the ready queue to be run at regular intervals. */
void readyTask(SubscriptionId taskId) = 0;
/** A task has nothing to do (or is waiting for some event). */
void sleepTask(SubscriptionId taskId) = 0;
/** Destroy the task associated with 'taskId'. */
void destroyTask(SubscriptionId taskId) = 0;
//void setPriority(SubscriptionId taskId, int prio) = 0;
};
/** Scheduler runs through the queue in the order that tasks were made
* ready. */
class RoundRobinScheduler : Scheduler {
struct TaskInfo;
typedef std::list<TaskInfo*> FunctionList;
typedef std::map<SubscriptionId, TaskInfo*> TaskIdMap;
struct TaskInfo {
SubscriptionId id;
TaskFunction func;
FunctionList *activeQueue;
FunctionList::iterator removeIter;
/* Help scheduler decide how much time to allocate btwn frames */
//DeltaTime lastTimes[NUM_AVERAGES];
//DeltaTime expectedTime;
};
TaskIdMap mTaskIdMap;
FunctionList mReadyQueue;
SubscriptionId mRunningTask;
public:
SubscriptionId createTask(TaskFunction func) {
SubscriptionId myId = SubscriptionIdClass::alloc();
TaskInfo* ti = new TaskInfo;
ti->id = myId;
ti->func = func;
ti->activeQueue = NULL;
mTaskIdMap.insert(TaskIdMap::value_type(myId, ti));
}
void readyTask(SubscriptionId taskId) {
TaskIdMap::iterator iter = mTaskIdMap.find(taskId);
if (iter == mTaskIdMap.end()) {
return;
}
TaskInfo* ti = (*iter).second;
if (ti->activeQueue == NULL) {
ti->activeQueue = &mReadyQueue;
mReadyQueue.push_back(ti);
FunctionList::iterator iter = mReadyQueue.end();
--iter;
ti->removeIter = iter;
}
}
void sleepTask(SubscriptionId taskId) {
TaskIdMap::iterator iter = mTaskIdMap.find(taskId);
if (iter == mTaskIdMap.end()) {
return;
}
TaskInfo* ti = (*iter).second;
if (ti->activeQueue != NULL) {
ti->activeQueue->remove(ti->removeIter);
ti->activeQueue = NULL;
}
}
void destroyTask(SubscriptionId taskId) {
TaskIdMap::iterator iter = mTaskIdMap.find(taskId);
if (iter == mTaskIdMap.end()) {
return;
}
TaskInfo* ti = (*iter).second;
if (ti->activeQueue != NULL) {
ti->activeQueue->remove(ti->removeIter);
ti->activeQueue = NULL;
}
delete ti;
mTaskIdMap.remove(iter);
}
};
}
}
#endif
<commit_msg>Remove unused Scheduler classes.<commit_after><|endoftext|>
|
<commit_before>/*
* Copyright 2007-2017 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Internal.hxx"
#include "Request.hxx"
#include "direct.hxx"
#include "util/Exception.hxx"
#include <daemon/log.h>
#include <sys/socket.h>
#include <errno.h>
#include <string.h>
size_t
HttpServerConnection::OnData(const void *data, size_t length)
{
assert(socket.IsConnected() || request.request == nullptr);
assert(response.istream.IsDefined());
assert(!response.pending_drained);
if (!socket.IsConnected())
return 0;
ssize_t nbytes = socket.Write(data, length);
if (likely(nbytes >= 0)) {
response.bytes_sent += nbytes;
response.length += (off_t)nbytes;
ScheduleWrite();
return (size_t)nbytes;
}
if (gcc_likely(nbytes == WRITE_BLOCKING)) {
response.want_write = true;
return 0;
}
if (nbytes == WRITE_DESTROYED)
return 0;
SocketErrorErrno("write error on HTTP connection");
return 0;
}
ssize_t
HttpServerConnection::OnDirect(FdType type, int fd, size_t max_length)
{
assert(socket.IsConnected() || request.request == nullptr);
assert(response.istream.IsDefined());
assert(!response.pending_drained);
if (!socket.IsConnected())
return 0;
ssize_t nbytes = socket.WriteFrom(fd, type, max_length);
if (likely(nbytes > 0)) {
response.bytes_sent += nbytes;
response.length += (off_t)nbytes;
ScheduleWrite();
} else if (nbytes == WRITE_BLOCKING) {
response.want_write = true;
return ISTREAM_RESULT_BLOCKING;
} else if (nbytes == WRITE_DESTROYED)
return ISTREAM_RESULT_CLOSED;
return nbytes;
}
void
HttpServerConnection::OnEof()
{
assert(request.read_state != Request::START &&
request.read_state != Request::HEADERS);
assert(request.request != nullptr);
assert(response.istream.IsDefined());
assert(!response.pending_drained);
response.istream.Clear();
ResponseIstreamFinished();
}
void
HttpServerConnection::OnError(std::exception_ptr ep)
{
assert(response.istream.IsDefined());
response.istream.Clear();
/* we clear this cancel_ptr here so http_server_request_close()
won't think we havn't sent a response yet */
request.cancel_ptr = nullptr;
Error(NestException(ep,
std::runtime_error("error on HTTP response stream")));
}
void
HttpServerConnection::SetResponseIstream(Istream &r)
{
response.istream.Set(r, *this, istream_direct_mask_to(socket.GetType()));
}
bool
HttpServerConnection::ResponseIstreamFinished()
{
socket.UnscheduleWrite();
Log();
/* check for end of chunked request body again, just in case
DechunkIstream has announced this in a derred event */
if (request.read_state == Request::BODY && request_body_reader->IsEOF()) {
request.read_state = Request::END;
request_body_reader->DestroyEof();
if (!IsValid())
return false;
}
if (request.read_state == Request::BODY &&
!request.expect_100_continue) {
/* We are still reading the request body, which we don't need
anymore. To discard it, we simply close the connection by
disabling keepalive; this seems cheaper than redirecting
the rest of the body to /dev/null */
keep_alive = false;
request.read_state = Request::END;
request_body_reader->DestroyError(std::make_exception_ptr(std::runtime_error("request body discarded")));
if (!IsValid())
return false;
}
pool_trash(&request.request->pool);
pool_unref(&request.request->pool);
request.request = nullptr;
request.bytes_received = 0;
response.bytes_sent = 0;
request.read_state = Request::START;
if (keep_alive) {
/* handle pipelined request (if any), or set up events for
next request */
socket.ScheduleReadNoTimeout(false);
idle_timeout.Add(http_server_idle_timeout);
return true;
} else {
/* keepalive disabled and response is finished: we must close
the connection */
if (socket.IsDrained()) {
Done();
return false;
} else {
/* there is still data in the filter's output buffer; wait for
that to drain, which will trigger
http_server_socket_drained() */
assert(!response.pending_drained);
response.pending_drained = true;
return true;
}
}
}
<commit_msg>http_server: unschedule write after EAGAIN from splice()<commit_after>/*
* Copyright 2007-2017 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Internal.hxx"
#include "Request.hxx"
#include "direct.hxx"
#include "util/Exception.hxx"
#include <daemon/log.h>
#include <sys/socket.h>
#include <errno.h>
#include <string.h>
size_t
HttpServerConnection::OnData(const void *data, size_t length)
{
assert(socket.IsConnected() || request.request == nullptr);
assert(response.istream.IsDefined());
assert(!response.pending_drained);
if (!socket.IsConnected())
return 0;
ssize_t nbytes = socket.Write(data, length);
if (likely(nbytes >= 0)) {
response.bytes_sent += nbytes;
response.length += (off_t)nbytes;
ScheduleWrite();
return (size_t)nbytes;
}
if (gcc_likely(nbytes == WRITE_BLOCKING)) {
response.want_write = true;
return 0;
}
if (nbytes == WRITE_DESTROYED)
return 0;
SocketErrorErrno("write error on HTTP connection");
return 0;
}
ssize_t
HttpServerConnection::OnDirect(FdType type, int fd, size_t max_length)
{
assert(socket.IsConnected() || request.request == nullptr);
assert(response.istream.IsDefined());
assert(!response.pending_drained);
if (!socket.IsConnected())
return 0;
ssize_t nbytes = socket.WriteFrom(fd, type, max_length);
if (likely(nbytes > 0)) {
response.bytes_sent += nbytes;
response.length += (off_t)nbytes;
ScheduleWrite();
} else if (nbytes == WRITE_BLOCKING) {
response.want_write = true;
return ISTREAM_RESULT_BLOCKING;
} else if (nbytes == WRITE_DESTROYED)
return ISTREAM_RESULT_CLOSED;
else if (gcc_likely(nbytes < 0) && errno == EAGAIN)
socket.UnscheduleWrite();
return nbytes;
}
void
HttpServerConnection::OnEof()
{
assert(request.read_state != Request::START &&
request.read_state != Request::HEADERS);
assert(request.request != nullptr);
assert(response.istream.IsDefined());
assert(!response.pending_drained);
response.istream.Clear();
ResponseIstreamFinished();
}
void
HttpServerConnection::OnError(std::exception_ptr ep)
{
assert(response.istream.IsDefined());
response.istream.Clear();
/* we clear this cancel_ptr here so http_server_request_close()
won't think we havn't sent a response yet */
request.cancel_ptr = nullptr;
Error(NestException(ep,
std::runtime_error("error on HTTP response stream")));
}
void
HttpServerConnection::SetResponseIstream(Istream &r)
{
response.istream.Set(r, *this, istream_direct_mask_to(socket.GetType()));
}
bool
HttpServerConnection::ResponseIstreamFinished()
{
socket.UnscheduleWrite();
Log();
/* check for end of chunked request body again, just in case
DechunkIstream has announced this in a derred event */
if (request.read_state == Request::BODY && request_body_reader->IsEOF()) {
request.read_state = Request::END;
request_body_reader->DestroyEof();
if (!IsValid())
return false;
}
if (request.read_state == Request::BODY &&
!request.expect_100_continue) {
/* We are still reading the request body, which we don't need
anymore. To discard it, we simply close the connection by
disabling keepalive; this seems cheaper than redirecting
the rest of the body to /dev/null */
keep_alive = false;
request.read_state = Request::END;
request_body_reader->DestroyError(std::make_exception_ptr(std::runtime_error("request body discarded")));
if (!IsValid())
return false;
}
pool_trash(&request.request->pool);
pool_unref(&request.request->pool);
request.request = nullptr;
request.bytes_received = 0;
response.bytes_sent = 0;
request.read_state = Request::START;
if (keep_alive) {
/* handle pipelined request (if any), or set up events for
next request */
socket.ScheduleReadNoTimeout(false);
idle_timeout.Add(http_server_idle_timeout);
return true;
} else {
/* keepalive disabled and response is finished: we must close
the connection */
if (socket.IsDrained()) {
Done();
return false;
} else {
/* there is still data in the filter's output buffer; wait for
that to drain, which will trigger
http_server_socket_drained() */
assert(!response.pending_drained);
response.pending_drained = true;
return true;
}
}
}
<|endoftext|>
|
<commit_before>/*------------------------------------------------------------------------------
Copyright (c) 2004 Media Development Loan Fund
This file is part of the LiveSupport project.
http://livesupport.campware.org/
To report bugs, send an e-mail to bugs@campware.org
LiveSupport is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
LiveSupport is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with LiveSupport; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Author : $Author: fgerlits $
Version : $Revision: 1.3 $
Location : $Source: /home/paul/cvs2svn-livesupport/newcvsrepo/livesupport/modules/core/src/XmlRpcToolsTest.cxx,v $
------------------------------------------------------------------------------*/
/* ============================================================ include files */
#ifdef HAVE_CONFIG_H
#include "configure.h"
#endif
#if HAVE_UNISTD_H
#include <unistd.h>
#else
#error "Need unistd.h"
#endif
#include <string>
#include <iostream>
#include <XmlRpcValue.h>
#include "LiveSupport/Core/XmlRpcTools.h"
#include "XmlRpcToolsTest.h"
using namespace LiveSupport::Core;
using namespace std;
using namespace XmlRpc;
/* =================================================== local data structures */
/* ================================================ local constants & macros */
CPPUNIT_TEST_SUITE_REGISTRATION(XmlRpcToolsTest);
/**
* The name of the configuration file for the playlist.
*/
const std::string configFileName = "etc/playlist.xml";
/* =============================================== local function prototypes */
/* ============================================================= module code */
/*------------------------------------------------------------------------------
* Configure a Configurable with an XML file.
*----------------------------------------------------------------------------*/
void
XmlRpcToolsTest :: configure(
Ptr<Configurable>::Ref configurable,
const std::string fileName)
throw (CPPUNIT_NS::Exception)
{
try {
Ptr<xmlpp::DomParser>::Ref parser(
new xmlpp::DomParser(configFileName, true));
const xmlpp::Document * document = parser->get_document();
const xmlpp::Element * root = document->get_root_node();
configurable->configure(*root);
} catch (std::invalid_argument &e) {
CPPUNIT_FAIL("semantic error in configuration file");
} catch (xmlpp::exception &e) {
CPPUNIT_FAIL("error parsing configuration file");
}
}
/*------------------------------------------------------------------------------
* Set up the test environment
*----------------------------------------------------------------------------*/
void
XmlRpcToolsTest :: setUp(void) throw ()
{
}
/*------------------------------------------------------------------------------
* Clean up the test environment
*----------------------------------------------------------------------------*/
void
XmlRpcToolsTest :: tearDown(void) throw ()
{
}
/*------------------------------------------------------------------------------
* Just a very simple smoke test
*----------------------------------------------------------------------------*/
void
XmlRpcToolsTest :: firstTest(void)
throw (CPPUNIT_NS::Exception)
{
XmlRpcValue xmlRpcPlaylist;
XmlRpcValue xmlRpcAudioClip;
Ptr<Playlist>::Ref playlist = Ptr<Playlist>::Ref(new Playlist());
Ptr<const AudioClip>::Ref audioClip;
// set up a playlist instance
configure(playlist, configFileName);
audioClip = playlist->begin()->second->getAudioClip();
// run the packing methods
XmlRpcTools :: playlistToXmlRpcValue(playlist, xmlRpcPlaylist);
XmlRpcTools :: audioClipToXmlRpcValue(audioClip, xmlRpcAudioClip);
CPPUNIT_ASSERT(xmlRpcPlaylist.hasMember("playlist"));
CPPUNIT_ASSERT(xmlRpcPlaylist["playlist"].getType()
== XmlRpcValue::TypeString);
Ptr<Playlist>::Ref copyOfPlaylist(new Playlist());
xmlpp::DomParser parser;
CPPUNIT_ASSERT_NO_THROW(parser.parse_memory(std::string(
xmlRpcPlaylist["playlist"] )));
xmlpp::Element* configElement;
CPPUNIT_ASSERT_NO_THROW(configElement = parser.get_document()
->get_root_node());
CPPUNIT_ASSERT_NO_THROW(copyOfPlaylist->configure(*configElement));
CPPUNIT_ASSERT(*copyOfPlaylist->getId() == *playlist->getId());
CPPUNIT_ASSERT(*copyOfPlaylist->getTitle() == *playlist->getTitle());
CPPUNIT_ASSERT(*copyOfPlaylist->getPlaylength()
== *playlist->getPlaylength());
CPPUNIT_ASSERT(xmlRpcAudioClip.hasMember("audioClip"));
CPPUNIT_ASSERT(xmlRpcAudioClip["audioClip"].getType()
== XmlRpcValue::TypeString);
Ptr<AudioClip>::Ref copyOfAudioClip(new AudioClip());
CPPUNIT_ASSERT_NO_THROW(parser.parse_memory(std::string(
xmlRpcAudioClip["audioClip"] )));
CPPUNIT_ASSERT_NO_THROW(configElement = parser.get_document()
->get_root_node());
CPPUNIT_ASSERT_NO_THROW(copyOfAudioClip->configure(*configElement));
CPPUNIT_ASSERT(*copyOfAudioClip->getId() == *audioClip->getId());
CPPUNIT_ASSERT(*copyOfAudioClip->getTitle() == *audioClip->getTitle());
CPPUNIT_ASSERT(*copyOfAudioClip->getPlaylength()
== *audioClip->getPlaylength());
XmlRpcValue xmlRpcPlaylistId;
Ptr<UniqueId>::Ref playlistId(new UniqueId(rand()));
Ptr<UniqueId>::Ref audioClipId(new UniqueId(rand()));
Ptr<time_duration>::Ref relativeOffset(new time_duration(0,0,rand(),0));
xmlRpcPlaylistId["playlistId"] = std::string(*playlistId);
xmlRpcPlaylistId["audioClipId"] = std::string(*audioClipId);
xmlRpcPlaylistId["relativeOffset"] = relativeOffset->total_seconds();
// run the unpacking methods
Ptr<UniqueId>::Ref newPlaylistId;
Ptr<UniqueId>::Ref newAudioClipId;
Ptr<time_duration>::Ref newRelativeOffset;
try {
newPlaylistId = XmlRpcTools::extractPlaylistId(xmlRpcPlaylistId);
newAudioClipId = XmlRpcTools::extractAudioClipId(xmlRpcPlaylistId);
newRelativeOffset = XmlRpcTools::extractRelativeOffset(xmlRpcPlaylistId);
} catch (std::invalid_argument &e) {
CPPUNIT_FAIL(e.what());
}
CPPUNIT_ASSERT(*playlistId == *newPlaylistId);
CPPUNIT_ASSERT(*audioClipId == *newAudioClipId);
CPPUNIT_ASSERT(*relativeOffset == *newRelativeOffset);
}
/*------------------------------------------------------------------------------
* Testing markError()
*----------------------------------------------------------------------------*/
void
XmlRpcToolsTest :: errorTest(void)
throw (CPPUNIT_NS::Exception)
{
XmlRpcValue xmlRpcValue;
try {
XmlRpcTools :: markError(42, "this is an error", xmlRpcValue);
CPPUNIT_FAIL("did not throw exception in markError()");
} catch (XmlRpc::XmlRpcException &e) {
CPPUNIT_ASSERT(e.getCode() == 42);
CPPUNIT_ASSERT(e.getMessage() == "this is an error");
}
}
<commit_msg>added (unnecesary) initialization of pointer to make the compiler happy<commit_after>/*------------------------------------------------------------------------------
Copyright (c) 2004 Media Development Loan Fund
This file is part of the LiveSupport project.
http://livesupport.campware.org/
To report bugs, send an e-mail to bugs@campware.org
LiveSupport is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
LiveSupport is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with LiveSupport; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Author : $Author: fgerlits $
Version : $Revision: 1.4 $
Location : $Source: /home/paul/cvs2svn-livesupport/newcvsrepo/livesupport/modules/core/src/XmlRpcToolsTest.cxx,v $
------------------------------------------------------------------------------*/
/* ============================================================ include files */
#ifdef HAVE_CONFIG_H
#include "configure.h"
#endif
#if HAVE_UNISTD_H
#include <unistd.h>
#else
#error "Need unistd.h"
#endif
#include <string>
#include <iostream>
#include <XmlRpcValue.h>
#include "LiveSupport/Core/XmlRpcTools.h"
#include "XmlRpcToolsTest.h"
using namespace LiveSupport::Core;
using namespace std;
using namespace XmlRpc;
/* =================================================== local data structures */
/* ================================================ local constants & macros */
CPPUNIT_TEST_SUITE_REGISTRATION(XmlRpcToolsTest);
/**
* The name of the configuration file for the playlist.
*/
const std::string configFileName = "etc/playlist.xml";
/* =============================================== local function prototypes */
/* ============================================================= module code */
/*------------------------------------------------------------------------------
* Configure a Configurable with an XML file.
*----------------------------------------------------------------------------*/
void
XmlRpcToolsTest :: configure(
Ptr<Configurable>::Ref configurable,
const std::string fileName)
throw (CPPUNIT_NS::Exception)
{
try {
Ptr<xmlpp::DomParser>::Ref parser(
new xmlpp::DomParser(configFileName, true));
const xmlpp::Document * document = parser->get_document();
const xmlpp::Element * root = document->get_root_node();
configurable->configure(*root);
} catch (std::invalid_argument &e) {
CPPUNIT_FAIL("semantic error in configuration file");
} catch (xmlpp::exception &e) {
CPPUNIT_FAIL("error parsing configuration file");
}
}
/*------------------------------------------------------------------------------
* Set up the test environment
*----------------------------------------------------------------------------*/
void
XmlRpcToolsTest :: setUp(void) throw ()
{
}
/*------------------------------------------------------------------------------
* Clean up the test environment
*----------------------------------------------------------------------------*/
void
XmlRpcToolsTest :: tearDown(void) throw ()
{
}
/*------------------------------------------------------------------------------
* Just a very simple smoke test
*----------------------------------------------------------------------------*/
void
XmlRpcToolsTest :: firstTest(void)
throw (CPPUNIT_NS::Exception)
{
XmlRpcValue xmlRpcPlaylist;
XmlRpcValue xmlRpcAudioClip;
Ptr<Playlist>::Ref playlist = Ptr<Playlist>::Ref(new Playlist());
Ptr<const AudioClip>::Ref audioClip;
// set up a playlist instance
configure(playlist, configFileName);
audioClip = playlist->begin()->second->getAudioClip();
// run the packing methods
XmlRpcTools :: playlistToXmlRpcValue(playlist, xmlRpcPlaylist);
XmlRpcTools :: audioClipToXmlRpcValue(audioClip, xmlRpcAudioClip);
CPPUNIT_ASSERT(xmlRpcPlaylist.hasMember("playlist"));
CPPUNIT_ASSERT(xmlRpcPlaylist["playlist"].getType()
== XmlRpcValue::TypeString);
Ptr<Playlist>::Ref copyOfPlaylist(new Playlist());
xmlpp::DomParser parser;
CPPUNIT_ASSERT_NO_THROW(parser.parse_memory(std::string(
xmlRpcPlaylist["playlist"] )));
xmlpp::Element* configElement = 0;
CPPUNIT_ASSERT_NO_THROW(configElement = parser.get_document()
->get_root_node());
CPPUNIT_ASSERT(configElement);
CPPUNIT_ASSERT_NO_THROW(copyOfPlaylist->configure(*configElement));
CPPUNIT_ASSERT(*copyOfPlaylist->getId() == *playlist->getId());
CPPUNIT_ASSERT(*copyOfPlaylist->getTitle() == *playlist->getTitle());
CPPUNIT_ASSERT(*copyOfPlaylist->getPlaylength()
== *playlist->getPlaylength());
CPPUNIT_ASSERT(xmlRpcAudioClip.hasMember("audioClip"));
CPPUNIT_ASSERT(xmlRpcAudioClip["audioClip"].getType()
== XmlRpcValue::TypeString);
Ptr<AudioClip>::Ref copyOfAudioClip(new AudioClip());
CPPUNIT_ASSERT_NO_THROW(parser.parse_memory(std::string(
xmlRpcAudioClip["audioClip"] )));
CPPUNIT_ASSERT_NO_THROW(configElement = parser.get_document()
->get_root_node());
CPPUNIT_ASSERT_NO_THROW(copyOfAudioClip->configure(*configElement));
CPPUNIT_ASSERT(*copyOfAudioClip->getId() == *audioClip->getId());
CPPUNIT_ASSERT(*copyOfAudioClip->getTitle() == *audioClip->getTitle());
CPPUNIT_ASSERT(*copyOfAudioClip->getPlaylength()
== *audioClip->getPlaylength());
XmlRpcValue xmlRpcPlaylistId;
Ptr<UniqueId>::Ref playlistId(new UniqueId(rand()));
Ptr<UniqueId>::Ref audioClipId(new UniqueId(rand()));
Ptr<time_duration>::Ref relativeOffset(new time_duration(0,0,rand(),0));
xmlRpcPlaylistId["playlistId"] = std::string(*playlistId);
xmlRpcPlaylistId["audioClipId"] = std::string(*audioClipId);
xmlRpcPlaylistId["relativeOffset"] = relativeOffset->total_seconds();
// run the unpacking methods
Ptr<UniqueId>::Ref newPlaylistId;
Ptr<UniqueId>::Ref newAudioClipId;
Ptr<time_duration>::Ref newRelativeOffset;
try {
newPlaylistId = XmlRpcTools::extractPlaylistId(xmlRpcPlaylistId);
newAudioClipId = XmlRpcTools::extractAudioClipId(xmlRpcPlaylistId);
newRelativeOffset = XmlRpcTools::extractRelativeOffset(xmlRpcPlaylistId);
} catch (std::invalid_argument &e) {
CPPUNIT_FAIL(e.what());
}
CPPUNIT_ASSERT(*playlistId == *newPlaylistId);
CPPUNIT_ASSERT(*audioClipId == *newAudioClipId);
CPPUNIT_ASSERT(*relativeOffset == *newRelativeOffset);
}
/*------------------------------------------------------------------------------
* Testing markError()
*----------------------------------------------------------------------------*/
void
XmlRpcToolsTest :: errorTest(void)
throw (CPPUNIT_NS::Exception)
{
XmlRpcValue xmlRpcValue;
try {
XmlRpcTools :: markError(42, "this is an error", xmlRpcValue);
CPPUNIT_FAIL("did not throw exception in markError()");
} catch (XmlRpc::XmlRpcException &e) {
CPPUNIT_ASSERT(e.getCode() == 42);
CPPUNIT_ASSERT(e.getMessage() == "this is an error");
}
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.