text
stringlengths 54
60.6k
|
---|
<commit_before>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-
Copyright 2015
Raffaello D. Di Napoli
This file is part of Abaclade.
Abaclade is free software: you can redistribute it and/or modify it under the terms of the GNU
General Public License as published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
Abaclade 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 Abaclade. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/
#include <abaclade.hxx>
#include <abaclade/testing/test_case.hxx>
#include <abaclade/list.hxx>
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::test::list_basic
namespace abc {
namespace test {
ABC_TESTING_TEST_CASE_FUNC(list_basic, "abc::list – basic operations") {
ABC_TRACE_FUNC(this);
list<int> l;
ABC_TESTING_ASSERT_EQUAL(l.size(), 0u);
ABC_TESTING_ASSERT_TRUE(l.begin() == l.end());
l.push_front(10);
ABC_TESTING_ASSERT_EQUAL(l.size(), 1u);
l.push_back(20);
ABC_TESTING_ASSERT_EQUAL(l.size(), 2u);
l.pop_front();
ABC_TESTING_ASSERT_EQUAL(l.size(), 1u);
l.pop_back();
ABC_TESTING_ASSERT_EQUAL(l.size(), 0u);
l.clear();
ABC_TESTING_ASSERT_EQUAL(l.size(), 0u);
}
} //namespace test
} //namespace abc
<commit_msg>Add more abc::list test assertions<commit_after>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-
Copyright 2015
Raffaello D. Di Napoli
This file is part of Abaclade.
Abaclade is free software: you can redistribute it and/or modify it under the terms of the GNU
General Public License as published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
Abaclade 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 Abaclade. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/
#include <abaclade.hxx>
#include <abaclade/testing/test_case.hxx>
#include <abaclade/list.hxx>
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::test::list_basic
namespace abc {
namespace test {
ABC_TESTING_TEST_CASE_FUNC(list_basic, "abc::list – basic operations") {
ABC_TRACE_FUNC(this);
list<int> l;
ABC_TESTING_ASSERT_EQUAL(l.size(), 0u);
// These assertions target const begin/end.
ABC_TESTING_ASSERT_TRUE(l.cbegin() == l.cend());
ABC_TESTING_ASSERT_TRUE(l.crbegin() == l.crend());
l.push_front(10);
ABC_TESTING_ASSERT_EQUAL(l.size(), 1u);
{
/* This uses begin(), not cbegin(), so we can test equality comparison between const/non-const
iterators. */
auto it(l.begin());
ABC_TESTING_ASSERT_EQUAL(*it, 10);
++it;
ABC_TESTING_ASSERT_TRUE(it == l.cend());
}
l.push_back(20);
ABC_TESTING_ASSERT_EQUAL(l.size(), 2u);
{
// This iterates backwards and is longer than, but symmetrical to, the block above.
auto it(l.rbegin());
ABC_TESTING_ASSERT_EQUAL(*it, 20);
++it;
ABC_TESTING_ASSERT_EQUAL(*it, 10);
++it;
ABC_TESTING_ASSERT_TRUE(it == l.crend());
}
l.pop_front();
ABC_TESTING_ASSERT_EQUAL(l.size(), 1u);
{
// Now iterate backwards using a forward iterator.
auto it(l.end());
--it;
ABC_TESTING_ASSERT_EQUAL(*it, 20);
ABC_TESTING_ASSERT_TRUE(it == l.cbegin());
}
l.pop_back();
ABC_TESTING_ASSERT_EQUAL(l.size(), 0u);
// These assertions target non-const begin/end.
ABC_TESTING_ASSERT_TRUE(l.begin() == l.end());
ABC_TESTING_ASSERT_TRUE(l.rbegin() == l.rend());
l.push_front(30);
ABC_TESTING_ASSERT_EQUAL(l.size(), 1u);
l.clear();
ABC_TESTING_ASSERT_EQUAL(l.size(), 0u);
}
} //namespace test
} //namespace abc
<|endoftext|> |
<commit_before>#ifndef __TENSOR3_HPP_INCLUDED
#define __TENSOR3_HPP_INCLUDED
#include "matrix.hpp"
// Include standard headers
#include <stdint.h> // uint32_t etc.
namespace linear_algebra
{
class Tensor3
{
public:
// constructor.
Tensor3(uint32_t height, uint32_t width, uint32_t depth);
// copy constructor.
Tensor3(Tensor3& old_tensor3);
// constructor.
Tensor3(Matrix& old_matrix);
// destructor.
~Tensor3();
// Inspired by http://stackoverflow.com/questions/6969881/operator-overload/6969904#6969904
class Proxy2D
{
public:
Proxy2D(float** array_of_arrays) : array_of_arrays(array_of_arrays) { }
class Proxy
{
public:
Proxy(float* proxy_array) : proxy_array(proxy_array) { }
float& operator[](const uint32_t index)
{
return proxy_array[index];
}
private:
float* proxy_array;
};
Proxy operator[](const uint32_t index)
{
return array_of_arrays[index];
}
private:
float** array_of_arrays;
};
void operator<<(const float rhs);
void operator<<(const std::vector<float>& rhs);
Proxy2D operator[](const uint32_t index)
{
return Proxy2D(array_of_arrays_of_arrays[index]);
}
private:
bool is_cube;
uint32_t width;
uint32_t height;
uint32_t depth;
bool is_fully_populated;
// For populating, the order of coordinates from
// the one changing fastest to the one changing slowest is:
// x, y, z
int32_t next_x_to_populate;
int32_t next_y_to_populate;
int32_t next_z_to_populate;
float*** array_of_arrays_of_arrays;
};
}
#endif
<commit_msg>Added a comment.<commit_after>#ifndef __TENSOR3_HPP_INCLUDED
#define __TENSOR3_HPP_INCLUDED
#include "matrix.hpp"
// Include standard headers
#include <stdint.h> // uint32_t etc.
namespace linear_algebra
{
class Tensor3
{
// `class Tensor3` uses the same coordinate order as MATLAB,
// to make testing easier. So: y, x, z.
// y = 0 is the uppermost slice
// x = 0 is the leftmost slice.
// z = 0 is the front slice.
public:
// constructor.
Tensor3(uint32_t height, uint32_t width, uint32_t depth);
// copy constructor.
Tensor3(Tensor3& old_tensor3);
// constructor.
Tensor3(Matrix& old_matrix);
// destructor.
~Tensor3();
// Inspired by http://stackoverflow.com/questions/6969881/operator-overload/6969904#6969904
class Proxy2D
{
public:
Proxy2D(float** array_of_arrays) : array_of_arrays(array_of_arrays) { }
class Proxy
{
public:
Proxy(float* proxy_array) : proxy_array(proxy_array) { }
float& operator[](const uint32_t index)
{
return proxy_array[index];
}
private:
float* proxy_array;
};
Proxy operator[](const uint32_t index)
{
return array_of_arrays[index];
}
private:
float** array_of_arrays;
};
void operator<<(const float rhs);
void operator<<(const std::vector<float>& rhs);
Proxy2D operator[](const uint32_t index)
{
return Proxy2D(array_of_arrays_of_arrays[index]);
}
private:
bool is_cube;
uint32_t width;
uint32_t height;
uint32_t depth;
bool is_fully_populated;
// For populating, the order of coordinates from
// the one changing fastest to the one changing slowest is:
// x, y, z
int32_t next_x_to_populate;
int32_t next_y_to_populate;
int32_t next_z_to_populate;
float*** array_of_arrays_of_arrays;
};
}
#endif
<|endoftext|> |
<commit_before>#include <vector>
#include <thread>
#include <mutex>
#include <algorithm>
#include <signal.h>
#include <ev3/servo.h>
namespace ev3cv {
namespace {
std::vector<servo *> servos;
std::mutex servos_lock;
std::thread controller_thread;
}
void controller_main() {
// Clock to use for controllers.
typedef std::chrono::high_resolution_clock clock;
// Sampling period for the controllers.
static const std::chrono::milliseconds dt(10);
auto t0 = clock::now();
for(auto t = t0; ; t += dt) {
if (dt.count() > 0) {
std::lock_guard<std::mutex> lock(servos_lock);
for (auto i : servos) {
i->tick(dt.count());
}
if (servos.empty())
break;
}
std::this_thread::sleep_until(t);
}
}
servo::servo(const ev3dev::port_type &port) : m_(port), pid_(5000, 5000, 200, 2, 5000) {
reset();
{
std::lock_guard<std::mutex> lock(servos_lock);
servos.push_back(this);
}
// If we don't have a controller thread, make one.
if (!controller_thread.joinable()) {
std::thread new_thread(controller_main);
std::swap(controller_thread, new_thread);
}
}
servo::~servo() {
servos_lock.lock();
servos.erase(std::find(servos.begin(), servos.end(), this));
// If there are no more live motors, wait for the controller thread to complete.
if (servos.empty()) {
servos_lock.unlock();
controller_thread.join();
} else {
servos_lock.unlock();
}
m_.reset();
}
void servo::run() {
{
std::lock_guard<std::mutex> lock(this->lock_);
pid_.reset();
}
m_.set_run_mode(ev3dev::motor::run_mode_forever);
tick(0);
m_.run();
}
void servo::stop(bool hold) {
std::lock_guard<std::mutex> lock(this->lock_);
m_.set_stop_mode(hold ? ev3dev::motor::stop_mode_hold : ev3dev::motor::stop_mode_coast);
m_.stop();
pid_.reset();
}
void servo::reset(int position) {
std::lock_guard<std::mutex> lock(this->lock_);
m_.reset();
m_.set_position(position);
pid_.reset();
max_duty_cycle_ = 100;
}
void servo::tick(int dt) {
std::lock_guard<std::mutex> lock(this->lock_);
int x = position();
if (sp_fn_) {
t_ += dt;
pid_.set_setpoint(sp_fn_(x, t_, dt));
}
int y = pid_.tick(x, dt)/1024;
m_.set_duty_cycle_setpoint(clamp(y, -max_duty_cycle_, max_duty_cycle_));
}
int servo::position_setpoint() const {
return pid_.setpoint();
}
void servo::set_position_setpoint(int sp) {
std::lock_guard<std::mutex> lock(this->lock_);
sp_fn_ = nullptr;
pid_.set_setpoint(sp);
}
void servo::set_position_setpoint(std::function<int(int, int, int)> sp_fn) {
std::lock_guard<std::mutex> lock(this->lock_);
sp_fn_ = sp_fn;
t_ = 0;
pid_.set_setpoint(sp_fn(position(), t_, 0));
}
void servo::set_max_duty_cycle(int x) {
std::lock_guard<std::mutex> lock(this->lock_);
max_duty_cycle_ = x;
}
} // namespace ev3cv<commit_msg>Fixed noisy station keeping<commit_after>#include <vector>
#include <thread>
#include <mutex>
#include <algorithm>
#include <signal.h>
#include <ev3/servo.h>
namespace ev3cv {
namespace {
std::vector<servo *> servos;
std::mutex servos_lock;
std::thread controller_thread;
}
void controller_main() {
// Clock to use for controllers.
typedef std::chrono::high_resolution_clock clock;
// Sampling period for the controllers.
static const std::chrono::milliseconds dt(10);
auto t0 = clock::now();
for(auto t = t0; ; t += dt) {
if (dt.count() > 0) {
std::lock_guard<std::mutex> lock(servos_lock);
for (auto i : servos) {
i->tick(dt.count());
}
if (servos.empty())
break;
}
std::this_thread::sleep_until(t);
}
}
servo::servo(const ev3dev::port_type &port) : m_(port), pid_(5000, 5000, 200, 0, 5000) {
reset();
{
std::lock_guard<std::mutex> lock(servos_lock);
servos.push_back(this);
}
// If we don't have a controller thread, make one.
if (!controller_thread.joinable()) {
std::thread new_thread(controller_main);
std::swap(controller_thread, new_thread);
}
}
servo::~servo() {
servos_lock.lock();
servos.erase(std::find(servos.begin(), servos.end(), this));
// If there are no more live motors, wait for the controller thread to complete.
if (servos.empty()) {
servos_lock.unlock();
controller_thread.join();
} else {
servos_lock.unlock();
}
m_.reset();
}
void servo::run() {
{
std::lock_guard<std::mutex> lock(this->lock_);
pid_.reset();
}
m_.set_run_mode(ev3dev::motor::run_mode_forever);
tick(0);
m_.run();
}
void servo::stop(bool hold) {
std::lock_guard<std::mutex> lock(this->lock_);
m_.set_stop_mode(hold ? ev3dev::motor::stop_mode_hold : ev3dev::motor::stop_mode_coast);
m_.stop();
pid_.reset();
}
void servo::reset(int position) {
std::lock_guard<std::mutex> lock(this->lock_);
m_.reset();
m_.set_position(position);
pid_.reset();
max_duty_cycle_ = 100;
}
void servo::tick(int dt) {
std::lock_guard<std::mutex> lock(this->lock_);
int x = position();
if (sp_fn_) {
t_ += dt;
pid_.set_setpoint(sp_fn_(x, t_, dt));
}
int y = pid_.tick(x, dt)/1024;
m_.set_duty_cycle_setpoint(clamp(y, -max_duty_cycle_, max_duty_cycle_));
}
int servo::position_setpoint() const {
return pid_.setpoint();
}
void servo::set_position_setpoint(int sp) {
std::lock_guard<std::mutex> lock(this->lock_);
sp_fn_ = nullptr;
pid_.set_setpoint(sp);
}
void servo::set_position_setpoint(std::function<int(int, int, int)> sp_fn) {
std::lock_guard<std::mutex> lock(this->lock_);
sp_fn_ = sp_fn;
t_ = 0;
pid_.set_setpoint(sp_fn(position(), t_, 0));
}
void servo::set_max_duty_cycle(int x) {
std::lock_guard<std::mutex> lock(this->lock_);
max_duty_cycle_ = x;
}
} // namespace ev3cv<|endoftext|> |
<commit_before>#include <netdb.h>
#include <netinet/tcp.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/poll.h>
#include <sys/types.h>
#include <errno.h>
#include <fcntl.h>
#include <queue>
#include "Connection.h"
using douban::mc::io::BufferWriter;
using douban::mc::io::BufferReader;
namespace douban {
namespace mc {
Connection::Connection()
: m_counter(0), m_port(0), m_socketFd(-1),
m_alive(false), m_hasAlias(false), m_deadUntil(0),
m_connectTimeout(MC_DEFAULT_CONNECT_TIMEOUT),
m_retryTimeout(MC_DEFAULT_RETRY_TIMEOUT) {
m_name[0] = '\0';
m_host[0] = '\0';
m_buffer_writer = new BufferWriter();
m_buffer_reader = new BufferReader();
m_parser.setBufferReader(m_buffer_reader);
}
Connection::Connection(const Connection& conn) {
// never_called
}
Connection::~Connection() {
this->close();
delete m_buffer_writer;
delete m_buffer_reader;
}
int Connection::init(const char* host, uint32_t port, const char* alias) {
snprintf(m_host, sizeof m_host, "%s", host);
m_port = port;
if (alias == NULL) {
m_hasAlias = false;
snprintf(m_name, sizeof m_name, "%s:%u", m_host, m_port);
} else {
m_hasAlias = true;
snprintf(m_name, sizeof m_name, "%s", alias);
}
return -1; // -1 means the connection is not established yet
}
int Connection::connect() {
assert(!m_alive);
this->close();
struct addrinfo hints, *server_addrinfo = NULL, *ai_ptr = NULL;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
char str_port[MC_NI_MAXSERV] = "\0";
snprintf(str_port, MC_NI_MAXSERV, "%u", m_port);
if (getaddrinfo(m_host, str_port, &hints, &server_addrinfo) != 0) {
if (server_addrinfo) {
freeaddrinfo(server_addrinfo);
}
return -1;
}
int opt_nodelay = 1, opt_keepalive = 1;
for (ai_ptr = server_addrinfo; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next) {
int fd = socket(ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
if (fd == -1) {
continue;
}
// non blocking
int flags = -1;
do {
flags = fcntl(fd, F_GETFL, 0);
} while (flags == -1 && (errno == EINTR || errno == EAGAIN));
if (flags == -1) {
goto try_next_ai;
}
if ((flags & O_NONBLOCK) == 0) {
int rv = -1;
do {
rv = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
} while (rv == -1 && (errno == EINTR || errno == EAGAIN));
if (rv == -1) {
goto try_next_ai;
}
}
// no delay
if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt_nodelay, sizeof opt_nodelay) != 0) {
goto try_next_ai;
}
// keep alive
if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &opt_keepalive, sizeof opt_keepalive) != 0) {
goto try_next_ai;
}
// make sure the connection is established
if (connectPoll(fd, ai_ptr) == 0) {
m_socketFd = fd;
m_alive = true;
break;
}
try_next_ai:
::close(fd);
continue;
}
if (server_addrinfo) {
freeaddrinfo(server_addrinfo);
}
return m_alive ? 0 : -1;
}
int Connection::connectPoll(int fd, struct addrinfo* ai_ptr) {
int rv = ::connect(fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
if (rv == 0) {
return 0;
}
assert(rv == -1);
switch (errno) {
case EINPROGRESS:
case EALREADY:
{
nfds_t n_fds = 1;
pollfd_t pollfds[n_fds];
pollfds[0].fd = fd;
pollfds[0].events = POLLOUT;
int max_timeout = 6;
while (--max_timeout) {
int rv = poll(pollfds, n_fds, m_connectTimeout);
if (rv == 1) {
if (pollfds[0].revents & (POLLERR | POLLHUP | POLLNVAL)) {
return -1;
} else {
return 0;
}
} else if (rv == -1) {
return -1;
}
}
return -1;
}
default:
return -1;
}
}
void Connection::close() {
if (m_socketFd > 0) {
m_alive = false;
::close(m_socketFd);
m_socketFd = -1;
}
}
bool Connection::tryReconnect() {
if (!m_alive) {
time_t now;
time(&now);
if (now >= m_deadUntil) {
int rv = this->connect();
if (rv == 0) {
if (m_deadUntil > 0) {
log_info("Connection %s is back to live at %lu", m_name, now);
}
m_deadUntil = 0;
} else {
m_deadUntil = now + m_retryTimeout;
// log_info("%s is still dead", m_name);
}
}
}
return m_alive;
}
void Connection::markDead(const char* reason, int delay) {
if (m_alive) {
time(&m_deadUntil);
m_deadUntil += delay; // check after `delay` seconds, default 0
this->close();
log_warn("Connection %s is dead(reason: %s, delay: %d), next check at %lu",
m_name, reason, delay, m_deadUntil);
std::queue<struct iovec>* q = m_parser.getRequestKeys();
if (!q->empty()) {
log_warn("%s: first request key: %.*s", m_name,
static_cast<int>(q->front().iov_len),
static_cast<char*>(q->front().iov_base));
}
}
}
int Connection::socketFd() const {
return m_socketFd;
}
void Connection::takeBuffer(const char* const buf, size_t buf_len) {
m_buffer_writer->takeBuffer(buf, buf_len);
}
void Connection::addRequestKey(const char* const buf, const size_t buf_len) {
m_parser.addRequestKey(buf, buf_len);
}
size_t Connection::requestKeyCount() {
return m_parser.requestKeyCount();
}
void Connection::setParserMode(ParserMode md) {
m_parser.setMode(md);
}
void Connection::takeNumber(int64_t val) {
m_buffer_writer->takeNumber(val);
}
ssize_t Connection::send() {
struct msghdr msg = {};
size_t n = 0;
msg.msg_iov = const_cast<struct iovec *>(m_buffer_writer->getReadPtr(n));
msg.msg_iovlen = n;
// otherwise may lead to EMSGSIZE, SEE issue#3 on code
int flags = 0;
if (msg.msg_iovlen > MC_UIO_MAXIOV) {
msg.msg_iovlen = MC_UIO_MAXIOV;
flags = MC_MSG_MORE;
}
ssize_t nSent = ::sendmsg(m_socketFd, &msg, flags);
if (nSent == -1) {
m_buffer_writer->reset();
return -1;
} else {
m_buffer_writer->commitRead(nSent);
}
size_t msgLeft = m_buffer_writer->msgIovlen();
if (msgLeft == 0) {
m_buffer_writer->reset();
return 0;
} else {
return msgLeft;
}
}
ssize_t Connection::recv() {
size_t bufferSize = m_buffer_reader->getNextPreferedDataBlockSize();
size_t bufferSizeAvailable = m_buffer_reader->prepareWriteBlock(bufferSize);
char* writePtr = m_buffer_reader->getWritePtr();
ssize_t bufferSizeActual = ::recv(m_socketFd, writePtr, bufferSizeAvailable, 0);
// log_info("%p recv(%lu) %.*s", this, bufferSizeActual, (int)bufferSizeActual, writePtr);
if (bufferSizeActual > 0) {
m_buffer_reader->commitWrite(bufferSizeActual);
}
return bufferSizeActual;
}
void Connection::process(err_code_t& err) {
return m_parser.process_packets(err);
}
types::RetrievalResultList* Connection::getRetrievalResults() {
return m_parser.getRetrievalResults();
}
types::MessageResultList* Connection::getMessageResults() {
return m_parser.getMessageResults();
}
types::LineResultList* Connection::getLineResults() {
return m_parser.getLineResults();
}
types::UnsignedResultList* Connection::getUnsignedResults() {
return m_parser.getUnsignedResults();
}
std::queue<struct iovec>* Connection::getRequestKeys() {
return m_parser.getRequestKeys();
}
void Connection::reset() {
m_counter = 0;
m_parser.reset();
m_buffer_reader->reset();
m_buffer_writer->reset(); // flush data dispatched but not sent
}
void Connection::setRetryTimeout(int timeout) {
m_retryTimeout = timeout;
}
void Connection::setConnectTimeout(int timeout) {
m_connectTimeout = timeout;
}
} // namespace mc
} // namespace douban
<commit_msg>Connection::addRequestKey args use key instead of buf<commit_after>#include <netdb.h>
#include <netinet/tcp.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/poll.h>
#include <sys/types.h>
#include <errno.h>
#include <fcntl.h>
#include <queue>
#include "Connection.h"
using douban::mc::io::BufferWriter;
using douban::mc::io::BufferReader;
namespace douban {
namespace mc {
Connection::Connection()
: m_counter(0), m_port(0), m_socketFd(-1),
m_alive(false), m_hasAlias(false), m_deadUntil(0),
m_connectTimeout(MC_DEFAULT_CONNECT_TIMEOUT),
m_retryTimeout(MC_DEFAULT_RETRY_TIMEOUT) {
m_name[0] = '\0';
m_host[0] = '\0';
m_buffer_writer = new BufferWriter();
m_buffer_reader = new BufferReader();
m_parser.setBufferReader(m_buffer_reader);
}
Connection::Connection(const Connection& conn) {
// never_called
}
Connection::~Connection() {
this->close();
delete m_buffer_writer;
delete m_buffer_reader;
}
int Connection::init(const char* host, uint32_t port, const char* alias) {
snprintf(m_host, sizeof m_host, "%s", host);
m_port = port;
if (alias == NULL) {
m_hasAlias = false;
snprintf(m_name, sizeof m_name, "%s:%u", m_host, m_port);
} else {
m_hasAlias = true;
snprintf(m_name, sizeof m_name, "%s", alias);
}
return -1; // -1 means the connection is not established yet
}
int Connection::connect() {
assert(!m_alive);
this->close();
struct addrinfo hints, *server_addrinfo = NULL, *ai_ptr = NULL;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
char str_port[MC_NI_MAXSERV] = "\0";
snprintf(str_port, MC_NI_MAXSERV, "%u", m_port);
if (getaddrinfo(m_host, str_port, &hints, &server_addrinfo) != 0) {
if (server_addrinfo) {
freeaddrinfo(server_addrinfo);
}
return -1;
}
int opt_nodelay = 1, opt_keepalive = 1;
for (ai_ptr = server_addrinfo; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next) {
int fd = socket(ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
if (fd == -1) {
continue;
}
// non blocking
int flags = -1;
do {
flags = fcntl(fd, F_GETFL, 0);
} while (flags == -1 && (errno == EINTR || errno == EAGAIN));
if (flags == -1) {
goto try_next_ai;
}
if ((flags & O_NONBLOCK) == 0) {
int rv = -1;
do {
rv = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
} while (rv == -1 && (errno == EINTR || errno == EAGAIN));
if (rv == -1) {
goto try_next_ai;
}
}
// no delay
if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt_nodelay, sizeof opt_nodelay) != 0) {
goto try_next_ai;
}
// keep alive
if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &opt_keepalive, sizeof opt_keepalive) != 0) {
goto try_next_ai;
}
// make sure the connection is established
if (connectPoll(fd, ai_ptr) == 0) {
m_socketFd = fd;
m_alive = true;
break;
}
try_next_ai:
::close(fd);
continue;
}
if (server_addrinfo) {
freeaddrinfo(server_addrinfo);
}
return m_alive ? 0 : -1;
}
int Connection::connectPoll(int fd, struct addrinfo* ai_ptr) {
int rv = ::connect(fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
if (rv == 0) {
return 0;
}
assert(rv == -1);
switch (errno) {
case EINPROGRESS:
case EALREADY:
{
nfds_t n_fds = 1;
pollfd_t pollfds[n_fds];
pollfds[0].fd = fd;
pollfds[0].events = POLLOUT;
int max_timeout = 6;
while (--max_timeout) {
int rv = poll(pollfds, n_fds, m_connectTimeout);
if (rv == 1) {
if (pollfds[0].revents & (POLLERR | POLLHUP | POLLNVAL)) {
return -1;
} else {
return 0;
}
} else if (rv == -1) {
return -1;
}
}
return -1;
}
default:
return -1;
}
}
void Connection::close() {
if (m_socketFd > 0) {
m_alive = false;
::close(m_socketFd);
m_socketFd = -1;
}
}
bool Connection::tryReconnect() {
if (!m_alive) {
time_t now;
time(&now);
if (now >= m_deadUntil) {
int rv = this->connect();
if (rv == 0) {
if (m_deadUntil > 0) {
log_info("Connection %s is back to live at %lu", m_name, now);
}
m_deadUntil = 0;
} else {
m_deadUntil = now + m_retryTimeout;
// log_info("%s is still dead", m_name);
}
}
}
return m_alive;
}
void Connection::markDead(const char* reason, int delay) {
if (m_alive) {
time(&m_deadUntil);
m_deadUntil += delay; // check after `delay` seconds, default 0
this->close();
log_warn("Connection %s is dead(reason: %s, delay: %d), next check at %lu",
m_name, reason, delay, m_deadUntil);
std::queue<struct iovec>* q = m_parser.getRequestKeys();
if (!q->empty()) {
log_warn("%s: first request key: %.*s", m_name,
static_cast<int>(q->front().iov_len),
static_cast<char*>(q->front().iov_base));
}
}
}
int Connection::socketFd() const {
return m_socketFd;
}
void Connection::takeBuffer(const char* const buf, size_t buf_len) {
m_buffer_writer->takeBuffer(buf, buf_len);
}
void Connection::addRequestKey(const char* const key, const size_t len) {
m_parser.addRequestKey(key, len);
}
size_t Connection::requestKeyCount() {
return m_parser.requestKeyCount();
}
void Connection::setParserMode(ParserMode md) {
m_parser.setMode(md);
}
void Connection::takeNumber(int64_t val) {
m_buffer_writer->takeNumber(val);
}
ssize_t Connection::send() {
struct msghdr msg = {};
size_t n = 0;
msg.msg_iov = const_cast<struct iovec *>(m_buffer_writer->getReadPtr(n));
msg.msg_iovlen = n;
// otherwise may lead to EMSGSIZE, SEE issue#3 on code
int flags = 0;
if (msg.msg_iovlen > MC_UIO_MAXIOV) {
msg.msg_iovlen = MC_UIO_MAXIOV;
flags = MC_MSG_MORE;
}
ssize_t nSent = ::sendmsg(m_socketFd, &msg, flags);
if (nSent == -1) {
m_buffer_writer->reset();
return -1;
} else {
m_buffer_writer->commitRead(nSent);
}
size_t msgLeft = m_buffer_writer->msgIovlen();
if (msgLeft == 0) {
m_buffer_writer->reset();
return 0;
} else {
return msgLeft;
}
}
ssize_t Connection::recv() {
size_t bufferSize = m_buffer_reader->getNextPreferedDataBlockSize();
size_t bufferSizeAvailable = m_buffer_reader->prepareWriteBlock(bufferSize);
char* writePtr = m_buffer_reader->getWritePtr();
ssize_t bufferSizeActual = ::recv(m_socketFd, writePtr, bufferSizeAvailable, 0);
// log_info("%p recv(%lu) %.*s", this, bufferSizeActual, (int)bufferSizeActual, writePtr);
if (bufferSizeActual > 0) {
m_buffer_reader->commitWrite(bufferSizeActual);
}
return bufferSizeActual;
}
void Connection::process(err_code_t& err) {
return m_parser.process_packets(err);
}
types::RetrievalResultList* Connection::getRetrievalResults() {
return m_parser.getRetrievalResults();
}
types::MessageResultList* Connection::getMessageResults() {
return m_parser.getMessageResults();
}
types::LineResultList* Connection::getLineResults() {
return m_parser.getLineResults();
}
types::UnsignedResultList* Connection::getUnsignedResults() {
return m_parser.getUnsignedResults();
}
std::queue<struct iovec>* Connection::getRequestKeys() {
return m_parser.getRequestKeys();
}
void Connection::reset() {
m_counter = 0;
m_parser.reset();
m_buffer_reader->reset();
m_buffer_writer->reset(); // flush data dispatched but not sent
}
void Connection::setRetryTimeout(int timeout) {
m_retryTimeout = timeout;
}
void Connection::setConnectTimeout(int timeout) {
m_connectTimeout = timeout;
}
} // namespace mc
} // namespace douban
<|endoftext|> |
<commit_before>#include "planner.hpp"
#include "algorithms.hpp"
#include "common.hpp"
#include "types.hpp"
#include <algorithm>
#include <chrono>
#include <cstdio>
#include <functional>
#include <vector>
using namespace std::chrono;
namespace mpel {
Planner::Planner(Planner::Config pc)
: _pc(pc)
{
}
void Planner::load_workspace(const Workspace& ws)
{
_ws = ws;
// generate the roadmap
auto t0 = high_resolution_clock::now();
_g = _pc.graph_builder(_ws.map);
auto t1 = high_resolution_clock::now();
t_graph = duration_cast<microseconds>(t1 - t0).count();
}
GraphRef Planner::roadmap() const { return _g; }
MapRef Planner::map() const { return _ws.map; }
struct dcomp {
Point _p;
dcomp(PointRef p)
: _p(p)
{
}
bool operator()(PointRef a, PointRef b)
{
double dx1 = a.x - _p.x;
double dy1 = a.y - _p.y;
double dx2 = b.x - _p.x;
double dy2 = b.y - _p.y;
return dx1 * dx1 + dy1 * dy1 < dx2 * dx2 + dy2 * dy2;
}
};
Path Planner::solve(ProblemDefinition pdef)
{
// find point closest to given points in graph
if (is_collision(_ws.map, pdef.start)) return Path();
if (is_collision(_ws.map, pdef.goal)) return Path();
Path p;
Point in, out;
// find some vertices in graph close to start and goal and connect them
Graph tmp_g = _g;
size_t nneigh = std::min((size_t)5, tmp_g.vertex_list().size());
std::vector<Point> start_neigh
= k_best(tmp_g.vertex_list().begin(), tmp_g.vertex_list().end(), nneigh, dcomp(pdef.start));
std::vector<Point> goal_neigh
= k_best(tmp_g.vertex_list().begin(), tmp_g.vertex_list().end(), nneigh, dcomp(pdef.goal));
size_t in_segment = 0, out_segment = 0; // check the number of edges which could be connected
for (size_t i = 0; i < nneigh; ++i) {
Segment s1 = Segment(pdef.start, start_neigh[i]);
if (not is_collision(_ws.map, s1)) {
tmp_g.add_edge(pdef.start, start_neigh[i], distance(pdef.start, start_neigh[i]));
in_segment++;
}
Segment s2 = Segment(pdef.goal, goal_neigh[i]);
if (not is_collision(_ws.map, s2)) {
tmp_g.add_edge(pdef.goal, goal_neigh[i], distance(pdef.goal, goal_neigh[i]));
out_segment++;
}
}
if (in_segment == 0 or out_segment == 0) { // If the terminal points could not be successfully inserted
std::cout << "[Planner::solve] Terminal points could not be inserted in the graph, "
<< "check if the graph is sufficiently dense" << std::endl;
return Path();
} else {
auto t0 = high_resolution_clock::now();
p = _pc.graph_search(tmp_g, pdef.start, pdef.goal);
auto t1 = high_resolution_clock::now();
t_search = duration_cast<microseconds>(t1 - t0).count();
t0 = high_resolution_clock::now();
Path ret = (p.size() > 0 ? _pc.interpolator(_ws.map, p) : p);
t1 = high_resolution_clock::now();
t_interp = duration_cast<microseconds>(t1 - t0).count();
return ret;
}
}
void Planner::show_stats() const
{
printf("Graph builder: %9.3f ms\n", 1e-3 * t_graph);
printf("Graph search : %9.3f ms\n", 1e-3 * t_search);
printf("Interpolation: %9.3f ms\n", 1e-3 * t_interp);
}
}
<commit_msg>Added logging information [Refer #17]<commit_after>#include "planner.hpp"
#include "algorithms.hpp"
#include "common.hpp"
#include "types.hpp"
#include <algorithm>
#include <chrono>
#include <cstdio>
#include <functional>
#include <vector>
using namespace std::chrono;
namespace mpel {
Planner::Planner(Planner::Config pc)
: _pc(pc)
{
}
void Planner::load_workspace(const Workspace& ws)
{
_ws = ws;
// generate the roadmap
auto t0 = high_resolution_clock::now();
_g = _pc.graph_builder(_ws.map);
auto t1 = high_resolution_clock::now();
t_graph = duration_cast<microseconds>(t1 - t0).count();
}
GraphRef Planner::roadmap() const { return _g; }
MapRef Planner::map() const { return _ws.map; }
struct dcomp {
Point _p;
dcomp(PointRef p)
: _p(p)
{
}
bool operator()(PointRef a, PointRef b)
{
double dx1 = a.x - _p.x;
double dy1 = a.y - _p.y;
double dx2 = b.x - _p.x;
double dy2 = b.y - _p.y;
return dx1 * dx1 + dy1 * dy1 < dx2 * dx2 + dy2 * dy2;
}
};
Path Planner::solve(ProblemDefinition pdef)
{
// find point closest to given points in graph
if (is_collision(_ws.map, pdef.start)) return Path();
if (is_collision(_ws.map, pdef.goal)) return Path();
Path p;
Point in, out;
// find some vertices in graph close to start and goal and connect them
Graph tmp_g = _g;
size_t nneigh = std::min((size_t)5, tmp_g.vertex_list().size());
std::vector<Point> start_neigh
= k_best(tmp_g.vertex_list().begin(), tmp_g.vertex_list().end(), nneigh, dcomp(pdef.start));
std::vector<Point> goal_neigh
= k_best(tmp_g.vertex_list().begin(), tmp_g.vertex_list().end(), nneigh, dcomp(pdef.goal));
size_t in_segment = 0, out_segment = 0; // check the number of edges which could be connected
for (size_t i = 0; i < nneigh; ++i) {
Segment s1 = Segment(pdef.start, start_neigh[i]);
if (not is_collision(_ws.map, s1)) {
tmp_g.add_edge(pdef.start, start_neigh[i], distance(pdef.start, start_neigh[i]));
in_segment++;
}
Segment s2 = Segment(pdef.goal, goal_neigh[i]);
if (not is_collision(_ws.map, s2)) {
tmp_g.add_edge(pdef.goal, goal_neigh[i], distance(pdef.goal, goal_neigh[i]));
out_segment++;
}
}
Path ret;
if (in_segment == 0 or out_segment == 0) { // If the terminal points could not be successfully inserted
std::cout << "[Planner::solve] Terminal points could not be inserted in the graph, "
<< "check if the graph is sufficiently dense" << std::endl;
} else {
auto t0 = high_resolution_clock::now();
p = _pc.graph_search(tmp_g, pdef.start, pdef.goal);
auto t1 = high_resolution_clock::now();
t_search = duration_cast<microseconds>(t1 - t0).count();
t0 = high_resolution_clock::now();
ret = (p.size() > 0 ? _pc.interpolator(_ws.map, p) : p);
t1 = high_resolution_clock::now();
t_interp = duration_cast<microseconds>(t1 - t0).count();
}
if (ret.size() == 0) {
std::cout << "[Planner::solve] No path found! Returning empty path" << std::endl;
}
return ret;
}
void Planner::show_stats() const
{
printf("Graph builder: %9.3f ms\n", 1e-3 * t_graph);
printf("Graph search : %9.3f ms\n", 1e-3 * t_search);
printf("Interpolation: %9.3f ms\n", 1e-3 * t_interp);
}
}
<|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.
*
*/
#include <cmath>
namespace pcl
{
inline float
normAngle (float alpha)
{
return (alpha >= 0 ?
fmodf (alpha + static_cast<float>(M_PI),
2.0f * static_cast<float>(M_PI))
- static_cast<float>(M_PI)
:
-(fmodf (static_cast<float>(M_PI) - alpha,
2.0f * static_cast<float>(M_PI))
- static_cast<float>(M_PI)));
}
inline float
rad2deg (float alpha)
{
return (alpha * 57.29578f);
}
inline float
deg2rad (float alpha)
{
return (alpha * 0.017453293f);
}
inline double
rad2deg (double alpha)
{
return (alpha * 57.29578);
}
inline double
deg2rad (double alpha)
{
return (alpha * 0.017453293);
}
}
<commit_msg>add missing include for M_PI under MSVC<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.
*
*/
#include <cmath>
#include <pcl/pcl_macros.h>
namespace pcl
{
inline float
normAngle (float alpha)
{
return (alpha >= 0 ?
fmodf (alpha + static_cast<float>(M_PI),
2.0f * static_cast<float>(M_PI))
- static_cast<float>(M_PI)
:
-(fmodf (static_cast<float>(M_PI) - alpha,
2.0f * static_cast<float>(M_PI))
- static_cast<float>(M_PI)));
}
inline float
rad2deg (float alpha)
{
return (alpha * 57.29578f);
}
inline float
deg2rad (float alpha)
{
return (alpha * 0.017453293f);
}
inline double
rad2deg (double alpha)
{
return (alpha * 57.29578);
}
inline double
deg2rad (double alpha)
{
return (alpha * 0.017453293);
}
}
<|endoftext|> |
<commit_before>/*
Copyright 2005-2007 Adobe Systems Incorporated
Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt
or a copy at http://stlab.adobe.com/licenses.html)
*/
/****************************************************************************************************/
#include <GG/adobe/future/widgets/headers/platform_image.hpp>
#include <GG/adobe/future/widgets/headers/display.hpp>
#include <GG/adobe/future/widgets/headers/platform_metrics.hpp>
#include <GG/adobe/future/widgets/headers/widget_utils.hpp>
#include <GG/adobe/memory.hpp>
#include <string>
#include <cassert>
#include <GG/GUI.h>
#include <GG/StaticGraphic.h>
#include <GG/StyleFactory.h>
/****************************************************************************************************/
namespace adobe {
/****************************************************************************************************/
namespace implementation {
/*************************************************************************************************/
class ImageFilter :
public GG::Wnd
{
public:
ImageFilter(image_t& image) : m_image(image) {}
virtual bool EventFilter(GG::Wnd*, const GG::WndEvent& event)
{
bool retval = false;
if (event.Type() == GG::WndEvent::LDrag) {
GG::Pt cur_point(event.Point());
if (m_image.last_point_m != cur_point) {
double x(0);
double y(0);
double delta_x(Value(m_image.last_point_m.x - cur_point.x));
double delta_y(Value(m_image.last_point_m.y - cur_point.y));
get_value(m_image.metadata_m, static_name_t("x"), x);
get_value(m_image.metadata_m, static_name_t("y"), y);
m_image.metadata_m.insert(dictionary_t::value_type(static_name_t("delta_x"),
any_regular_t(delta_x)));
m_image.metadata_m.insert(dictionary_t::value_type(static_name_t("delta_y"),
any_regular_t(delta_y)));
m_image.metadata_m.insert(dictionary_t::value_type(static_name_t("dragging"),
any_regular_t(true)));
m_image.metadata_m.insert(dictionary_t::value_type(static_name_t("x"),
any_regular_t(x + delta_x)));
m_image.metadata_m.insert(dictionary_t::value_type(static_name_t("y"),
any_regular_t(y + delta_y)));
m_image.callback_m(m_image.metadata_m);
}
m_image.last_point_m = cur_point;
retval = true;
} else if (event.Type() == GG::WndEvent::LButtonUp ||
event.Type() == GG::WndEvent::LClick) {
m_image.metadata_m.insert(dictionary_t::value_type(static_name_t("delta_x"),
any_regular_t(0)));
m_image.metadata_m.insert(dictionary_t::value_type(static_name_t("delta_y"),
any_regular_t(0)));
m_image.metadata_m.insert(dictionary_t::value_type(static_name_t("dragging"),
any_regular_t(false)));
m_image.callback_m(m_image.metadata_m);
retval = true;
}
return retval;
}
image_t& m_image;
};
} // implementation
} // adobe
/****************************************************************************************************/
namespace {
/****************************************************************************************************/
const GG::X fixed_width(250);
const GG::Y fixed_height(Value(fixed_width));
/****************************************************************************************************/
GG::X get_width(adobe::image_t& image)
{ return image.image_m ? image.image_m->DefaultWidth() : fixed_width; }
/****************************************************************************************************/
GG::Y get_height(adobe::image_t& image)
{ return image.image_m ? image.image_m->DefaultHeight() : fixed_height; }
/****************************************************************************************************/
void reset_image(adobe::image_t& image, const adobe::image_t::view_model_type& view)
{
delete image.window_m;
if (view) {
boost::shared_ptr<GG::StyleFactory> style = GG::GUI::GetGUI()->GetStyleFactory();
image.window_m =
style->NewStaticGraphic(
GG::X0, GG::Y0, get_width(image), get_height(image),
view, GG::GRAPHIC_NONE, GG::INTERACTIVE
);
image.filter_m.reset(new adobe::implementation::ImageFilter(image));
image.window_m->InstallEventFilter(image.filter_m.get());
}
}
/****************************************************************************************************/
} // namespace
namespace adobe {
/****************************************************************************************************/
image_t::image_t(const view_model_type& image) :
window_m(0),
image_m(image),
enabled_m(false)
{
metadata_m.insert(dictionary_t::value_type(static_name_t("delta_x"), any_regular_t(0)));
metadata_m.insert(dictionary_t::value_type(static_name_t("delta_y"), any_regular_t(0)));
metadata_m.insert(dictionary_t::value_type(static_name_t("dragging"), any_regular_t(false)));
metadata_m.insert(dictionary_t::value_type(static_name_t("x"), any_regular_t(0)));
metadata_m.insert(dictionary_t::value_type(static_name_t("y"), any_regular_t(0)));
}
/****************************************************************************************************/
void image_t::display(const view_model_type& value)
{
image_m = value;
reset_image(*this, image_m);
}
/****************************************************************************************************/
void image_t::monitor(const setter_proc_type& proc)
{ callback_m = proc; }
/****************************************************************************************************/
void image_t::enable(bool make_enabled)
{ enabled_m = make_enabled; }
/****************************************************************************************************/
void place(image_t& value, const place_data_t& place_data)
{
implementation::set_control_bounds(value.window_m, place_data);
if (value.callback_m)
{
dictionary_t old_metadata(value.metadata_m);
double width(Value(std::min(fixed_width, get_width(value))));
double height(Value(std::min(fixed_height, get_height(value))));
value.metadata_m.insert(dictionary_t::value_type(static_name_t("width"), any_regular_t(width)));
value.metadata_m.insert(dictionary_t::value_type(static_name_t("height"), any_regular_t(height)));
if (old_metadata != value.metadata_m)
value.callback_m(value.metadata_m);
}
}
/****************************************************************************************************/
void measure(image_t& value, extents_t& result)
{
if (value.callback_m)
result.horizontal().length_m = Value(fixed_width);
else
result.horizontal().length_m = Value(get_width(value));
}
/****************************************************************************************************/
void measure_vertical(image_t& value, extents_t& result,
const place_data_t& placed_horizontal)
{
if (value.callback_m) {
result.vertical().length_m = Value(fixed_height);
} else {
// NOTE (fbrereto) : We calculate and use the aspect ratio here to
// maintain a proper initial height and width in
// the case when the image grew based on how it
// is being laid out.
float aspect_ratio =
Value(get_height(value)) / static_cast<float>(Value(get_width(value)));
result.vertical().length_m =
static_cast<long>(placed_horizontal.horizontal().length_m * aspect_ratio);
}
}
/****************************************************************************************************/
void enable(image_t& value, bool make_enabled)
{ value.window_m->Disable(!make_enabled); }
/*************************************************************************************************/
template <>
platform_display_type insert<image_t>(display_t& display,
platform_display_type& parent,
image_t& element)
{
assert(!element.window_m);
reset_image(element, element.image_m);
return display.insert(parent, get_display(element));
}
/****************************************************************************************************/
} // namespace adobe
/****************************************************************************************************/
<commit_msg>Removed the wonky event filtering on images in the experimental Eve bindings.<commit_after>/*
Copyright 2005-2007 Adobe Systems Incorporated
Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt
or a copy at http://stlab.adobe.com/licenses.html)
*/
/****************************************************************************************************/
#include <GG/adobe/future/widgets/headers/platform_image.hpp>
#include <GG/adobe/future/widgets/headers/display.hpp>
#include <GG/adobe/future/widgets/headers/platform_metrics.hpp>
#include <GG/adobe/future/widgets/headers/widget_utils.hpp>
#include <GG/adobe/memory.hpp>
#include <string>
#include <cassert>
#include <GG/GUI.h>
#include <GG/StaticGraphic.h>
#include <GG/StyleFactory.h>
/****************************************************************************************************/
namespace {
/****************************************************************************************************/
const GG::X fixed_width(250);
const GG::Y fixed_height(Value(fixed_width));
/****************************************************************************************************/
GG::X get_width(adobe::image_t& image)
{ return image.image_m ? image.image_m->DefaultWidth() : fixed_width; }
/****************************************************************************************************/
GG::Y get_height(adobe::image_t& image)
{ return image.image_m ? image.image_m->DefaultHeight() : fixed_height; }
/****************************************************************************************************/
void reset_image(adobe::image_t& image, const adobe::image_t::view_model_type& view)
{
delete image.window_m;
if (view) {
boost::shared_ptr<GG::StyleFactory> style = GG::GUI::GetGUI()->GetStyleFactory();
image.window_m =
style->NewStaticGraphic(
GG::X0, GG::Y0, get_width(image), get_height(image),
view, GG::GRAPHIC_NONE, GG::INTERACTIVE
);
}
}
/****************************************************************************************************/
} // namespace
namespace adobe {
/****************************************************************************************************/
image_t::image_t(const view_model_type& image) :
window_m(0),
image_m(image),
enabled_m(false)
{
metadata_m.insert(dictionary_t::value_type(static_name_t("delta_x"), any_regular_t(0)));
metadata_m.insert(dictionary_t::value_type(static_name_t("delta_y"), any_regular_t(0)));
metadata_m.insert(dictionary_t::value_type(static_name_t("dragging"), any_regular_t(false)));
metadata_m.insert(dictionary_t::value_type(static_name_t("x"), any_regular_t(0)));
metadata_m.insert(dictionary_t::value_type(static_name_t("y"), any_regular_t(0)));
}
/****************************************************************************************************/
void image_t::display(const view_model_type& value)
{
image_m = value;
reset_image(*this, image_m);
}
/****************************************************************************************************/
void image_t::monitor(const setter_proc_type& proc)
{ callback_m = proc; }
/****************************************************************************************************/
void image_t::enable(bool make_enabled)
{ enabled_m = make_enabled; }
/****************************************************************************************************/
void place(image_t& value, const place_data_t& place_data)
{
implementation::set_control_bounds(value.window_m, place_data);
if (value.callback_m)
{
dictionary_t old_metadata(value.metadata_m);
double width(Value(std::min(fixed_width, get_width(value))));
double height(Value(std::min(fixed_height, get_height(value))));
value.metadata_m.insert(dictionary_t::value_type(static_name_t("width"), any_regular_t(width)));
value.metadata_m.insert(dictionary_t::value_type(static_name_t("height"), any_regular_t(height)));
if (old_metadata != value.metadata_m)
value.callback_m(value.metadata_m);
}
}
/****************************************************************************************************/
void measure(image_t& value, extents_t& result)
{
if (value.callback_m)
result.horizontal().length_m = Value(fixed_width);
else
result.horizontal().length_m = Value(get_width(value));
}
/****************************************************************************************************/
void measure_vertical(image_t& value, extents_t& result,
const place_data_t& placed_horizontal)
{
if (value.callback_m) {
result.vertical().length_m = Value(fixed_height);
} else {
// NOTE (fbrereto) : We calculate and use the aspect ratio here to
// maintain a proper initial height and width in
// the case when the image grew based on how it
// is being laid out.
float aspect_ratio =
Value(get_height(value)) / static_cast<float>(Value(get_width(value)));
result.vertical().length_m =
static_cast<long>(placed_horizontal.horizontal().length_m * aspect_ratio);
}
}
/****************************************************************************************************/
void enable(image_t& value, bool make_enabled)
{ value.window_m->Disable(!make_enabled); }
/*************************************************************************************************/
template <>
platform_display_type insert<image_t>(display_t& display,
platform_display_type& parent,
image_t& element)
{
assert(!element.window_m);
reset_image(element, element.image_m);
return display.insert(parent, get_display(element));
}
/****************************************************************************************************/
} // namespace adobe
/****************************************************************************************************/
<|endoftext|> |
<commit_before>// This file is part of the dune-stuff project:
// https://users.dune-project.org/projects/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_STUFF_LA_CONTAINER_PATTERN_HH
#define DUNE_STUFF_LA_CONTAINER_PATTERN_HH
#include <cstddef>
#include <vector>
#include <set>
namespace Dune {
namespace Stuff {
namespace LA {
class SparsityPatternDefault
{
private:
typedef std::vector< std::set< size_t > > BaseType;
public:
typedef BaseType::value_type InnerType;
typedef typename BaseType::const_iterator ConstOuterIteratorType;
SparsityPatternDefault(const size_t _size);
size_t size() const;
InnerType& inner(const size_t ii);
const InnerType& inner(const size_t ii) const;
ConstOuterIteratorType begin() const;
ConstOuterIteratorType end() const;
bool operator==(const SparsityPatternDefault& other) const;
bool operator!=(const SparsityPatternDefault& other) const;
private:
BaseType vectorOfSets_;
}; // class SparsityPatternDefault
//// forward of the Interface
//template< class T >
//class MatrixInterface;
//template< class T >
//SparsityPatternDefault* createCompressedSparsityPattern(const SparsityPatternDefault& uncompressedPattern,
// const MatrixInterface< T >& matrix,
// const typename T::ElementType threshhold = typename T::ElementType(0))
//{
// assert(!(threshhold < typename T::ElementType(0)) && "Please provide a nonnegative threshhold!");
// // we create a new pattern of only nonzero entries
// SparsityPatternDefault* compressedPattern = new SparsityPatternDefault(uncompressedPattern.size());
// typename T::ElementType absValue(0);
// // * therefore we loop over the uncompressed pattern
// for (typename SparsityPatternDefault::size_t row = 0; row < uncompressedPattern.size(); ++row) {
// // * get the uncompressed row,
// const auto& uncompressedRowSet = uncompressedPattern.set(row);
// // * get the new one
// auto& compressedRowSet = compressedPattern->set(row);
// // * and loop over the uncompressed row
// for (auto col : uncompressedRowSet) {
// // * get the value in the matric
// absValue = std::abs(matrix.get(row, col));
// // * and add the column to the new pattern, if the value is large enough
// if (absValue > threshhold)
// compressedRowSet.insert(col);
// }
// }
// return compressedPattern;
//} // ... compressSparsityPattern(...)
} // namespace LA
} // namespace Stuff
} // namespace Dune
#endif // DUNE_STUFF_LA_CONTAINER_PATTERN_HH
<commit_msg>[la.container.pattern] add empty ctor<commit_after>// This file is part of the dune-stuff project:
// https://users.dune-project.org/projects/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_STUFF_LA_CONTAINER_PATTERN_HH
#define DUNE_STUFF_LA_CONTAINER_PATTERN_HH
#include <cstddef>
#include <vector>
#include <set>
namespace Dune {
namespace Stuff {
namespace LA {
class SparsityPatternDefault
{
private:
typedef std::vector< std::set< size_t > > BaseType;
public:
typedef BaseType::value_type InnerType;
typedef typename BaseType::const_iterator ConstOuterIteratorType;
SparsityPatternDefault(const size_t _size = 0);
size_t size() const;
InnerType& inner(const size_t ii);
const InnerType& inner(const size_t ii) const;
ConstOuterIteratorType begin() const;
ConstOuterIteratorType end() const;
bool operator==(const SparsityPatternDefault& other) const;
bool operator!=(const SparsityPatternDefault& other) const;
private:
BaseType vectorOfSets_;
}; // class SparsityPatternDefault
//// forward of the Interface
//template< class T >
//class MatrixInterface;
//template< class T >
//SparsityPatternDefault* createCompressedSparsityPattern(const SparsityPatternDefault& uncompressedPattern,
// const MatrixInterface< T >& matrix,
// const typename T::ElementType threshhold = typename T::ElementType(0))
//{
// assert(!(threshhold < typename T::ElementType(0)) && "Please provide a nonnegative threshhold!");
// // we create a new pattern of only nonzero entries
// SparsityPatternDefault* compressedPattern = new SparsityPatternDefault(uncompressedPattern.size());
// typename T::ElementType absValue(0);
// // * therefore we loop over the uncompressed pattern
// for (typename SparsityPatternDefault::size_t row = 0; row < uncompressedPattern.size(); ++row) {
// // * get the uncompressed row,
// const auto& uncompressedRowSet = uncompressedPattern.set(row);
// // * get the new one
// auto& compressedRowSet = compressedPattern->set(row);
// // * and loop over the uncompressed row
// for (auto col : uncompressedRowSet) {
// // * get the value in the matric
// absValue = std::abs(matrix.get(row, col));
// // * and add the column to the new pattern, if the value is large enough
// if (absValue > threshhold)
// compressedRowSet.insert(col);
// }
// }
// return compressedPattern;
//} // ... compressSparsityPattern(...)
} // namespace LA
} // namespace Stuff
} // namespace Dune
#endif // DUNE_STUFF_LA_CONTAINER_PATTERN_HH
<|endoftext|> |
<commit_before><commit_msg>Edited whitespace.<commit_after><|endoftext|> |
<commit_before>/**
* @file device_properties.hxx
* @author Cameron Shinn ([email protected])
* @brief
* @version 0.1
* @date 2020-11-09
*
* @copyright Copyright (c) 2020
*
*/
#pragma once
#include <type_traits>
#ifndef SM_TARGET
#define SM_TARGET 0
#endif
namespace gunrock {
namespace cuda {
/**
* @brief CUDA dim3 template representation, since dim3 cannot be used as a
* template argument
* @tparam x_ Dimension in the X direction
* @tparam y_ Dimension in the Y direction
* @tparam z_ Dimension in the Z direction
*/
template<unsigned int x_, unsigned int y_ = 1, unsigned int z_ = 1>
struct dim3_t {
enum : unsigned int { x = x_, y = y_, z = z_ };
};
/**
* @brief Struct holding kernel parameters will be passed in upon launch
* @tparam block_dimensions_ Block dimensions to launch with
* @tparam grid_dimensions_ Grid dimensions to launch with
* @tparam shared_memory_bytes_ Amount of shared memory to allocate
*
* @todo dimensions should be dim3 instead of unsigned int
*/
template<
typename block_dimensions_,
typename grid_dimensions_,
unsigned int shared_memory_bytes_ = 0
>
struct launch_params_t {
typedef block_dimensions_ block_dimensions;
typedef grid_dimensions_ grid_dimensions;
enum : unsigned int { shared_memory_bytes = shared_memory_bytes_ };
};
#define TEST_SM 75 // Temporary until we figure out how to get cabability combined
/**
* @brief Struct holding kernel parameters for a specific SM version
* @tparam combined_ver_ Combined major and minor compute capability version
* @tparam block_dimensions_ Block dimensions to launch with
* @tparam grid_dimensions_ Grid dimensions to launch with
* @tparam shared_memory_bytes_ Amount of shared memory to allocate
*/
template<
unsigned int combined_ver_,
typename block_dimensions_,
typename grid_dimensions_,
unsigned int shared_memory_bytes_ = 0
>
struct sm_launch_params_t : launch_params_t<
block_dimensions_,
grid_dimensions_,
shared_memory_bytes_
> {
enum : unsigned int {combined_ver = combined_ver_};
};
template<
typename block_dimensions_,
typename grid_dimensions_,
unsigned int shared_memory_bytes_ = 0
>
struct fallback_launch_params_t : sm_launch_params_t<
0,
block_dimensions_,
grid_dimensions_,
shared_memory_bytes_
> {};
// Easier declaration inside launch box template
template<
typename block_dimensions_,
typename grid_dimensions_,
unsigned int shared_memory_bytes_ = 0
>
using fallback_t = fallback_launch_params_t<
block_dimensions_,
grid_dimensions_,
shared_memory_bytes_
>;
// Easier declaration inside launch box template
template<
unsigned int combined_ver_,
typename block_dimensions_,
typename grid_dimensions_,
unsigned int shared_memory_bytes_ = 0
>
using sm_t = sm_launch_params_t<
combined_ver_,
block_dimensions_,
grid_dimensions_,
shared_memory_bytes_
>;
// Define named sm_launch_params_t structs for each SM version
#define SM_LAUNCH_PARAMS(combined) \
template< \
typename block_dimensions_, \
typename grid_dimensions_, \
unsigned int shared_memory_bytes_ = 0 \
> \
using sm_##combined##_t = sm_launch_params_t< \
combined, \
block_dimensions_, \
grid_dimensions_, \
shared_memory_bytes_ \
>;
// Add Hopper when the SM version number becomes known (presumably 90)
SM_LAUNCH_PARAMS(86)
SM_LAUNCH_PARAMS(80)
SM_LAUNCH_PARAMS(75)
SM_LAUNCH_PARAMS(72)
SM_LAUNCH_PARAMS(70)
SM_LAUNCH_PARAMS(62)
SM_LAUNCH_PARAMS(61)
SM_LAUNCH_PARAMS(60)
SM_LAUNCH_PARAMS(53)
SM_LAUNCH_PARAMS(52)
SM_LAUNCH_PARAMS(50)
SM_LAUNCH_PARAMS(37)
SM_LAUNCH_PARAMS(35)
SM_LAUNCH_PARAMS(30)
#undef SM_LAUNCH_PARAMS
template<typename... sm_lp_v>
struct device_launch_params_t;
// 1st to (N-1)th sm_launch_param_t template parameters
template<typename sm_lp_t, typename... sm_lp_v>
struct device_launch_params_t<sm_lp_t, sm_lp_v...> :
std::conditional_t<
sm_lp_t::combined_ver == 0,
device_launch_params_t<sm_lp_v..., sm_lp_t>, // If found, move fallback_launch_params_t to end of template parameter pack
std::conditional_t< // Otherwise check sm_lp_t for device's SM version
sm_lp_t::combined_ver == SM_TARGET,
sm_lp_t,
device_launch_params_t<sm_lp_v...>
>
> {};
//////////////// https://stackoverflow.com/a/3926854
// "false" but dependent on a template parameter so the compiler can't optimize it for static_assert()
template<typename T>
struct always_false {
enum { value = false };
};
// Raises static (compile-time) assert when referenced
template<typename T>
struct raise_not_found_error_t {
static_assert(always_false<T>::value, "launch_box_t could not find valid launch_params_t");
};
////////////////
// Nth sm_launch_param_t template parameter
template<typename sm_lp_t>
struct device_launch_params_t<sm_lp_t> :
std::conditional_t<
sm_lp_t::combined_ver == SM_TARGET || sm_lp_t::combined_ver == 0,
sm_lp_t,
raise_not_found_error_t<void> // Raises a compiler error
> {};
/**
* @brief Collection of kernel launch parameters for multiple architectures
* @tparam sm_lp_v... Pack of sm_launch_params_t types for each desired arch
*/
template<typename... sm_lp_v>
struct launch_box_t : device_launch_params_t<sm_lp_v...> {
// Some methods to make it easy to access launch_params
};
} // namespace gunrock
} // namespace cuda
<commit_msg>Remove TEST_SM macro<commit_after>/**
* @file device_properties.hxx
* @author Cameron Shinn ([email protected])
* @brief
* @version 0.1
* @date 2020-11-09
*
* @copyright Copyright (c) 2020
*
*/
#pragma once
#include <type_traits>
#ifndef SM_TARGET
#define SM_TARGET 0
#endif
namespace gunrock {
namespace cuda {
/**
* @brief CUDA dim3 template representation, since dim3 cannot be used as a
* template argument
* @tparam x_ Dimension in the X direction
* @tparam y_ Dimension in the Y direction
* @tparam z_ Dimension in the Z direction
*/
template<unsigned int x_, unsigned int y_ = 1, unsigned int z_ = 1>
struct dim3_t {
enum : unsigned int { x = x_, y = y_, z = z_ };
};
/**
* @brief Struct holding kernel parameters will be passed in upon launch
* @tparam block_dimensions_ Block dimensions to launch with
* @tparam grid_dimensions_ Grid dimensions to launch with
* @tparam shared_memory_bytes_ Amount of shared memory to allocate
*
* @todo dimensions should be dim3 instead of unsigned int
*/
template<
typename block_dimensions_,
typename grid_dimensions_,
unsigned int shared_memory_bytes_ = 0
>
struct launch_params_t {
typedef block_dimensions_ block_dimensions;
typedef grid_dimensions_ grid_dimensions;
enum : unsigned int { shared_memory_bytes = shared_memory_bytes_ };
};
/**
* @brief Struct holding kernel parameters for a specific SM version
* @tparam combined_ver_ Combined major and minor compute capability version
* @tparam block_dimensions_ Block dimensions to launch with
* @tparam grid_dimensions_ Grid dimensions to launch with
* @tparam shared_memory_bytes_ Amount of shared memory to allocate
*/
template<
unsigned int combined_ver_,
typename block_dimensions_,
typename grid_dimensions_,
unsigned int shared_memory_bytes_ = 0
>
struct sm_launch_params_t : launch_params_t<
block_dimensions_,
grid_dimensions_,
shared_memory_bytes_
> {
enum : unsigned int {combined_ver = combined_ver_};
};
template<
typename block_dimensions_,
typename grid_dimensions_,
unsigned int shared_memory_bytes_ = 0
>
struct fallback_launch_params_t : sm_launch_params_t<
0,
block_dimensions_,
grid_dimensions_,
shared_memory_bytes_
> {};
// Easier declaration inside launch box template
template<
typename block_dimensions_,
typename grid_dimensions_,
unsigned int shared_memory_bytes_ = 0
>
using fallback_t = fallback_launch_params_t<
block_dimensions_,
grid_dimensions_,
shared_memory_bytes_
>;
// Easier declaration inside launch box template
template<
unsigned int combined_ver_,
typename block_dimensions_,
typename grid_dimensions_,
unsigned int shared_memory_bytes_ = 0
>
using sm_t = sm_launch_params_t<
combined_ver_,
block_dimensions_,
grid_dimensions_,
shared_memory_bytes_
>;
// Define named sm_launch_params_t structs for each SM version
#define SM_LAUNCH_PARAMS(combined) \
template< \
typename block_dimensions_, \
typename grid_dimensions_, \
unsigned int shared_memory_bytes_ = 0 \
> \
using sm_##combined##_t = sm_launch_params_t< \
combined, \
block_dimensions_, \
grid_dimensions_, \
shared_memory_bytes_ \
>;
// Add Hopper when the SM version number becomes known (presumably 90)
SM_LAUNCH_PARAMS(86)
SM_LAUNCH_PARAMS(80)
SM_LAUNCH_PARAMS(75)
SM_LAUNCH_PARAMS(72)
SM_LAUNCH_PARAMS(70)
SM_LAUNCH_PARAMS(62)
SM_LAUNCH_PARAMS(61)
SM_LAUNCH_PARAMS(60)
SM_LAUNCH_PARAMS(53)
SM_LAUNCH_PARAMS(52)
SM_LAUNCH_PARAMS(50)
SM_LAUNCH_PARAMS(37)
SM_LAUNCH_PARAMS(35)
SM_LAUNCH_PARAMS(30)
#undef SM_LAUNCH_PARAMS
template<typename... sm_lp_v>
struct device_launch_params_t;
// 1st to (N-1)th sm_launch_param_t template parameters
template<typename sm_lp_t, typename... sm_lp_v>
struct device_launch_params_t<sm_lp_t, sm_lp_v...> :
std::conditional_t<
sm_lp_t::combined_ver == 0,
device_launch_params_t<sm_lp_v..., sm_lp_t>, // If found, move fallback_launch_params_t to end of template parameter pack
std::conditional_t< // Otherwise check sm_lp_t for device's SM version
sm_lp_t::combined_ver == SM_TARGET,
sm_lp_t,
device_launch_params_t<sm_lp_v...>
>
> {};
//////////////// https://stackoverflow.com/a/3926854
// "false" but dependent on a template parameter so the compiler can't optimize it for static_assert()
template<typename T>
struct always_false {
enum { value = false };
};
// Raises static (compile-time) assert when referenced
template<typename T>
struct raise_not_found_error_t {
static_assert(always_false<T>::value, "launch_box_t could not find valid launch_params_t");
};
////////////////
// Nth sm_launch_param_t template parameter
template<typename sm_lp_t>
struct device_launch_params_t<sm_lp_t> :
std::conditional_t<
sm_lp_t::combined_ver == SM_TARGET || sm_lp_t::combined_ver == 0,
sm_lp_t,
raise_not_found_error_t<void> // Raises a compiler error
> {};
/**
* @brief Collection of kernel launch parameters for multiple architectures
* @tparam sm_lp_v... Pack of sm_launch_params_t types for each desired arch
*/
template<typename... sm_lp_v>
struct launch_box_t : device_launch_params_t<sm_lp_v...> {
// Some methods to make it easy to access launch_params
};
} // namespace gunrock
} // namespace cuda
<|endoftext|> |
<commit_before>
/*
* Copyright 2015 Cloudius Systems
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include "core/reactor.hh"
#include "core/app-template.hh"
#include "message/messaging_service.hh"
#include "gms/failure_detector.hh"
#include "gms/gossiper.hh"
#include "gms/application_state.hh"
#include "service/storage_service.hh"
#include "utils/fb_utilities.hh"
#include "locator/snitch_base.hh"
#include "log.hh"
#include <chrono>
namespace bpo = boost::program_options;
int main(int ac, char ** av) {
distributed<database> db;
app_template app;
app.add_options()
("seed", bpo::value<std::vector<std::string>>(), "IP address of seed node")
("listen-address", bpo::value<std::string>()->default_value("0.0.0.0"), "IP address to listen");
return app.run_deprecated(ac, av, [&db, &app] {
auto config = app.configuration();
logging::logger_registry().set_logger_level("gossip", logging::log_level::trace);
const gms::inet_address listen = gms::inet_address(config["listen-address"].as<std::string>());
utils::fb_utilities::set_broadcast_address(listen);
auto vv = std::make_shared<gms::versioned_value::factory>();
locator::i_endpoint_snitch::create_snitch("SimpleSnitch").then([&db] {
return service::init_storage_service(db);
}).then([vv, listen, config] {
return net::get_messaging_service().start(listen);
}).then([config] {
auto& server = net::get_local_messaging_service();
auto port = server.port();
auto listen = server.listen_address();
print("Messaging server listening on ip %s port %d ...\n", listen, port);
return gms::get_failure_detector().start();
}).then([vv, config] {
return gms::get_gossiper().start();
}).then([vv, config] {
std::set<gms::inet_address> seeds;
for (auto s : config["seed"].as<std::vector<std::string>>()) {
seeds.emplace(std::move(s));
}
std::cout << "Start gossiper service ...\n";
auto& gossiper = gms::get_local_gossiper();
gossiper.set_seeds(std::move(seeds));
gossiper.set_cluster_name("Test Cluster");
std::map<gms::application_state, gms::versioned_value> app_states = {
{ gms::application_state::LOAD, vv->load(0.5) },
};
using namespace std::chrono;
auto now = high_resolution_clock::now().time_since_epoch();
int generation_number = duration_cast<seconds>(now).count();
return gossiper.start(generation_number, app_states);
}).then([vv] {
auto reporter = std::make_shared<timer<lowres_clock>>();
reporter->set_callback ([reporter] {
auto& gossiper = gms::get_local_gossiper();
gossiper.dump_endpoint_state_map();
auto& fd = gms::get_local_failure_detector();
print("%s", fd);
});
reporter->arm_periodic(std::chrono::milliseconds(1000));
auto app_state_adder = std::make_shared<timer<lowres_clock>>();
app_state_adder->set_callback ([vv, app_state_adder] {
static double load = 0.5;
auto& gossiper = gms::get_local_gossiper();
auto state = gms::application_state::LOAD;
auto value = vv->load(load);
gossiper.add_local_application_state(state, value);
load += 0.0001;
});
app_state_adder->arm_periodic(std::chrono::seconds(1));
});
});
}
<commit_msg>tests: Remove redundant debug info for gossip<commit_after>
/*
* Copyright 2015 Cloudius Systems
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include "core/reactor.hh"
#include "core/app-template.hh"
#include "message/messaging_service.hh"
#include "gms/failure_detector.hh"
#include "gms/gossiper.hh"
#include "gms/application_state.hh"
#include "service/storage_service.hh"
#include "utils/fb_utilities.hh"
#include "locator/snitch_base.hh"
#include "log.hh"
#include <chrono>
namespace bpo = boost::program_options;
int main(int ac, char ** av) {
distributed<database> db;
app_template app;
app.add_options()
("seed", bpo::value<std::vector<std::string>>(), "IP address of seed node")
("listen-address", bpo::value<std::string>()->default_value("0.0.0.0"), "IP address to listen");
return app.run_deprecated(ac, av, [&db, &app] {
auto config = app.configuration();
logging::logger_registry().set_logger_level("gossip", logging::log_level::trace);
const gms::inet_address listen = gms::inet_address(config["listen-address"].as<std::string>());
utils::fb_utilities::set_broadcast_address(listen);
auto vv = std::make_shared<gms::versioned_value::factory>();
locator::i_endpoint_snitch::create_snitch("SimpleSnitch").then([&db] {
return service::init_storage_service(db);
}).then([vv, listen, config] {
return net::get_messaging_service().start(listen);
}).then([config] {
auto& server = net::get_local_messaging_service();
auto port = server.port();
auto listen = server.listen_address();
print("Messaging server listening on ip %s port %d ...\n", listen, port);
return gms::get_failure_detector().start();
}).then([vv, config] {
return gms::get_gossiper().start();
}).then([vv, config] {
std::set<gms::inet_address> seeds;
for (auto s : config["seed"].as<std::vector<std::string>>()) {
seeds.emplace(std::move(s));
}
std::cout << "Start gossiper service ...\n";
auto& gossiper = gms::get_local_gossiper();
gossiper.set_seeds(std::move(seeds));
gossiper.set_cluster_name("Test Cluster");
std::map<gms::application_state, gms::versioned_value> app_states = {
{ gms::application_state::LOAD, vv->load(0.5) },
};
using namespace std::chrono;
auto now = high_resolution_clock::now().time_since_epoch();
int generation_number = duration_cast<seconds>(now).count();
return gossiper.start(generation_number, app_states);
}).then([vv] {
auto app_state_adder = std::make_shared<timer<lowres_clock>>();
app_state_adder->set_callback ([vv, app_state_adder] {
static double load = 0.5;
auto& gossiper = gms::get_local_gossiper();
auto state = gms::application_state::LOAD;
auto value = vv->load(load);
gossiper.add_local_application_state(state, value);
load += 0.0001;
});
app_state_adder->arm_periodic(std::chrono::seconds(1));
});
});
}
<|endoftext|> |
<commit_before>/*******************************************************************************
* ALMA - Atacama Large Millimiter Array
* (c) European Southern Observatory, 2002
* Copyright by ESO (in the framework of the ALMA collaboration)
* and Cosylab 2002, All rights reserved
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* "@$Id: acsContainerHandlerImpl.cpp,v 1.17 2010/11/02 13:00:35 tstaig Exp $"
*
* who when what
* -------- -------- ----------------------------------------------
* msekoran 2006-06-21 created
* agrimstr 2007-11-07 extracted container interface implementation to separate
* class
*/
#include "acsContainerHandlerImpl.h"
#include <unistd.h>
/*****************************************************************/
ACSContainerHandlerImpl::ACSContainerHandlerImpl () : h_name("ACS Container Daemon"), h_type(::acsdaemon::containerDaemonServiceName)
{
}
ACSContainerHandlerImpl::~ACSContainerHandlerImpl (void)
{
}
std::string ACSContainerHandlerImpl::getName(void)
{
return h_name;
}
std::string ACSContainerHandlerImpl::getType(void)
{
return h_type;
}
std::string ACSContainerHandlerImpl::getPort(void)
{
return ACSPorts::getContainerDaemonPort();
}
/************************** CORBA interface ****************************/
void
ACSContainerHandlerImpl::start_container (
const char * container_type,
const char * container_name,
::CORBA::Short instance_number,
const ::ACS::stringSeq & type_modifiers,
const char * additional_command_line
)
ACE_THROW_SPEC ((
CORBA::SystemException,
::acsdaemonErrType::FailedToStartContainerEx,
::ACSErrTypeCommon::BadParameterEx
))
{
if (container_type == 0 ||
*container_type == 0)
{
::ACSErrTypeCommon::BadParameterExImpl ex(__FILE__, __LINE__,
"::ACSContainerDaemonImpl::start_container");
ex.setParameter("container_type");
throw ex.getBadParameterEx();
}
if (container_name == 0 ||
*container_name == 0)
{
::ACSErrTypeCommon::BadParameterExImpl ex(__FILE__, __LINE__,
"::ACSContainerDaemonImpl::start_container");
ex.setParameter("container_name");
throw ex.getBadParameterEx();
}
const char * cmdln = (additional_command_line ? additional_command_line : "");
// About type modifier "archiveContainer", see COMP-1316 and COMP-1996
int isArchiveContainer = 0;
int isCasaContainer = 0;
for (unsigned int i = 0; i < type_modifiers.length(); ++i) {
if (!strcmp(type_modifiers[i], "archiveContainer")) {
if (!strcmp(container_type,"java"))
isArchiveContainer = 1;
break;
}
else if (!strcmp(type_modifiers[i], "casaContainer")) {
isCasaContainer = 1;
break;
}
}
// execute: "acsStartContainer -<type> -b <instance> <name> <args>"
// TODO checks for ';', '&', '|' chars, they can run any other command!
//get the directory name to store the container stdout
std::string logDirectory="~/.acs/commandcenter/";
char * acsdata = ACE_OS::getenv("ACSDATA");
if(acsdata != 0)
logDirectory = std::string(acsdata) + std::string("/logs/");
char * host = ACE_OS::getenv("HOST");
if(host != NULL)
logDirectory = logDirectory + std::string(host) + std::string("/");
std::string containerName(container_name);
std::string::size_type pos=containerName.rfind("/");
if(pos != std::string::npos){
logDirectory.append(containerName,0,pos+1);
containerName.erase(0,pos+1);
}
//create the directory
std::string mkdir("mkdir -p ");
mkdir.append(logDirectory);
ACE_OS::system(mkdir.c_str());
std::string timeStamp(getStringifiedTimeStamp().c_str());
if( timeStamp.find(":") != std::string::npos)
timeStamp.replace(timeStamp.find(":"),1,".");
if( timeStamp.find(":") != std::string::npos )
timeStamp.replace(timeStamp.find(":"),1,".");
if( timeStamp.find("T") != std::string::npos)
timeStamp.replace(timeStamp.find("T"),1,"_");
char command[1000];
if (isArchiveContainer)
snprintf(command, 1000, "acsStartContainerOracleClasspath -%s -b %d %s %s &> %sacsStartContainer_%s_%s&", "java", instance_number, container_name, cmdln, logDirectory.c_str(), containerName.c_str(), timeStamp.c_str());
else if (isCasaContainer)
snprintf(command, 1000, "acsStartContainerWithCASA -%s -b %d %s %s &> %sacsStartContainer_%s_%s&", container_type, instance_number, container_name, cmdln, logDirectory.c_str(), containerName.c_str(), timeStamp.c_str());
else
snprintf(command, 1000, "acsStartContainer -%s -b %d %s %s &> %sacsStartContainer_%s_%s&", container_type, instance_number, container_name, cmdln, logDirectory.c_str(), containerName.c_str(), timeStamp.c_str());
ACS_SHORT_LOG ((LM_INFO, "Executing: '%s'.", command));
int result = ACE_OS::system(command);
if (result < 0)
{
throw ::acsdaemonErrType::FailedToStartContainerExImpl(
__FILE__, __LINE__,
"::ACSContainerDaemonImpl::start_container").getFailedToStartContainerEx();
}
}
void
ACSContainerHandlerImpl::stop_container (
const char * container_name,
::CORBA::Short instance_number,
const char * additional_command_line
)
ACE_THROW_SPEC ((
CORBA::SystemException,
::acsdaemonErrType::FailedToStopContainerEx,
::ACSErrTypeCommon::BadParameterEx
))
{
if (container_name == 0 ||
*container_name == 0)
{
::ACSErrTypeCommon::BadParameterExImpl ex(__FILE__, __LINE__,
"::ACSContainerDaemonImpl::stop_container");
ex.setParameter("container_name");
throw ex.getBadParameterEx();
}
const char * cmdln = (additional_command_line ? additional_command_line : "");
//get the directory name to store the container stdout
std::string logDirectory="~/.acs/commandcenter/";
std::string containerName(container_name);
std::string::size_type pos=containerName.rfind("/");
if(pos != std::string::npos){
logDirectory.append(containerName,0,pos+1);
containerName.erase(0,pos+1);
}
//create the directory
std::string mkdir("mkdir -p ");
mkdir.append(logDirectory);
ACE_OS::system(mkdir.c_str());
std::string timeStamp(getStringifiedTimeStamp().c_str());
if( timeStamp.find(":") != std::string::npos)
timeStamp.replace(timeStamp.find(":"),1,".");
if( timeStamp.find(":") != std::string::npos )
timeStamp.replace(timeStamp.find(":"),1,".");
if( timeStamp.find("T") != std::string::npos)
timeStamp.replace(timeStamp.find("T"),1,"_");
// execute: "acsStopContainer -b <instance> <name> <args>"
// TODO checks for ';', '&', '|' chars, they can run any other command!
char command[1000];
snprintf(command, 1000, "acsStopContainer -b %d %s %s &> %sacsStopContainer_%s_%s&", instance_number, container_name, cmdln, logDirectory.c_str(), containerName.c_str(), timeStamp.c_str());
ACS_SHORT_LOG ((LM_INFO, "Executing: '%s'.", command));
int result = ACE_OS::system(command);
if (result < 0)
{
throw ::acsdaemonErrType::FailedToStopContainerExImpl(
__FILE__, __LINE__,
"::ACSContainerDaemonImpl::stop_container").getFailedToStopContainerEx();
}
}
void
ACSContainerHandlerImpl::shutdown ()
ACE_THROW_SPEC ((
CORBA::SystemException,
::maciErrType::NoPermissionEx
))
{
if (h_service->isProtected())
{
throw ::maciErrType::NoPermissionEx();
}
ACS_SHORT_LOG ((LM_INFO, "Shutting down the ACS Container Daemon on remote request..."));
h_service->shutdown(false);
}
<commit_msg>Small fix that was lacking to fullfill COMP-3705 request, regarding change of directory for acsdaemon logs.<commit_after>/*******************************************************************************
* ALMA - Atacama Large Millimiter Array
* (c) European Southern Observatory, 2002
* Copyright by ESO (in the framework of the ALMA collaboration)
* and Cosylab 2002, All rights reserved
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* "@$Id: acsContainerHandlerImpl.cpp,v 1.18 2011/03/11 15:00:21 tstaig Exp $"
*
* who when what
* -------- -------- ----------------------------------------------
* msekoran 2006-06-21 created
* agrimstr 2007-11-07 extracted container interface implementation to separate
* class
*/
#include "acsContainerHandlerImpl.h"
#include <unistd.h>
/*****************************************************************/
ACSContainerHandlerImpl::ACSContainerHandlerImpl () : h_name("ACS Container Daemon"), h_type(::acsdaemon::containerDaemonServiceName)
{
}
ACSContainerHandlerImpl::~ACSContainerHandlerImpl (void)
{
}
std::string ACSContainerHandlerImpl::getName(void)
{
return h_name;
}
std::string ACSContainerHandlerImpl::getType(void)
{
return h_type;
}
std::string ACSContainerHandlerImpl::getPort(void)
{
return ACSPorts::getContainerDaemonPort();
}
/************************** CORBA interface ****************************/
void
ACSContainerHandlerImpl::start_container (
const char * container_type,
const char * container_name,
::CORBA::Short instance_number,
const ::ACS::stringSeq & type_modifiers,
const char * additional_command_line
)
ACE_THROW_SPEC ((
CORBA::SystemException,
::acsdaemonErrType::FailedToStartContainerEx,
::ACSErrTypeCommon::BadParameterEx
))
{
if (container_type == 0 ||
*container_type == 0)
{
::ACSErrTypeCommon::BadParameterExImpl ex(__FILE__, __LINE__,
"::ACSContainerDaemonImpl::start_container");
ex.setParameter("container_type");
throw ex.getBadParameterEx();
}
if (container_name == 0 ||
*container_name == 0)
{
::ACSErrTypeCommon::BadParameterExImpl ex(__FILE__, __LINE__,
"::ACSContainerDaemonImpl::start_container");
ex.setParameter("container_name");
throw ex.getBadParameterEx();
}
const char * cmdln = (additional_command_line ? additional_command_line : "");
// About type modifier "archiveContainer", see COMP-1316 and COMP-1996
int isArchiveContainer = 0;
int isCasaContainer = 0;
for (unsigned int i = 0; i < type_modifiers.length(); ++i) {
if (!strcmp(type_modifiers[i], "archiveContainer")) {
if (!strcmp(container_type,"java"))
isArchiveContainer = 1;
break;
}
else if (!strcmp(type_modifiers[i], "casaContainer")) {
isCasaContainer = 1;
break;
}
}
// execute: "acsStartContainer -<type> -b <instance> <name> <args>"
// TODO checks for ';', '&', '|' chars, they can run any other command!
//get the directory name to store the container stdout
std::string logDirectory="~/.acs/commandcenter/";
char * acsdata = ACE_OS::getenv("ACSDATA");
if(acsdata != 0)
logDirectory = std::string(acsdata) + std::string("/logs/");
char * host = ACE_OS::getenv("HOST");
if(host != NULL)
logDirectory = logDirectory + std::string(host) + std::string("/");
std::string containerName(container_name);
std::string::size_type pos=containerName.rfind("/");
if(pos != std::string::npos){
logDirectory.append(containerName,0,pos+1);
containerName.erase(0,pos+1);
}
//create the directory
std::string mkdir("mkdir -p ");
mkdir.append(logDirectory);
ACE_OS::system(mkdir.c_str());
std::string timeStamp(getStringifiedTimeStamp().c_str());
if( timeStamp.find(":") != std::string::npos)
timeStamp.replace(timeStamp.find(":"),1,".");
if( timeStamp.find(":") != std::string::npos )
timeStamp.replace(timeStamp.find(":"),1,".");
if( timeStamp.find("T") != std::string::npos)
timeStamp.replace(timeStamp.find("T"),1,"_");
char command[1000];
if (isArchiveContainer)
snprintf(command, 1000, "acsStartContainerOracleClasspath -%s -b %d %s %s &> %sacsStartContainer_%s_%s&", "java", instance_number, container_name, cmdln, logDirectory.c_str(), containerName.c_str(), timeStamp.c_str());
else if (isCasaContainer)
snprintf(command, 1000, "acsStartContainerWithCASA -%s -b %d %s %s &> %sacsStartContainer_%s_%s&", container_type, instance_number, container_name, cmdln, logDirectory.c_str(), containerName.c_str(), timeStamp.c_str());
else
snprintf(command, 1000, "acsStartContainer -%s -b %d %s %s &> %sacsStartContainer_%s_%s&", container_type, instance_number, container_name, cmdln, logDirectory.c_str(), containerName.c_str(), timeStamp.c_str());
ACS_SHORT_LOG ((LM_INFO, "Executing: '%s'.", command));
int result = ACE_OS::system(command);
if (result < 0)
{
throw ::acsdaemonErrType::FailedToStartContainerExImpl(
__FILE__, __LINE__,
"::ACSContainerDaemonImpl::start_container").getFailedToStartContainerEx();
}
}
void
ACSContainerHandlerImpl::stop_container (
const char * container_name,
::CORBA::Short instance_number,
const char * additional_command_line
)
ACE_THROW_SPEC ((
CORBA::SystemException,
::acsdaemonErrType::FailedToStopContainerEx,
::ACSErrTypeCommon::BadParameterEx
))
{
if (container_name == 0 ||
*container_name == 0)
{
::ACSErrTypeCommon::BadParameterExImpl ex(__FILE__, __LINE__,
"::ACSContainerDaemonImpl::stop_container");
ex.setParameter("container_name");
throw ex.getBadParameterEx();
}
const char * cmdln = (additional_command_line ? additional_command_line : "");
//get the directory name to store the container stdout
std::string logDirectory="~/.acs/commandcenter/";
char * acsdata = ACE_OS::getenv("ACSDATA");
if(acsdata != 0)
logDirectory = std::string(acsdata) + std::string("/logs/");
char * host = ACE_OS::getenv("HOST");
if(host != NULL)
logDirectory = logDirectory + std::string(host) + std::string("/");
std::string containerName(container_name);
std::string::size_type pos=containerName.rfind("/");
if(pos != std::string::npos){
logDirectory.append(containerName,0,pos+1);
containerName.erase(0,pos+1);
}
//create the directory
std::string mkdir("mkdir -p ");
mkdir.append(logDirectory);
ACE_OS::system(mkdir.c_str());
std::string timeStamp(getStringifiedTimeStamp().c_str());
if( timeStamp.find(":") != std::string::npos)
timeStamp.replace(timeStamp.find(":"),1,".");
if( timeStamp.find(":") != std::string::npos )
timeStamp.replace(timeStamp.find(":"),1,".");
if( timeStamp.find("T") != std::string::npos)
timeStamp.replace(timeStamp.find("T"),1,"_");
// execute: "acsStopContainer -b <instance> <name> <args>"
// TODO checks for ';', '&', '|' chars, they can run any other command!
char command[1000];
snprintf(command, 1000, "acsStopContainer -b %d %s %s &> %sacsStopContainer_%s_%s&", instance_number, container_name, cmdln, logDirectory.c_str(), containerName.c_str(), timeStamp.c_str());
ACS_SHORT_LOG ((LM_INFO, "Executing: '%s'.", command));
int result = ACE_OS::system(command);
if (result < 0)
{
throw ::acsdaemonErrType::FailedToStopContainerExImpl(
__FILE__, __LINE__,
"::ACSContainerDaemonImpl::stop_container").getFailedToStopContainerEx();
}
}
void
ACSContainerHandlerImpl::shutdown ()
ACE_THROW_SPEC ((
CORBA::SystemException,
::maciErrType::NoPermissionEx
))
{
if (h_service->isProtected())
{
throw ::maciErrType::NoPermissionEx();
}
ACS_SHORT_LOG ((LM_INFO, "Shutting down the ACS Container Daemon on remote request..."));
h_service->shutdown(false);
}
<|endoftext|> |
<commit_before>#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
/**
* @param prices: Given an integer array
* @return: Maximum profit
*/
long maxProfit(vector<int> &prices) {
auto const N = prices.size();
if (N == 0)
return 0;
vector<vector<vector<long>>> dp(
N + 2, vector<vector<long>>(
3, vector<long>(
2, std::numeric_limits<int>::min())));
dp[0][0][0] = 0;
for (int i = 0; i < N + 1; i++) {
for (int j = 0; j < 2; j++) {
dp[i + 1][j][0] = max(dp[i + 1][j][0], dp[i][j][0]);
dp[i + 1][j][1] = max( { dp[i + 1][j][1], dp[i][j][1], dp[i][j][0] - prices[i] });
dp[i + 1][j + 1][0] = max( { dp[i + 1][j + 1][0], dp[i][j+1][0], dp[i][j][1] + prices[i] });
}
}
// for (int i = 0; i < N + 1; i++) {
// for (int j = 0; j < 2 + 1; j++) {
// printf("(%ld, %ld) | ", dp[i][j][0], dp[i][j][1]);
// }
// cout << endl;
// }
long ans = 0;
for (int j = 0; j < 3; j++) {
ans = max(ans, dp[N][j][0]);
}
return ans;
}
};
int main() {
Solution sol;
vector<vector<int>> prices_vec = { { 1, -2, 3, -1, -4, 2, 3, 7 }, { 1, 3, 4, 1 }, { 2, 1, 4, 5, 2, 9, 7 } };
for (auto& prices : prices_vec) {
auto ans = sol.maxProfit(prices);
cout << "ans: " << ans << endl;
}
return 1;
}
<commit_msg>made the solution closer to ST's solution<commit_after>#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
/**
* @param prices: Given an integer array
* @return: Maximum profit
*/
long maxProfit(vector<int> &prices) {
auto const N = prices.size();
if (N == 0)
return 0;
vector<vector<vector<long>>> dp(
N + 2, vector<vector<long>>(
4, vector<long>(
2, std::numeric_limits<int>::min())));
dp[0][0][0] = 0;
for (int i = 0; i < N + 1; i++) {
for (int j = 0; j < 2 + 1; j++) {
dp[i + 1][j][0] = max(dp[i + 1][j][0], dp[i][j][0]);
dp[i + 1][j][1] = max( { dp[i + 1][j][1], dp[i][j][1], dp[i][j][0] - prices[i] });
dp[i + 1][j + 1][0] = max( { dp[i + 1][j + 1][0], dp[i][j][1] + prices[i] });
}
}
// for (int i = 0; i < N + 1; i++) {
// for (int j = 0; j < 2 + 1; j++) {
// printf("(%ld, %ld) | ", dp[i][j][0], dp[i][j][1]);
// }
// cout << endl;
// }
long ans = 0;
for (int j = 0; j < 3; j++) {
ans = max(ans, dp[N][j][0]);
}
return ans;
}
};
int main() {
Solution sol;
vector<vector<int>> prices_vec = { { 1, -2, 3, -1, -4, 2, 3, 7 }, { 1, 3, 4, 1 }, { 2, 1, 4, 5, 2, 9, 7 } };
for (auto& prices : prices_vec) {
auto ans = sol.maxProfit(prices);
cout << "ans: " << ans << endl;
}
return 1;
}
<|endoftext|> |
<commit_before>/**
* Appcelerator Kroll - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2008 Appcelerator, Inc. All Rights Reserved.
*/
#include "k_python_list.h"
namespace kroll
{
KPythonTuple::KPythonTuple(PyObject *tuple) :
tuple(tuple),
object(new KPythonObject(tuple, true))
{
PyLockGIL lock;
Py_INCREF(this->tuple);
}
KPythonTuple::~KPythonTuple()
{
PyLockGIL lock;
Py_DECREF(this->tuple);
}
void KPythonTuple::Append(SharedValue value)
{
throw ValueException::FromString("Cannot modify the size of a Python tuple.");
}
unsigned int KPythonTuple::Size()
{
PyLockGIL lock;
return PyTuple_Size(this->tuple);
}
bool KPythonTuple::Remove(unsigned int index)
{
throw ValueException::FromString("Cannot modify the size of a Python tuple.");
return false;
}
SharedValue KPythonTuple::At(unsigned int index)
{
PyLockGIL lock;
if (index >= 0 && index < this->Size())
{
PyObject *p = PyTuple_GetItem(this->tuple, index);
SharedValue v = PythonUtils::ToKrollValue(p);
Py_DECREF(p);
return v;
}
else
{
return Value::Undefined;
}
}
void KPythonTuple::Set(const char *name, SharedValue value)
{
throw ValueException::FromString("Cannot modify a Python tuple.");
}
void KPythonTuple::SetAt(unsigned int index, SharedValue value)
{
throw ValueException::FromString("Cannot modify a Python tuple.");
}
SharedValue KPythonTuple::Get(const char *name)
{
PyAllowThreads allow;
if (KList::IsInt(name))
{
unsigned int index = (unsigned int) atoi(name);
if (index >= 0)
{
return this->At(index);
}
}
return object->Get(name);
}
SharedStringList KPythonTuple::GetPropertyNames()
{
SharedStringList property_names = object->GetPropertyNames();
for (size_t i = 0; i < this->Size(); i++)
{
std::string name = KList::IntToChars(i);
property_names->push_back(new std::string(name));
}
return property_names;
}
PyObject* KPythonTuple::ToPython()
{
return this->object->ToPython();
}
bool KPythonTuple::Equals(SharedKObject other)
{
AutoPtr<KPythonTuple> pyOther = other.cast<KPythonTuple>();
if (pyOther.isNull())
{
return false;
}
else
{
return pyOther->ToPython() == this->ToPython();
}
}
}
<commit_msg>Remove uneeded PyAllowThreads that was causing a crash<commit_after>/**
* Appcelerator Kroll - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2008 Appcelerator, Inc. All Rights Reserved.
*/
#include "k_python_list.h"
namespace kroll
{
KPythonTuple::KPythonTuple(PyObject *tuple) :
tuple(tuple),
object(new KPythonObject(tuple, true))
{
PyLockGIL lock;
Py_INCREF(this->tuple);
}
KPythonTuple::~KPythonTuple()
{
PyLockGIL lock;
Py_DECREF(this->tuple);
}
void KPythonTuple::Append(SharedValue value)
{
throw ValueException::FromString("Cannot modify the size of a Python tuple.");
}
unsigned int KPythonTuple::Size()
{
PyLockGIL lock;
return PyTuple_Size(this->tuple);
}
bool KPythonTuple::Remove(unsigned int index)
{
throw ValueException::FromString("Cannot modify the size of a Python tuple.");
return false;
}
SharedValue KPythonTuple::At(unsigned int index)
{
PyLockGIL lock;
if (index >= 0 && index < this->Size())
{
PyObject *p = PyTuple_GetItem(this->tuple, index);
SharedValue v = PythonUtils::ToKrollValue(p);
Py_DECREF(p);
return v;
}
else
{
return Value::Undefined;
}
}
void KPythonTuple::Set(const char *name, SharedValue value)
{
throw ValueException::FromString("Cannot modify a Python tuple.");
}
void KPythonTuple::SetAt(unsigned int index, SharedValue value)
{
throw ValueException::FromString("Cannot modify a Python tuple.");
}
SharedValue KPythonTuple::Get(const char *name)
{
if (KList::IsInt(name))
{
unsigned int index = (unsigned int) atoi(name);
if (index >= 0)
{
return this->At(index);
}
}
return object->Get(name);
}
SharedStringList KPythonTuple::GetPropertyNames()
{
SharedStringList property_names = object->GetPropertyNames();
for (size_t i = 0; i < this->Size(); i++)
{
std::string name = KList::IntToChars(i);
property_names->push_back(new std::string(name));
}
return property_names;
}
PyObject* KPythonTuple::ToPython()
{
return this->object->ToPython();
}
bool KPythonTuple::Equals(SharedKObject other)
{
AutoPtr<KPythonTuple> pyOther = other.cast<KPythonTuple>();
if (pyOther.isNull())
{
return false;
}
else
{
return pyOther->ToPython() == this->ToPython();
}
}
}
<|endoftext|> |
<commit_before>#include "DotCircuit.h"
extern "C" {
#include "provsql_utils.h"
#include <unistd.h>
}
#include <cassert>
#include <string>
#include <fstream>
#include <sstream>
#include <cstdlib>
// Has to be redefined because of name hiding
unsigned DotCircuit::setGate(const uuid &u, DotGate type)
{
unsigned id = Circuit::setGate(u, type);
if(type == DotGate::IN)
inputs.insert(id);
return id;
}
unsigned DotCircuit::setGate(const uuid &u, DotGate type, std::string d)
{
unsigned id = setGate(u, type);
desc[id] = d;
return id;
}
unsigned DotCircuit::addGate()
{
unsigned id=Circuit::addGate();
desc.push_back("");
return id;
}
//Outputs the gate in Graphviz dot format
std::string DotCircuit::toString(unsigned ) const
{
std::string op;
std::string result="graph circuit{\n node [shape=plaintext];\n";
//looping through the gates
//eliminating the minusr and minusl gates
unsigned i=0;
for(auto g:gates){
if(g != DotGate::OMINUSR && g != DotGate::OMINUSL){
result += std::to_string(i)+" [label=";
switch(g) {
case DotGate::IN:
result+="\""+desc[i]+"\"";
break;
case DotGate::OMINUS:
result+="\"⊖\"";
break;
case DotGate::UNDETERMINED:
result+="\"?\"";
break;
case DotGate::OTIMES:
result+="\"⊗\"";
break;
case DotGate::OPLUS:
result+="\"⊕\"";
break;
case DotGate::EQ:
result+="\""+desc[i]+"\"";
break;
case DotGate::PROJECT:
result+="\"Π"+desc[i]+"\"";
break;
case DotGate::OMINUSR:
case DotGate::OMINUSL:
break;
}
result+="];\n";
}
i++;
}
//looping through the gates and their wires
for(size_t i=0;i<wires.size();++i){
if(gates[i] != DotGate::OMINUSR && gates[i] != DotGate::OMINUSL){
for(auto s: wires[i])
{
if(gates[s] == DotGate::OMINUSR || gates[s] == DotGate::OMINUSL) {
for(auto t: wires[s]) {
result += std::to_string(i)+" -- "+std::to_string(t)+";\n";
}
}
else {
result += std::to_string(i)+" -- "+std::to_string(s)+";\n";
}
}
}
}
return result+"}";
}
void DotCircuit::render() const {
//Writing dot to a temporary file
int fd;
char cfilename[] = "/tmp/provsqlXXXXXX";
fd = mkstemp(cfilename);
close(fd);
std::string filename=cfilename, outfilename=filename+".pdf";
std::ofstream ofs(filename.c_str());
ofs << toString(0);
ofs.close();
//Executing the Graphviz dot renderer
std::string cmdline="dot -Tpdf "+filename+" -o "+outfilename;
int retvalue=system(cmdline.c_str());
if(retvalue)
throw CircuitException("Error executing Graphviz dot");
//Opening the PDF viewer
#ifdef __linux__
//assuming evince on linux
cmdline="export DISPLAY=':0'; xhost +; evince "+outfilename + " &";
retvalue=system(cmdline.c_str());
#else
throw CircuitException("Unsupported operating system for viewing");
#endif
}
<commit_msg>Added right and left labels on the circuit.<commit_after>#include "DotCircuit.h"
extern "C" {
#include "provsql_utils.h"
#include <unistd.h>
}
#include <cassert>
#include <string>
#include <fstream>
#include <sstream>
#include <cstdlib>
// Has to be redefined because of name hiding
unsigned DotCircuit::setGate(const uuid &u, DotGate type)
{
unsigned id = Circuit::setGate(u, type);
if(type == DotGate::IN)
inputs.insert(id);
return id;
}
unsigned DotCircuit::setGate(const uuid &u, DotGate type, std::string d)
{
unsigned id = setGate(u, type);
desc[id] = d;
return id;
}
unsigned DotCircuit::addGate()
{
unsigned id=Circuit::addGate();
desc.push_back("");
return id;
}
//Outputs the gate in Graphviz dot format
std::string DotCircuit::toString(unsigned ) const
{
std::string op;
std::string result="graph circuit{\n node [shape=plaintext];\n";
//looping through the gates
//eliminating the minusr and minusl gates
unsigned i=0;
for(auto g:gates){
if(g != DotGate::OMINUSR && g != DotGate::OMINUSL){
result += std::to_string(i)+" [label=";
switch(g) {
case DotGate::IN:
result+="\""+desc[i]+"\"";
break;
case DotGate::OMINUS:
result+="\"⊖\"";
break;
case DotGate::UNDETERMINED:
result+="\"?\"";
break;
case DotGate::OTIMES:
result+="\"⊗\"";
break;
case DotGate::OPLUS:
result+="\"⊕\"";
break;
case DotGate::EQ:
result+="\""+desc[i]+"\"";
break;
case DotGate::PROJECT:
result+="\"Π"+desc[i]+"\"";
break;
case DotGate::OMINUSR:
case DotGate::OMINUSL:
break;
}
result+="];\n";
}
i++;
}
//looping through the gates and their wires
for(size_t i=0;i<wires.size();++i){
if(gates[i] != DotGate::OMINUSR && gates[i] != DotGate::OMINUSL){
for(auto s: wires[i])
{
if(gates[s] == DotGate::OMINUSR || gates[s] == DotGate::OMINUSL) {
for(auto t: wires[s]) {
result += std::to_string(i)+" -- "+std::to_string(t);
if(gates[s] == DotGate::OMINUSR)
result += " [label=\"R\"];\n";
else
result += " [label=\"L\"];\n";
}
}
else {
result += std::to_string(i)+" -- "+std::to_string(s)+";\n";
}
}
}
}
return result+"}";
}
void DotCircuit::render() const {
//Writing dot to a temporary file
int fd;
char cfilename[] = "/tmp/provsqlXXXXXX";
fd = mkstemp(cfilename);
close(fd);
std::string filename=cfilename, outfilename=filename+".pdf";
std::ofstream ofs(filename.c_str());
ofs << toString(0);
ofs.close();
//Executing the Graphviz dot renderer
std::string cmdline="dot -Tpdf "+filename+" -o "+outfilename;
int retvalue=system(cmdline.c_str());
if(retvalue)
throw CircuitException("Error executing Graphviz dot");
//Opening the PDF viewer
#ifdef __linux__
//assuming evince on linux
cmdline="export DISPLAY=':0'; xhost +; evince "+outfilename + " &";
retvalue=system(cmdline.c_str());
#else
throw CircuitException("Unsupported operating system for viewing");
#endif
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright (c) 2017 Sergey Alexandrov
*
* 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 <algorithm>
#include <map>
#include <boost/assert.hpp>
#if CV_MAJOR_VERSION >= 3
#include <opencv2/imgcodecs/imgcodecs.hpp>
#else
#include <opencv2/highgui/highgui.hpp>
#endif
#include <opencv2/core/core.hpp>
#include <boost/filesystem.hpp>
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>
#include "utils/mat_io.h"
#include "dataset.h"
Dataset::Dataset() : num_images_(0), image_size_(0, 0) {}
void Dataset::insert(int exposure_time, const cv::Mat& image) {
if (image_size_.area() == 0)
image_size_ = image.size();
else
BOOST_ASSERT_MSG(image_size_ == image.size(), "Attempted to insert images of different size into same dataset");
data_[exposure_time].push_back(image);
++num_images_;
}
cv::Size Dataset::getImageSize() const {
return image_size_;
}
size_t Dataset::getNumImages() const {
return num_images_;
}
size_t Dataset::getNumImages(int exposure_time) const {
if (data_.count(exposure_time))
return data_.at(exposure_time).size();
return 0;
}
std::vector<cv::Mat> Dataset::getImages(int exposure_time) const {
if (data_.count(exposure_time))
return data_.at(exposure_time);
return {};
}
std::vector<int> Dataset::getExposureTimes() const {
std::vector<int> exposures;
std::transform(data_.begin(), data_.end(), std::back_inserter(exposures),
[](const std::pair<int, std::vector<cv::Mat>>& p) { return p.first; });
return exposures;
}
std::vector<Dataset> Dataset::splitChannels() const {
BOOST_ASSERT_MSG(!data_.empty(), "Attempted to split empty dataset");
int num_channels = data_.begin()->second.begin()->channels();
if (num_channels == 1)
return std::vector<Dataset>(1, *this);
std::vector<Dataset> splitted(num_channels);
std::vector<cv::Mat> channels;
for (const auto& time_images : data_)
for (const auto& image : time_images.second) {
cv::split(image, channels);
for (int c = 0; c < num_channels; ++c)
splitted[c].insert(time_images.first, channels[c].clone());
}
return splitted;
}
void Dataset::asImageAndExposureTimeVectors(std::vector<cv::Mat>& images, std::vector<int>& exposure_times) const {
images.clear();
exposure_times.clear();
for (const auto& time_images : data_) {
for (const auto& image : time_images.second) {
images.push_back(image);
exposure_times.push_back(time_images.first);
}
}
}
void Dataset::save(const std::string& path, Format format) const {
namespace fs = boost::filesystem;
fs::path dir(path);
if (!fs::exists(dir))
fs::create_directories(dir);
boost::format fmt("%1$06d_%2$03zu.%3$s");
auto extension = format == PNG ? "png" : "mat";
for (const auto& time_images : data_)
for (size_t i = 0; i < time_images.second.size(); ++i) {
auto filename = (dir / boost::str(fmt % time_images.first % i % extension)).native();
if (format == PNG)
cv::imwrite(filename, time_images.second[i]);
else
utils::writeMat(filename, time_images.second[i]);
}
}
Dataset::Ptr Dataset::load(const std::string& path) {
namespace fs = boost::filesystem;
fs::path dir(path);
if (fs::exists(dir) && fs::is_directory(dir)) {
auto dataset = std::make_shared<Dataset>();
for (fs::directory_iterator iter = fs::directory_iterator(dir); iter != fs::directory_iterator(); ++iter) {
auto stem = iter->path().stem().string();
auto extension = iter->path().extension().string();
try {
auto exposure = boost::lexical_cast<int>(stem.substr(0, 6));
cv::Mat image;
if (extension == ".png")
image = cv::imread(iter->path().string());
else
image = utils::readMat(iter->path().string());
dataset->insert(exposure, image);
} catch (boost::bad_lexical_cast& e) {
}
}
return dataset;
} else {
return nullptr;
}
}
<commit_msg>Fix format string in Dataset::save()<commit_after>/******************************************************************************
* Copyright (c) 2017 Sergey Alexandrov
*
* 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 <algorithm>
#include <map>
#include <boost/assert.hpp>
#if CV_MAJOR_VERSION >= 3
#include <opencv2/imgcodecs/imgcodecs.hpp>
#else
#include <opencv2/highgui/highgui.hpp>
#endif
#include <opencv2/core/core.hpp>
#include <boost/filesystem.hpp>
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>
#include "utils/mat_io.h"
#include "dataset.h"
Dataset::Dataset() : num_images_(0), image_size_(0, 0) {}
void Dataset::insert(int exposure_time, const cv::Mat& image) {
if (image_size_.area() == 0)
image_size_ = image.size();
else
BOOST_ASSERT_MSG(image_size_ == image.size(), "Attempted to insert images of different size into same dataset");
data_[exposure_time].push_back(image);
++num_images_;
}
cv::Size Dataset::getImageSize() const {
return image_size_;
}
size_t Dataset::getNumImages() const {
return num_images_;
}
size_t Dataset::getNumImages(int exposure_time) const {
if (data_.count(exposure_time))
return data_.at(exposure_time).size();
return 0;
}
std::vector<cv::Mat> Dataset::getImages(int exposure_time) const {
if (data_.count(exposure_time))
return data_.at(exposure_time);
return {};
}
std::vector<int> Dataset::getExposureTimes() const {
std::vector<int> exposures;
std::transform(data_.begin(), data_.end(), std::back_inserter(exposures),
[](const std::pair<int, std::vector<cv::Mat>>& p) { return p.first; });
return exposures;
}
std::vector<Dataset> Dataset::splitChannels() const {
BOOST_ASSERT_MSG(!data_.empty(), "Attempted to split empty dataset");
int num_channels = data_.begin()->second.begin()->channels();
if (num_channels == 1)
return std::vector<Dataset>(1, *this);
std::vector<Dataset> splitted(num_channels);
std::vector<cv::Mat> channels;
for (const auto& time_images : data_)
for (const auto& image : time_images.second) {
cv::split(image, channels);
for (int c = 0; c < num_channels; ++c)
splitted[c].insert(time_images.first, channels[c].clone());
}
return splitted;
}
void Dataset::asImageAndExposureTimeVectors(std::vector<cv::Mat>& images, std::vector<int>& exposure_times) const {
images.clear();
exposure_times.clear();
for (const auto& time_images : data_) {
for (const auto& image : time_images.second) {
images.push_back(image);
exposure_times.push_back(time_images.first);
}
}
}
void Dataset::save(const std::string& path, Format format) const {
namespace fs = boost::filesystem;
fs::path dir(path);
if (!fs::exists(dir))
fs::create_directories(dir);
boost::format fmt("%1$06d_%2$03d.%3$s");
auto extension = format == PNG ? "png" : "mat";
for (const auto& time_images : data_)
for (size_t i = 0; i < time_images.second.size(); ++i) {
auto filename = (dir / boost::str(fmt % time_images.first % i % extension)).native();
if (format == PNG)
cv::imwrite(filename, time_images.second[i]);
else
utils::writeMat(filename, time_images.second[i]);
}
}
Dataset::Ptr Dataset::load(const std::string& path) {
namespace fs = boost::filesystem;
fs::path dir(path);
if (fs::exists(dir) && fs::is_directory(dir)) {
auto dataset = std::make_shared<Dataset>();
for (fs::directory_iterator iter = fs::directory_iterator(dir); iter != fs::directory_iterator(); ++iter) {
auto stem = iter->path().stem().string();
auto extension = iter->path().extension().string();
try {
auto exposure = boost::lexical_cast<int>(stem.substr(0, 6));
cv::Mat image;
if (extension == ".png")
image = cv::imread(iter->path().string());
else
image = utils::readMat(iter->path().string());
dataset->insert(exposure, image);
} catch (boost::bad_lexical_cast& e) {
}
}
return dataset;
} else {
return nullptr;
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: JAccess.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: vg $ $Date: 2003-06-25 11:04:24 $
*
* 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_JACCESS_HXX
#include "JAccess.hxx"
#endif
#ifndef DBAUI_JOINTABLEVIEW_HXX
#include "JoinTableView.hxx"
#endif
#ifndef DBAUI_JOINTABLEVIEW_HXX
#include "JoinTableView.hxx"
#endif
#ifndef DBAUI_TABLEWINDOW_HXX
#include "TableWindow.hxx"
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_
#include <com/sun/star/accessibility/AccessibleRole.hpp>
#endif
#ifndef DBAUI_JOINDESIGNVIEW_HXX
#include "JoinDesignView.hxx"
#endif
#ifndef DBAUI_JOINCONTROLLER_HXX
#include "JoinController.hxx"
#endif
#ifndef DBAUI_TABLECONNECTION_HXX
#include "TableConnection.hxx"
#endif
namespace dbaui
{
using namespace ::com::sun::star::accessibility;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
OJoinDesignViewAccess::OJoinDesignViewAccess(OJoinTableView* _pTableView)
:VCLXAccessibleComponent(_pTableView->GetComponentInterface().is() ? _pTableView->GetWindowPeer() : NULL)
,m_pTableView(_pTableView)
{
}
// -----------------------------------------------------------------------------
::rtl::OUString SAL_CALL OJoinDesignViewAccess::getImplementationName() throw(RuntimeException)
{
return getImplementationName_Static();
}
// -----------------------------------------------------------------------------
::rtl::OUString OJoinDesignViewAccess::getImplementationName_Static(void) throw( RuntimeException )
{
return ::rtl::OUString::createFromAscii("org.openoffice.comp.dbu.JoinViewAccessibility");
}
// -----------------------------------------------------------------------------
// XAccessibleContext
sal_Int32 SAL_CALL OJoinDesignViewAccess::getAccessibleChildCount( ) throw (RuntimeException)
{
// TODO may be this will change to only visible windows
// this is the same assumption mt implements
::osl::MutexGuard aGuard( m_aMutex );
sal_Int32 nChildCount = 0;
if ( m_pTableView )
nChildCount = m_pTableView->GetTabWinCount() + m_pTableView->getTableConnections()->size();
return nChildCount;
}
// -----------------------------------------------------------------------------
Reference< XAccessible > SAL_CALL OJoinDesignViewAccess::getAccessibleChild( sal_Int32 i ) throw (IndexOutOfBoundsException,RuntimeException)
{
Reference< XAccessible > aRet;
::osl::MutexGuard aGuard( m_aMutex );
if(i >= 0 && i < getAccessibleChildCount() && m_pTableView )
{
// check if we should return a table window or a connection
sal_Int32 nTableWindowCount = m_pTableView->GetTabWinCount();
if( i < nTableWindowCount )
{
OJoinTableView::OTableWindowMap::iterator aIter = m_pTableView->GetTabWinMap()->begin();
for (sal_Int32 j=i; j; ++aIter,--j)
;
aRet = aIter->second->GetAccessible();
}
else if( size_t(i - nTableWindowCount) < m_pTableView->getTableConnections()->size() )
aRet = (*m_pTableView->getTableConnections())[i - nTableWindowCount]->getAccessible();
}
else
throw IndexOutOfBoundsException();
return aRet;
}
// -----------------------------------------------------------------------------
sal_Bool OJoinDesignViewAccess::isEditable() const
{
return m_pTableView && !m_pTableView->getDesignView()->getController()->isReadOnly();
}
// -----------------------------------------------------------------------------
sal_Int16 SAL_CALL OJoinDesignViewAccess::getAccessibleRole( ) throw (RuntimeException)
{
return AccessibleRole::VIEW_PORT;
}
// -----------------------------------------------------------------------------
Reference< XAccessibleContext > SAL_CALL OJoinDesignViewAccess::getAccessibleContext( ) throw (::com::sun::star::uno::RuntimeException)
{
return this;
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// XInterface
// -----------------------------------------------------------------------------
IMPLEMENT_FORWARD_XINTERFACE2( OJoinDesignViewAccess, VCLXAccessibleComponent, OJoinDesignViewAccess_BASE )
// -----------------------------------------------------------------------------
// XTypeProvider
// -----------------------------------------------------------------------------
IMPLEMENT_FORWARD_XTYPEPROVIDER2( OJoinDesignViewAccess, VCLXAccessibleComponent, OJoinDesignViewAccess_BASE )
}
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS oj07 (1.7.38); FILE MERGED 2003/08/21 13:48:05 oj 1.7.38.1: #111118# derive the tableconnection from window to fit into accessiblity tree<commit_after>/*************************************************************************
*
* $RCSfile: JAccess.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2004-03-02 12:46:12 $
*
* 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_JACCESS_HXX
#include "JAccess.hxx"
#endif
#ifndef DBAUI_JOINTABLEVIEW_HXX
#include "JoinTableView.hxx"
#endif
#ifndef DBAUI_JOINTABLEVIEW_HXX
#include "JoinTableView.hxx"
#endif
#ifndef DBAUI_TABLEWINDOW_HXX
#include "TableWindow.hxx"
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_
#include <com/sun/star/accessibility/AccessibleRole.hpp>
#endif
#ifndef DBAUI_JOINDESIGNVIEW_HXX
#include "JoinDesignView.hxx"
#endif
#ifndef DBAUI_JOINCONTROLLER_HXX
#include "JoinController.hxx"
#endif
#ifndef DBAUI_TABLECONNECTION_HXX
#include "TableConnection.hxx"
#endif
namespace dbaui
{
using namespace ::com::sun::star::accessibility;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
OJoinDesignViewAccess::OJoinDesignViewAccess(OJoinTableView* _pTableView)
:VCLXAccessibleComponent(_pTableView->GetComponentInterface().is() ? _pTableView->GetWindowPeer() : NULL)
,m_pTableView(_pTableView)
{
}
// -----------------------------------------------------------------------------
::rtl::OUString SAL_CALL OJoinDesignViewAccess::getImplementationName() throw(RuntimeException)
{
return getImplementationName_Static();
}
// -----------------------------------------------------------------------------
::rtl::OUString OJoinDesignViewAccess::getImplementationName_Static(void) throw( RuntimeException )
{
return ::rtl::OUString::createFromAscii("org.openoffice.comp.dbu.JoinViewAccessibility");
}
// -----------------------------------------------------------------------------
// XAccessibleContext
sal_Int32 SAL_CALL OJoinDesignViewAccess::getAccessibleChildCount( ) throw (RuntimeException)
{
// TODO may be this will change to only visible windows
// this is the same assumption mt implements
::osl::MutexGuard aGuard( m_aMutex );
sal_Int32 nChildCount = 0;
if ( m_pTableView )
nChildCount = m_pTableView->GetTabWinCount() + m_pTableView->getTableConnections()->size();
return nChildCount;
}
// -----------------------------------------------------------------------------
Reference< XAccessible > SAL_CALL OJoinDesignViewAccess::getAccessibleChild( sal_Int32 i ) throw (IndexOutOfBoundsException,RuntimeException)
{
Reference< XAccessible > aRet;
::osl::MutexGuard aGuard( m_aMutex );
if(i >= 0 && i < getAccessibleChildCount() && m_pTableView )
{
// check if we should return a table window or a connection
sal_Int32 nTableWindowCount = m_pTableView->GetTabWinCount();
if( i < nTableWindowCount )
{
OJoinTableView::OTableWindowMap::iterator aIter = m_pTableView->GetTabWinMap()->begin();
for (sal_Int32 j=i; j; ++aIter,--j)
;
aRet = aIter->second->GetAccessible();
}
else if( size_t(i - nTableWindowCount) < m_pTableView->getTableConnections()->size() )
aRet = (*m_pTableView->getTableConnections())[i - nTableWindowCount]->GetAccessible();
}
else
throw IndexOutOfBoundsException();
return aRet;
}
// -----------------------------------------------------------------------------
sal_Bool OJoinDesignViewAccess::isEditable() const
{
return m_pTableView && !m_pTableView->getDesignView()->getController()->isReadOnly();
}
// -----------------------------------------------------------------------------
sal_Int16 SAL_CALL OJoinDesignViewAccess::getAccessibleRole( ) throw (RuntimeException)
{
return AccessibleRole::VIEW_PORT;
}
// -----------------------------------------------------------------------------
Reference< XAccessibleContext > SAL_CALL OJoinDesignViewAccess::getAccessibleContext( ) throw (::com::sun::star::uno::RuntimeException)
{
return this;
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// XInterface
// -----------------------------------------------------------------------------
IMPLEMENT_FORWARD_XINTERFACE2( OJoinDesignViewAccess, VCLXAccessibleComponent, OJoinDesignViewAccess_BASE )
// -----------------------------------------------------------------------------
// XTypeProvider
// -----------------------------------------------------------------------------
IMPLEMENT_FORWARD_XTYPEPROVIDER2( OJoinDesignViewAccess, VCLXAccessibleComponent, OJoinDesignViewAccess_BASE )
}
// -----------------------------------------------------------------------------
<|endoftext|> |
<commit_before>#define THEWIZARDPLUSPLUS_WIZARD_PARSER_PARSER_MACROSES
#include "vendor/fmt/format.hpp"
#include "vendor/better-enums/enum_strict.hpp"
#include "vendor/range/v3/view/drop.hpp"
#include "vendor/range/v3/view/transform.hpp"
#include "vendor/range/v3/view/chunk.hpp"
#include "vendor/docopt/docopt.hpp"
#include "vendor/json.hpp"
#include "vendor/range/v3/numeric/accumulate.hpp"
#include "vendor/range/v3/view/filter.hpp"
#include "vendor/range/v3/to_container.hpp"
#include "vendor/range/v3/view/concat.hpp"
#include "vendor/range/v3/view/single.hpp"
#include <thewizardplusplus/wizard_parser/lexer/lexeme.hpp>
#include <thewizardplusplus/wizard_parser/transformers/transform.hpp>
#include <thewizardplusplus/wizard_parser/transformers/transformers.hpp>
#include <thewizardplusplus/wizard_parser/parser/rule_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/dummy_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/typing_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/match_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/concatenation_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/lookahead_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/repetition_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/alternation_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/ast_node.hpp>
#include <thewizardplusplus/wizard_parser/utilities/utilities.hpp>
#include <thewizardplusplus/wizard_parser/lexer/tokenize.hpp>
#include <thewizardplusplus/wizard_parser/lexer/token.hpp>
#include <unordered_map>
#include <string>
#include <cstddef>
#include <functional>
#include <vector>
#include <stdexcept>
#include <cstdint>
#include <regex>
#include <iostream>
#include <cstdlib>
#include <iterator>
#include <exception>
using namespace thewizardplusplus::wizard_parser;
using namespace thewizardplusplus::wizard_parser::parser::operators;
using namespace std::literals::string_literals;
using constant_group = std::unordered_map<std::string, double>;
struct function final {
const std::size_t arity;
const std::function<double(const std::vector<double>&)> handler;
};
using function_group = std::unordered_map<std::string, function>;
struct positional_exception: std::runtime_error {
const std::string description;
const std::size_t offset;
positional_exception(
const std::string& description,
const std::size_t& offset
);
};
positional_exception::positional_exception(
const std::string& description,
const std::size_t& offset
):
std::runtime_error{fmt::format("{:s} (offset: {:d})", description, offset)},
description{description},
offset{offset}
{}
BETTER_ENUM(entity_type, std::uint8_t,
symbol,
token,
eoi,
node,
constant,
function
)
template<entity_type::_integral type>
struct unexpected_entity_exception final: positional_exception {
static_assert(entity_type::_is_valid(type));
explicit unexpected_entity_exception(const std::size_t& offset);
};
template<entity_type::_integral type>
unexpected_entity_exception<type>::unexpected_entity_exception(
const std::size_t& offset
):
positional_exception{
fmt::format(
"unexpected {:s}",
entity_type::_from_integral(type)._to_string()
),
offset
}
{}
const auto usage =
R"(Usage:
./example -h | --help
./example [-t TARGET | --target TARGET] [--] <expression>
./example [-t TARGET | --target TARGET] (-s | --stdin)
Options:
-h, --help - show this message;
-t TARGET, --target TARGET - preliminary target of processing
(allowed: tokens, cst);
-s, --stdin - read an expression from stdin.)";
const auto lexemes = lexer::lexeme_group{
{std::regex{R"(\+)"}, "plus"},
{std::regex{"-"}, "minus"},
{std::regex{R"(\*)"}, "star"},
{std::regex{"/"}, "slash"},
{std::regex{"%"}, "percent"},
{std::regex{R"(\()"}, "opening_parenthesis"},
{std::regex{R"(\))"}, "closing_parenthesis"},
{std::regex{","}, "comma"},
{std::regex{R"(\d+(?:\.\d+)?(?:e-?\d+)?)"}, "number"},
{std::regex{R"([A-Za-z_]\w*)"}, "identifier"},
{std::regex{R"(\s+)"}, "whitespace"}
};
const auto handlers = std::vector<transformers::ast_node_handler>{
transformers::remove_nothings,
transformers::join_sequences
};
const auto constants = constant_group{
{"pi", 3.1415926535897932384626433},
{"e", 2.7182818284590452353602874}
};
const auto functions = function_group{
{"+", {2, [] (const auto& arguments) {
return arguments.front() + arguments.back();
}}},
{"-", {2, [] (const auto& arguments) {
return arguments.front() - arguments.back();
}}},
{"*", {2, [] (const auto& arguments) {
return arguments.front() * arguments.back();
}}},
{"/", {2, [] (const auto& arguments) {
return arguments.front() / arguments.back();
}}},
{"%", {2, [] (const auto& arguments) {
return static_cast<std::int64_t>(arguments.front())
% static_cast<std::int64_t>(arguments.back());
}}},
{"floor", {1, [] (const auto& arguments) {
return std::floor(arguments.front());
}}},
{"ceil", {1, [] (const auto& arguments) {
return std::ceil(arguments.front());
}}},
{"trunc", {1, [] (const auto& arguments) {
return std::trunc(arguments.front());
}}},
{"round", {1, [] (const auto& arguments) {
return std::round(arguments.front());
}}},
{"sin", {1, [] (const auto& arguments) {
return std::sin(arguments.front());
}}},
{"cos", {1, [] (const auto& arguments) {
return std::cos(arguments.front());
}}},
{"tn", {1, [] (const auto& arguments) {
return std::tan(arguments.front());
}}},
{"arcsin", {1, [] (const auto& arguments) {
return std::asin(arguments.front());
}}},
{"arccos", {1, [] (const auto& arguments) {
return std::acos(arguments.front());
}}},
{"arctn", {1, [] (const auto& arguments) {
return std::atan(arguments.front());
}}},
{"angle", {2, [] (const auto& arguments) {
return std::atan2(arguments.back(), arguments.front());
}}},
{"pow", {2, [] (const auto& arguments) {
return std::pow(arguments.front(), arguments.back());
}}},
{"sqrt", {1, [] (const auto& arguments) {
return std::sqrt(arguments.front());
}}},
{"exp", {1, [] (const auto& arguments) {
return std::exp(arguments.front());
}}},
{"ln", {1, [] (const auto& arguments) {
return std::log(arguments.front());
}}},
{"lg", {1, [] (const auto& arguments) {
return std::log10(arguments.front());
}}},
{"abs", {1, [] (const auto& arguments) {
return std::abs(arguments.front());
}}},
};
void stop(const int& code, std::ostream& stream, const std::string& message) {
stream << fmt::format("{:s}\n", message);
std::exit(code);
}
parser::rule_parser::pointer make_parser() {
const auto expression_dummy = parser::dummy();
RULE(function_call) = "identifier"_t >> &"("_v >>
-(expression_dummy >> *(&","_v >> expression_dummy))
>> &")"_v;
RULE(atom) = "number"_t
| function_call
| "identifier"_t
| (&"("_v >> expression_dummy >> &")"_v);
RULE(unary) = *("-"_v) >> atom;
RULE(product) = unary >> *(("*"_v | "/"_v | "%"_v) >> unary);
RULE(sum) = product >> *(("+"_v | "-"_v) >> product);
expression_dummy->set_parser(sum);
return sum;
}
const parser::ast_node_group& inspect_sequence(const parser::ast_node& ast) {
return ast.children.front().children;
}
double evaluate_ast_node(
const parser::ast_node& ast,
const constant_group& constants,
const function_group& functions
) {
const auto evaluate_with_context = [&] (const auto& ast) {
return evaluate_ast_node(ast, constants, functions);
};
if (ast.type == "number") {
return std::stod(ast.value, nullptr);
} else if (ast.type == "identifier") {
try {
return constants.at(ast.value);
} catch (const std::out_of_range& exception) {
throw unexpected_entity_exception<entity_type::constant>{
parser::get_offset(ast)
};
}
} else if (ast.type == "atom") {
const auto type = (+parser::ast_node_type::sequence)._to_string();
const auto first_child = ast.children.front().type == type
? inspect_sequence(ast).front()
: ast.children.front();
return evaluate_with_context(first_child);
} else if (ast.type == "unary") {
const auto result = evaluate_with_context(inspect_sequence(ast).back());
const auto sign = (inspect_sequence(ast).size()-1) % 2 ? -1 : 1;
return sign * result;
} else if (ast.type == "function_call") {
try {
const auto name = inspect_sequence(ast).front().value;
const auto arguments = inspect_sequence(ast)
| ranges::view::drop(1)
| ranges::view::transform([&] (const auto& ast) {
return evaluate_with_context(ast);
});
const auto function = functions.at(name);
if (arguments.size() != function.arity) {
throw positional_exception{
fmt::format(
"function requires {:d} {:s}",
function.arity,
function.arity == 1 ? "argument" : "arguments"
),
parser::get_offset(ast)
};
}
return function.handler(arguments);
} catch (const std::out_of_range& exception) {
throw unexpected_entity_exception<entity_type::function>{
parser::get_offset(ast)
};
}
} else if (ast.type == "product" || ast.type == "sum") {
const auto first_operand =
evaluate_with_context(inspect_sequence(ast).front());
const auto children_chunks = inspect_sequence(ast)
| ranges::view::drop(1)
| ranges::view::chunk(2)
| ranges::view::transform([] (const auto& chunk) {
return chunk | ranges::to_<parser::ast_node_group>();
});
return ranges::accumulate(
children_chunks,
first_operand,
[&] (const auto& result, const auto& chunk) {
const auto name = chunk.front().value;
const auto second_operand = evaluate_with_context(chunk.back());
return functions.at(name).handler({result, second_operand});
}
);
} else {
throw unexpected_entity_exception<entity_type::node>{parser::get_offset(ast)};
}
}
int main(int argc, char* argv[]) try {
const auto options = docopt::docopt(usage, {argv+1, argv+argc}, true);
const auto code = options.at("--stdin").asBool()
? std::string{std::istreambuf_iterator<char>{std::cin}, {}}
: options.at("<expression>").asString();
const auto [tokens, rest_offset] = lexer::tokenize(lexemes, code);
if (rest_offset != code.size()) {
throw unexpected_entity_exception<entity_type::symbol>{rest_offset};
}
auto cleaned_tokens = tokens
| ranges::view::filter([] (const auto& token) {
return token.type != "whitespace";
})
| ranges::to_<lexer::token_group>();
if (options.at("--target") == "tokens"s) {
stop(EXIT_SUCCESS, std::cout, nlohmann::json(cleaned_tokens).dump());
}
const auto ast = make_parser()->parse(cleaned_tokens);
if (!ast.rest_tokens.empty()) {
throw unexpected_entity_exception<entity_type::token>{
lexer::get_offset(ast.rest_tokens)
};
}
if (!ast.node) {
throw unexpected_entity_exception<entity_type::eoi>{code.size()};
}
const auto completed_handlers = ranges::view::concat(
// replace CST nodes offsets which are equal
// to the utilities::integral_infinity constant to a code size
ranges::view::single([&] (const auto& ast) {
const auto offset = ast.offset == utilities::integral_infinity
? code.size()
: ast.offset;
return parser::ast_node{ast.type, ast.value, ast.children, offset};
}),
handlers
);
const auto transformed_ast = ranges::accumulate(
completed_handlers,
*ast.node,
transformers::transform
);
if (options.at("--target") == "cst"s) {
stop(EXIT_SUCCESS, std::cout, nlohmann::json(transformed_ast).dump());
}
const auto result = evaluate_ast_node(transformed_ast, constants, functions);
stop(EXIT_SUCCESS, std::cout, std::to_string(result));
} catch (const std::exception& exception) {
stop(EXIT_FAILURE, std::cerr, fmt::format("error: {:s}", exception.what()));
}
<commit_msg>Add the `transformers` module: simplify the example<commit_after>#define THEWIZARDPLUSPLUS_WIZARD_PARSER_PARSER_MACROSES
#include "vendor/fmt/format.hpp"
#include "vendor/better-enums/enum_strict.hpp"
#include "vendor/range/v3/view/drop.hpp"
#include "vendor/range/v3/view/transform.hpp"
#include "vendor/range/v3/view/chunk.hpp"
#include "vendor/docopt/docopt.hpp"
#include "vendor/json.hpp"
#include "vendor/range/v3/numeric/accumulate.hpp"
#include "vendor/range/v3/view/filter.hpp"
#include "vendor/range/v3/to_container.hpp"
#include <thewizardplusplus/wizard_parser/lexer/lexeme.hpp>
#include <thewizardplusplus/wizard_parser/parser/rule_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/dummy_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/typing_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/match_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/concatenation_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/lookahead_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/repetition_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/alternation_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/ast_node.hpp>
#include <thewizardplusplus/wizard_parser/lexer/tokenize.hpp>
#include <thewizardplusplus/wizard_parser/lexer/token.hpp>
#include <thewizardplusplus/wizard_parser/transformers/transformers.hpp>
#include <thewizardplusplus/wizard_parser/transformers/transform.hpp>
#include <unordered_map>
#include <string>
#include <cstddef>
#include <functional>
#include <vector>
#include <stdexcept>
#include <cstdint>
#include <regex>
#include <iostream>
#include <cstdlib>
#include <iterator>
#include <exception>
using namespace thewizardplusplus::wizard_parser;
using namespace thewizardplusplus::wizard_parser::parser::operators;
using namespace std::literals::string_literals;
using constant_group = std::unordered_map<std::string, double>;
struct function final {
const std::size_t arity;
const std::function<double(const std::vector<double>&)> handler;
};
using function_group = std::unordered_map<std::string, function>;
struct positional_exception: std::runtime_error {
const std::string description;
const std::size_t offset;
positional_exception(
const std::string& description,
const std::size_t& offset
);
};
positional_exception::positional_exception(
const std::string& description,
const std::size_t& offset
):
std::runtime_error{fmt::format("{:s} (offset: {:d})", description, offset)},
description{description},
offset{offset}
{}
BETTER_ENUM(entity_type, std::uint8_t,
symbol,
token,
eoi,
node,
constant,
function
)
template<entity_type::_integral type>
struct unexpected_entity_exception final: positional_exception {
static_assert(entity_type::_is_valid(type));
explicit unexpected_entity_exception(const std::size_t& offset);
};
template<entity_type::_integral type>
unexpected_entity_exception<type>::unexpected_entity_exception(
const std::size_t& offset
):
positional_exception{
fmt::format(
"unexpected {:s}",
entity_type::_from_integral(type)._to_string()
),
offset
}
{}
const auto usage =
R"(Usage:
./example -h | --help
./example [-t TARGET | --target TARGET] [--] <expression>
./example [-t TARGET | --target TARGET] (-s | --stdin)
Options:
-h, --help - show this message;
-t TARGET, --target TARGET - preliminary target of processing
(allowed: tokens, cst);
-s, --stdin - read an expression from stdin.)";
const auto lexemes = lexer::lexeme_group{
{std::regex{R"(\+)"}, "plus"},
{std::regex{"-"}, "minus"},
{std::regex{R"(\*)"}, "star"},
{std::regex{"/"}, "slash"},
{std::regex{"%"}, "percent"},
{std::regex{R"(\()"}, "opening_parenthesis"},
{std::regex{R"(\))"}, "closing_parenthesis"},
{std::regex{","}, "comma"},
{std::regex{R"(\d+(?:\.\d+)?(?:e-?\d+)?)"}, "number"},
{std::regex{R"([A-Za-z_]\w*)"}, "identifier"},
{std::regex{R"(\s+)"}, "whitespace"}
};
const auto constants = constant_group{
{"pi", 3.1415926535897932384626433},
{"e", 2.7182818284590452353602874}
};
const auto functions = function_group{
{"+", {2, [] (const auto& arguments) {
return arguments.front() + arguments.back();
}}},
{"-", {2, [] (const auto& arguments) {
return arguments.front() - arguments.back();
}}},
{"*", {2, [] (const auto& arguments) {
return arguments.front() * arguments.back();
}}},
{"/", {2, [] (const auto& arguments) {
return arguments.front() / arguments.back();
}}},
{"%", {2, [] (const auto& arguments) {
return static_cast<std::int64_t>(arguments.front())
% static_cast<std::int64_t>(arguments.back());
}}},
{"floor", {1, [] (const auto& arguments) {
return std::floor(arguments.front());
}}},
{"ceil", {1, [] (const auto& arguments) {
return std::ceil(arguments.front());
}}},
{"trunc", {1, [] (const auto& arguments) {
return std::trunc(arguments.front());
}}},
{"round", {1, [] (const auto& arguments) {
return std::round(arguments.front());
}}},
{"sin", {1, [] (const auto& arguments) {
return std::sin(arguments.front());
}}},
{"cos", {1, [] (const auto& arguments) {
return std::cos(arguments.front());
}}},
{"tn", {1, [] (const auto& arguments) {
return std::tan(arguments.front());
}}},
{"arcsin", {1, [] (const auto& arguments) {
return std::asin(arguments.front());
}}},
{"arccos", {1, [] (const auto& arguments) {
return std::acos(arguments.front());
}}},
{"arctn", {1, [] (const auto& arguments) {
return std::atan(arguments.front());
}}},
{"angle", {2, [] (const auto& arguments) {
return std::atan2(arguments.back(), arguments.front());
}}},
{"pow", {2, [] (const auto& arguments) {
return std::pow(arguments.front(), arguments.back());
}}},
{"sqrt", {1, [] (const auto& arguments) {
return std::sqrt(arguments.front());
}}},
{"exp", {1, [] (const auto& arguments) {
return std::exp(arguments.front());
}}},
{"ln", {1, [] (const auto& arguments) {
return std::log(arguments.front());
}}},
{"lg", {1, [] (const auto& arguments) {
return std::log10(arguments.front());
}}},
{"abs", {1, [] (const auto& arguments) {
return std::abs(arguments.front());
}}},
};
void stop(const int& code, std::ostream& stream, const std::string& message) {
stream << fmt::format("{:s}\n", message);
std::exit(code);
}
parser::rule_parser::pointer make_parser() {
const auto expression_dummy = parser::dummy();
RULE(function_call) = "identifier"_t >> &"("_v >>
-(expression_dummy >> *(&","_v >> expression_dummy))
>> &")"_v;
RULE(atom) = "number"_t
| function_call
| "identifier"_t
| (&"("_v >> expression_dummy >> &")"_v);
RULE(unary) = *("-"_v) >> atom;
RULE(product) = unary >> *(("*"_v | "/"_v | "%"_v) >> unary);
RULE(sum) = product >> *(("+"_v | "-"_v) >> product);
expression_dummy->set_parser(sum);
return sum;
}
const parser::ast_node_group& inspect_sequence(const parser::ast_node& ast) {
return ast.children.front().children;
}
double evaluate_ast_node(
const parser::ast_node& ast,
const constant_group& constants,
const function_group& functions
) {
const auto evaluate_with_context = [&] (const auto& ast) {
return evaluate_ast_node(ast, constants, functions);
};
if (ast.type == "number") {
return std::stod(ast.value, nullptr);
} else if (ast.type == "identifier") {
try {
return constants.at(ast.value);
} catch (const std::out_of_range& exception) {
throw unexpected_entity_exception<entity_type::constant>{
parser::get_offset(ast)
};
}
} else if (ast.type == "atom") {
const auto type = (+parser::ast_node_type::sequence)._to_string();
const auto first_child = ast.children.front().type == type
? inspect_sequence(ast).front()
: ast.children.front();
return evaluate_with_context(first_child);
} else if (ast.type == "unary") {
const auto result = evaluate_with_context(inspect_sequence(ast).back());
const auto sign = (inspect_sequence(ast).size()-1) % 2 ? -1 : 1;
return sign * result;
} else if (ast.type == "function_call") {
try {
const auto name = inspect_sequence(ast).front().value;
const auto arguments = inspect_sequence(ast)
| ranges::view::drop(1)
| ranges::view::transform([&] (const auto& ast) {
return evaluate_with_context(ast);
});
const auto function = functions.at(name);
if (arguments.size() != function.arity) {
throw positional_exception{
fmt::format(
"function requires {:d} {:s}",
function.arity,
function.arity == 1 ? "argument" : "arguments"
),
parser::get_offset(ast)
};
}
return function.handler(arguments);
} catch (const std::out_of_range& exception) {
throw unexpected_entity_exception<entity_type::function>{
parser::get_offset(ast)
};
}
} else if (ast.type == "product" || ast.type == "sum") {
const auto first_operand =
evaluate_with_context(inspect_sequence(ast).front());
const auto children_chunks = inspect_sequence(ast)
| ranges::view::drop(1)
| ranges::view::chunk(2)
| ranges::view::transform([] (const auto& chunk) {
return chunk | ranges::to_<parser::ast_node_group>();
});
return ranges::accumulate(
children_chunks,
first_operand,
[&] (const auto& result, const auto& chunk) {
const auto name = chunk.front().value;
const auto second_operand = evaluate_with_context(chunk.back());
return functions.at(name).handler({result, second_operand});
}
);
} else {
throw unexpected_entity_exception<entity_type::node>{parser::get_offset(ast)};
}
}
int main(int argc, char* argv[]) try {
const auto options = docopt::docopt(usage, {argv+1, argv+argc}, true);
const auto code = options.at("--stdin").asBool()
? std::string{std::istreambuf_iterator<char>{std::cin}, {}}
: options.at("<expression>").asString();
const auto [tokens, rest_offset] = lexer::tokenize(lexemes, code);
if (rest_offset != code.size()) {
throw unexpected_entity_exception<entity_type::symbol>{rest_offset};
}
auto cleaned_tokens = tokens
| ranges::view::filter([] (const auto& token) {
return token.type != "whitespace";
})
| ranges::to_<lexer::token_group>();
if (options.at("--target") == "tokens"s) {
stop(EXIT_SUCCESS, std::cout, nlohmann::json(cleaned_tokens).dump());
}
const auto ast = make_parser()->parse(cleaned_tokens);
if (!ast.rest_tokens.empty()) {
throw unexpected_entity_exception<entity_type::token>{
lexer::get_offset(ast.rest_tokens)
};
}
if (!ast.node) {
throw unexpected_entity_exception<entity_type::eoi>{code.size()};
}
const auto transformed_ast = ranges::accumulate(
{transformers::remove_nothings, transformers::join_sequences},
*ast.node,
transformers::transform
);
if (options.at("--target") == "cst"s) {
stop(EXIT_SUCCESS, std::cout, nlohmann::json(transformed_ast).dump());
}
const auto result = evaluate_ast_node(transformed_ast, constants, functions);
stop(EXIT_SUCCESS, std::cout, std::to_string(result));
} catch (const std::exception& exception) {
stop(EXIT_FAILURE, std::cerr, fmt::format("error: {:s}", exception.what()));
}
<|endoftext|> |
<commit_before>
#ifndef EC_MANAGER_HPP
#define EC_MANAGER_HPP
#define EC_INIT_ENTITIES_SIZE 256
#define EC_GROW_SIZE_AMOUNT 256
#include <cstddef>
#include <tuple>
#include <utility>
#include "Meta/Combine.hpp"
#include "Bitset.hpp"
namespace EC
{
template <typename ComponentsList, typename TagsList>
struct Manager
{
public:
using Combined = EC::Meta::Combine<ComponentsList, TagsList>;
using BitsetType = EC::Bitset<ComponentsList, TagsList>;
private:
template <typename... Types>
struct Storage
{
using type = std::tuple<std::vector<Types>... >;
};
using ComponentsStorage = typename EC::Meta::Morph<ComponentsList, Storage<> >::type;
// Entity: isAlive, dataIndex, ComponentsTags Info
using EntitiesTupleType = std::tuple<bool, std::size_t, BitsetType>;
using EntitiesType = std::vector<EntitiesTupleType>;
EntitiesType entities;
ComponentsStorage componentsStorage;
std::size_t currentCapacity = 0;
std::size_t currentSize = 0;
public:
Manager()
{
resize(EC_INIT_ENTITIES_SIZE);
}
private:
void resize(std::size_t newCapacity)
{
if(currentCapacity >= newCapacity)
{
return;
}
EC::Meta::forEach<ComponentsList>([this, newCapacity] (auto t) {
std::get<std::vector<decltype(t)> >(this->componentsStorage).resize(newCapacity);
});
entities.resize(newCapacity);
for(std::size_t i = currentCapacity; i < newCapacity; ++i)
{
entities[i] = std::make_tuple(false, i, BitsetType{});
}
currentCapacity = newCapacity;
}
public:
std::size_t addEntity()
{
if(currentSize == currentCapacity)
{
resize(currentCapacity + EC_GROW_SIZE_AMOUNT);
}
std::get<bool>(entities[currentSize]) = true;
return currentSize++;
}
void deleteEntity(std::size_t index)
{
std::get<bool>(entities.at(index)) = false;
}
bool hasEntity(std::size_t index) const
{
return index < currentSize;
}
bool isAlive(std::size_t index) const
{
return hasEntity(index) && std::get<bool>(entities.at(index));
}
const EntitiesTupleType& getEntityInfo(std::size_t index) const
{
return entities.at(index);
}
template <typename Component>
Component& getEntityData(std::size_t index)
{
return std::get<std::vector<Component> >(componentsStorage).at(std::get<std::size_t>(entities.at(index)));
}
template <typename Component>
bool hasComponent(std::size_t index) const
{
return std::get<BitsetType>(entities.at(index)).template getComponentBit<Component>();
}
template <typename Tag>
bool hasTag(std::size_t index) const
{
return std::get<BitsetType>(entities.at(index)).template getTagBit<Tag>();
}
void cleanup()
{
if(currentSize == 0)
{
return;
}
std::size_t rhs = currentSize - 1;
std::size_t lhs = 0;
while(lhs < rhs)
{
while(!std::get<bool>(entities[rhs]))
{
if(rhs == 0)
{
currentSize = 0;
return;
}
--rhs;
}
if(lhs >= rhs)
{
break;
}
else if(!std::get<bool>(entities[lhs]))
{
// lhs is marked for deletion
// swap lhs entity with rhs entity
std::swap(entities[lhs], entities.at(rhs));
// clear deleted bitset
std::get<BitsetType>(entities[rhs]).reset();
// inc/dec pointers
++lhs; --rhs;
}
else
{
++lhs;
}
}
currentSize = rhs + 1;
}
template <typename Component, typename... Args>
void addComponent(std::size_t entityID, Args&&... args)
{
if(!hasEntity(entityID) || !isAlive(entityID))
{
return;
}
Component component(args...);
std::get<BitsetType>(entities[entityID]).template getComponentBit<Component>() = true;
std::get<std::vector<Component> >(componentsStorage)[std::get<std::size_t>(entities[entityID])] = component;
}
template <typename Component>
void removeComponent(std::size_t entityID)
{
if(!hasEntity(entityID) || !isAlive(entityID))
{
return;
}
std::get<BitsetType>(entities[entityID]).template getComponentBit<Component>() = false;
}
template <typename Tag>
void addTag(std::size_t entityID)
{
if(!hasEntity(entityID) || !isAlive(entityID))
{
return;
}
std::get<BitsetType>(entities[entityID]).template getTagBit<Tag>() = true;
}
template <typename Tag>
void removeTag(std::size_t entityID)
{
if(!hasEntity(entityID) || !isAlive(entityID))
{
return;
}
std::get<BitsetType>(entities[entityID]).template getTagBit<Tag>() = false;
}
private:
template <typename... Types>
struct ForMatchingSignatureHelper
{
template <typename CType, typename Function>
static void call(std::size_t entityID, CType& ctype, Function&& function)
{
function(
entityID,
ctype.template getEntityData<Types>(entityID)...
);
}
};
public:
template <typename Signature, typename Function>
void forMatchingSignature(Function&& function)
{
using SignatureComponents = typename EC::Meta::Matching<Signature, ComponentsList>::type;
using Helper = EC::Meta::Morph<SignatureComponents, ForMatchingSignatureHelper<> >;
BitsetType signatureBitset = BitsetType::template generateBitset<Signature>();
for(std::size_t i = 0; i < currentSize; ++i)
{
if(!std::get<bool>(entities[i]))
{
continue;
}
if((signatureBitset & std::get<BitsetType>(entities[i])) == signatureBitset)
{
Helper::call(i, *this, std::forward<Function>(function));
}
}
}
};
}
#endif
/*! \class EC::Manager
\brief Manages an EntityComponent system.
*/
/*! \fn EC::Manager::Manager()
\brief Initializes the manager with a default capacity.
The default capacity is set with macro EC_INIT_ENTITIES_SIZE,
and will grow by amounts of EC_GROW_SIZE_AMOUNT when needed.
*/
/*! \fn std::size_t EC::Manager::addEntity()
\brief Adds an entity to the system, returning the ID of the entity.
WARNING: The ID of an entity may change after calls to cleanup().
Only use the ID given during usage of forMatchingSignature().
*/
/*! \fn void EC::Manager::deleteEntity(std::size_t index)
\brief Marks an entity for deletion.
A deleted Entity is not actually deleted until cleanup() is called.
While an Entity is "deleted" but still in the system, calls to forMatchingSignature()
will ignore the Entity.
*/
/*! \fn bool EC::Manager::hasEntity(std::size_t index) const
\brief Checks if the Entity with the given ID is in the system.
Note that deleted Entities that haven't yet been cleaned up (via cleanup()) are
considered still in the system.
*/
/*! \fn bool EC::Manager::isAlive(std::size_t index) const
\brief Checks if the Entity is not marked as deleted.
Note that invalid Entities (Entities where calls to hasEntity() returns false)
will return false.
*/
/*! \fn const EntitiesTupleType& EC::Manager::getEntityInfo(std::size_t index) const
\brief Returns a const reference to an Entity's info.
An Entity's info is a std::tuple with a bool, std::size_t, and a bitset.
\n The bool determines if the Entity is alive.
\n The std::size_t is the ID to this Entity's data in the system.
\n The bitset shows what Components and Tags belong to the Entity.
*/
/*! \fn Component& EC::Manager::getEntityData(std::size_t index)
\brief Returns a reference to a component belonging to the given Entity.
This function will return a reference to a Component regardless of whether or
not the Entity actually owns the reference. If the Entity doesn't own the Component,
changes to the Component will not affect any Entity. It is recommended to use
hasComponent() to determine if the Entity actually owns that Component.
*/
/*! \fn bool EC::Manager::hasComponent(std::size_t index) const
\brief Checks whether or not the given Entity has the given Component.
Example:
\code{.cpp}
manager.hasComponent<C0>(entityID);
\endcode
*/
/*! \fn bool EC::Manager::hasTag(std::size_t index) const
\brief Checks whether or not the given Entity has the given Tag.
Example:
\code{.cpp}
manager.hasTag<T0>(entityID);
\endcode
*/
/*! \fn void EC::Manager::cleanup()
\brief Does garbage collection on Entities.
Does housekeeping on the vector containing Entities that will result in
entity IDs changing if some Entities were marked for deletion.
<b>This function should be called periodically to correctly handle deletion of entities.</b>
*/
/*! \fn void EC::Manager::addComponent(std::size_t entityID, Args&&... args)
\brief Adds a component to the given Entity.
Additional parameters given to this function will construct the Component with those
parameters.
Example:
\code{.cpp}
struct C0
{
C0(int a, char b) : a(a), b(b)
{}
int a;
char b;
}
manager.addComponent<C0>(entityID, 10, 'd');
\endcode
*/
/*! \fn void EC::Manager::removeComponent(std::size_t entityID)
\brief Removes the given Component from the given Entity.
If the Entity does not have the Component given, nothing will change.
Example:
\code{.cpp}
manager.removeComponent<C0>(entityID);
\endcode
*/
/*! \fn void EC::Manager::addTag(std::size_t entityID)
\brief Adds the given Tag to the given Entity.
Example:
\code{.cpp}
manager.addTag<T0>(entityID);
\endcode
*/
/*! \fn void EC::Manager::removeTag(std::size_t entityID)
\brief Removes the given Tag from the given Entity.
If the Entity does not have the Tag given, nothing will change.
Example:
\code{.cpp}
manager.removeTag<T0>(entityID);
\endcode
*/
/*! \fn void EC::Manager::forMatchingSignature(Function&& function)
\brief Calls the given function on all Entities matching the given Signature.
The function object given to this function must accept std::size_t as its first
parameter and Component references for the rest of the parameters. Tags specified in the
Signature are only used as filters and will not be given as a parameter to the function.
Example:
\code{.cpp}
manager.forMatchingSignature<TypeList<C0, C1, T0>>([] (std::size_t ID, C0& component0, C1& component1) {
// Lambda function contents here.
});
\endcode
Note, the ID given to the function is not permanent. An entity's ID may change when cleanup() is called.
*/
<commit_msg>Slight addition to EC::Manager documentation<commit_after>
#ifndef EC_MANAGER_HPP
#define EC_MANAGER_HPP
#define EC_INIT_ENTITIES_SIZE 256
#define EC_GROW_SIZE_AMOUNT 256
#include <cstddef>
#include <tuple>
#include <utility>
#include "Meta/Combine.hpp"
#include "Bitset.hpp"
namespace EC
{
template <typename ComponentsList, typename TagsList>
struct Manager
{
public:
using Combined = EC::Meta::Combine<ComponentsList, TagsList>;
using BitsetType = EC::Bitset<ComponentsList, TagsList>;
private:
template <typename... Types>
struct Storage
{
using type = std::tuple<std::vector<Types>... >;
};
using ComponentsStorage = typename EC::Meta::Morph<ComponentsList, Storage<> >::type;
// Entity: isAlive, dataIndex, ComponentsTags Info
using EntitiesTupleType = std::tuple<bool, std::size_t, BitsetType>;
using EntitiesType = std::vector<EntitiesTupleType>;
EntitiesType entities;
ComponentsStorage componentsStorage;
std::size_t currentCapacity = 0;
std::size_t currentSize = 0;
public:
Manager()
{
resize(EC_INIT_ENTITIES_SIZE);
}
private:
void resize(std::size_t newCapacity)
{
if(currentCapacity >= newCapacity)
{
return;
}
EC::Meta::forEach<ComponentsList>([this, newCapacity] (auto t) {
std::get<std::vector<decltype(t)> >(this->componentsStorage).resize(newCapacity);
});
entities.resize(newCapacity);
for(std::size_t i = currentCapacity; i < newCapacity; ++i)
{
entities[i] = std::make_tuple(false, i, BitsetType{});
}
currentCapacity = newCapacity;
}
public:
std::size_t addEntity()
{
if(currentSize == currentCapacity)
{
resize(currentCapacity + EC_GROW_SIZE_AMOUNT);
}
std::get<bool>(entities[currentSize]) = true;
return currentSize++;
}
void deleteEntity(std::size_t index)
{
std::get<bool>(entities.at(index)) = false;
}
bool hasEntity(std::size_t index) const
{
return index < currentSize;
}
bool isAlive(std::size_t index) const
{
return hasEntity(index) && std::get<bool>(entities.at(index));
}
const EntitiesTupleType& getEntityInfo(std::size_t index) const
{
return entities.at(index);
}
template <typename Component>
Component& getEntityData(std::size_t index)
{
return std::get<std::vector<Component> >(componentsStorage).at(std::get<std::size_t>(entities.at(index)));
}
template <typename Component>
bool hasComponent(std::size_t index) const
{
return std::get<BitsetType>(entities.at(index)).template getComponentBit<Component>();
}
template <typename Tag>
bool hasTag(std::size_t index) const
{
return std::get<BitsetType>(entities.at(index)).template getTagBit<Tag>();
}
void cleanup()
{
if(currentSize == 0)
{
return;
}
std::size_t rhs = currentSize - 1;
std::size_t lhs = 0;
while(lhs < rhs)
{
while(!std::get<bool>(entities[rhs]))
{
if(rhs == 0)
{
currentSize = 0;
return;
}
--rhs;
}
if(lhs >= rhs)
{
break;
}
else if(!std::get<bool>(entities[lhs]))
{
// lhs is marked for deletion
// swap lhs entity with rhs entity
std::swap(entities[lhs], entities.at(rhs));
// clear deleted bitset
std::get<BitsetType>(entities[rhs]).reset();
// inc/dec pointers
++lhs; --rhs;
}
else
{
++lhs;
}
}
currentSize = rhs + 1;
}
template <typename Component, typename... Args>
void addComponent(std::size_t entityID, Args&&... args)
{
if(!hasEntity(entityID) || !isAlive(entityID))
{
return;
}
Component component(args...);
std::get<BitsetType>(entities[entityID]).template getComponentBit<Component>() = true;
std::get<std::vector<Component> >(componentsStorage)[std::get<std::size_t>(entities[entityID])] = component;
}
template <typename Component>
void removeComponent(std::size_t entityID)
{
if(!hasEntity(entityID) || !isAlive(entityID))
{
return;
}
std::get<BitsetType>(entities[entityID]).template getComponentBit<Component>() = false;
}
template <typename Tag>
void addTag(std::size_t entityID)
{
if(!hasEntity(entityID) || !isAlive(entityID))
{
return;
}
std::get<BitsetType>(entities[entityID]).template getTagBit<Tag>() = true;
}
template <typename Tag>
void removeTag(std::size_t entityID)
{
if(!hasEntity(entityID) || !isAlive(entityID))
{
return;
}
std::get<BitsetType>(entities[entityID]).template getTagBit<Tag>() = false;
}
private:
template <typename... Types>
struct ForMatchingSignatureHelper
{
template <typename CType, typename Function>
static void call(std::size_t entityID, CType& ctype, Function&& function)
{
function(
entityID,
ctype.template getEntityData<Types>(entityID)...
);
}
};
public:
template <typename Signature, typename Function>
void forMatchingSignature(Function&& function)
{
using SignatureComponents = typename EC::Meta::Matching<Signature, ComponentsList>::type;
using Helper = EC::Meta::Morph<SignatureComponents, ForMatchingSignatureHelper<> >;
BitsetType signatureBitset = BitsetType::template generateBitset<Signature>();
for(std::size_t i = 0; i < currentSize; ++i)
{
if(!std::get<bool>(entities[i]))
{
continue;
}
if((signatureBitset & std::get<BitsetType>(entities[i])) == signatureBitset)
{
Helper::call(i, *this, std::forward<Function>(function));
}
}
}
};
}
#endif
/*! \class EC::Manager
\brief Manages an EntityComponent system.
EC::Manager must be created with a list of all used Components and all used tags.
Example:
\code{.cpp}
EC::Manager<TypeList<C0, C1, C2>, TypeList<T0, T1>> manager;
\endcode
*/
/*! \fn EC::Manager::Manager()
\brief Initializes the manager with a default capacity.
The default capacity is set with macro EC_INIT_ENTITIES_SIZE,
and will grow by amounts of EC_GROW_SIZE_AMOUNT when needed.
*/
/*! \fn std::size_t EC::Manager::addEntity()
\brief Adds an entity to the system, returning the ID of the entity.
WARNING: The ID of an entity may change after calls to cleanup().
Only use the ID given during usage of forMatchingSignature().
*/
/*! \fn void EC::Manager::deleteEntity(std::size_t index)
\brief Marks an entity for deletion.
A deleted Entity is not actually deleted until cleanup() is called.
While an Entity is "deleted" but still in the system, calls to forMatchingSignature()
will ignore the Entity.
*/
/*! \fn bool EC::Manager::hasEntity(std::size_t index) const
\brief Checks if the Entity with the given ID is in the system.
Note that deleted Entities that haven't yet been cleaned up (via cleanup()) are
considered still in the system.
*/
/*! \fn bool EC::Manager::isAlive(std::size_t index) const
\brief Checks if the Entity is not marked as deleted.
Note that invalid Entities (Entities where calls to hasEntity() returns false)
will return false.
*/
/*! \fn const EntitiesTupleType& EC::Manager::getEntityInfo(std::size_t index) const
\brief Returns a const reference to an Entity's info.
An Entity's info is a std::tuple with a bool, std::size_t, and a bitset.
\n The bool determines if the Entity is alive.
\n The std::size_t is the ID to this Entity's data in the system.
\n The bitset shows what Components and Tags belong to the Entity.
*/
/*! \fn Component& EC::Manager::getEntityData(std::size_t index)
\brief Returns a reference to a component belonging to the given Entity.
This function will return a reference to a Component regardless of whether or
not the Entity actually owns the reference. If the Entity doesn't own the Component,
changes to the Component will not affect any Entity. It is recommended to use
hasComponent() to determine if the Entity actually owns that Component.
*/
/*! \fn bool EC::Manager::hasComponent(std::size_t index) const
\brief Checks whether or not the given Entity has the given Component.
Example:
\code{.cpp}
manager.hasComponent<C0>(entityID);
\endcode
*/
/*! \fn bool EC::Manager::hasTag(std::size_t index) const
\brief Checks whether or not the given Entity has the given Tag.
Example:
\code{.cpp}
manager.hasTag<T0>(entityID);
\endcode
*/
/*! \fn void EC::Manager::cleanup()
\brief Does garbage collection on Entities.
Does housekeeping on the vector containing Entities that will result in
entity IDs changing if some Entities were marked for deletion.
<b>This function should be called periodically to correctly handle deletion of entities.</b>
*/
/*! \fn void EC::Manager::addComponent(std::size_t entityID, Args&&... args)
\brief Adds a component to the given Entity.
Additional parameters given to this function will construct the Component with those
parameters.
Example:
\code{.cpp}
struct C0
{
C0(int a, char b) : a(a), b(b)
{}
int a;
char b;
}
manager.addComponent<C0>(entityID, 10, 'd');
\endcode
*/
/*! \fn void EC::Manager::removeComponent(std::size_t entityID)
\brief Removes the given Component from the given Entity.
If the Entity does not have the Component given, nothing will change.
Example:
\code{.cpp}
manager.removeComponent<C0>(entityID);
\endcode
*/
/*! \fn void EC::Manager::addTag(std::size_t entityID)
\brief Adds the given Tag to the given Entity.
Example:
\code{.cpp}
manager.addTag<T0>(entityID);
\endcode
*/
/*! \fn void EC::Manager::removeTag(std::size_t entityID)
\brief Removes the given Tag from the given Entity.
If the Entity does not have the Tag given, nothing will change.
Example:
\code{.cpp}
manager.removeTag<T0>(entityID);
\endcode
*/
/*! \fn void EC::Manager::forMatchingSignature(Function&& function)
\brief Calls the given function on all Entities matching the given Signature.
The function object given to this function must accept std::size_t as its first
parameter and Component references for the rest of the parameters. Tags specified in the
Signature are only used as filters and will not be given as a parameter to the function.
Example:
\code{.cpp}
manager.forMatchingSignature<TypeList<C0, C1, T0>>([] (std::size_t ID, C0& component0, C1& component1) {
// Lambda function contents here.
});
\endcode
Note, the ID given to the function is not permanent. An entity's ID may change when cleanup() is called.
*/
<|endoftext|> |
<commit_before><commit_msg>tsan: fix suppress_java logic<commit_after><|endoftext|> |
<commit_before>/*
* libjingle
* Copyright 2015 Google Inc.
*
* 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 "talk/app/webrtc/androidvideocapturer.h"
#include "talk/media/webrtc/webrtcvideoframe.h"
#include "webrtc/base/bind.h"
#include "webrtc/base/callback.h"
#include "webrtc/base/common.h"
#include "webrtc/base/json.h"
#include "webrtc/base/timeutils.h"
#include "webrtc/base/thread.h"
#include "webrtc/common_video/libyuv/include/webrtc_libyuv.h"
namespace webrtc {
using cricket::WebRtcVideoFrame;
using rtc::scoped_ptr;
using rtc::scoped_refptr;
// An implementation of cricket::VideoFrameFactory for frames that are not
// guaranteed to outlive the created cricket::VideoFrame.
// A frame is injected using UpdateCapturedFrame, and converted into a
// cricket::VideoFrame with
// CreateAliasedFrame. UpdateCapturedFrame should be called before
// CreateAliasedFrame for every frame.
class AndroidVideoCapturer::FrameFactory : public cricket::VideoFrameFactory {
public:
FrameFactory(int width,
int height,
const scoped_refptr<AndroidVideoCapturerDelegate>& delegate)
: start_time_(rtc::TimeNanos()), delegate_(delegate) {
// Create a CapturedFrame that only contains header information, not the
// actual pixel data.
captured_frame_.width = width;
captured_frame_.height = height;
captured_frame_.pixel_height = 1;
captured_frame_.pixel_width = 1;
captured_frame_.rotation = 0;
captured_frame_.data = NULL;
captured_frame_.data_size = cricket::CapturedFrame::kUnknownDataSize;
captured_frame_.fourcc = static_cast<uint32>(cricket::FOURCC_ANY);
}
void UpdateCapturedFrame(void* frame_data,
int length,
int width,
int height,
int rotation,
int64 time_stamp_in_ns) {
captured_frame_.fourcc = static_cast<uint32>(cricket::FOURCC_YV12);
captured_frame_.data = frame_data;
captured_frame_.width = width;
captured_frame_.height = height;
captured_frame_.elapsed_time = rtc::TimeNanos() - start_time_;
captured_frame_.time_stamp = time_stamp_in_ns;
captured_frame_.rotation = rotation;
captured_frame_.data_size = length;
}
const cricket::CapturedFrame* GetCapturedFrame() const {
return &captured_frame_;
}
cricket::VideoFrame* CreateAliasedFrame(
const cricket::CapturedFrame* captured_frame,
int dst_width,
int dst_height) const override {
// This override of CreateAliasedFrame creates a copy of the frame since
// |captured_frame_.data| is only guaranteed to be valid during the scope
// of |AndroidVideoCapturer::OnIncomingFrame_w|.
// Check that captured_frame is actually our frame.
CHECK(captured_frame == &captured_frame_);
if (!apply_rotation_ || captured_frame->rotation == kVideoRotation_0) {
CHECK(captured_frame->fourcc == cricket::FOURCC_YV12);
const uint8_t* y_plane = static_cast<uint8_t*>(captured_frame_.data);
// Android guarantees that the stride is a multiple of 16.
// http://developer.android.com/reference/android/hardware/Camera.Parameters.html#setPreviewFormat%28int%29
int y_stride;
int uv_stride;
webrtc::Calc16ByteAlignedStride(captured_frame->width, &y_stride,
&uv_stride);
const uint8_t* v_plane = y_plane + y_stride * captured_frame->height;
const uint8_t* u_plane =
v_plane + uv_stride * webrtc::AlignInt(captured_frame->height, 2) / 2;
// Create a WrappedI420Buffer and bind the |no_longer_used| callback
// to the static method ReturnFrame. The |delegate_| is bound as an
// argument which means that the callback will hold a reference to
// |delegate_|.
rtc::scoped_refptr<WrappedI420Buffer> buffer(
new rtc::RefCountedObject<webrtc::WrappedI420Buffer>(
dst_width, dst_height, captured_frame->width,
captured_frame->height, y_plane, y_stride, u_plane, uv_stride,
v_plane, uv_stride,
rtc::Bind(&AndroidVideoCapturer::FrameFactory::ReturnFrame,
delegate_,
captured_frame->time_stamp)));
return new WebRtcVideoFrame(
buffer, captured_frame->elapsed_time,
captured_frame->time_stamp, captured_frame->GetRotation());
}
scoped_ptr<WebRtcVideoFrame> frame(new WebRtcVideoFrame());
frame->Init(captured_frame, dst_width, dst_height, apply_rotation_);
// frame->Init copies the data in |captured_frame| so it is safe to return
// the buffer immediately.
delegate_->ReturnBuffer(captured_frame->time_stamp);
return frame.release();
}
static void ReturnFrame(scoped_refptr<AndroidVideoCapturerDelegate> delegate,
int64 time_stamp) {
delegate->ReturnBuffer(time_stamp);
}
private:
uint64 start_time_;
cricket::CapturedFrame captured_frame_;
scoped_refptr<AndroidVideoCapturerDelegate> delegate_;
};
AndroidVideoCapturer::AndroidVideoCapturer(
const rtc::scoped_refptr<AndroidVideoCapturerDelegate>& delegate)
: running_(false),
delegate_(delegate),
frame_factory_(NULL),
current_state_(cricket::CS_STOPPED) {
thread_checker_.DetachFromThread();
std::string json_string = delegate_->GetSupportedFormats();
LOG(LS_INFO) << json_string;
Json::Value json_values;
Json::Reader reader(Json::Features::strictMode());
if (!reader.parse(json_string, json_values)) {
LOG(LS_ERROR) << "Failed to parse formats.";
}
std::vector<cricket::VideoFormat> formats;
for (Json::ArrayIndex i = 0; i < json_values.size(); ++i) {
const Json::Value& json_value = json_values[i];
CHECK(!json_value["width"].isNull() && !json_value["height"].isNull() &&
!json_value["framerate"].isNull());
cricket::VideoFormat format(
json_value["width"].asInt(),
json_value["height"].asInt(),
cricket::VideoFormat::FpsToInterval(json_value["framerate"].asInt()),
cricket::FOURCC_YV12);
formats.push_back(format);
}
SetSupportedFormats(formats);
}
AndroidVideoCapturer::~AndroidVideoCapturer() {
CHECK(!running_);
}
cricket::CaptureState AndroidVideoCapturer::Start(
const cricket::VideoFormat& capture_format) {
LOG(LS_INFO) << " AndroidVideoCapturer::Start w = " << capture_format.width
<< " h = " << capture_format.height;
CHECK(thread_checker_.CalledOnValidThread());
CHECK(!running_);
frame_factory_ = new AndroidVideoCapturer::FrameFactory(
capture_format.width, capture_format.height, delegate_.get());
set_frame_factory(frame_factory_);
running_ = true;
delegate_->Start(
capture_format.width, capture_format.height,
cricket::VideoFormat::IntervalToFps(capture_format.interval), this);
SetCaptureFormat(&capture_format);
current_state_ = cricket::CS_STARTING;
return current_state_;
}
void AndroidVideoCapturer::Stop() {
LOG(LS_INFO) << " AndroidVideoCapturer::Stop ";
CHECK(thread_checker_.CalledOnValidThread());
CHECK(running_);
running_ = false;
SetCaptureFormat(NULL);
delegate_->Stop();
current_state_ = cricket::CS_STOPPED;
SignalStateChange(this, current_state_);
}
bool AndroidVideoCapturer::IsRunning() {
CHECK(thread_checker_.CalledOnValidThread());
return running_;
}
bool AndroidVideoCapturer::GetPreferredFourccs(std::vector<uint32>* fourccs) {
CHECK(thread_checker_.CalledOnValidThread());
fourccs->push_back(cricket::FOURCC_YV12);
return true;
}
void AndroidVideoCapturer::OnCapturerStarted(bool success) {
CHECK(thread_checker_.CalledOnValidThread());
cricket::CaptureState new_state =
success ? cricket::CS_RUNNING : cricket::CS_FAILED;
if (new_state == current_state_)
return;
current_state_ = new_state;
// TODO(perkj): SetCaptureState can not be used since it posts to |thread_|.
// But |thread_ | is currently just the thread that happened to create the
// cricket::VideoCapturer.
SignalStateChange(this, new_state);
}
void AndroidVideoCapturer::OnIncomingFrame(void* frame_data,
int length,
int width,
int height,
int rotation,
int64 time_stamp) {
CHECK(thread_checker_.CalledOnValidThread());
frame_factory_->UpdateCapturedFrame(frame_data, length, width, height,
rotation, time_stamp);
SignalFrameCaptured(this, frame_factory_->GetCapturedFrame());
}
void AndroidVideoCapturer::OnOutputFormatRequest(
int width, int height, int fps) {
CHECK(thread_checker_.CalledOnValidThread());
const cricket::VideoFormat& current = video_adapter()->output_format();
cricket::VideoFormat format(
width, height, cricket::VideoFormat::FpsToInterval(fps), current.fourcc);
video_adapter()->OnOutputFormatRequest(format);
}
} // namespace webrtc
<commit_msg>AndroidVideoCapturer: Return frames that have been dropped<commit_after>/*
* libjingle
* Copyright 2015 Google Inc.
*
* 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 "talk/app/webrtc/androidvideocapturer.h"
#include "talk/media/webrtc/webrtcvideoframe.h"
#include "webrtc/base/bind.h"
#include "webrtc/base/callback.h"
#include "webrtc/base/common.h"
#include "webrtc/base/json.h"
#include "webrtc/base/timeutils.h"
#include "webrtc/base/thread.h"
#include "webrtc/common_video/libyuv/include/webrtc_libyuv.h"
namespace webrtc {
using cricket::WebRtcVideoFrame;
using rtc::scoped_ptr;
using rtc::scoped_refptr;
// An implementation of cricket::VideoFrameFactory for frames that are not
// guaranteed to outlive the created cricket::VideoFrame.
// A frame is injected using UpdateCapturedFrame, and converted into a
// cricket::VideoFrame with
// CreateAliasedFrame. UpdateCapturedFrame should be called before
// CreateAliasedFrame for every frame.
class AndroidVideoCapturer::FrameFactory : public cricket::VideoFrameFactory {
public:
FrameFactory(int width,
int height,
const scoped_refptr<AndroidVideoCapturerDelegate>& delegate)
: start_time_(rtc::TimeNanos()), delegate_(delegate) {
// Create a CapturedFrame that only contains header information, not the
// actual pixel data.
captured_frame_.width = width;
captured_frame_.height = height;
captured_frame_.pixel_height = 1;
captured_frame_.pixel_width = 1;
captured_frame_.rotation = 0;
captured_frame_.data = NULL;
captured_frame_.data_size = cricket::CapturedFrame::kUnknownDataSize;
captured_frame_.fourcc = static_cast<uint32>(cricket::FOURCC_ANY);
}
void UpdateCapturedFrame(void* frame_data,
int length,
int width,
int height,
int rotation,
int64 time_stamp_in_ns) {
// Make sure we don't overwrite the previous frame.
CHECK(captured_frame_.data == nullptr);
captured_frame_.fourcc = static_cast<uint32>(cricket::FOURCC_YV12);
captured_frame_.data = frame_data;
captured_frame_.width = width;
captured_frame_.height = height;
captured_frame_.elapsed_time = rtc::TimeNanos() - start_time_;
captured_frame_.time_stamp = time_stamp_in_ns;
captured_frame_.rotation = rotation;
captured_frame_.data_size = length;
}
void ClearCapturedFrame() const {
captured_frame_.data = nullptr;
captured_frame_.width = 0;
captured_frame_.height = 0;
captured_frame_.elapsed_time = 0;
captured_frame_.time_stamp = 0;
captured_frame_.data_size = 0;
}
const cricket::CapturedFrame* GetCapturedFrame() const {
return &captured_frame_;
}
cricket::VideoFrame* CreateAliasedFrame(
const cricket::CapturedFrame* captured_frame,
int dst_width,
int dst_height) const override {
// This override of CreateAliasedFrame creates a copy of the frame since
// |captured_frame_.data| is only guaranteed to be valid during the scope
// of |AndroidVideoCapturer::OnIncomingFrame_w|.
// Check that captured_frame is actually our frame.
CHECK(captured_frame == &captured_frame_);
CHECK(captured_frame->data != nullptr);
if (!apply_rotation_ || captured_frame->rotation == kVideoRotation_0) {
CHECK(captured_frame->fourcc == cricket::FOURCC_YV12);
const uint8_t* y_plane = static_cast<uint8_t*>(captured_frame_.data);
// Android guarantees that the stride is a multiple of 16.
// http://developer.android.com/reference/android/hardware/Camera.Parameters.html#setPreviewFormat%28int%29
int y_stride;
int uv_stride;
webrtc::Calc16ByteAlignedStride(captured_frame->width, &y_stride,
&uv_stride);
const uint8_t* v_plane = y_plane + y_stride * captured_frame->height;
const uint8_t* u_plane =
v_plane + uv_stride * webrtc::AlignInt(captured_frame->height, 2) / 2;
// Create a WrappedI420Buffer and bind the |no_longer_used| callback
// to the static method ReturnFrame. The |delegate_| is bound as an
// argument which means that the callback will hold a reference to
// |delegate_|.
rtc::scoped_refptr<WrappedI420Buffer> buffer(
new rtc::RefCountedObject<webrtc::WrappedI420Buffer>(
dst_width, dst_height, captured_frame->width,
captured_frame->height, y_plane, y_stride, u_plane, uv_stride,
v_plane, uv_stride,
rtc::Bind(&AndroidVideoCapturer::FrameFactory::ReturnFrame,
delegate_,
captured_frame->time_stamp)));
cricket::VideoFrame* cricket_frame = new WebRtcVideoFrame(
buffer, captured_frame->elapsed_time,
captured_frame->time_stamp, captured_frame->GetRotation());
// |cricket_frame| is now responsible for returning the frame. Clear
// |captured_frame_| so the frame isn't returned twice.
ClearCapturedFrame();
return cricket_frame;
}
scoped_ptr<WebRtcVideoFrame> frame(new WebRtcVideoFrame());
frame->Init(captured_frame, dst_width, dst_height, apply_rotation_);
return frame.release();
}
static void ReturnFrame(scoped_refptr<AndroidVideoCapturerDelegate> delegate,
int64 time_stamp) {
delegate->ReturnBuffer(time_stamp);
}
private:
uint64 start_time_;
// |captured_frame_| is mutable as a hacky way to modify it inside
// CreateAliasedframe().
mutable cricket::CapturedFrame captured_frame_;
scoped_refptr<AndroidVideoCapturerDelegate> delegate_;
};
AndroidVideoCapturer::AndroidVideoCapturer(
const rtc::scoped_refptr<AndroidVideoCapturerDelegate>& delegate)
: running_(false),
delegate_(delegate),
frame_factory_(NULL),
current_state_(cricket::CS_STOPPED) {
thread_checker_.DetachFromThread();
std::string json_string = delegate_->GetSupportedFormats();
LOG(LS_INFO) << json_string;
Json::Value json_values;
Json::Reader reader(Json::Features::strictMode());
if (!reader.parse(json_string, json_values)) {
LOG(LS_ERROR) << "Failed to parse formats.";
}
std::vector<cricket::VideoFormat> formats;
for (Json::ArrayIndex i = 0; i < json_values.size(); ++i) {
const Json::Value& json_value = json_values[i];
CHECK(!json_value["width"].isNull() && !json_value["height"].isNull() &&
!json_value["framerate"].isNull());
cricket::VideoFormat format(
json_value["width"].asInt(),
json_value["height"].asInt(),
cricket::VideoFormat::FpsToInterval(json_value["framerate"].asInt()),
cricket::FOURCC_YV12);
formats.push_back(format);
}
SetSupportedFormats(formats);
}
AndroidVideoCapturer::~AndroidVideoCapturer() {
CHECK(!running_);
}
cricket::CaptureState AndroidVideoCapturer::Start(
const cricket::VideoFormat& capture_format) {
LOG(LS_INFO) << " AndroidVideoCapturer::Start w = " << capture_format.width
<< " h = " << capture_format.height;
CHECK(thread_checker_.CalledOnValidThread());
CHECK(!running_);
frame_factory_ = new AndroidVideoCapturer::FrameFactory(
capture_format.width, capture_format.height, delegate_.get());
set_frame_factory(frame_factory_);
running_ = true;
delegate_->Start(
capture_format.width, capture_format.height,
cricket::VideoFormat::IntervalToFps(capture_format.interval), this);
SetCaptureFormat(&capture_format);
current_state_ = cricket::CS_STARTING;
return current_state_;
}
void AndroidVideoCapturer::Stop() {
LOG(LS_INFO) << " AndroidVideoCapturer::Stop ";
CHECK(thread_checker_.CalledOnValidThread());
CHECK(running_);
running_ = false;
SetCaptureFormat(NULL);
delegate_->Stop();
current_state_ = cricket::CS_STOPPED;
SignalStateChange(this, current_state_);
}
bool AndroidVideoCapturer::IsRunning() {
CHECK(thread_checker_.CalledOnValidThread());
return running_;
}
bool AndroidVideoCapturer::GetPreferredFourccs(std::vector<uint32>* fourccs) {
CHECK(thread_checker_.CalledOnValidThread());
fourccs->push_back(cricket::FOURCC_YV12);
return true;
}
void AndroidVideoCapturer::OnCapturerStarted(bool success) {
CHECK(thread_checker_.CalledOnValidThread());
cricket::CaptureState new_state =
success ? cricket::CS_RUNNING : cricket::CS_FAILED;
if (new_state == current_state_)
return;
current_state_ = new_state;
// TODO(perkj): SetCaptureState can not be used since it posts to |thread_|.
// But |thread_ | is currently just the thread that happened to create the
// cricket::VideoCapturer.
SignalStateChange(this, new_state);
}
void AndroidVideoCapturer::OnIncomingFrame(void* frame_data,
int length,
int width,
int height,
int rotation,
int64 time_stamp) {
CHECK(thread_checker_.CalledOnValidThread());
frame_factory_->UpdateCapturedFrame(frame_data, length, width, height,
rotation, time_stamp);
SignalFrameCaptured(this, frame_factory_->GetCapturedFrame());
if (frame_factory_->GetCapturedFrame()->data == nullptr) {
// Ownership has been passed to a WrappedI420Buffer. Do nothing.
} else {
// |captured_frame_| has either been copied or dropped, return it
// immediately.
delegate_->ReturnBuffer(time_stamp);
frame_factory_->ClearCapturedFrame();
}
}
void AndroidVideoCapturer::OnOutputFormatRequest(
int width, int height, int fps) {
CHECK(thread_checker_.CalledOnValidThread());
const cricket::VideoFormat& current = video_adapter()->output_format();
cricket::VideoFormat format(
width, height, cricket::VideoFormat::FpsToInterval(fps), current.fourcc);
video_adapter()->OnOutputFormatRequest(format);
}
} // namespace webrtc
<|endoftext|> |
<commit_before>
#include "QstCommInt.h"
/*****************************************************************************/
/* 普通显示 */
/*****************************************************************************/
/*
=======================================
文本数据显示
=======================================
*/
CR_API void_t
qst_txt_show (
__CR_IN__ void_t* parm,
__CR_IN__ ansi_t cha
)
{
ansi_t show[2];
sQstComm* ctx = (sQstComm*)parm;
CTextOper* opr = (CTextOper*)ctx->oper;
/* 过滤无法显示的字符 */
if (cha != CR_AC('\n') &&
cha != CR_AC('\r') && !is_printA(cha))
show[0] = CR_AC(' ');
else
show[0] = cha;
show[1] = NIL;
opr->text(show);
}
/*
=======================================
16进制数据显示
=======================================
*/
CR_API void_t
qst_hex_show (
__CR_IN__ void_t* parm,
__CR_IN__ ansi_t cha
)
{
ansi_t show[4];
sQstComm* ctx = (sQstComm*)parm;
CTextOper* opr = (CTextOper*)ctx->oper;
/* 转换成16进制数显示 */
sprintf(show, "%02X ", cha);
opr->text(show);
}
/*****************************************************************************/
/* 色彩显示 */
/*****************************************************************************/
/* ANSI 转义处理上下文 */
static uint_t s_state;
static uint_t s_at_idx;
static bool_t s_buffer;
static bool_t s_type[4]; /* 高亮 + 下划线 + 闪烁 + 反色 */
static sint_t s_color[2]; /* 前景色 + 背景色 */
static ansi_t s_attr[33];
static ansi_t* s_span = NULL;
static iDATOT* s_html = NULL;
/*
=======================================
创建 ANSI 上下文
=======================================
*/
CR_API bool_t
qst_csi_init (void_t)
{
s_state = 0;
s_buffer = FALSE;
s_span = NULL;
s_color[0] = s_color[1] = -1;
mem_zero(s_type, sizeof(s_type));
s_html = create_buff_out(512);
if (s_html == NULL)
return (FALSE);
return (TRUE);
}
/*
=======================================
释放 ANSI 上下文
=======================================
*/
CR_API void_t
qst_csi_free (void_t)
{
CR_VCALL(s_html)->release(s_html);
TRY_FREE(s_span);
}
/*
=======================================
清除 ANSI 上下文
=======================================
*/
CR_API void_t
qst_csi_clear (void_t)
{
s_state = 0;
s_buffer = FALSE;
SAFE_FREE(s_span);
s_color[0] = s_color[1] = -1;
mem_zero(s_type, sizeof(s_type));
CR_VCALL(s_html)->reput(s_html, 0);
}
/* 颜色常数表 */
static const ansi_t* s_lo_color[] =
{
"#000000;", "#800000;", "#008000;", "#808000;",
"#000080;", "#800080;", "#008080;", "#C0C0C0;",
};
static const ansi_t* s_hi_color[] =
{
"#808080;", "#FF0000;", "#00FF00;", "#FFFF00;",
"#0000FF;", "#FF00FF;", "#00FFFF;", "#FFFFFF;",
};
/*
---------------------------------------
处理 ANSI 转义属性
---------------------------------------
*/
static void_t
qst_csi_render (
__CR_IN__ CTextOper* opr
)
{
uint_t at[3];
leng_t count;
ansi_t** attrs;
if (s_buffer)
{
ansi_t* str;
ansi_t* send;
/* 发送之前的 HTML 串 */
CR_VCALL(s_html)->write(s_html, "</span>", 8);
str = (ansi_t*)(CR_VCALL(s_html)->flush(s_html));
send = str_fmtA("%s%s", s_span, str);
if (send != NULL) {
opr->html(send);
mem_free(send);
}
CR_VCALL(s_html)->reput(s_html, 0);
SAFE_FREE(s_span);
}
/* 解析转义属性 */
attrs = str_splitA(s_attr, ';', &count);
if (attrs == NULL)
return;
if (count > cntsof(at))
count = cntsof(at);
for (leng_t idx = 0; idx < count; idx++) {
at[idx] = str2intA(attrs[idx]);
if (at[idx] == 0) {
s_color[0] = s_color[1] = -1;
mem_zero(s_type, sizeof(s_type));
mem_free(attrs);
s_buffer = FALSE;
return;
}
}
mem_free(attrs);
s_buffer = TRUE;
const ansi_t* tx = "";
const ansi_t* fg = "";
const ansi_t* bk = "";
const ansi_t* fc = "";
const ansi_t* bc = "";
/* 加入相应的 HTML 标签 */
for (leng_t idx = 0; idx < count; idx++) {
switch (at[idx])
{
default: /* 颜色 */
if (at[idx] >= 30 && at[idx] <= 37)
s_color[0] = at[idx] - 30;
else
if (at[idx] >= 40 && at[idx] <= 47)
s_color[1] = at[idx] - 40;
break;
case 1: /* 高亮 */
s_type[0] = TRUE;
break;
case 4: /* 下划线 */
s_type[1] = TRUE;
break;
case 24:
s_type[1] = FALSE;
break;
case 5: /* 闪烁 */
s_type[2] = TRUE;
break;
case 25:
s_type[2] = FALSE;
break;
case 7: /* 反色 */
s_type[3] = TRUE;
break;
case 27:
s_type[3] = FALSE;
break;
}
}
/* 颜色风格 */
if (s_color[0] > 0) {
if (s_type[0])
fc = s_hi_color[s_color[0]];
else
fc = s_lo_color[s_color[0]];
}
if (s_color[1] > 0) {
if (s_type[0])
bc = s_hi_color[s_color[1]];
else
bc = s_lo_color[s_color[1]];
}
/* 下划线风格 */
if (s_type[1])
tx = "text-decoration:underline;";
/* 反色风格 */
if (s_type[3]) {
if (s_color[0] > 0)
fg = "background-color:";
if (s_color[1] > 0)
bk = "color:";
}
else {
if (s_color[0] > 0)
fg = "color:";
if (s_color[1] > 0)
bk = "background-color:";
}
s_span = str_fmtA("<span style=\"%s%s%s%s%s\">", tx, fg, fc, bk, bc);
}
/*
---------------------------------------
输出 HTML 转义字符
---------------------------------------
*/
static void_t
qst_csi_output (
__CR_IN__ CTextOper* opr,
__CR_IN__ ansi_t cha
)
{
ansi_t* str;
ansi_t* send;
if (cha == CR_AC('\"')) {
CR_VCALL(s_html)->write(s_html, """, 6);
}
else
if (cha == CR_AC('&')) {
CR_VCALL(s_html)->write(s_html, "&", 5);
}
else
if (cha == CR_AC('\'')) {
CR_VCALL(s_html)->write(s_html, "'", 6);
}
else
if (cha == CR_AC('<')) {
CR_VCALL(s_html)->write(s_html, "<", 4);
}
else
if (cha == CR_AC('>')) {
CR_VCALL(s_html)->write(s_html, ">", 4);
}
else
if (cha == CR_AC('\r') || cha == CR_AC('\n')) {
CR_VCALL(s_html)->write(s_html, "</span><br>", 12);
str = (ansi_t*)(CR_VCALL(s_html)->flush(s_html));
send = str_fmtA("%s%s", s_span, str);
if (send != NULL) {
opr->html(send);
mem_free(send);
}
CR_VCALL(s_html)->reput(s_html, 0);
}
else {
CR_VCALL(s_html)->putb_no(s_html, cha);
}
}
/*
=======================================
ANSI 转义文本显示
=======================================
*/
CR_API void_t
qst_csi_show (
__CR_IN__ void_t* parm,
__CR_IN__ ansi_t cha
)
{
ansi_t show[4];
sQstComm* ctx = (sQstComm*)parm;
CTextOper* opr = (CTextOper*)ctx->oper;
switch (s_state)
{
case 0: /* 查找 ESC 阶段 */
if (cha != 0x1B) {
if (cha != CR_AC('\n') &&
cha != CR_AC('\r') && !is_printA(cha))
show[0] = CR_AC(' ');
else
show[0] = cha;
show[1] = NIL;
if (s_buffer)
qst_csi_output(opr, show[0]);
else
opr->text(show);
}
else {
s_state += 1;
}
break;
case 1: /* 查找 '[' 阶段 */
if (cha != CR_AC('[')) {
show[0] = CR_AC(' ');
if (cha != CR_AC('\n') &&
cha != CR_AC('\r') && !is_printA(cha))
show[1] = CR_AC(' ');
else
show[1] = cha;
show[2] = NIL;
if (s_buffer) {
qst_csi_output(opr, show[0]);
qst_csi_output(opr, show[1]);
}
else {
opr->text(show);
}
s_state = 0;
}
else {
s_state += 1;
s_at_idx = 0;
}
break;
default:
/* case 2: */ /* 查找 'm' 阶段 */
if (cha == CR_AC('m') ||
s_at_idx >= sizeof(s_attr) - 1) {
s_attr[s_at_idx] = NIL;
qst_csi_render(opr);
s_state = 0;
}
else {
s_attr[s_at_idx++] = cha;
}
break;
}
}
<commit_msg>QstComm: 修正 ANSI 渲染的逻辑问题<commit_after>
#include "QstCommInt.h"
/*****************************************************************************/
/* 普通显示 */
/*****************************************************************************/
/*
=======================================
文本数据显示
=======================================
*/
CR_API void_t
qst_txt_show (
__CR_IN__ void_t* parm,
__CR_IN__ ansi_t cha
)
{
ansi_t show[2];
sQstComm* ctx = (sQstComm*)parm;
CTextOper* opr = (CTextOper*)ctx->oper;
/* 过滤无法显示的字符 */
if (cha != CR_AC('\n') &&
cha != CR_AC('\r') && !is_printA(cha))
show[0] = CR_AC(' ');
else
show[0] = cha;
show[1] = NIL;
opr->text(show);
}
/*
=======================================
16进制数据显示
=======================================
*/
CR_API void_t
qst_hex_show (
__CR_IN__ void_t* parm,
__CR_IN__ ansi_t cha
)
{
ansi_t show[4];
sQstComm* ctx = (sQstComm*)parm;
CTextOper* opr = (CTextOper*)ctx->oper;
/* 转换成16进制数显示 */
sprintf(show, "%02X ", cha);
opr->text(show);
}
/*****************************************************************************/
/* 色彩显示 */
/*****************************************************************************/
/* ANSI 转义处理上下文 */
static bool_t s_have;
static bool_t s_buffer;
static uint_t s_state;
static uint_t s_at_idx;
static bool_t s_type[6]; /* 高亮 + 下划线 + 上划线 + 中划线 + 反色 + 闪烁 */
static sint_t s_color[2]; /* 前景色 + 背景色 */
static ansi_t s_attr[33];
static iDATOT* s_html = NULL;
/*
=======================================
创建 ANSI 上下文
=======================================
*/
CR_API bool_t
qst_csi_init (void_t)
{
s_state = 0;
s_have = s_buffer = FALSE;
s_color[0] = s_color[1] = -1;
mem_zero(s_type, sizeof(s_type));
s_html = create_buff_out(512);
if (s_html == NULL)
return (FALSE);
return (TRUE);
}
/*
=======================================
释放 ANSI 上下文
=======================================
*/
CR_API void_t
qst_csi_free (void_t)
{
CR_VCALL(s_html)->release(s_html);
}
/*
=======================================
清除 ANSI 上下文
=======================================
*/
CR_API void_t
qst_csi_clear (void_t)
{
s_state = 0;
s_have = s_buffer = FALSE;
s_color[0] = s_color[1] = -1;
mem_zero(s_type, sizeof(s_type));
CR_VCALL(s_html)->reput(s_html, 0);
}
/* 颜色常数表 */
static const ansi_t* s_lo_color[] =
{
"#000000;", "#800000;", "#008000;", "#808000;",
"#000080;", "#800080;", "#008080;", "#C0C0C0;",
};
static const ansi_t* s_hi_color[] =
{
"#808080;", "#FF0000;", "#00FF00;", "#FFFF00;",
"#0000FF;", "#FF00FF;", "#00FFFF;", "#FFFFFF;",
};
/*
---------------------------------------
渲染 ANSI 字符串
---------------------------------------
*/
static void_t
qst_csi_render (
__CR_IN__ CTextOper* opr,
__CR_IN__ const ansi_t* tail
)
{
ansi_t* str;
ansi_t* send;
ansi_t* span;
const ansi_t* fg = "";
const ansi_t* bk = "";
const ansi_t* fc = "";
const ansi_t* bc = "";
const ansi_t* tx = "text-decoration:none;";
/* 颜色风格 */
if (s_color[0] > 0) {
if (s_type[0])
fc = s_hi_color[s_color[0]];
else
fc = s_lo_color[s_color[0]];
}
if (s_color[1] > 0) {
if (s_type[0])
bc = s_hi_color[s_color[1]];
else
bc = s_lo_color[s_color[1]];
}
/* 下划线|划线风格 */
if (s_type[1])
tx = "text-decoration:underline;";
else
if (s_type[2])
tx = "text-decoration:overline;";
else
if (s_type[3])
tx = "text-decoration:line-through;";
/* 反色风格 */
if (s_type[4]) {
if (s_color[0] > 0)
fg = "background-color:";
if (s_color[1] > 0)
bk = "color:";
}
else {
if (s_color[0] > 0)
fg = "color:";
if (s_color[1] > 0)
bk = "background-color:";
}
/* 闪烁风格 - 未实现 */
/*********************/
span = str_fmtA("<span style=\"%s%s%s%s%s\">", tx, fg, fc, bk, bc);
if (span != NULL) {
if (tail != NULL) {
CR_VCALL(s_html)->write(s_html, "</span>", 7);
CR_VCALL(s_html)->write(s_html, tail, str_sizeA(tail));
}
else {
CR_VCALL(s_html)->write(s_html, "</span>", 8);
}
str = (ansi_t*)(CR_VCALL(s_html)->flush(s_html));
send = str_fmtA("%s%s", span, str);
if (send != NULL) {
opr->html(send);
mem_free(send);
}
CR_VCALL(s_html)->reput(s_html, 0);
s_have = FALSE;
mem_free(span);
}
}
/*
---------------------------------------
处理 ANSI 转义属性
---------------------------------------
*/
static void_t
qst_csi_attrib (
__CR_IN__ CTextOper* opr
)
{
leng_t idx;
uint_t at[8];
leng_t count;
ansi_t** attrs;
/* 发送上次结果 */
if (s_have)
qst_csi_render(opr, NULL);
/* 解析转义属性 */
attrs = str_splitA(s_attr, ';', &count);
if (attrs == NULL)
return;
if (count > cntsof(at))
count = cntsof(at);
for (idx = 0; idx < count; idx++) {
at[idx] = str2intA(attrs[idx]);
if (at[idx] == 0) {
s_have = s_buffer = FALSE;
s_color[0] = s_color[1] = -1;
mem_zero(s_type, sizeof(s_type));
mem_free(attrs);
return;
}
}
mem_free(attrs);
s_buffer = TRUE;
for (idx = 0; idx < count; idx++) {
switch (at[idx])
{
default: /* 颜色 */
if (at[idx] >= 30 && at[idx] <= 37)
s_color[0] = at[idx] - 30;
else
if (at[idx] >= 40 && at[idx] <= 47)
s_color[1] = at[idx] - 40;
break;
case 1: /* 高亮 */
s_type[0] = TRUE;
break;
case 4: /* 下划线 */
s_type[1] = TRUE;
break;
case 24:
s_type[1] = FALSE;
break;
case 53: /* 上划线 */
s_type[2] = TRUE;
break;
case 55:
s_type[2] = FALSE;
break;
case 9: /* 中划线 */
s_type[3] = TRUE;
break;
case 29:
s_type[3] = FALSE;
break;
case 7: /* 反色 */
s_type[4] = TRUE;
break;
case 27:
s_type[4] = FALSE;
break;
case 5: /* 闪烁 */
s_type[5] = TRUE;
break;
case 25:
s_type[5] = FALSE;
break;
}
}
}
/*
---------------------------------------
输出 HTML 转义字符
---------------------------------------
*/
static void_t
qst_csi_output (
__CR_IN__ CTextOper* opr,
__CR_IN__ ansi_t cha
)
{
if (cha == CR_AC('\"')) {
s_have = TRUE;
CR_VCALL(s_html)->write(s_html, """, 6);
}
else
if (cha == CR_AC('&')) {
s_have = TRUE;
CR_VCALL(s_html)->write(s_html, "&", 5);
}
else
if (cha == CR_AC('\'')) {
s_have = TRUE;
CR_VCALL(s_html)->write(s_html, "'", 6);
}
else
if (cha == CR_AC('<')) {
s_have = TRUE;
CR_VCALL(s_html)->write(s_html, "<", 4);
}
else
if (cha == CR_AC('>')) {
s_have = TRUE;
CR_VCALL(s_html)->write(s_html, ">", 4);
}
else
if (cha == CR_AC('\r') || cha == CR_AC('\n')) {
qst_csi_render(opr, "<br>");
}
else {
s_have = TRUE;
CR_VCALL(s_html)->putb_no(s_html, cha);
}
}
/*
=======================================
ANSI 转义文本显示
=======================================
*/
CR_API void_t
qst_csi_show (
__CR_IN__ void_t* parm,
__CR_IN__ ansi_t cha
)
{
ansi_t show[4];
sQstComm* ctx = (sQstComm*)parm;
CTextOper* opr = (CTextOper*)ctx->oper;
switch (s_state)
{
case 0: /* 查找 ESC 阶段 */
if (cha != 0x1B) {
if (cha != CR_AC('\n') &&
cha != CR_AC('\r') && !is_printA(cha))
show[0] = CR_AC(' ');
else
show[0] = cha;
show[1] = NIL;
if (s_buffer)
qst_csi_output(opr, show[0]);
else
opr->text(show);
}
else {
s_state += 1;
}
break;
case 1: /* 查找 '[' 阶段 */
if (cha != CR_AC('[')) {
show[0] = CR_AC(' ');
if (cha != CR_AC('\n') &&
cha != CR_AC('\r') && !is_printA(cha))
show[1] = CR_AC(' ');
else
show[1] = cha;
show[2] = NIL;
if (s_buffer) {
qst_csi_output(opr, show[0]);
qst_csi_output(opr, show[1]);
}
else {
opr->text(show);
}
s_state = 0;
}
else {
s_state += 1;
s_at_idx = 0;
}
break;
default:
/* case 2: */ /* 查找 'm' 阶段 */
if (cha == CR_AC('m') ||
s_at_idx >= sizeof(s_attr) - 1) {
s_attr[s_at_idx] = NIL;
qst_csi_attrib(opr);
s_state = 0;
}
else {
s_attr[s_at_idx++] = cha;
}
break;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved
*/
#include "../StroikaPreComp.h"
#include "Activity.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::Execution;
/*
********************************************************************************
*********************** Activity<Characters::String> ***************************
********************************************************************************
*/
Characters::String Activity<Characters::String>::AsString () const
{
return fArg_;
}
/*
********************************************************************************
*************************** Activity<wstring_view> *****************************
********************************************************************************
*/
Characters::String Activity<wstring_view>::AsString () const
{
return fArg_;
}
/*
********************************************************************************
****************** Execution::CaptureCurrentActivities *************************
********************************************************************************
*/
Containers::Stack<Activity<>> Execution::CaptureCurrentActivities ()
{
vector<Activity<>> rv;
// no locks needed because thread local
for (const Private_::Activities_::StackElt_* si = Private_::Activities_::sTop_; si != nullptr; si = si->fPrev) {
AssertNotNull (si->fActivity);
rv.push_back (Activity<>{si->fActivity->AsString ()});
}
Containers::Stack<Activity<>> result;
for (auto i = rv.rbegin (); i != rv.rend (); ++i) {
result.Push (*i);
}
return result;
}
<commit_msg>fixed Execution::CaptureCurrentActivities ()<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved
*/
#include "../StroikaPreComp.h"
#include <list>
#include "../Debug/Trace.h"
#include "Activity.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::Execution;
/*
********************************************************************************
*********************** Activity<Characters::String> ***************************
********************************************************************************
*/
Characters::String Activity<Characters::String>::AsString () const
{
return fArg_;
}
/*
********************************************************************************
*************************** Activity<wstring_view> *****************************
********************************************************************************
*/
Characters::String Activity<wstring_view>::AsString () const
{
return fArg_;
}
/*
********************************************************************************
****************** Execution::CaptureCurrentActivities *************************
********************************************************************************
*/
Containers::Stack<Activity<>> Execution::CaptureCurrentActivities ()
{
list<Activity<>> rv;
// no locks needed because thread local
for (const Private_::Activities_::StackElt_* si = Private_::Activities_::sTop_; si != nullptr; si = si->fPrev) {
AssertNotNull (si->fActivity);
rv.push_front (Activity<>{si->fActivity->AsString ()});
}
Containers::Stack<Activity<>> result;
for (auto i = rv.rbegin (); i != rv.rend (); ++i) {
result.Push (*i);
}
return result;
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <malloc.h>
typedef enum{
MIN_HEAP,
MAX_HEAP
}heap_type_t;
typedef struct{
heap_type_t type;
size_t length;
size_t itemSize;
size_t size;
void* data;
}heap_t;
int heap_init(heap_t* heap, heap_type_t type, size_t itemSize, size_t size)
{
heap->type=type;
heap->length=0;
heap->size=size;
heap->itemSize=itemSize;
heap->data=(void*)malloc(itemSize*size);
return heap->data ? 1 : 0;
}
void heap_close(heap_t *heap)
{
free(heap->data);
heap->length=heap->size=heap->itemSize=0;
heap->data=NULL;
}
#define __swap(type, arr, p0, p1) do{\
type temp = (arr)[(p0)];\
(arr)[(p0)] = (arr)[(p1)];\
(arr)[(p1)] = (temp);\
}while(0)
typedef long item_t;
int heap_push(heap_t *heap, item_t value){
size_t sizeNew;
void* dataNew;
size_t pos=heap->length, parentPos;
item_t *heapData;
/* Heap space memory expansion */
if(heap->length >= heap->size){
sizeNew=heap->size+((heap->size)>>1);
dataNew=(void*)realloc(heap->data,(heap->itemSize)*sizeNew);
if(!dataNew){
return 0;
}
heap->data=dataNew;
heap->size=sizeNew;
}
/* Handle heap push */
heapData=(item_t*)(heap->data);
heapData[heap->length]=value;
heap->length++;
while(pos){
parentPos=(pos-1)>>1;
if((MIN_HEAP==heap->type && heapData[parentPos]<=heapData[pos])
|| (MAX_HEAP==heap->type && heapData[parentPos]>=heapData[pos])){
break;
}
__swap(item_t, heapData, parentPos, pos);
pos=parentPos;
}
return 1;
}
int heap_pop(heap_t *heap, item_t *item)
{
item_t *arrData=(item_t*)(heap->data), heapTopOrig,
value, leftVal, rightVal, temp;
size_t pos=0, length, leftPos, rightPos;
if(!(heap->length)){
return 0;
}
*item = arrData[0];
(heap->length)--;
if(!(heap->length)){
return 1;
}
arrData[0]=arrData[heap->length];
length=heap->length;
while(pos<length){
value=arrData[pos]; leftPos=(pos<<1)+1; rightPos=(pos<<1)+2;
if(rightPos>=length){
if(leftPos>=length){
break;
}
leftVal=arrData[leftPos];
if((MIN_HEAP==heap->type && leftVal<value)
||(MAX_HEAP==heap->type && leftVal>value)){
__swap(item_t, arrData, leftPos, pos);
}
break;
}
leftVal=arrData[leftPos]; rightVal=arrData[rightPos];
if((MIN_HEAP==heap->type && value<=leftVal && value<=rightVal)
||(MAX_HEAP==heap->type && value>=leftVal && value>=rightVal)){
break;
}
if((MIN_HEAP==heap->type && leftVal<=rightVal)
||(MAX_HEAP==heap->type && leftVal>=rightVal)){
__swap(item_t, arrData, leftPos, pos);
pos=leftPos;
}else{
__swap(item_t, arrData, rightPos, pos);
pos=rightPos;
}
}
return 1;
}
void printHelp()
{
fputs("Usage: topn.exe count\n", stderr);
fputs(" count parameter in negative value means smallest n numbers.", stderr);
}
int main(int argc, char *argv[])
{
int maxn=0,i;
long inputCount = 0;
size_t count;
heap_t heap;
item_t heapTop, input, outval, *sorted;
if (argc <= 1) {
printHelp();
return 1;
}
inputCount = atol(argv[1]);
if (inputCount == 0) {
printHelp();
return 1;
}
if (inputCount < 0) {
maxn = 0;
count = -inputCount;
} else {
maxn = 1;
count = inputCount;
}
heap_init(&heap, maxn?MIN_HEAP:MAX_HEAP, sizeof(item_t), count+1);
sorted=(item_t*)malloc(sizeof(item_t)*count);
while(EOF!=scanf("%d",&input)){
if(heap.length<count){
heap_push(&heap, input);
continue;
}
heapTop=((item_t*)(heap.data))[0];
if((maxn && input>heapTop) || (!maxn && input<heapTop)){
heap_push(&heap, input);
heap_pop(&heap, &outval);
}
}
i=0;
while(heap_pop(&heap, &outval)){
sorted[i]=outval;
i++;
}
while(i--){
printf("%u\n",sorted[i]);
}
free(sorted);
heap_close(&heap);
return 0;
}<commit_msg>Updated<commit_after>#include <stdio.h>
#include <malloc.h>
typedef enum{
MIN_HEAP,
MAX_HEAP
}heap_type_t;
typedef struct{
heap_type_t type;
size_t length;
size_t itemSize;
size_t size;
void* data;
}heap_t;
int heap_init(heap_t* heap, heap_type_t type, size_t itemSize, size_t size)
{
heap->type=type;
heap->length=0;
heap->size=size;
heap->itemSize=itemSize;
heap->data=(void*)malloc(itemSize*size);
return heap->data ? 1 : 0;
}
void heap_close(heap_t *heap)
{
free(heap->data);
heap->length=heap->size=heap->itemSize=0;
heap->data=NULL;
}
#define __swap(type, arr, p0, p1) do{\
type temp = (arr)[(p0)];\
(arr)[(p0)] = (arr)[(p1)];\
(arr)[(p1)] = (temp);\
}while(0)
typedef long item_t;
int heap_push(heap_t *heap, item_t value){
size_t sizeNew;
void* dataNew;
size_t pos=heap->length, parentPos;
item_t *heapData;
/* Heap space memory expansion */
if(heap->length >= heap->size){
sizeNew=heap->size+((heap->size)>>1);
dataNew=(void*)realloc(heap->data,(heap->itemSize)*sizeNew);
if(!dataNew){
return 0;
}
heap->data=dataNew;
heap->size=sizeNew;
}
/* Handle heap push */
heapData=(item_t*)(heap->data);
heapData[heap->length]=value;
heap->length++;
while(pos){
parentPos=(pos-1)>>1;
if((MIN_HEAP==heap->type && heapData[parentPos]<=heapData[pos])
|| (MAX_HEAP==heap->type && heapData[parentPos]>=heapData[pos])){
break;
}
__swap(item_t, heapData, parentPos, pos);
pos=parentPos;
}
return 1;
}
int heap_pop(heap_t *heap, item_t *item)
{
item_t *arrData=(item_t*)(heap->data), heapTopOrig,
value, leftVal, rightVal, temp;
size_t pos=0, length, leftPos, rightPos;
if(!(heap->length)){
return 0;
}
*item = arrData[0];
(heap->length)--;
if(!(heap->length)){
return 1;
}
arrData[0]=arrData[heap->length];
length=heap->length;
while(pos<length){
value=arrData[pos]; leftPos=(pos<<1)+1; rightPos=(pos<<1)+2;
if(rightPos>=length){
if(leftPos>=length){
break;
}
leftVal=arrData[leftPos];
if((MIN_HEAP==heap->type && leftVal<value)
||(MAX_HEAP==heap->type && leftVal>value)){
__swap(item_t, arrData, leftPos, pos);
}
break;
}
leftVal=arrData[leftPos]; rightVal=arrData[rightPos];
if((MIN_HEAP==heap->type && value<=leftVal && value<=rightVal)
||(MAX_HEAP==heap->type && value>=leftVal && value>=rightVal)){
break;
}
if((MIN_HEAP==heap->type && leftVal<=rightVal)
||(MAX_HEAP==heap->type && leftVal>=rightVal)){
__swap(item_t, arrData, leftPos, pos);
pos=leftPos;
}else{
__swap(item_t, arrData, rightPos, pos);
pos=rightPos;
}
}
return 1;
}
void printHelp()
{
fputs("Usage: topn.exe count\n", stderr);
fputs(" count parameter in negative value means smallest n numbers.", stderr);
}
int main(int argc, char *argv[])
{
int maxn=0,i;
long inputCount = 0;
size_t count;
heap_t heap;
item_t heapTop, input, outval, *sorted;
if (argc <= 1) {
printHelp();
return 1;
}
inputCount = atol(argv[1]);
if (inputCount == 0) {
printHelp();
return 1;
}
if (inputCount < 0) {
maxn = 0;
count = -inputCount;
} else {
maxn = 1;
count = inputCount;
}
heap_init(&heap, maxn?MIN_HEAP:MAX_HEAP, sizeof(item_t), count+1);
sorted=(item_t*)malloc(sizeof(item_t)*count);
while(EOF!=scanf("%ld",&input)){
if(heap.length<count){
heap_push(&heap, input);
continue;
}
heapTop=((item_t*)(heap.data))[0];
if((maxn && input>heapTop) || (!maxn && input<heapTop)){
heap_push(&heap, input);
heap_pop(&heap, &outval);
}
}
i=0;
while(heap_pop(&heap, &outval)){
sorted[i]=outval;
i++;
}
while(i--){
printf("%ld\n",sorted[i]);
}
free(sorted);
heap_close(&heap);
return 0;
}<|endoftext|> |
<commit_before>/*
* Tree.hpp -- tree structure and algorithms
*
* Copyright (c) 2007-2010, Frank Mertens
*
* See ../LICENSE for the license.
*/
#ifndef PONA_TREE_HPP
#define PONA_TREE_HPP
#include "atoms"
namespace pona
{
class Tree: public Instance
{
public:
typedef Tree Node;
~Tree();
inline Ref<Node> parent() const { return parent_; }
inline Ref<Node> firstChild() const { return firstChild_; }
inline Ref<Node> lastChild() const { return lastChild_; }
inline Ref<Node> nextSibling() const { return nextSibling_; }
inline Ref<Node> previousSibling() const { return previousSibling_; }
inline void appendChild(Ref<Node> node) { insertChild(node, lastChild_); }
void insertChild(Ref<Node> node, Ref<Node> previousSibling = 0);
void appendAllChildrenOf(Ref<Node> node);
void unlink();
// iterating leafs
Ref<Node> firstLeaf() const;
Ref<Node> lastLeaf() const;
Ref<Node> nextLeaf() const;
Ref<Node> previousLeaf() const;
// iterating all nodes
inline Ref<Node> first() const { return firstLeaf(); }
inline Ref<Node> last() const { return lastLeaf(); }
inline Ref<Node> next() const { return (nextSibling_) ? nextSibling_->firstLeaf() : parent_; }
inline Ref<Node> previous() const { return (previousSibling_) ? previousSibling_->lastLeaf() : parent_; }
inline int countChildren() const {
return (firstChild_) ? firstChild_->countSiblings() : 0;
}
int countSiblings() const;
/** Duplicate a tree structure with optionally omitting nodes which do not
* meat a filter criteria.
*/
template<template<class> class Filter, class TreeType>
static Ref<TreeType, Owner> duplicate(Ref<TreeType> original);
/** Pass-through filter.
*/
template<class TreeType>
class IncludeAll {
public:
inline static bool pass(Ref<TreeType>) { return true; }
};
/** Convenience method.
*/
template<class TreeType>
inline static Ref<TreeType, Owner> duplicate(Ref<TreeType> original) {
return duplicate<TreeType, IncludeAll>(original);
}
private:
Ref<Node, SetNull> parent_;
Ref<Node, Owner> firstChild_;
Ref<Node, Owner> lastChild_;
Ref<Node, Owner> nextSibling_;
Ref<Node, SetNull> previousSibling_;
};
template<template<class> class Filter, class TreeType>
Ref<TreeType, Owner> Tree::duplicate(Ref<TreeType> original)
{
Ref<TreeType, Owner> newTree = new TreeType(*original);
check(!newTree->firstChild_);
Ref<TreeType> child = original->firstChild();
while (child) {
if (Filter<TreeType>::pass(child)) {
Ref<TreeType, Owner> newChild = duplicate(child);
newTree->appendChild(newChild);
}
child = child->nextSibling_;
}
return newTree;
}
} // namespace pona
#endif // PONA_TREE_HPP
<commit_msg>Build fixes.<commit_after>/*
* Tree.hpp -- tree structure and algorithms
*
* Copyright (c) 2007-2010, Frank Mertens
*
* See ../LICENSE for the license.
*/
#ifndef PONA_TREE_HPP
#define PONA_TREE_HPP
#include "atoms"
namespace pona
{
class Tree: public Instance
{
public:
typedef Tree Node;
~Tree();
inline Ref<Node> parent() const { return parent_; }
inline Ref<Node> firstChild() const { return firstChild_; }
inline Ref<Node> lastChild() const { return lastChild_; }
inline Ref<Node> nextSibling() const { return nextSibling_; }
inline Ref<Node> previousSibling() const { return previousSibling_; }
inline void appendChild(Ref<Node> node) { insertChild(node, lastChild_); }
void insertChild(Ref<Node> node, Ref<Node> previousSibling = 0);
void appendAllChildrenOf(Ref<Node> node);
void unlink();
// iterating leafs
Ref<Node> firstLeaf() const;
Ref<Node> lastLeaf() const;
Ref<Node> nextLeaf() const;
Ref<Node> previousLeaf() const;
// iterating all nodes
inline Ref<Node> first() const { return firstLeaf(); }
inline Ref<Node> last() const { return lastLeaf(); }
inline Ref<Node> next() const { return (nextSibling_) ? nextSibling_->firstLeaf() : parent(); }
inline Ref<Node> previous() const { return (previousSibling_) ? previousSibling_->lastLeaf() : parent(); }
inline int countChildren() const {
return (firstChild_) ? firstChild_->countSiblings() : 0;
}
int countSiblings() const;
/** Duplicate a tree structure with optionally omitting nodes which do not
* meat a filter criteria.
*/
template<template<class> class Filter, class TreeType>
static Ref<TreeType, Owner> duplicate(Ref<TreeType> original);
/** Pass-through filter.
*/
template<class TreeType>
class IncludeAll {
public:
inline static bool pass(Ref<TreeType>) { return true; }
};
/** Convenience method.
*/
template<class TreeType>
inline static Ref<TreeType, Owner> duplicate(Ref<TreeType> original) {
return duplicate<TreeType, IncludeAll>(original);
}
private:
Ref<Node, SetNull> parent_;
Ref<Node, Owner> firstChild_;
Ref<Node, Owner> lastChild_;
Ref<Node, Owner> nextSibling_;
Ref<Node, SetNull> previousSibling_;
};
template<template<class> class Filter, class TreeType>
Ref<TreeType, Owner> Tree::duplicate(Ref<TreeType> original)
{
Ref<TreeType, Owner> newTree = new TreeType(*original);
check(!newTree->firstChild_);
Ref<TreeType> child = original->firstChild();
while (child) {
if (Filter<TreeType>::pass(child)) {
Ref<TreeType, Owner> newChild = duplicate(child);
newTree->appendChild(newChild);
}
child = child->nextSibling_;
}
return newTree;
}
} // namespace pona
#endif // PONA_TREE_HPP
<|endoftext|> |
<commit_before>
#include "config_palettizer.cxx"
#include "destTextureImage.cxx"
#include "eggFile.cxx"
#include "filenameUnifier.cxx"
#include "imageFile.cxx"
#include "omitReason.cxx"
#include "pal_string_utils.cxx"
#include "paletteGroup.cxx"
#include "paletteGroups.cxx"
#include "paletteImage.cxx"
#include "palettePage.cxx"
#include "palettizer.cxx"
#include "sourceTextureImage.cxx"
#include "textureImage.cxx"
#include "textureMemoryCounter.cxx"
#include "texturePlacement.cxx"
#include "texturePosition.cxx"
#include "textureProperties.cxx"
#include "textureReference.cxx"
#include "textureRequest.cxx"
#include "txaFile.cxx"
#include "txaLine.cxx"
<commit_msg>dos2unix<commit_after>
#include "config_palettizer.cxx"
#include "destTextureImage.cxx"
#include "eggFile.cxx"
#include "filenameUnifier.cxx"
#include "imageFile.cxx"
#include "omitReason.cxx"
#include "pal_string_utils.cxx"
#include "paletteGroup.cxx"
#include "paletteGroups.cxx"
#include "paletteImage.cxx"
#include "palettePage.cxx"
#include "palettizer.cxx"
#include "sourceTextureImage.cxx"
#include "textureImage.cxx"
#include "textureMemoryCounter.cxx"
#include "texturePlacement.cxx"
#include "texturePosition.cxx"
#include "textureProperties.cxx"
#include "textureReference.cxx"
#include "textureRequest.cxx"
#include "txaFile.cxx"
#include "txaLine.cxx"
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <string>
#include "notch.hpp"
#include "notch_io.hpp" // IDXReader
#include "notch_pre.hpp" // OneHotEncoder
#include "notch_metrics.hpp" // AClassifier
using namespace std;
const string IMAGES_FILE = "../data/train-images-idx3-ubyte";
const string LABELS_FILE = "../data/train-labels-idx1-ubyte";
const string IMAGES_TEST_FILE = "../data/t10k-images-idx3-ubyte";
const string LABELS_TEST_FILE = "../data/t10k-labels-idx1-ubyte";
const string SAVE_NETWORK_SNAPSHOT = "demo_mnist_network.txt";
LabeledDataset readMNIST(const string &imagesFile, const string labelsFile) {
ifstream trainImages(imagesFile, ios_base::binary);
if (!trainImages.is_open()) {
cerr << "Can't open file " << imagesFile << "\n"
<< "Run getmnist.py in ../data/ to download data\n";
exit(0);
}
ifstream trainLabels(labelsFile, ios_base::binary);
if (!trainLabels.is_open()) {
cerr << "Can't open file " << labelsFile << "\n"
<< "Run getmnist.py in ../data/ to download data\n";
exit(0);
}
cout << "reading MNIST images from " << imagesFile << "\n";
cout << "reading MNIST labels from " << labelsFile << "\n";
LabeledDataset mnist = IDXReader().read(trainImages, trainLabels);
return mnist;
}
class IntClassifier : public AClassifier < int, 1 > {
private:
OneHotEncoder &enc;
Net &net;
public:
IntClassifier(Net &net, OneHotEncoder &enc)
: enc(enc), net(net) {}
virtual int aslabel(const Output &out) {
return enc.unapply(out)[0];
}
virtual int classify(const Input &in) {
return enc.unapply(net.output(in))[0];
}
};
float meanLossEstimate(Net &net, LabeledDataset &dataset, size_t maxcount=0) {
float total;
size_t n = 0;
for (auto sample : dataset) {
total += net.loss(sample.data, sample.label);
n++;
if (maxcount > 0 && n >= maxcount) {
break;
}
}
return total / n;
}
int main() {
LabeledDataset mnist = readMNIST(IMAGES_FILE, LABELS_FILE);
LabeledDataset mnistTest = readMNIST(IMAGES_TEST_FILE, LABELS_TEST_FILE);
OneHotEncoder onehot(mnist.getLabels());
mnist.applyToLabels(onehot);
mnistTest.applyToLabels(onehot);
// test on a small dataset while running
unique_ptr<RNG> rng = Init::newRNG();
mnistTest.shuffle(rng);
mnistTest.truncate(1000);
Net net = MakeNet(mnist.inputDim())
.addFC(300, scaledTanh)
.addFC(mnist.outputDim(), scaledTanh)
.addL2Loss()
.init();
IntClassifier metrics(net, onehot);
net.setLearningPolicy(FixedRate(1e-5, 0.9));
SGD::train(net, mnist, 1 /* epochs */,
noEpochCallback,
IterationCallback { 1000, [&](int i) {
auto cm = metrics.test(mnistTest);
cout << "sample "
<< i << ": "
<< "E = "
<< setprecision(6)
<< meanLossEstimate(net, mnistTest) << " "
<< "PPV = "
<< setprecision(3)
<< cm.precision() << " "
<< "TPR = "
<< setprecision(3)
<< cm.recall() << " "
<< "ACC = "
<< setprecision(3)
<< cm.accuracy() << " "
<< "F1 = "
<< setprecision(3)
<< cm.F1score() << endl;
return false;
}});
ofstream nnfile(SAVE_NETWORK_SNAPSHOT);
if (nnfile.is_open()) {
PlainTextNetworkWriter(nnfile) << net << "\n";
cout << "wrote " << SAVE_NETWORK_SNAPSHOT << "\n";
}
}
<commit_msg>demo_mnist: use AdaDelta, 300-100-10 MLP, do full test every epoch<commit_after>#include <iostream>
#include <fstream>
#include <string>
#include "notch.hpp"
#include "notch_io.hpp" // IDXReader
#include "notch_pre.hpp" // OneHotEncoder
#include "notch_metrics.hpp" // AClassifier
using namespace std;
const string IMAGES_FILE = "../data/train-images-idx3-ubyte";
const string LABELS_FILE = "../data/train-labels-idx1-ubyte";
const string IMAGES_TEST_FILE = "../data/t10k-images-idx3-ubyte";
const string LABELS_TEST_FILE = "../data/t10k-labels-idx1-ubyte";
const string SAVE_NETWORK_SNAPSHOT = "demo_mnist_network.txt";
LabeledDataset readMNIST(const string &imagesFile, const string labelsFile) {
ifstream trainImages(imagesFile, ios_base::binary);
if (!trainImages.is_open()) {
cerr << "Can't open file " << imagesFile << "\n"
<< "Run getmnist.py in ../data/ to download data\n";
exit(0);
}
ifstream trainLabels(labelsFile, ios_base::binary);
if (!trainLabels.is_open()) {
cerr << "Can't open file " << labelsFile << "\n"
<< "Run getmnist.py in ../data/ to download data\n";
exit(0);
}
cout << "reading MNIST images from " << imagesFile << "\n";
cout << "reading MNIST labels from " << labelsFile << "\n";
LabeledDataset mnist = IDXReader().read(trainImages, trainLabels);
return mnist;
}
class IntClassifier : public AClassifier < int, 1 > {
private:
OneHotEncoder &enc;
Net &net;
public:
IntClassifier(Net &net, OneHotEncoder &enc)
: enc(enc), net(net) {}
virtual int aslabel(const Output &out) {
return enc.unapply(out)[0];
}
virtual int classify(const Input &in) {
return enc.unapply(net.output(in))[0];
}
};
float meanLossEstimate(Net &net, LabeledDataset &dataset, size_t maxcount=0) {
float total;
size_t n = 0;
for (auto sample : dataset) {
total += net.loss(sample.data, sample.label);
n++;
if (maxcount > 0 && n >= maxcount) {
break;
}
}
return total / n;
}
int main() {
LabeledDataset mnist = readMNIST(IMAGES_FILE, LABELS_FILE);
LabeledDataset mnistTest = readMNIST(IMAGES_TEST_FILE, LABELS_TEST_FILE);
LabeledDataset mnistMiniTest = readMNIST(IMAGES_TEST_FILE, LABELS_TEST_FILE);
OneHotEncoder onehot(mnist.getLabels());
mnist.applyToLabels(onehot);
mnistTest.applyToLabels(onehot);
mnistMiniTest.applyToLabels(onehot);
// test on a small dataset while running
unique_ptr<RNG> rng = Init::newRNG();
mnistMiniTest.shuffle(rng);
mnistMiniTest.truncate(1000);
Net net = MakeNet(mnist.inputDim())
.addFC(300, scaledTanh)
.addFC(100, leakyReLU)
.addFC(mnist.outputDim(), scaledTanh)
.addSoftmax()
.init();
IntClassifier metrics(net, onehot);
net.setLearningPolicy(AdaDelta());
SGD::train(net, mnist, 3 /* epochs */,
EpochCallback { 1, [&](int i) {
auto cm = metrics.test(mnistTest);
cout << "epoch "
<< i << ": "
<< "E = "
<< setprecision(6)
<< meanLossEstimate(net, mnistTest) << " "
<< "PPV = "
<< setprecision(3)
<< cm.precision() << " "
<< "TPR = "
<< setprecision(3)
<< cm.recall() << " "
<< "ACC = "
<< setprecision(3)
<< cm.accuracy() << " "
<< "F1 = "
<< setprecision(3)
<< cm.F1score() << endl;
return false;
}},
IterationCallback { 1000, [&](int i) {
auto cm = metrics.test(mnistMiniTest);
cout << "sample "
<< i << ": "
<< "E = "
<< setprecision(6)
<< meanLossEstimate(net, mnistMiniTest) << " "
<< "PPV = "
<< setprecision(3)
<< cm.precision() << " "
<< "TPR = "
<< setprecision(3)
<< cm.recall() << " "
<< "ACC = "
<< setprecision(3)
<< cm.accuracy() << " "
<< "F1 = "
<< setprecision(3)
<< cm.F1score() << endl;
return false;
}});
ofstream nnfile(SAVE_NETWORK_SNAPSHOT);
if (nnfile.is_open()) {
PlainTextNetworkWriter(nnfile) << net << "\n";
cout << "wrote " << SAVE_NETWORK_SNAPSHOT << "\n";
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright NumFOCUS
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "itkMultiphaseSparseFiniteDifferenceImageFilter.h"
#include "itkScalarChanAndVeseLevelSetFunction.h"
#include "itkPrintHelper.h"
#include "itkTestingMacros.h"
namespace itk
{
template <typename TInputImage,
typename TFeatureImage,
typename TOutputImage,
typename TFiniteDifferenceFunction,
typename TIdCell>
class MultiphaseSparseFiniteDifferenceImageFilterTestHelper
: public MultiphaseSparseFiniteDifferenceImageFilter<TInputImage,
TFeatureImage,
TOutputImage,
TFiniteDifferenceFunction,
TIdCell>
{
public:
/** Standard class type aliases. */
using Self = MultiphaseSparseFiniteDifferenceImageFilterTestHelper;
using Superclass =
MultiphaseSparseFiniteDifferenceImageFilter<TInputImage, TFeatureImage, TOutputImage, TFiniteDifferenceFunction>;
using Pointer = SmartPointer<Self>;
using ConstPointer = SmartPointer<const Self>;
/** Run-time type information (and related methods) */
itkTypeMacro(MultiphaseSparseFiniteDifferenceImageFilterTestHelper, MultiphaseSparseFiniteDifferenceImageFilter);
itkNewMacro(Self);
void
AllocateUpdateBuffer() override
{}
using typename Superclass::TimeStepType;
void
ApplyUpdate(TimeStepType itkNotUsed(dt)) override
{}
TimeStepType
CalculateChange() override
{
return TimeStepType(1.0);
}
void
CopyInputToOutput() override
{}
};
} // namespace itk
int
itkMultiphaseSparseFiniteDifferenceImageFilterTest(int, char *[])
{
constexpr unsigned int Dimension = 3;
using LevelSetImageType = itk::Image<double, Dimension>;
using FeatureImageType = itk::Image<float, Dimension>;
using OutputImageType = itk::Image<unsigned char, Dimension>;
using DataHelperType = itk::ScalarChanAndVeseLevelSetFunctionData<LevelSetImageType, FeatureImageType>;
using SharedDataHelperType =
itk::ConstrainedRegionBasedLevelSetFunctionSharedData<LevelSetImageType, FeatureImageType, DataHelperType>;
using RegionBasedLevelSetFunctionType =
itk::ScalarChanAndVeseLevelSetFunction<LevelSetImageType, FeatureImageType, SharedDataHelperType>;
RegionBasedLevelSetFunctionType::Pointer function = RegionBasedLevelSetFunctionType::New();
if (function.IsNull())
{
return EXIT_FAILURE;
}
using IdCellType = unsigned long;
using FilterType = itk::MultiphaseSparseFiniteDifferenceImageFilterTestHelper<LevelSetImageType,
FeatureImageType,
OutputImageType,
RegionBasedLevelSetFunctionType,
IdCellType>;
FilterType::Pointer filter = FilterType::New();
// Instantiate the filter of interest to exercise its basic object methods
typename FilterType::Superclass::Pointer multiphaseSparseFiniteDiffFilter = FilterType::Superclass::New();
ITK_EXERCISE_BASIC_OBJECT_METHODS(multiphaseSparseFiniteDiffFilter,
MultiphaseSparseFiniteDifferenceImageFilter,
MultiphaseFiniteDifferenceImageFilter);
// Exercise the class Set/Get methods to increase coverage
unsigned int numberOfLayers = Dimension;
filter->SetNumberOfLayers(numberOfLayers);
ITK_TEST_SET_GET_VALUE(numberOfLayers, filter->GetNumberOfLayers());
using ValueType = typename FilterType::ValueType;
ValueType isoSurfaceValue = itk::NumericTraits<ValueType>::ZeroValue();
filter->SetIsoSurfaceValue(isoSurfaceValue);
ITK_TEST_SET_GET_VALUE(isoSurfaceValue, filter->GetIsoSurfaceValue());
bool interpolateSurfaceLocation = true;
ITK_TEST_SET_GET_BOOLEAN(filter, InterpolateSurfaceLocation, interpolateSurfaceLocation);
std::cout << "Test finished." << std::endl;
return EXIT_SUCCESS;
}
<commit_msg>COMP: fixed compile errors due to incorrect superclass identification<commit_after>/*=========================================================================
*
* Copyright NumFOCUS
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "itkMultiphaseSparseFiniteDifferenceImageFilter.h"
#include "itkScalarChanAndVeseLevelSetFunction.h"
#include "itkPrintHelper.h"
#include "itkTestingMacros.h"
namespace itk
{
template <typename TInputImage,
typename TFeatureImage,
typename TOutputImage,
typename TFiniteDifferenceFunction,
typename TIdCell>
class MultiphaseSparseFiniteDifferenceImageFilterTestHelper
: public MultiphaseSparseFiniteDifferenceImageFilter<TInputImage,
TFeatureImage,
TOutputImage,
TFiniteDifferenceFunction,
TIdCell>
{
public:
/** Standard class type aliases. */
using Self = MultiphaseSparseFiniteDifferenceImageFilterTestHelper;
using Superclass = MultiphaseSparseFiniteDifferenceImageFilter<TInputImage,
TFeatureImage,
TOutputImage,
TFiniteDifferenceFunction,
TIdCell>;
using Pointer = SmartPointer<Self>;
using ConstPointer = SmartPointer<const Self>;
/** Run-time type information (and related methods) */
itkTypeMacro(MultiphaseSparseFiniteDifferenceImageFilterTestHelper, MultiphaseSparseFiniteDifferenceImageFilter);
itkNewMacro(Self);
void
AllocateUpdateBuffer() override
{}
using typename Superclass::TimeStepType;
void
ApplyUpdate(TimeStepType itkNotUsed(dt)) override
{}
TimeStepType
CalculateChange() override
{
return TimeStepType(1.0);
}
void
CopyInputToOutput() override
{}
};
} // namespace itk
int
itkMultiphaseSparseFiniteDifferenceImageFilterTest(int, char *[])
{
constexpr unsigned int Dimension = 3;
using LevelSetImageType = itk::Image<double, Dimension>;
using FeatureImageType = itk::Image<float, Dimension>;
using OutputImageType = itk::Image<unsigned char, Dimension>;
using DataHelperType = itk::ScalarChanAndVeseLevelSetFunctionData<LevelSetImageType, FeatureImageType>;
using SharedDataHelperType =
itk::ConstrainedRegionBasedLevelSetFunctionSharedData<LevelSetImageType, FeatureImageType, DataHelperType>;
using RegionBasedLevelSetFunctionType =
itk::ScalarChanAndVeseLevelSetFunction<LevelSetImageType, FeatureImageType, SharedDataHelperType>;
RegionBasedLevelSetFunctionType::Pointer function = RegionBasedLevelSetFunctionType::New();
if (function.IsNull())
{
return EXIT_FAILURE;
}
using IdCellType = unsigned long;
using FilterType = itk::MultiphaseSparseFiniteDifferenceImageFilterTestHelper<LevelSetImageType,
FeatureImageType,
OutputImageType,
RegionBasedLevelSetFunctionType,
IdCellType>;
FilterType::Pointer filter = FilterType::New();
// Instantiate the filter of interest to exercise its basic object methods
typename FilterType::Superclass::Pointer multiphaseSparseFiniteDiffFilter = FilterType::Superclass::New();
ITK_EXERCISE_BASIC_OBJECT_METHODS(multiphaseSparseFiniteDiffFilter,
MultiphaseSparseFiniteDifferenceImageFilter,
MultiphaseFiniteDifferenceImageFilter);
// Exercise the class Set/Get methods to increase coverage
unsigned int numberOfLayers = Dimension;
filter->SetNumberOfLayers(numberOfLayers);
ITK_TEST_SET_GET_VALUE(numberOfLayers, filter->GetNumberOfLayers());
using ValueType = typename FilterType::ValueType;
ValueType isoSurfaceValue = itk::NumericTraits<ValueType>::ZeroValue();
filter->SetIsoSurfaceValue(isoSurfaceValue);
ITK_TEST_SET_GET_VALUE(isoSurfaceValue, filter->GetIsoSurfaceValue());
bool interpolateSurfaceLocation = true;
ITK_TEST_SET_GET_BOOLEAN(filter, InterpolateSurfaceLocation, interpolateSurfaceLocation);
std::cout << "Test finished." << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: Awrapadox.hxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: hr $ $Date: 2006-06-20 02:00: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
*
************************************************************************/
#ifndef _CONNECTIVITY_ADO_AWRAPADOX_HXX_
#define _CONNECTIVITY_ADO_AWRAPADOX_HXX_
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef __User_FWD_DEFINED__
#define __User_FWD_DEFINED__
typedef struct _ADOUser User;
#endif /* __User_FWD_DEFINED__ */
#ifndef __Group_FWD_DEFINED__
#define __Group_FWD_DEFINED__
typedef struct _ADOGroup Group;
#endif /* __Group_FWD_DEFINED__ */
#ifndef __Column_FWD_DEFINED__
#define __Column_FWD_DEFINED__
typedef struct _ADOColumn Column;
#endif /* __Column_FWD_DEFINED__ */
#ifndef __Index_FWD_DEFINED__
#define __Index_FWD_DEFINED__
typedef struct _ADOIndex Index;
#endif /* __cplusplus */
#ifndef __Key_FWD_DEFINED__
#define __Key_FWD_DEFINED__
typedef struct _ADOKey Key;
#endif /* __Key_FWD_DEFINED__ */
#ifndef __Table_FWD_DEFINED__
#define __Table_FWD_DEFINED__
typedef struct _ADOTable Table;
#endif /* __Table_FWD_DEFINED__ */
#include "ado_pre_sys_include.h"
#include <adoint.h>
#include <ado/ADOCTINT.H>
#include "ado_post_sys_include.h"
#ifndef _CONNECTIVITY_ADO_AOLEWRAP_HXX_
#include "ado/Aolewrap.hxx"
#endif
#ifndef _CONNECTIVITY_ADO_AOLEVARIANT_HXX_
#include "ado/Aolevariant.hxx"
#endif
#ifndef _CONNECTIVITY_ADO_ADOIMP_HXX_
#include "ado/adoimp.hxx"
#endif
#include "ado/Awrapado.hxx"
#include "ado/WrapColumn.hxx"
#include "ado/WrapIndex.hxx"
#include "ado/WrapKey.hxx"
#include "ado/WrapTable.hxx"
#include "ado/WrapCatalog.hxx"
namespace connectivity
{
namespace ado
{
class WpADOView : public WpOLEBase<ADOView>
{
public:
WpADOView(ADOView* pInt=NULL) : WpOLEBase<ADOView>(pInt){}
WpADOView(const WpADOView& rhs){operator=(rhs);}
inline WpADOView& operator=(const WpADOView& rhs)
{WpOLEBase<ADOView>::operator=(rhs); return *this;}
::rtl::OUString get_Name() const;
void get_Command(OLEVariant& _rVar) const;
void put_Command(OLEVariant& _rVar);
};
class WpADOGroup : public WpOLEBase<ADOGroup>
{
public:
WpADOGroup(ADOGroup* pInt=NULL) : WpOLEBase<ADOGroup>(pInt){}
WpADOGroup(const WpADOGroup& rhs){operator=(rhs);}
inline WpADOGroup& operator=(const WpADOGroup& rhs)
{WpOLEBase<ADOGroup>::operator=(rhs); return *this;}
void Create();
::rtl::OUString get_Name() const;
void put_Name(const ::rtl::OUString& _rName);
RightsEnum GetPermissions(
/* [in] */ const OLEVariant& Name,
/* [in] */ ObjectTypeEnum ObjectType);
sal_Bool SetPermissions(
/* [in] */ const OLEVariant& Name,
/* [in] */ ObjectTypeEnum ObjectType,
/* [in] */ ActionEnum Action,
/* [in] */ RightsEnum Rights);
WpADOUsers get_Users( );
};
class WpADOUser : public WpOLEBase<_ADOUser>
{
public:
WpADOUser(_ADOUser* pInt=NULL) : WpOLEBase<_ADOUser>(pInt){}
WpADOUser(const WpADOUser& rhs){operator=(rhs);}
inline WpADOUser& operator=(const WpADOUser& rhs)
{WpOLEBase<_ADOUser>::operator=(rhs); return *this;}
void Create();
::rtl::OUString get_Name() const;
void put_Name(const ::rtl::OUString& _rName);
sal_Bool ChangePassword(const ::rtl::OUString& _rPwd,const ::rtl::OUString& _rNewPwd);
WpADOGroups get_Groups();
RightsEnum GetPermissions(
/* [in] */ const OLEVariant& Name,
/* [in] */ ObjectTypeEnum ObjectType);
sal_Bool SetPermissions(
/* [in] */ const OLEVariant& Name,
/* [in] */ ObjectTypeEnum ObjectType,
/* [in] */ ActionEnum Action,
/* [in] */ RightsEnum Rights);
};
}
}
#endif // _CONNECTIVITY_ADO_AWRAPADOX_HXX_
<commit_msg>INTEGRATION: CWS ause036 (1.12.116); FILE MERGED 2006/06/09 12:18:49 hjs 1.12.116.1: #125767# change includes to deal with changed location<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: Awrapadox.hxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: ihi $ $Date: 2006-06-29 12:51:12 $
*
* 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 _CONNECTIVITY_ADO_AWRAPADOX_HXX_
#define _CONNECTIVITY_ADO_AWRAPADOX_HXX_
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef __User_FWD_DEFINED__
#define __User_FWD_DEFINED__
typedef struct _ADOUser User;
#endif /* __User_FWD_DEFINED__ */
#ifndef __Group_FWD_DEFINED__
#define __Group_FWD_DEFINED__
typedef struct _ADOGroup Group;
#endif /* __Group_FWD_DEFINED__ */
#ifndef __Column_FWD_DEFINED__
#define __Column_FWD_DEFINED__
typedef struct _ADOColumn Column;
#endif /* __Column_FWD_DEFINED__ */
#ifndef __Index_FWD_DEFINED__
#define __Index_FWD_DEFINED__
typedef struct _ADOIndex Index;
#endif /* __cplusplus */
#ifndef __Key_FWD_DEFINED__
#define __Key_FWD_DEFINED__
typedef struct _ADOKey Key;
#endif /* __Key_FWD_DEFINED__ */
#ifndef __Table_FWD_DEFINED__
#define __Table_FWD_DEFINED__
typedef struct _ADOTable Table;
#endif /* __Table_FWD_DEFINED__ */
#include "ado_pre_sys_include.h"
#include <adoint.h>
#include <adoctint.h>
#include "ado_post_sys_include.h"
#ifndef _CONNECTIVITY_ADO_AOLEWRAP_HXX_
#include "ado/Aolewrap.hxx"
#endif
#ifndef _CONNECTIVITY_ADO_AOLEVARIANT_HXX_
#include "ado/Aolevariant.hxx"
#endif
#ifndef _CONNECTIVITY_ADO_ADOIMP_HXX_
#include "ado/adoimp.hxx"
#endif
#include "ado/Awrapado.hxx"
#include "ado/WrapColumn.hxx"
#include "ado/WrapIndex.hxx"
#include "ado/WrapKey.hxx"
#include "ado/WrapTable.hxx"
#include "ado/WrapCatalog.hxx"
namespace connectivity
{
namespace ado
{
class WpADOView : public WpOLEBase<ADOView>
{
public:
WpADOView(ADOView* pInt=NULL) : WpOLEBase<ADOView>(pInt){}
WpADOView(const WpADOView& rhs){operator=(rhs);}
inline WpADOView& operator=(const WpADOView& rhs)
{WpOLEBase<ADOView>::operator=(rhs); return *this;}
::rtl::OUString get_Name() const;
void get_Command(OLEVariant& _rVar) const;
void put_Command(OLEVariant& _rVar);
};
class WpADOGroup : public WpOLEBase<ADOGroup>
{
public:
WpADOGroup(ADOGroup* pInt=NULL) : WpOLEBase<ADOGroup>(pInt){}
WpADOGroup(const WpADOGroup& rhs){operator=(rhs);}
inline WpADOGroup& operator=(const WpADOGroup& rhs)
{WpOLEBase<ADOGroup>::operator=(rhs); return *this;}
void Create();
::rtl::OUString get_Name() const;
void put_Name(const ::rtl::OUString& _rName);
RightsEnum GetPermissions(
/* [in] */ const OLEVariant& Name,
/* [in] */ ObjectTypeEnum ObjectType);
sal_Bool SetPermissions(
/* [in] */ const OLEVariant& Name,
/* [in] */ ObjectTypeEnum ObjectType,
/* [in] */ ActionEnum Action,
/* [in] */ RightsEnum Rights);
WpADOUsers get_Users( );
};
class WpADOUser : public WpOLEBase<_ADOUser>
{
public:
WpADOUser(_ADOUser* pInt=NULL) : WpOLEBase<_ADOUser>(pInt){}
WpADOUser(const WpADOUser& rhs){operator=(rhs);}
inline WpADOUser& operator=(const WpADOUser& rhs)
{WpOLEBase<_ADOUser>::operator=(rhs); return *this;}
void Create();
::rtl::OUString get_Name() const;
void put_Name(const ::rtl::OUString& _rName);
sal_Bool ChangePassword(const ::rtl::OUString& _rPwd,const ::rtl::OUString& _rNewPwd);
WpADOGroups get_Groups();
RightsEnum GetPermissions(
/* [in] */ const OLEVariant& Name,
/* [in] */ ObjectTypeEnum ObjectType);
sal_Bool SetPermissions(
/* [in] */ const OLEVariant& Name,
/* [in] */ ObjectTypeEnum ObjectType,
/* [in] */ ActionEnum Action,
/* [in] */ RightsEnum Rights);
};
}
}
#endif // _CONNECTIVITY_ADO_AWRAPADOX_HXX_
<|endoftext|> |
<commit_before>#include "../../../runtime/types/InternalTypes.h"
#include "../../../runtime/utils/Formatting.h"
void ListType::__constructor__() {
Program::push(Program::create<ListInstance>());
}
void ListType::append() {
auto self = Program::argument<ListInstance>();
auto item = Program::pop();
self->val.push_back(item);
Program::push(self);
}
void ListType::pop() {
auto self = Program::argument<ListInstance>();
auto elem = self->val.back();
self->val.pop_back();
Program::push(elem);
}
void ListType::contains() {
auto self = Program::argument<ListInstance>();
auto item = Program::pop();
Program::push(std::find(self->val.begin(), self->val.end(), item) != self->val.end());
}
void ListType::iterator() {
auto self = Program::argument<ListInstance>();
Program::push(Program::create<IteratorInstance>(*self));
}
void ListType::get() {
auto self = Program::argument<ListInstance>();
auto index = Program::argument<NumberInstance>();
Program::push(self->val[index->val]);
}
void ListType::set() {
auto self = Program::argument<ListInstance>();
auto value = Program::pop();
auto index = Program::argument<NumberInstance>();
self->val[index->val] = value;
}
void ListType::length() {
auto self = Program::argument<ListInstance>();
Program::push(Program::create<NumberInstance>(self->val.size()));
}
void ListType::swap() {
auto self = Program::argument<ListInstance>();
auto index2 = Program::argument<NumberInstance>();
auto index1 = Program::argument<NumberInstance>();
auto i = index1->val, j = index2->val;
auto temp = self->val[i];
self->val[i] = self->val[j];
self->val[j] = temp;
}
void ListType::range() {
auto end = Program::argument<NumberInstance>();
auto start = Program::argument<NumberInstance>();
auto lst = Program::create<ListInstance>();
lst->val.resize(static_cast<unsigned int>(end->val - start->val));
for(long long idx = start->val, val = 0; idx < end->val; idx++, val++) lst->val[idx] = Program::create<NumberInstance>(val);
Program::push(lst);
}
std::string ListInstance::text() {
return to_string(val);
}
bool ListInstance::boolean() {
return !val.empty();
}
bool ListInstance::operator==(const BaseThingInstance &other) const {
auto other_list = dynamic_cast<const ListInstance*>(&other);
return other_list && this->val == other_list->val;
}
size_t ListInstance::hash() const {
throw RuntimeError("List is a mutable object and cannot be hashed"); // TODO: throw user mode exception
}
<commit_msg>Fix incorrect implementation of list.range<commit_after>#include "../../../runtime/types/InternalTypes.h"
#include "../../../runtime/utils/Formatting.h"
void ListType::__constructor__() {
Program::push(Program::create<ListInstance>());
}
void ListType::append() {
auto self = Program::argument<ListInstance>();
auto item = Program::pop();
self->val.push_back(item);
Program::push(self);
}
void ListType::pop() {
auto self = Program::argument<ListInstance>();
auto elem = self->val.back();
self->val.pop_back();
Program::push(elem);
}
void ListType::contains() {
auto self = Program::argument<ListInstance>();
auto item = Program::pop();
Program::push(std::find(self->val.begin(), self->val.end(), item) != self->val.end());
}
void ListType::iterator() {
auto self = Program::argument<ListInstance>();
Program::push(Program::create<IteratorInstance>(*self));
}
void ListType::get() {
auto self = Program::argument<ListInstance>();
auto index = Program::argument<NumberInstance>();
Program::push(self->val[index->val]);
}
void ListType::set() {
auto self = Program::argument<ListInstance>();
auto value = Program::pop();
auto index = Program::argument<NumberInstance>();
self->val[index->val] = value;
}
void ListType::length() {
auto self = Program::argument<ListInstance>();
Program::push(Program::create<NumberInstance>(self->val.size()));
}
void ListType::swap() {
auto self = Program::argument<ListInstance>();
auto index2 = Program::argument<NumberInstance>();
auto index1 = Program::argument<NumberInstance>();
auto i = index1->val, j = index2->val;
auto temp = self->val[i];
self->val[i] = self->val[j];
self->val[j] = temp;
}
void ListType::range() {
auto end = Program::argument<NumberInstance>();
auto start = Program::argument<NumberInstance>();
auto lst = Program::create<ListInstance>();
lst->val.resize(static_cast<unsigned int>(end->val - start->val));
for(long long idx = 0, val = start->val; idx < end->val - start->val; idx++, val++) lst->val[idx] = Program::create<NumberInstance>(val);
Program::push(lst);
}
std::string ListInstance::text() {
return to_string(val);
}
bool ListInstance::boolean() {
return !val.empty();
}
bool ListInstance::operator==(const BaseThingInstance &other) const {
auto other_list = dynamic_cast<const ListInstance*>(&other);
return other_list && this->val == other_list->val;
}
size_t ListInstance::hash() const {
throw RuntimeError("List is a mutable object and cannot be hashed"); // TODO: throw user mode exception
}
<|endoftext|> |
<commit_before>#include "LikelihoodProfiler.h"
// from STL
#include <set>
// from ROOT
#include "TCanvas.h"
#include "TGraph.h"
#include "TH2D.h"
#include "TAxis.h"
#include "TStyle.h"
// from RooFit
#include "RooFitResult.h"
// from DooCore
#include <doocore/io/MsgStream.h>
#include <doocore/io/Progress.h>
#include <doocore/lutils/lutils.h>
// from DooFit
#include "doofit/fitter/AbsFitter.h"
#include "doofit/toy/ToyStudyStd/ToyStudyStd.h"
doofit::plotting::profiles::LikelihoodProfiler::LikelihoodProfiler()
: num_samples_(30)
{}
std::vector<double> doofit::plotting::profiles::LikelihoodProfiler::SetSamplePoint(unsigned int step) {
using namespace doocore::io;
std::vector<double> sample_vals;
int i(scan_vars_.size() - 1);
//sdebug << "step = " << step << endmsg;
for (auto var : scan_vars_) {
int step_this = step/std::pow(num_samples_,i);
step -= step_this*std::pow(num_samples_,i);
--i;
double val(start_vals_[var->GetName()] + 3*var->getError()*(-1.0 + 2.0/static_cast<double>(num_samples_)*step_this));
var->setVal(val);
var->setConstant(true);
sample_vals.push_back(val);
//sdebug << " " << var->GetName() << " = " << step_this << " @ " << var->getVal() << endmsg;
}
return sample_vals;
}
void doofit::plotting::profiles::LikelihoodProfiler::Scan() {
using namespace doocore::io;
//RooRealVar* parameter_scan = scan_vars_.front();
//num_samples_ = 12;
unsigned int num_dimensions = scan_vars_.size();
unsigned int num_total_samples = std::pow(num_samples_,num_dimensions);
unsigned int step = 0;
// double value_start = parameter_scan->getVal();
// double value_scan = value_start - 5.0*parameter_scan->getError();
for (auto var : scan_vars_) {
start_vals_[var->GetName()] = var->getVal();
}
Progress p("Sampling likelihood", num_total_samples);
while (step < num_total_samples) {
//parameter_scan->setVal(value_scan);
//parameter_scan->setConstant(true);
//sinfo << "PROFILE: " << value_scan << endmsg;
std::vector<double> sample_vals(SetSamplePoint(step));
fitter_->set_shutup(true);
fitter_->Fit();
fit_results_.push_back(fitter_->fit_result());
//sinfo << fitter_->NegativeLogLikelihood() << endmsg;
//value_scan += 1*parameter_scan->getError();
++step;
++p;
}
p.Finish();
}
void doofit::plotting::profiles::LikelihoodProfiler::ReadFitResults(doofit::toy::ToyStudyStd& toy_study) {
using namespace doofit::toy;
FitResultContainer fit_result_container(toy_study.GetFitResult());
const RooFitResult* fit_result(std::get<0>(fit_result_container));
while (fit_result != nullptr) {
fit_results_.push_back(fit_result);
fit_result_container = toy_study.GetFitResult();
fit_result = std::get<0>(fit_result_container);
}
}
bool doofit::plotting::profiles::LikelihoodProfiler::FitResultOkay(const RooFitResult& fit_result) const {
using namespace doocore::io;
if (fit_result.covQual() < 2) {
return false;
} else if (fit_result.statusCodeHistory(0) < 0) {
return false;
} else {
return true;
}
}
void doofit::plotting::profiles::LikelihoodProfiler::PlotHandler(const std::string& plot_path) {
using namespace doocore::io;
std::map<std::string, std::vector<double>> val_scan;
std::vector<double> val_nll;
for (auto var : scan_vars_) {
RooRealVar* var_fixed = dynamic_cast<RooRealVar*>(fit_results_.front()->constPars().find(var->GetName()));
scan_vars_titles_.push_back(var_fixed->GetTitle());
}
double min_nll(0.0);
for (auto result : fit_results_) {
if (FitResultOkay(*result)) {
for (auto var : scan_vars_) {
RooRealVar* var_fixed = dynamic_cast<RooRealVar*>(result->constPars().find(var->GetName()));
if (var_fixed == nullptr) {
serr << "Error in LikelihoodProfiler::PlotHandler(): Cannot find fixed parameter "
<< var->GetName() << " in fit result!" << endmsg;
throw;
}
val_scan[var->GetName()].push_back(var_fixed->getVal());
}
if (min_nll == 0.0 || min_nll > result->minNll()) {
min_nll = result->minNll();
}
val_nll.push_back(result->minNll());
}
}
for (auto &nll : val_nll) {
if (nll != 0.0) {
nll -= min_nll;
}
}
if (val_scan.size() == 1) {
doocore::lutils::setStyle();
gStyle->SetPadLeftMargin(0.12);
gStyle->SetTitleOffset(0.75, "y");
} else if (val_scan.size() == 2) {
doocore::lutils::setStyle("2d");
gStyle->SetNumberContours(999);
gStyle->SetPadRightMargin(0.16);
gStyle->SetTitleOffset(0.75, "z");
}
TCanvas c("c", "c", 800, 600);
if (val_scan.size() == 1) {
const std::vector<double>& val_x = val_scan.begin()->second;
TGraph graph(val_nll.size(), &val_x[0], &val_nll[0]);
graph.Draw("AP");
graph.GetXaxis()->SetTitle(scan_vars_titles_.at(0).c_str());
graph.GetYaxis()->SetTitle("#DeltaLL");
graph.SetMarkerStyle(1);
//graph.SetMarkerSize(10);
graph.SetMarkerColor(kBlue+3);
//c.SaveAs("profile.pdf");
doocore::lutils::printPlot(&c, "profile", plot_path);
} else if (val_scan.size() == 2) {
const std::vector<double>& val_x = val_scan.begin()->second;
const std::vector<double>& val_y = val_scan.rbegin()->second;
auto minmax_x = std::minmax_element(val_x.begin(), val_x.end());
auto minmax_y = std::minmax_element(val_y.begin(), val_y.end());
std::set<double> distinct_x, distinct_y;
for (auto x : val_x) {
distinct_x.insert(x);
}
for (auto y : val_y) {
distinct_y.insert(y);
}
double min_nll(0.0), max_nll(0.0);
for (auto nll : val_nll) {
if (nll != 0 && (min_nll == 0.0 || nll < min_nll)) {
min_nll = nll;
}
if (nll != 0 && (max_nll == 0.0 || nll > max_nll)) {
max_nll = nll;
}
}
double min_x = *minmax_x.first - (*minmax_x.second-*minmax_x.first)/(distinct_x.size()-1)*0.5;
double max_x = *minmax_x.second + (*minmax_x.second-*minmax_x.first)/(distinct_x.size()-1)*0.5;
double min_y = *minmax_y.first - (*minmax_y.second-*minmax_y.first)/(distinct_y.size()-1)*0.5;
double max_y = *minmax_y.second + (*minmax_y.second-*minmax_y.first)/(distinct_y.size()-1)*0.5;
TH2D histogram("histogram", "histogram", distinct_x.size(), min_x, max_x, distinct_y.size(), min_y, max_y);
// sdebug << "histogram x: " << *minmax_x.first << " - " << *minmax_x.second << endmsg;
// sdebug << "histogram y: " << *minmax_y.first << " - " << *minmax_y.second << endmsg;
for (int i=0; i<val_nll.size(); ++i) {
// sdebug << val_x.at(i) << ", " << val_y.at(i) << " - " << val_nll.at(i) << endmsg;
// sdebug << "Bin: " << histogram.FindBin(val_x.at(i), val_y.at(i)) << endmsg;
int nbin_x, nbin_y, nbin_z;
histogram.GetBinXYZ(histogram.FindBin(val_x.at(i), val_y.at(i)), nbin_x, nbin_y, nbin_z);
// sdebug << "Bin center x: " << histogram.GetXaxis()->GetBinCenter(nbin_x) << endmsg;
// sdebug << "Bin center y: " << histogram.GetYaxis()->GetBinCenter(nbin_y) << endmsg;
histogram.SetBinContent(histogram.FindBin(val_x.at(i), val_y.at(i)), val_nll.at(i));
}
histogram.Draw("COLZ");
histogram.GetZaxis()->SetRangeUser(min_nll, max_nll);
histogram.SetXTitle(scan_vars_titles_.at(0).c_str());
histogram.SetYTitle(scan_vars_titles_.at(1).c_str());
histogram.SetZTitle("#DeltaLL");
//c.SaveAs("profile.pdf");
doocore::lutils::printPlot(&c, "profile", plot_path);
c.SetLogz(true);
doocore::lutils::printPlot(&c, "profile_log", plot_path);
} else {
serr << "Error in LikelihoodProfiler::PlotHandler(): Cannot (yet) plot 3D likelihood." << endmsg;
throw;
}
}
<commit_msg>LikelihoodProfiler: improvements<commit_after>#include "LikelihoodProfiler.h"
// from STL
#include <set>
// from ROOT
#include "TCanvas.h"
#include "TGraph.h"
#include "TH2D.h"
#include "TAxis.h"
#include "TStyle.h"
#include "TColor.h"
// from RooFit
#include "RooFitResult.h"
// from DooCore
#include <doocore/io/MsgStream.h>
#include <doocore/io/Progress.h>
#include <doocore/lutils/lutils.h>
// from DooFit
#include "doofit/fitter/AbsFitter.h"
#include "doofit/toy/ToyStudyStd/ToyStudyStd.h"
doofit::plotting::profiles::LikelihoodProfiler::LikelihoodProfiler()
: num_samples_(30)
{}
std::vector<double> doofit::plotting::profiles::LikelihoodProfiler::SetSamplePoint(unsigned int step) {
using namespace doocore::io;
std::vector<double> sample_vals;
int i(scan_vars_.size() - 1);
//sdebug << "step = " << step << endmsg;
for (auto var : scan_vars_) {
int step_this = step/std::pow(num_samples_,i);
step -= step_this*std::pow(num_samples_,i);
--i;
double val(start_vals_[var->GetName()] + 3*var->getError()*(-1.0 + 2.0/static_cast<double>(num_samples_)*step_this));
var->setVal(val);
var->setConstant(true);
sample_vals.push_back(val);
//sdebug << " " << var->GetName() << " = " << step_this << " @ " << var->getVal() << endmsg;
}
return sample_vals;
}
void doofit::plotting::profiles::LikelihoodProfiler::Scan() {
using namespace doocore::io;
//RooRealVar* parameter_scan = scan_vars_.front();
//num_samples_ = 12;
unsigned int num_dimensions = scan_vars_.size();
unsigned int num_total_samples = std::pow(num_samples_,num_dimensions);
unsigned int step = 0;
// double value_start = parameter_scan->getVal();
// double value_scan = value_start - 5.0*parameter_scan->getError();
for (auto var : scan_vars_) {
start_vals_[var->GetName()] = var->getVal();
}
Progress p("Sampling likelihood", num_total_samples);
while (step < num_total_samples) {
//parameter_scan->setVal(value_scan);
//parameter_scan->setConstant(true);
//sinfo << "PROFILE: " << value_scan << endmsg;
std::vector<double> sample_vals(SetSamplePoint(step));
fitter_->set_shutup(true);
fitter_->Fit();
fit_results_.push_back(fitter_->fit_result());
//sinfo << fitter_->NegativeLogLikelihood() << endmsg;
//value_scan += 1*parameter_scan->getError();
++step;
++p;
}
p.Finish();
}
void doofit::plotting::profiles::LikelihoodProfiler::ReadFitResults(doofit::toy::ToyStudyStd& toy_study) {
using namespace doofit::toy;
using namespace doocore::io;
FitResultContainer fit_result_container(toy_study.GetFitResult());
const RooFitResult* fit_result(std::get<0>(fit_result_container));
int i = 0;
while (fit_result != nullptr && i < 1000) {
fit_results_.push_back(fit_result);
fit_result_container = toy_study.GetFitResult();
fit_result = std::get<0>(fit_result_container);
//++i;
}
}
bool doofit::plotting::profiles::LikelihoodProfiler::FitResultOkay(const RooFitResult& fit_result) const {
using namespace doocore::io;
if (fit_result.covQual() < 2) {
return false;
} else if (fit_result.statusCodeHistory(0) < 0) {
return false;
} else {
return true;
}
}
void doofit::plotting::profiles::LikelihoodProfiler::PlotHandler(const std::string& plot_path) {
using namespace doocore::io;
std::map<std::string, std::vector<double>> val_scan;
std::vector<double> val_nll;
for (auto var : scan_vars_) {
RooRealVar* var_fixed = dynamic_cast<RooRealVar*>(fit_results_.front()->constPars().find(var->GetName()));
scan_vars_titles_.push_back(var_fixed->GetTitle());
}
int i = 0;
double min_nll(0.0);
Progress p("Processing read in fit results", fit_results_.size());
for (auto result : fit_results_) {
if (FitResultOkay(*result)) {
for (auto var : scan_vars_) {
RooRealVar* var_fixed = dynamic_cast<RooRealVar*>(result->constPars().find(var->GetName()));
if (var_fixed == nullptr) {
serr << "Error in LikelihoodProfiler::PlotHandler(): Cannot find fixed parameter "
<< var->GetName() << " in fit result!" << endmsg;
throw;
}
val_scan[var->GetName()].push_back(var_fixed->getVal());
}
if (min_nll == 0.0 || min_nll > result->minNll()) {
min_nll = result->minNll();
}
val_nll.push_back(result->minNll());
++p;
}
}
p.Finish();
for (auto &nll : val_nll) {
if (nll != 0.0) {
nll -= min_nll;
}
}
if (val_scan.size() == 1) {
doocore::lutils::setStyle();
gStyle->SetPadLeftMargin(0.12);
gStyle->SetTitleOffset(0.75, "y");
} else if (val_scan.size() == 2) {
doocore::lutils::setStyle("2d");
//gStyle->SetNumberContours(999);
gStyle->SetPadRightMargin(0.16);
gStyle->SetTitleOffset(0.75, "z");
}
TCanvas c("c", "c", 800, 600);
if (val_scan.size() == 1) {
const std::vector<double>& val_x = val_scan.begin()->second;
TGraph graph(val_nll.size(), &val_x[0], &val_nll[0]);
graph.Draw("AP");
graph.GetXaxis()->SetTitle(scan_vars_titles_.at(0).c_str());
graph.GetYaxis()->SetTitle("#DeltaLL");
graph.SetMarkerStyle(1);
//graph.SetMarkerSize(10);
graph.SetMarkerColor(kBlue+3);
//c.SaveAs("profile.pdf");
doocore::lutils::printPlot(&c, "profile", plot_path);
} else if (val_scan.size() == 2) {
const std::vector<double>& val_x = val_scan.begin()->second;
const std::vector<double>& val_y = val_scan.rbegin()->second;
auto minmax_x = std::minmax_element(val_x.begin(), val_x.end());
auto minmax_y = std::minmax_element(val_y.begin(), val_y.end());
Progress p_distinct("Counting distinct x and y values", val_x.size()+val_y.size());
std::set<double> distinct_x, distinct_y;
for (auto x : val_x) {
distinct_x.insert(x);
++p_distinct;
}
for (auto y : val_y) {
distinct_y.insert(y);
++p_distinct;
}
p_distinct.Finish();
double min_nll(0.0), max_nll(0.0);
for (auto nll : val_nll) {
if (nll != 0 && (min_nll == 0.0 || nll < min_nll)) {
min_nll = nll;
}
if (nll != 0 && (max_nll == 0.0 || nll > max_nll)) {
max_nll = nll;
}
}
double min_x = *minmax_x.first - (*minmax_x.second-*minmax_x.first)/(distinct_x.size()-1)*0.5;
double max_x = *minmax_x.second + (*minmax_x.second-*minmax_x.first)/(distinct_x.size()-1)*0.5;
double min_y = *minmax_y.first - (*minmax_y.second-*minmax_y.first)/(distinct_y.size()-1)*0.5;
double max_y = *minmax_y.second + (*minmax_y.second-*minmax_y.first)/(distinct_y.size()-1)*0.5;
TH2D histogram("histogram", "histogram", distinct_x.size(), min_x, max_x, distinct_y.size(), min_y, max_y);
// sdebug << "histogram x: " << *minmax_x.first << " - " << *minmax_x.second << endmsg;
// sdebug << "histogram y: " << *minmax_y.first << " - " << *minmax_y.second << endmsg;
Progress p_hist("Filling 2D profile histogram", val_nll.size());
for (int i=0; i<val_nll.size(); ++i) {
// sdebug << val_x.at(i) << ", " << val_y.at(i) << " - " << val_nll.at(i) << endmsg;
// sdebug << "Bin: " << histogram.FindBin(val_x.at(i), val_y.at(i)) << endmsg;
int nbin_x, nbin_y, nbin_z;
histogram.GetBinXYZ(histogram.FindBin(val_x.at(i), val_y.at(i)), nbin_x, nbin_y, nbin_z);
// sdebug << "Bin center x: " << histogram.GetXaxis()->GetBinCenter(nbin_x) << endmsg;
// sdebug << "Bin center y: " << histogram.GetYaxis()->GetBinCenter(nbin_y) << endmsg;
histogram.SetBinContent(histogram.FindBin(val_x.at(i), val_y.at(i)), val_nll.at(i));
++p_hist;
}
p_hist.Finish();
const Int_t NRGBs = 6;
const Int_t NCont = 6;
// Double_t stops[NRGBs] = { 0.00 , 0.50 , 2.00 , 4.50 , 8.00 , 12.5 };
// Double_t red[NRGBs] = { 0.00 , 0.00 , 0.20 , 1.00 , 1.00 , 1.00 };
// Double_t green[NRGBs] = { 0.00 , 0.00 , 0.20 , 1.00 , 1.00 , 1.00 };
// Double_t blue[NRGBs] = { 0.20 , 1.00 , 1.00 , 1.00 , 1.00 , 1.00 };
// TColor::CreateGradientColorTable(NRGBs, stops, red, green, blue, NCont);
// gStyle->SetNumberContours(NCont);
// gStyle->SetPaintTextFormat(".1f");
sinfo << "LikelihoodProfiler::PlotHandler(): Drawing histogram." << endmsg;
histogram.Draw("COLZ");
histogram.GetZaxis()->SetRangeUser(min_nll, max_nll);
histogram.SetXTitle(scan_vars_titles_.at(0).c_str());
histogram.SetYTitle(scan_vars_titles_.at(1).c_str());
histogram.SetZTitle("#DeltaLL");
//c.SaveAs("profile.pdf");
sinfo << "LikelihoodProfiler::PlotHandler(): Saving linear histograms to output files." << endmsg;
doocore::lutils::printPlot(&c, "profile", plot_path, true);
sinfo << "LikelihoodProfiler::PlotHandler(): Saving logarithmic histograms to output files." << endmsg;
c.SetLogz(true);
doocore::lutils::printPlot(&c, "profile_log", plot_path, true);
sinfo << "LikelihoodProfiler::PlotHandler(): All done." << endmsg;
} else {
serr << "Error in LikelihoodProfiler::PlotHandler(): Cannot (yet) plot 3D likelihood." << endmsg;
throw;
}
}
<|endoftext|> |
<commit_before>/*
* fontcolour.cpp - font and colour chooser widget
* Program: kalarm
* Copyright © 2001-2008 by David Jarvie <[email protected]>
*
* 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 <QGroupBox>
#include <QPushButton>
#include <QLabel>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <kglobal.h>
#include <klocale.h>
#include <kfontchooser.h>
#include <kfontdialog.h>
#include <kcolordialog.h>
#include <khbox.h>
#include "kalarmapp.h"
#include "preferences.h"
#include "colourcombo.h"
#include "checkbox.h"
#include "fontcolour.moc"
FontColourChooser::FontColourChooser(QWidget *parent,
const QStringList &fontList, const QString& frameLabel, bool editColours,
bool fg, bool defaultFont, int visibleListSize)
: QWidget(parent),
mFgColourButton(0),
mRemoveColourButton(0),
mColourList(Preferences::messageColours()),
mReadOnly(false)
{
QVBoxLayout* topLayout = new QVBoxLayout(this);
topLayout->setMargin(0);
topLayout->setSpacing(KDialog::spacingHint());
QWidget* page = this;
if (!frameLabel.isNull())
{
page = new QGroupBox(frameLabel, this);
topLayout->addWidget(page);
topLayout = new QVBoxLayout(page);
topLayout->setMargin(KDialog::marginHint());
topLayout->setSpacing(KDialog::spacingHint());
}
if (fg)
{
QHBoxLayout* layout = new QHBoxLayout();
layout->setMargin(0);
topLayout->addLayout(layout);
KHBox* box = new KHBox(page); // to group widgets for QWhatsThis text
box->setMargin(0);
box->setSpacing(KDialog::spacingHint());
layout->addWidget(box);
QLabel* label = new QLabel(i18nc("@label:listbox", "Foreground color:"), box);
label->setMinimumSize(label->sizeHint());
mFgColourButton = new ColourCombo(box);
mFgColourButton->setMinimumSize(mFgColourButton->sizeHint());
connect(mFgColourButton, SIGNAL(activated(const QString&)), SLOT(setSampleColour()));
label->setBuddy(mFgColourButton);
box->setWhatsThis(i18nc("@info:whatsthis", "Select the alarm message foreground color"));
layout->addStretch();
}
QHBoxLayout* layout = new QHBoxLayout();
layout->setMargin(0);
topLayout->addLayout(layout);
KHBox* box = new KHBox(page); // to group widgets for QWhatsThis text
box->setMargin(0);
box->setSpacing(KDialog::spacingHint());
layout->addWidget(box);
QLabel* label = new QLabel(i18nc("@label:listbox", "Background color:"), box);
label->setMinimumSize(label->sizeHint());
mBgColourButton = new ColourCombo(box);
mBgColourButton->setMinimumSize(mBgColourButton->sizeHint());
connect(mBgColourButton, SIGNAL(activated(const QString&)), SLOT(setSampleColour()));
label->setBuddy(mBgColourButton);
box->setWhatsThis(i18nc("@info:whatsthis", "Select the alarm message background color"));
layout->addStretch();
if (editColours)
{
layout = new QHBoxLayout();
layout->setMargin(0);
topLayout->addLayout(layout);
QPushButton* button = new QPushButton(i18nc("@action:button", "Add Color..."), page);
button->setFixedSize(button->sizeHint());
connect(button, SIGNAL(clicked()), SLOT(slotAddColour()));
button->setWhatsThis(i18nc("@info:whatsthis", "Choose a new color to add to the color selection list."));
layout->addWidget(button);
mRemoveColourButton = new QPushButton(i18nc("@action:button", "Remove Color"), page);
mRemoveColourButton->setFixedSize(mRemoveColourButton->sizeHint());
connect(mRemoveColourButton, SIGNAL(clicked()), SLOT(slotRemoveColour()));
mRemoveColourButton->setWhatsThis(i18nc("@info:whatsthis", "Remove the color currently shown in the background color chooser, from the color selection list."));
layout->addWidget(mRemoveColourButton);
}
if (defaultFont)
{
layout = new QHBoxLayout();
layout->setMargin(0);
topLayout->addLayout(layout);
mDefaultFont = new CheckBox(i18nc("@option:check", "Use default font"), page);
mDefaultFont->setMinimumSize(mDefaultFont->sizeHint());
connect(mDefaultFont, SIGNAL(toggled(bool)), SLOT(slotDefaultFontToggled(bool)));
mDefaultFont->setWhatsThis(i18nc("@info:whatsthis", "Check to use the default font current at the time the alarm is displayed."));
layout->addWidget(mDefaultFont);
layout->addWidget(new QWidget(page)); // left adjust the widget
}
else
mDefaultFont = 0;
mFontChooser = new KFontChooser(page, KFontChooser::DisplayFrame, fontList, visibleListSize);
mFontChooser->installEventFilter(this); // for read-only mode
QList<QWidget*> kids = mFontChooser->findChildren<QWidget*>();
for (int i = 0, end = kids.count(); i < end; ++i)
kids[i]->installEventFilter(this);
topLayout->addWidget(mFontChooser);
slotDefaultFontToggled(false);
}
void FontColourChooser::setDefaultFont()
{
if (mDefaultFont)
mDefaultFont->setChecked(true);
}
void FontColourChooser::setFont(const QFont& font, bool onlyFixed)
{
if (mDefaultFont)
mDefaultFont->setChecked(false);
mFontChooser->setFont(font, onlyFixed);
}
bool FontColourChooser::defaultFont() const
{
return mDefaultFont ? mDefaultFont->isChecked() : false;
}
QFont FontColourChooser::font() const
{
return (mDefaultFont && mDefaultFont->isChecked()) ? QFont() : mFontChooser->font();
}
void FontColourChooser::setBgColour(const QColor& colour)
{
mBgColourButton->setColor(colour);
mFontChooser->setBackgroundColor(colour);
}
void FontColourChooser::setSampleColour()
{
QColor bg = mBgColourButton->color();
mFontChooser->setBackgroundColor(bg);
QColor fg = fgColour();
mFontChooser->setColor(fg);
if (mRemoveColourButton)
mRemoveColourButton->setEnabled(!mBgColourButton->isCustomColor()); // no deletion of custom colour
}
QColor FontColourChooser::bgColour() const
{
return mBgColourButton->color();
}
QColor FontColourChooser::fgColour() const
{
if (mFgColourButton)
return mFgColourButton->color();
else
{
QColor bg = mBgColourButton->color();
QPalette pal(bg, bg);
return pal.color(QPalette::Active, QPalette::Text);
}
}
QString FontColourChooser::sampleText() const
{
return mFontChooser->sampleText();
}
void FontColourChooser::setSampleText(const QString& text)
{
mFontChooser->setSampleText(text);
}
void FontColourChooser::setFgColour(const QColor& colour)
{
if (mFgColourButton)
{
mFgColourButton->setColor(colour);
mFontChooser->setColor(colour);
}
}
void FontColourChooser::setReadOnly(bool ro)
{
if (ro != mReadOnly)
{
mReadOnly = ro;
if (mFgColourButton)
mFgColourButton->setReadOnly(ro);
mBgColourButton->setReadOnly(ro);
mDefaultFont->setReadOnly(ro);
}
}
bool FontColourChooser::eventFilter(QObject*, QEvent* e)
{
if (mReadOnly)
{
switch (e->type())
{
case QEvent::MouseMove:
case QEvent::MouseButtonPress:
case QEvent::MouseButtonRelease:
case QEvent::MouseButtonDblClick:
case QEvent::KeyPress:
case QEvent::KeyRelease:
return true; // prevent the event being handled
default:
break;
}
}
return false;
}
void FontColourChooser::slotDefaultFontToggled(bool on)
{
mFontChooser->setEnabled(!on);
}
void FontColourChooser::setColours(const ColourList& colours)
{
mColourList = colours;
mBgColourButton->setColours(mColourList);
mFontChooser->setBackgroundColor(mBgColourButton->color());
}
void FontColourChooser::slotAddColour()
{
QColor colour;
if (KColorDialog::getColor(colour, this) == QDialog::Accepted)
{
mColourList.insert(colour);
mBgColourButton->setColours(mColourList);
}
}
void FontColourChooser::slotRemoveColour()
{
if (!mBgColourButton->isCustomColor())
{
mColourList.remove(mBgColourButton->color());
mBgColourButton->setColours(mColourList);
}
}
<commit_msg>Fix alignment of colour combos<commit_after>/*
* fontcolour.cpp - font and colour chooser widget
* Program: kalarm
* Copyright © 2001-2008 by David Jarvie <[email protected]>
*
* 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 <QGroupBox>
#include <QPushButton>
#include <QLabel>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <kglobal.h>
#include <klocale.h>
#include <kfontchooser.h>
#include <kfontdialog.h>
#include <kcolordialog.h>
#include <khbox.h>
#include "kalarmapp.h"
#include "preferences.h"
#include "colourcombo.h"
#include "checkbox.h"
#include "fontcolour.moc"
FontColourChooser::FontColourChooser(QWidget *parent,
const QStringList &fontList, const QString& frameLabel, bool editColours,
bool fg, bool defaultFont, int visibleListSize)
: QWidget(parent),
mFgColourButton(0),
mRemoveColourButton(0),
mColourList(Preferences::messageColours()),
mReadOnly(false)
{
QVBoxLayout* topLayout = new QVBoxLayout(this);
topLayout->setMargin(0);
topLayout->setSpacing(KDialog::spacingHint());
QWidget* page = this;
if (!frameLabel.isNull())
{
page = new QGroupBox(frameLabel, this);
topLayout->addWidget(page);
topLayout = new QVBoxLayout(page);
topLayout->setMargin(KDialog::marginHint());
topLayout->setSpacing(KDialog::spacingHint());
}
QHBoxLayout* hlayout = new QHBoxLayout();
hlayout->setMargin(0);
topLayout->addLayout(hlayout);
QVBoxLayout* colourLayout = new QVBoxLayout();
colourLayout->setMargin(0);
hlayout->addLayout(colourLayout);
if (fg)
{
KHBox* box = new KHBox(page); // to group widgets for QWhatsThis text
box->setMargin(0);
box->setSpacing(KDialog::spacingHint()/2);
colourLayout->addWidget(box);
QLabel* label = new QLabel(i18nc("@label:listbox", "Foreground color:"), box);
box->setStretchFactor(new QWidget(box), 0);
mFgColourButton = new ColourCombo(box);
connect(mFgColourButton, SIGNAL(activated(const QString&)), SLOT(setSampleColour()));
label->setBuddy(mFgColourButton);
box->setWhatsThis(i18nc("@info:whatsthis", "Select the alarm message foreground color"));
}
KHBox* box = new KHBox(page); // to group widgets for QWhatsThis text
box->setMargin(0);
box->setSpacing(KDialog::spacingHint()/2);
colourLayout->addWidget(box);
QLabel* label = new QLabel(i18nc("@label:listbox", "Background color:"), box);
box->setStretchFactor(new QWidget(box), 0);
mBgColourButton = new ColourCombo(box);
connect(mBgColourButton, SIGNAL(activated(const QString&)), SLOT(setSampleColour()));
label->setBuddy(mBgColourButton);
box->setWhatsThis(i18nc("@info:whatsthis", "Select the alarm message background color"));
hlayout->addStretch();
if (editColours)
{
QHBoxLayout* layout = new QHBoxLayout();
layout->setMargin(0);
topLayout->addLayout(layout);
QPushButton* button = new QPushButton(i18nc("@action:button", "Add Color..."), page);
button->setFixedSize(button->sizeHint());
connect(button, SIGNAL(clicked()), SLOT(slotAddColour()));
button->setWhatsThis(i18nc("@info:whatsthis", "Choose a new color to add to the color selection list."));
layout->addWidget(button);
mRemoveColourButton = new QPushButton(i18nc("@action:button", "Remove Color"), page);
mRemoveColourButton->setFixedSize(mRemoveColourButton->sizeHint());
connect(mRemoveColourButton, SIGNAL(clicked()), SLOT(slotRemoveColour()));
mRemoveColourButton->setWhatsThis(i18nc("@info:whatsthis", "Remove the color currently shown in the background color chooser, from the color selection list."));
layout->addWidget(mRemoveColourButton);
}
if (defaultFont)
{
QHBoxLayout* layout = new QHBoxLayout();
layout->setMargin(0);
topLayout->addLayout(layout);
mDefaultFont = new CheckBox(i18nc("@option:check", "Use default font"), page);
mDefaultFont->setMinimumSize(mDefaultFont->sizeHint());
connect(mDefaultFont, SIGNAL(toggled(bool)), SLOT(slotDefaultFontToggled(bool)));
mDefaultFont->setWhatsThis(i18nc("@info:whatsthis", "Check to use the default font current at the time the alarm is displayed."));
layout->addWidget(mDefaultFont);
layout->addWidget(new QWidget(page)); // left adjust the widget
}
else
mDefaultFont = 0;
mFontChooser = new KFontChooser(page, KFontChooser::DisplayFrame, fontList, visibleListSize);
mFontChooser->installEventFilter(this); // for read-only mode
QList<QWidget*> kids = mFontChooser->findChildren<QWidget*>();
for (int i = 0, end = kids.count(); i < end; ++i)
kids[i]->installEventFilter(this);
topLayout->addWidget(mFontChooser);
slotDefaultFontToggled(false);
}
void FontColourChooser::setDefaultFont()
{
if (mDefaultFont)
mDefaultFont->setChecked(true);
}
void FontColourChooser::setFont(const QFont& font, bool onlyFixed)
{
if (mDefaultFont)
mDefaultFont->setChecked(false);
mFontChooser->setFont(font, onlyFixed);
}
bool FontColourChooser::defaultFont() const
{
return mDefaultFont ? mDefaultFont->isChecked() : false;
}
QFont FontColourChooser::font() const
{
return (mDefaultFont && mDefaultFont->isChecked()) ? QFont() : mFontChooser->font();
}
void FontColourChooser::setBgColour(const QColor& colour)
{
mBgColourButton->setColor(colour);
mFontChooser->setBackgroundColor(colour);
}
void FontColourChooser::setSampleColour()
{
QColor bg = mBgColourButton->color();
mFontChooser->setBackgroundColor(bg);
QColor fg = fgColour();
mFontChooser->setColor(fg);
if (mRemoveColourButton)
mRemoveColourButton->setEnabled(!mBgColourButton->isCustomColor()); // no deletion of custom colour
}
QColor FontColourChooser::bgColour() const
{
return mBgColourButton->color();
}
QColor FontColourChooser::fgColour() const
{
if (mFgColourButton)
return mFgColourButton->color();
else
{
QColor bg = mBgColourButton->color();
QPalette pal(bg, bg);
return pal.color(QPalette::Active, QPalette::Text);
}
}
QString FontColourChooser::sampleText() const
{
return mFontChooser->sampleText();
}
void FontColourChooser::setSampleText(const QString& text)
{
mFontChooser->setSampleText(text);
}
void FontColourChooser::setFgColour(const QColor& colour)
{
if (mFgColourButton)
{
mFgColourButton->setColor(colour);
mFontChooser->setColor(colour);
}
}
void FontColourChooser::setReadOnly(bool ro)
{
if (ro != mReadOnly)
{
mReadOnly = ro;
if (mFgColourButton)
mFgColourButton->setReadOnly(ro);
mBgColourButton->setReadOnly(ro);
mDefaultFont->setReadOnly(ro);
}
}
bool FontColourChooser::eventFilter(QObject*, QEvent* e)
{
if (mReadOnly)
{
switch (e->type())
{
case QEvent::MouseMove:
case QEvent::MouseButtonPress:
case QEvent::MouseButtonRelease:
case QEvent::MouseButtonDblClick:
case QEvent::KeyPress:
case QEvent::KeyRelease:
return true; // prevent the event being handled
default:
break;
}
}
return false;
}
void FontColourChooser::slotDefaultFontToggled(bool on)
{
mFontChooser->setEnabled(!on);
}
void FontColourChooser::setColours(const ColourList& colours)
{
mColourList = colours;
mBgColourButton->setColours(mColourList);
mFontChooser->setBackgroundColor(mBgColourButton->color());
}
void FontColourChooser::slotAddColour()
{
QColor colour;
if (KColorDialog::getColor(colour, this) == QDialog::Accepted)
{
mColourList.insert(colour);
mBgColourButton->setColours(mColourList);
}
}
void FontColourChooser::slotRemoveColour()
{
if (!mBgColourButton->isCustomColor())
{
mColourList.remove(mBgColourButton->color());
mBgColourButton->setColours(mColourList);
}
}
<|endoftext|> |
<commit_before>#ifndef _CH_FRB_IO_HPP
#define _CH_FRB_IO_HPP
#if (__cplusplus < 201103) && !defined(__GXX_EXPERIMENTAL_CXX0X__)
#error "This source file needs to be compiled with C++0x support (g++ -std=c++0x)"
#endif
#include <string>
#include <vector>
#include <hdf5.h>
namespace ch_frb_io {
#if 0
}; // pacify emacs c-mode
#endif
// declared in ch_frb_io_internals.hpp
template<typename T> struct hdf5_extendable_dataset;
struct noncopyable
{
noncopyable() { }
noncopyable(const noncopyable &) = delete;
noncopyable& operator=(const noncopyable &) = delete;
};
// Note that there are two "intensity file" classes: intensity_hdf5_file
// for reading, and intensity_hdf5_ofile for wrtiing.
struct intensity_hdf5_file : noncopyable {
std::string filename;
int nfreq;
int npol;
int nt_file; // number of time samples in file (which can have gaps)
int nt_logical; // total number of samples in time range spanned by file, including gaps
//
// We currently throw an exception unless the frequencies are equally spaced and consecutive.
// Therefore, we don't keep a full list of frequencies, just the endpoints of the range and number of samples.
//
// This still leaves two possibilities: the frequencies can either be ordered from lowest to highest,
// or vice versa. The 'frequencies_are_increasing' flag is set in the former case. (Note that the
// standard CHIME convention is frequencies_are_increasing=false.)
//
// The 'freq_lo_MHz' and 'freq_hi_MHz' fields are the lowest and highest frequencies in the entire
// band. Just to spell this out in detail, if frequencies_are_increasing=true, then the i-th channel
// spans the frequency range
//
// [ freq_lo + i*(freq_hi-freq_lo)/nfreq, freq_lo + (i+1)*(freq_hi-freq_lo)/nfreq ]
//
// and if frequences_are_increasing=false, then the i-th channel spans frequency range
//
// [ freq_hi - (i+1)*(freq_hi-freq_lo)/nfreq, freq_hi - i*(freq_hi-freq_lo)/nfreq ]
//
// where 0 <= i <= nfreq-1.
//
bool frequencies_are_increasing;
double freq_lo_MHz;
double freq_hi_MHz;
//
// We distinguish between "file" time indices, which span the range 0 <= it < nt_file,
// and "logical" time indices, which span the range 0 <= it < nt_logical.
//
// The i-th logical time sample spans the time range
//
// [ time_lo + i*dt_sample, time_lo + (i+1)*dt_sample ]
//
double dt_sample;
double time_lo;
double time_hi; // always equal to time_lo + nt_logical * dt_sample
std::vector<double> times; // 1D array of length nt_file
std::vector<int> time_index_mapping; // 1D array of length nt_file, which maps a "file" index to a "logical" index.
// Polarization info (currently read from file but not really used)
std::vector<std::string> polarizations; // 1D array of length npol, each element is either "XX" or "YY"
// 3d arrays of shape (nfreq, npol, nt_file), verbatim from the hdf5 file.
// Rather than using them directly, you may want to use the member function get_unpolarized_intensity() below.
std::vector<float> intensity;
std::vector<float> weights;
// Summary statistics
double frac_ungapped; // fraction of "logical" time samples which aren't in time gaps
double frac_unmasked; // fraction of _ungapped_ data with large weight
// Construct from file. If 'noisy' is true, then a one-line message will be printed when the file is read.
explicit intensity_hdf5_file(const std::string &filename, bool noisy=true);
//
// Extracts a 2D array containing total intensity in time range [out_t0, out_t0+out_nt),
// summing over polarizations. The 'out_t0' and 'out_nt' are "logical" time indices, not
// "file" time indices. If this range of logical time indices contains gaps, the corresponding
// entries of the 'out_int' and 'out_wt' arrays will be filled with zeros.
//
// The 'out_int' and 'out_wt' arrays have shape (nfreq, out_nt).
//
// The 'out_stride' arg can be negative, if reversing the channel ordering is desired.
// If out_stride is zero, it defaults to out_nt.
//
void get_unpolarized_intensity(float *out_int, float *out_wt, int out_t0, int out_nt, int out_stride=0) const;
void run_unit_tests() const;
};
// Note that there are two "intensity file" classes: intensity_hdf5_file
// for reading, and intensity_hdf5_ofile for wrtiing.
struct intensity_hdf5_ofile {
std::string filename;
double dt_sample;
int nfreq;
int npol;
ssize_t curr_nt; // current size of file (in time samples, not including gaps)
ssize_t curr_ipos; // keeps track of gaps
double curr_time; // time in seconds relative to arbitrary origin
std::unique_ptr<hdf5_extendable_dataset<double> > time_dataset;
std::unique_ptr<hdf5_extendable_dataset<float> > intensity_dataset;
std::unique_ptr<hdf5_extendable_dataset<float> > weights_dataset;
// The freq0+freq1 constructor syntax supports either frequency channel ordering.
// E.g. for CHIME (where frequency channels are ordered highest to lowest), set freq0=800. freq1=400.
// The default nt_chunk=128 comes from ch_vdif_assembler chunk size, assuming downsampling by factor 512.
intensity_hdf5_ofile(const std::string &filename, int nfreq, const std::vector<std::string> &pol,
double freq0_MHz, double freq1_MHz, double dt_sample, ssize_t ipos0=0,
double time0=0.0, int bitshuffle=2, int nt_chunk=128);
~intensity_hdf5_ofile();
// The 'intensity' and 'weight' arrays have shape (nfreq, npol, nt_chunk)
// Note that there is no write() method, the data is incrementally written, and flushed when the destructor is called.
void append_chunk(ssize_t nt_chunk, float *intensity, float *weights, ssize_t chunk_ipos, double chunk_t0);
void append_chunk(ssize_t nt_chunk, float *intensity, float *weights, ssize_t chunk_ipos);
};
// -------------------------------------------------------------------------------------------------
//
// HDF5 wrappers (these are generally useful since the libhdf5 C/C++ api is so clunky)
template<typename T> inline hid_t hdf5_type();
// Reference: https://www.hdfgroup.org/HDF5/doc/H5.user/Datatypes.html
template<> inline hid_t hdf5_type<int>() { return H5T_NATIVE_INT; }
template<> inline hid_t hdf5_type<float>() { return H5T_NATIVE_FLOAT; }
template<> inline hid_t hdf5_type<double>() { return H5T_NATIVE_DOUBLE; }
template<> inline hid_t hdf5_type<unsigned char>() { return H5T_NATIVE_UCHAR; }
struct hdf5_file : noncopyable {
std::string filename;
hid_t file_id;
// If write=false, the file is opened read-only, and an exception is thrown if it doesn't exist.
// If write=true, the file is opened for writing. If the file already exists, it will either be clobbered
// or an exception will be thrown, depending on the value of 'clobber'.
hdf5_file(const std::string &filename, bool write=false, bool clobber=true);
~hdf5_file();
};
struct hdf5_group : noncopyable {
std::string filename;
std::string group_name;
hid_t group_id;
// If create=true, the group will be created if it doesn't exist.
hdf5_group(const hdf5_file &f, const std::string &group_name, bool create=false);
~hdf5_group();
bool has_attribute(const std::string &attr_name) const;
bool has_dataset(const std::string &dataset_name) const;
void get_attribute_shape(const std::string &attr_name, std::vector<hsize_t> &shape) const;
void get_dataset_shape(const std::string &attr_name, std::vector<hsize_t> &shape) const;
// Read scalar attribute
template<typename T> T read_attribute(const std::string &attr_name) const
{
T ret;
this->_read_attribute(attr_name, hdf5_type<T>(), reinterpret_cast<void *> (&ret), std::vector<hsize_t>());
return ret;
}
// Write scalar attribute
template<typename T> void write_attribute(const std::string &attr_name, const T &x)
{
this->_write_attribute(attr_name, hdf5_type<T>(), reinterpret_cast<const void *> (&x), std::vector<hsize_t>());
}
// Write 1D vector attribute
template<typename T> void write_attribute(const std::string &attr_name, const std::vector<T> &x)
{
std::vector<hsize_t> shape(1, x.size());
this->_write_attribute(attr_name, hdf5_type<T>(), reinterpret_cast<const void *> (&x[0]), shape);
}
// Read multidimensional dataset
template<typename T> void read_dataset(const std::string &dataset_name, T *out, const std::vector<hsize_t> &expected_shape) const
{
this->_read_dataset(dataset_name, hdf5_type<T>(), reinterpret_cast<void *> (out), expected_shape);
}
// Write multidimensional dataset
template<typename T> void write_dataset(const std::string &dataset_name, const T *data, const std::vector<hsize_t> &shape)
{
this->_write_dataset(dataset_name, hdf5_type<T>(), reinterpret_cast<const void *> (data), shape);
}
// This interface is intended for small string-valued datasets.
void write_string_dataset(const std::string &dataset_name, const std::vector<std::string> &data, const std::vector<hsize_t> &shape);
void read_string_dataset(const std::string &dataset_name, std::vector<std::string> &data, const std::vector<hsize_t> &expected_shape) const;
// Helpers
void _get_attribute_shape(const std::string &attr_name, hid_t attr_id, std::vector<hsize_t> &shape) const;
void _read_attribute(const std::string &attr_name, hid_t hdf5_type, void *out, const std::vector<hsize_t> &expected_shape) const;
void _write_attribute(const std::string &attr_name, hid_t hdf5_type, const void *data, const std::vector<hsize_t> &shape);
void _get_dataset_shape(const std::string &dataset_name, hid_t dataset_id, std::vector<hsize_t> &shape) const;
void _check_dataset_shape(const std::string &dataset_name, hid_t dataset_id, const std::vector<hsize_t> &expected_shape) const;
void _read_dataset(const std::string &dataset_name, hid_t hdf5_type, void *out, const std::vector<hsize_t> &expected_shape) const;
void _write_dataset(const std::string &dataset_name, hid_t hdf5_type, const void *data, const std::vector<hsize_t> &shape);
};
// This class isn't intended to be used directly; use the wrapper hdf5_extendable_dataset<T> below
struct _hdf5_extendable_dataset : noncopyable {
std::string filename;
std::string group_name;
std::string dataset_name;
std::string full_name;
std::vector<hsize_t> curr_shape;
int axis;
hid_t type;
hid_t dataset_id;
_hdf5_extendable_dataset(const hdf5_group &g, const std::string &dataset_name,
const std::vector<hsize_t> &chunk_shape, int axis, hid_t type, int bitshuffle);
~_hdf5_extendable_dataset();
void write(const void *data, const std::vector<hsize_t> &shape);
};
template<typename T>
struct hdf5_extendable_dataset {
_hdf5_extendable_dataset base;
//
// The 'bitshuffle' argument has the following meaning:
// 0 = no compression
// 1 = try to compress, but if plugin fails then just write uncompressed data instead
// 2 = try to compress, but if plugin fails then print a warning and write uncompressed data instead
// 3 = compression mandatory
//
// List of all filter_ids: https://www.hdfgroup.org/services/contributions.html
// Note that the compile-time constant 'bitshuffle_id' (=32008) is defined above.
//
hdf5_extendable_dataset(const hdf5_group &g, const std::string &dataset_name, const std::vector<hsize_t> &chunk_shape, int axis, int bitshuffle=0) :
base(g, dataset_name, chunk_shape, axis, hdf5_type<T>(), bitshuffle)
{ }
void write(const T *data, const std::vector<hsize_t> &shape)
{
base.write(data, shape);
}
};
} // namespace ch_frb_io
#endif // _CH_FRB_IO_HPP
<commit_msg>#include <memory><commit_after>#ifndef _CH_FRB_IO_HPP
#define _CH_FRB_IO_HPP
#if (__cplusplus < 201103) && !defined(__GXX_EXPERIMENTAL_CXX0X__)
#error "This source file needs to be compiled with C++0x support (g++ -std=c++0x)"
#endif
#include <string>
#include <vector>
#include <memory>
#include <hdf5.h>
namespace ch_frb_io {
#if 0
}; // pacify emacs c-mode
#endif
// declared in ch_frb_io_internals.hpp
template<typename T> struct hdf5_extendable_dataset;
struct noncopyable
{
noncopyable() { }
noncopyable(const noncopyable &) = delete;
noncopyable& operator=(const noncopyable &) = delete;
};
// Note that there are two "intensity file" classes: intensity_hdf5_file
// for reading, and intensity_hdf5_ofile for wrtiing.
struct intensity_hdf5_file : noncopyable {
std::string filename;
int nfreq;
int npol;
int nt_file; // number of time samples in file (which can have gaps)
int nt_logical; // total number of samples in time range spanned by file, including gaps
//
// We currently throw an exception unless the frequencies are equally spaced and consecutive.
// Therefore, we don't keep a full list of frequencies, just the endpoints of the range and number of samples.
//
// This still leaves two possibilities: the frequencies can either be ordered from lowest to highest,
// or vice versa. The 'frequencies_are_increasing' flag is set in the former case. (Note that the
// standard CHIME convention is frequencies_are_increasing=false.)
//
// The 'freq_lo_MHz' and 'freq_hi_MHz' fields are the lowest and highest frequencies in the entire
// band. Just to spell this out in detail, if frequencies_are_increasing=true, then the i-th channel
// spans the frequency range
//
// [ freq_lo + i*(freq_hi-freq_lo)/nfreq, freq_lo + (i+1)*(freq_hi-freq_lo)/nfreq ]
//
// and if frequences_are_increasing=false, then the i-th channel spans frequency range
//
// [ freq_hi - (i+1)*(freq_hi-freq_lo)/nfreq, freq_hi - i*(freq_hi-freq_lo)/nfreq ]
//
// where 0 <= i <= nfreq-1.
//
bool frequencies_are_increasing;
double freq_lo_MHz;
double freq_hi_MHz;
//
// We distinguish between "file" time indices, which span the range 0 <= it < nt_file,
// and "logical" time indices, which span the range 0 <= it < nt_logical.
//
// The i-th logical time sample spans the time range
//
// [ time_lo + i*dt_sample, time_lo + (i+1)*dt_sample ]
//
double dt_sample;
double time_lo;
double time_hi; // always equal to time_lo + nt_logical * dt_sample
std::vector<double> times; // 1D array of length nt_file
std::vector<int> time_index_mapping; // 1D array of length nt_file, which maps a "file" index to a "logical" index.
// Polarization info (currently read from file but not really used)
std::vector<std::string> polarizations; // 1D array of length npol, each element is either "XX" or "YY"
// 3d arrays of shape (nfreq, npol, nt_file), verbatim from the hdf5 file.
// Rather than using them directly, you may want to use the member function get_unpolarized_intensity() below.
std::vector<float> intensity;
std::vector<float> weights;
// Summary statistics
double frac_ungapped; // fraction of "logical" time samples which aren't in time gaps
double frac_unmasked; // fraction of _ungapped_ data with large weight
// Construct from file. If 'noisy' is true, then a one-line message will be printed when the file is read.
explicit intensity_hdf5_file(const std::string &filename, bool noisy=true);
//
// Extracts a 2D array containing total intensity in time range [out_t0, out_t0+out_nt),
// summing over polarizations. The 'out_t0' and 'out_nt' are "logical" time indices, not
// "file" time indices. If this range of logical time indices contains gaps, the corresponding
// entries of the 'out_int' and 'out_wt' arrays will be filled with zeros.
//
// The 'out_int' and 'out_wt' arrays have shape (nfreq, out_nt).
//
// The 'out_stride' arg can be negative, if reversing the channel ordering is desired.
// If out_stride is zero, it defaults to out_nt.
//
void get_unpolarized_intensity(float *out_int, float *out_wt, int out_t0, int out_nt, int out_stride=0) const;
void run_unit_tests() const;
};
// Note that there are two "intensity file" classes: intensity_hdf5_file
// for reading, and intensity_hdf5_ofile for wrtiing.
struct intensity_hdf5_ofile {
std::string filename;
double dt_sample;
int nfreq;
int npol;
ssize_t curr_nt; // current size of file (in time samples, not including gaps)
ssize_t curr_ipos; // keeps track of gaps
double curr_time; // time in seconds relative to arbitrary origin
std::unique_ptr<hdf5_extendable_dataset<double> > time_dataset;
std::unique_ptr<hdf5_extendable_dataset<float> > intensity_dataset;
std::unique_ptr<hdf5_extendable_dataset<float> > weights_dataset;
// The freq0+freq1 constructor syntax supports either frequency channel ordering.
// E.g. for CHIME (where frequency channels are ordered highest to lowest), set freq0=800. freq1=400.
// The default nt_chunk=128 comes from ch_vdif_assembler chunk size, assuming downsampling by factor 512.
intensity_hdf5_ofile(const std::string &filename, int nfreq, const std::vector<std::string> &pol,
double freq0_MHz, double freq1_MHz, double dt_sample, ssize_t ipos0=0,
double time0=0.0, int bitshuffle=2, int nt_chunk=128);
~intensity_hdf5_ofile();
// The 'intensity' and 'weight' arrays have shape (nfreq, npol, nt_chunk)
// Note that there is no write() method, the data is incrementally written, and flushed when the destructor is called.
void append_chunk(ssize_t nt_chunk, float *intensity, float *weights, ssize_t chunk_ipos, double chunk_t0);
void append_chunk(ssize_t nt_chunk, float *intensity, float *weights, ssize_t chunk_ipos);
};
// -------------------------------------------------------------------------------------------------
//
// HDF5 wrappers (these are generally useful since the libhdf5 C/C++ api is so clunky)
template<typename T> inline hid_t hdf5_type();
// Reference: https://www.hdfgroup.org/HDF5/doc/H5.user/Datatypes.html
template<> inline hid_t hdf5_type<int>() { return H5T_NATIVE_INT; }
template<> inline hid_t hdf5_type<float>() { return H5T_NATIVE_FLOAT; }
template<> inline hid_t hdf5_type<double>() { return H5T_NATIVE_DOUBLE; }
template<> inline hid_t hdf5_type<unsigned char>() { return H5T_NATIVE_UCHAR; }
struct hdf5_file : noncopyable {
std::string filename;
hid_t file_id;
// If write=false, the file is opened read-only, and an exception is thrown if it doesn't exist.
// If write=true, the file is opened for writing. If the file already exists, it will either be clobbered
// or an exception will be thrown, depending on the value of 'clobber'.
hdf5_file(const std::string &filename, bool write=false, bool clobber=true);
~hdf5_file();
};
struct hdf5_group : noncopyable {
std::string filename;
std::string group_name;
hid_t group_id;
// If create=true, the group will be created if it doesn't exist.
hdf5_group(const hdf5_file &f, const std::string &group_name, bool create=false);
~hdf5_group();
bool has_attribute(const std::string &attr_name) const;
bool has_dataset(const std::string &dataset_name) const;
void get_attribute_shape(const std::string &attr_name, std::vector<hsize_t> &shape) const;
void get_dataset_shape(const std::string &attr_name, std::vector<hsize_t> &shape) const;
// Read scalar attribute
template<typename T> T read_attribute(const std::string &attr_name) const
{
T ret;
this->_read_attribute(attr_name, hdf5_type<T>(), reinterpret_cast<void *> (&ret), std::vector<hsize_t>());
return ret;
}
// Write scalar attribute
template<typename T> void write_attribute(const std::string &attr_name, const T &x)
{
this->_write_attribute(attr_name, hdf5_type<T>(), reinterpret_cast<const void *> (&x), std::vector<hsize_t>());
}
// Write 1D vector attribute
template<typename T> void write_attribute(const std::string &attr_name, const std::vector<T> &x)
{
std::vector<hsize_t> shape(1, x.size());
this->_write_attribute(attr_name, hdf5_type<T>(), reinterpret_cast<const void *> (&x[0]), shape);
}
// Read multidimensional dataset
template<typename T> void read_dataset(const std::string &dataset_name, T *out, const std::vector<hsize_t> &expected_shape) const
{
this->_read_dataset(dataset_name, hdf5_type<T>(), reinterpret_cast<void *> (out), expected_shape);
}
// Write multidimensional dataset
template<typename T> void write_dataset(const std::string &dataset_name, const T *data, const std::vector<hsize_t> &shape)
{
this->_write_dataset(dataset_name, hdf5_type<T>(), reinterpret_cast<const void *> (data), shape);
}
// This interface is intended for small string-valued datasets.
void write_string_dataset(const std::string &dataset_name, const std::vector<std::string> &data, const std::vector<hsize_t> &shape);
void read_string_dataset(const std::string &dataset_name, std::vector<std::string> &data, const std::vector<hsize_t> &expected_shape) const;
// Helpers
void _get_attribute_shape(const std::string &attr_name, hid_t attr_id, std::vector<hsize_t> &shape) const;
void _read_attribute(const std::string &attr_name, hid_t hdf5_type, void *out, const std::vector<hsize_t> &expected_shape) const;
void _write_attribute(const std::string &attr_name, hid_t hdf5_type, const void *data, const std::vector<hsize_t> &shape);
void _get_dataset_shape(const std::string &dataset_name, hid_t dataset_id, std::vector<hsize_t> &shape) const;
void _check_dataset_shape(const std::string &dataset_name, hid_t dataset_id, const std::vector<hsize_t> &expected_shape) const;
void _read_dataset(const std::string &dataset_name, hid_t hdf5_type, void *out, const std::vector<hsize_t> &expected_shape) const;
void _write_dataset(const std::string &dataset_name, hid_t hdf5_type, const void *data, const std::vector<hsize_t> &shape);
};
// This class isn't intended to be used directly; use the wrapper hdf5_extendable_dataset<T> below
struct _hdf5_extendable_dataset : noncopyable {
std::string filename;
std::string group_name;
std::string dataset_name;
std::string full_name;
std::vector<hsize_t> curr_shape;
int axis;
hid_t type;
hid_t dataset_id;
_hdf5_extendable_dataset(const hdf5_group &g, const std::string &dataset_name,
const std::vector<hsize_t> &chunk_shape, int axis, hid_t type, int bitshuffle);
~_hdf5_extendable_dataset();
void write(const void *data, const std::vector<hsize_t> &shape);
};
template<typename T>
struct hdf5_extendable_dataset {
_hdf5_extendable_dataset base;
//
// The 'bitshuffle' argument has the following meaning:
// 0 = no compression
// 1 = try to compress, but if plugin fails then just write uncompressed data instead
// 2 = try to compress, but if plugin fails then print a warning and write uncompressed data instead
// 3 = compression mandatory
//
// List of all filter_ids: https://www.hdfgroup.org/services/contributions.html
// Note that the compile-time constant 'bitshuffle_id' (=32008) is defined above.
//
hdf5_extendable_dataset(const hdf5_group &g, const std::string &dataset_name, const std::vector<hsize_t> &chunk_shape, int axis, int bitshuffle=0) :
base(g, dataset_name, chunk_shape, axis, hdf5_type<T>(), bitshuffle)
{ }
void write(const T *data, const std::vector<hsize_t> &shape)
{
base.write(data, shape);
}
};
} // namespace ch_frb_io
#endif // _CH_FRB_IO_HPP
<|endoftext|> |
<commit_before>/*
main.cpp:
Copyright (C) 2006 Istvan Varga
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "CsoundGUI.hpp"
int main(int argc, char **argv)
{
CsoundGUIMain *mainWin;
bool enablePython = false;
if (csoundGetSizeOfMYFLT() == (int) sizeof(double))
enablePython = true;
for (int i = 1; i < argc; i++) {
if (std::strcmp(argv[i], "-python") == 0)
enablePython = true;
else if (std::strcmp(argv[i], "-nopython") == 0)
enablePython = false;
}
Fl::lock();
mainWin = new CsoundGUIMain;
mainWin->run(enablePython);
delete mainWin;
Fl::wait(0.0);
return 0;
}
<commit_msg>Call csoundInitialize()<commit_after>/*
main.cpp:
Copyright (C) 2006 Istvan Varga
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "CsoundGUI.hpp"
int main(int argc, char **argv)
{
CsoundGUIMain *mainWin;
bool enablePython = false;
if (csoundInitialize(&argc, &argv, 0) < 0)
return -1;
if (csoundGetSizeOfMYFLT() == (int) sizeof(double))
enablePython = true;
for (int i = 1; i < argc; i++) {
if (std::strcmp(argv[i], "-python") == 0)
enablePython = true;
else if (std::strcmp(argv[i], "-nopython") == 0)
enablePython = false;
}
Fl::lock();
mainWin = new CsoundGUIMain;
mainWin->run(enablePython);
delete mainWin;
Fl::wait(0.0);
return 0;
}
<|endoftext|> |
<commit_before>#include "../../utils/utils.hpp"
#include "../../rdb/rdb.hpp"
#include <cassert>
// Sorry, this is some of the ugliest code
// that I have ever written.
// If this is not the empty string then spt-it-out
// code showing the least squares fit is dumped
// to the given file.
std::string sptpath = "lms.spt";
extern "C" void dgels_( char* trans, int* m, int* n, int* nrhs, double* a, int* lda, double* b, int* ldb, double* work, int* lwork, int* info );
// h, g, d, D
enum { NFeatures = 4 };
// A is the column-major array of features
// from the sample of instances, and b is
// a vector of target h* values.
double *A, *b;
// Acopy is a copy of A which is trashed by dgels.
// If sptpath == "" then Acopy is not used.
double *Acopy;
// Hstar is a copy of b, because dgels trashes b.
// If sptpath == "" then hstar is not used.
double *hstar;
// Filled marks the rows of A that have been
// filled. Just used for a sanity check.
bool *filled;
// sz is the sample size.
unsigned long sz;
// t is the count of records seen so far.
// It is used by the reservoire sampling.
unsigned long t;
// setrow sets the rth row of the A matrix to h,g,d,D
static void setrow(unsigned int r, double h, double g, double d, double D);
static void dfline(std::vector<std::string>&, void*);
static void sptheader(FILE*);
static void sptpoints(FILE*);
static void sptfooter(FILE*);
int main(int argc, const char *argv[]) {
if (argc < 2)
fatal("usage: lms <sample size> <rdbroot> [key=value*]");
char *end = NULL;
sz = strtol(argv[1], &end, 10);
if (end == argv[1])
fatal("Invalid sample size: %s", argv[1]);
A = new double[NFeatures * sz];
b = new double[sz];
if (sptpath != "") {
Acopy = new double[NFeatures * sz];
hstar = new double[sz];
}
filled = new bool[sz];
for (unsigned int i = 0; i < sz; i++)
filled[i] = false;
const char *root = argv[2];
RdbAttrs attrs = attrargs(argc-3, argv+3);
fprintf(stderr, "sample size: %lu\n", sz);
fprintf(stderr, "root: %s\n", root);
fputs(attrs.string().c_str(), stderr);
fputc('\n', stderr);
auto paths = withattrs(root, attrs);
for (auto p = paths.begin(); p != paths.end(); p++) {
FILE *f = fopen(p->c_str(), "r");
if (!f) {
warnx(errno, "Failed to open %s for reading", p->c_str());
continue;
}
dfread(f, dfline);
fclose(f);
}
fprintf(stderr, "%lu solutions\n", t);
int m = t < sz ? t : sz;
for (unsigned int i = 0; i < (unsigned int) m; i++) {
if (!filled[i])
fatal("Row %u of %lu was never set", i, m);
}
if (m < NFeatures)
fatal("Require at least %u solutions", NFeatures);
FILE *sptfile = NULL;
if (sptpath != "") {
sptfile = fopen(sptpath.c_str(), "w");
if (!sptfile) {
fatalx(errno, "Failed to open %s for writing",
sptpath.c_str());
}
}
sptheader(sptfile);
int n = NFeatures;
int nrhs = 1;
int lda = m;
int ldb = m;
int info;
double wksz, *work;
// Get a good work size.
int lwork = -1;
char trans[] = "No transpose";
dgels_(trans, &m, &n, &nrhs, A, &lda, b, &ldb, &wksz,
&lwork, &info);
lwork = (int) wksz;
fprintf(stderr, "got lwork: %d\n", lwork);
work = new double[lwork];
// Solve.
dgels_(trans, &m, &n, &nrhs, A, &lda, b, &ldb, work,
&lwork, &info);
if (info > 0)
fatal("info=%d", info);
sptpoints(sptfile);
fprintf(stderr, "h=%g\ng=%g\nd=%g\nD=%g\n", b[0], b[1], b[2], b[3]);
printf( "%6.2f,%6.2f,%6.2f,%6.2f\n", b[0], b[1], b[2], b[3]);
sptfooter(sptfile);
return 0;
}
static void dfline(std::vector<std::string> &l, void*) {
if (l[0] != "#altrow" || l[1] != "path")
return;
t++;
unsigned long i = 0;
if (t-1 < sz)
i = t-1;
else
i = randgen.integer(0, t);
if (i >= sz)
return;
double g = strtod(l[2].c_str(), NULL);
double h = strtod(l[3].c_str(), NULL);
double D = strtod(l[4].c_str(), NULL);
double d = strtod(l[5].c_str(), NULL);
setrow(i, h, g, d, D);
b[i] = strtod(l[6].c_str(), NULL);
if (hstar)
hstar[i] = b[i];
}
static void setrow(unsigned int r, double h, double g, double d, double D) {
assert (r + 3*sz < NFeatures*sz);
A[r+0*sz] = h;
A[r+1*sz] = g;
A[r+2*sz] = d;
A[r+3*sz] = D;
if (Acopy) {
Acopy[r+0*sz] = h;
Acopy[r+1*sz] = g;
Acopy[r+2*sz] = d;
Acopy[r+3*sz] = D;
}
filled[r] = true;
}
static void sptheader(FILE *f) {
if (!f)
return;
fputs("(let* (\n", f);
}
static void sptpoints(FILE *f) {
if (!f)
return;
fputs("\t(points (\n", f);
int m = t < sz ? t : sz;
for (unsigned int i = 0; i < (unsigned int) m; i++) {
double htrue = hstar[i];
double h = Acopy[i+0*sz];
double g = Acopy[i+1*sz];
double d = Acopy[i+2*sz];
double D = Acopy[i+3*sz];
double hest = h*b[0] + g*b[1] + d*b[2] + D*b[3];
fprintf(f, "\t(%f %f)\n", htrue, hest);
}
fputs("\t))\n", f);
}
static void sptfooter(FILE *f) {
if (!f)
return;
fputs("\t(scatter (scatter-dataset :points points))\n", f);
fputs("\t(plot (num-by-num-plot\n", f);
fputs("\t\t:x-label \"h*\"\n", f);
fputs("\t\t:y-label \"hhat\"\n", f);
fputs("\t\t:dataset scatter))\n", f);
fputs(") (display plot))\n", f);
}<commit_msg>search: seed = 0 for LMS sampling.<commit_after>#include "../../utils/utils.hpp"
#include "../../rdb/rdb.hpp"
#include <cassert>
// Sorry, this is some of the ugliest code
// that I have ever written.
// If this is not the empty string then spt-it-out
// code showing the least squares fit is dumped
// to the given file.
std::string sptpath = "lms.spt";
extern "C" void dgels_( char* trans, int* m, int* n, int* nrhs, double* a, int* lda, double* b, int* ldb, double* work, int* lwork, int* info );
// h, g, d, D
enum { NFeatures = 4 };
// A is the column-major array of features
// from the sample of instances, and b is
// a vector of target h* values.
double *A, *b;
// Acopy is a copy of A which is trashed by dgels.
// If sptpath == "" then Acopy is not used.
double *Acopy;
// Hstar is a copy of b, because dgels trashes b.
// If sptpath == "" then hstar is not used.
double *hstar;
// Filled marks the rows of A that have been
// filled. Just used for a sanity check.
bool *filled;
// sz is the sample size.
unsigned long sz;
// t is the count of records seen so far.
// It is used by the reservoire sampling.
unsigned long t;
// setrow sets the rth row of the A matrix to h,g,d,D
static void setrow(unsigned int r, double h, double g, double d, double D);
static void dfline(std::vector<std::string>&, void*);
static void sptheader(FILE*);
static void sptpoints(FILE*);
static void sptfooter(FILE*);
int main(int argc, const char *argv[]) {
if (argc < 2)
fatal("usage: lms <sample size> <rdbroot> [key=value*]");
// Seed with zero.
randgen = Rand(0);
char *end = NULL;
sz = strtol(argv[1], &end, 10);
if (end == argv[1])
fatal("Invalid sample size: %s", argv[1]);
A = new double[NFeatures * sz];
b = new double[sz];
if (sptpath != "") {
Acopy = new double[NFeatures * sz];
hstar = new double[sz];
}
filled = new bool[sz];
for (unsigned int i = 0; i < sz; i++)
filled[i] = false;
const char *root = argv[2];
RdbAttrs attrs = attrargs(argc-3, argv+3);
fprintf(stderr, "sample size: %lu\n", sz);
fprintf(stderr, "root: %s\n", root);
fputs(attrs.string().c_str(), stderr);
fputc('\n', stderr);
auto paths = withattrs(root, attrs);
fprintf(stderr, "%lu data files\n", paths.size());
for (auto p = paths.begin(); p != paths.end(); p++) {
FILE *f = fopen(p->c_str(), "r");
if (!f) {
warnx(errno, "Failed to open %s for reading", p->c_str());
continue;
}
dfread(f, dfline);
fclose(f);
}
fprintf(stderr, "%lu data points\n", t);
int m = t < sz ? t : sz;
for (unsigned int i = 0; i < (unsigned int) m; i++) {
if (!filled[i])
fatal("Row %u of %lu was never set", i, m);
}
if (m < NFeatures)
fatal("Require at least %u solutions", NFeatures);
FILE *sptfile = NULL;
if (sptpath != "") {
sptfile = fopen(sptpath.c_str(), "w");
if (!sptfile) {
fatalx(errno, "Failed to open %s for writing",
sptpath.c_str());
}
}
sptheader(sptfile);
int n = NFeatures;
int nrhs = 1;
int lda = m;
int ldb = m;
int info;
double wksz, *work;
// Get a good work size.
int lwork = -1;
char trans[] = "No transpose";
dgels_(trans, &m, &n, &nrhs, A, &lda, b, &ldb, &wksz,
&lwork, &info);
lwork = (int) wksz;
fprintf(stderr, "got lwork: %d\n", lwork);
work = new double[lwork];
// Solve.
dgels_(trans, &m, &n, &nrhs, A, &lda, b, &ldb, work,
&lwork, &info);
if (info > 0)
fatal("info=%d", info);
sptpoints(sptfile);
fprintf(stderr, "h=%g\ng=%g\nd=%g\nD=%g\n", b[0], b[1], b[2], b[3]);
printf( "%6.2f,%6.2f,%6.2f,%6.2f\n", b[0], b[1], b[2], b[3]);
sptfooter(sptfile);
return 0;
}
static void dfline(std::vector<std::string> &l, void*) {
if (l[0] != "#altrow" || l[1] != "path")
return;
t++;
unsigned long i = 0;
if (t-1 < sz)
i = t-1;
else
i = randgen.integer(0, t);
if (i >= sz)
return;
double g = strtod(l[2].c_str(), NULL);
double h = strtod(l[3].c_str(), NULL);
double D = strtod(l[4].c_str(), NULL);
double d = strtod(l[5].c_str(), NULL);
setrow(i, h, g, d, D);
b[i] = strtod(l[6].c_str(), NULL);
if (hstar)
hstar[i] = b[i];
}
static void setrow(unsigned int r, double h, double g, double d, double D) {
assert (r + 3*sz < NFeatures*sz);
A[r+0*sz] = h;
A[r+1*sz] = g;
A[r+2*sz] = d;
A[r+3*sz] = D;
if (Acopy) {
Acopy[r+0*sz] = h;
Acopy[r+1*sz] = g;
Acopy[r+2*sz] = d;
Acopy[r+3*sz] = D;
}
filled[r] = true;
}
static void sptheader(FILE *f) {
if (!f)
return;
fputs("(let* (\n", f);
}
static void sptpoints(FILE *f) {
if (!f)
return;
fputs("\t(points (\n", f);
int m = t < sz ? t : sz;
for (unsigned int i = 0; i < (unsigned int) m; i++) {
double htrue = hstar[i];
double h = Acopy[i+0*sz];
double g = Acopy[i+1*sz];
double d = Acopy[i+2*sz];
double D = Acopy[i+3*sz];
double hest = h*b[0] + g*b[1] + d*b[2] + D*b[3];
fprintf(f, "\t(%f %f)\n", htrue, hest);
}
fputs("\t))\n", f);
}
static void sptfooter(FILE *f) {
if (!f)
return;
fputs("\t(scatter (scatter-dataset :points points))\n", f);
fputs("\t(plot (num-by-num-plot\n", f);
fputs("\t\t:x-label \"h*\"\n", f);
fputs("\t\t:y-label \"hhat\"\n", f);
fputs("\t\t:dataset scatter))\n", f);
fputs(") (display plot))\n", f);
}<|endoftext|> |
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkPhotoacousticOCLBeamformer.h"
#include "usServiceReference.h"
mitk::PhotoacousticOCLBeamformer::PhotoacousticOCLBeamformer()
: m_PixelCalculation( NULL )
{
this->AddSourceFile("DASQuadratic.cl");
this->AddSourceFile("DMASQuadratic.cl");
this->AddSourceFile("DASspherical.cl");
this->AddSourceFile("DMASspherical.cl");
this->m_FilterID = "PixelCalculation";
}
mitk::PhotoacousticOCLBeamformer::~PhotoacousticOCLBeamformer()
{
if ( this->m_PixelCalculation )
{
clReleaseKernel( m_PixelCalculation );
}
}
void mitk::PhotoacousticOCLBeamformer::Update()
{
//Check if context & program available
if (!this->Initialize())
{
us::ServiceReference<OclResourceService> ref = GetModuleContext()->GetServiceReference<OclResourceService>();
OclResourceService* resources = GetModuleContext()->GetService<OclResourceService>(ref);
// clean-up also the resources
resources->InvalidateStorage();
mitkThrow() <<"Filter is not initialized. Cannot update.";
}
else{
// Execute
this->Execute();
}
}
void mitk::PhotoacousticOCLBeamformer::Execute()
{
cl_int clErr = 0;
try
{
this->InitExec(this->m_PixelCalculation, m_OutputDim);
}
catch (const mitk::Exception& e)
{
MITK_ERROR << "Catched exception while initializing filter: " << e.what();
return;
}
if (m_Apodisation == nullptr)
{
MITK_INFO << "No apodisation function set; Beamforming will be done without any apodisation.";
m_Apodisation = new float[1];
m_Apodisation[0] = 1;
m_ApodArraySize = 1;
}
us::ServiceReference<OclResourceService> ref = GetModuleContext()->GetServiceReference<OclResourceService>();
OclResourceService* resources = GetModuleContext()->GetService<OclResourceService>(ref);
cl_context gpuContext = resources->GetContext();
cl_mem cl_input = clCreateBuffer(gpuContext, CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, sizeof(float) * m_ApodArraySize, m_Apodisation, &clErr);
CHECK_OCL_ERR(clErr);
// set kernel arguments
clErr = clSetKernelArg( this->m_PixelCalculation, 2, sizeof(cl_mem), &cl_input);
clErr |= clSetKernelArg( this->m_PixelCalculation, 3, sizeof(cl_ushort), &(this->m_ApodArraySize) );
clErr |= clSetKernelArg( this->m_PixelCalculation, 4, sizeof(cl_float), &(this->m_SpeedOfSound) );
clErr |= clSetKernelArg( this->m_PixelCalculation, 5, sizeof(cl_float), &(this->m_TimeSpacing) );
clErr |= clSetKernelArg( this->m_PixelCalculation, 6, sizeof(cl_float), &(this->m_Pitch) );
clErr |= clSetKernelArg( this->m_PixelCalculation, 7, sizeof(cl_float), &(this->m_Angle) );
clErr |= clSetKernelArg( this->m_PixelCalculation, 8, sizeof(cl_ushort), &(this->m_PAImage));
clErr |= clSetKernelArg(this->m_PixelCalculation, 9, sizeof(cl_ushort), &(this->m_TransducerElements));
CHECK_OCL_ERR( clErr );
// execute the filter on a 3D NDRange
this->ExecuteKernel( m_PixelCalculation, 3);
// signalize the GPU-side data changed
m_Output->Modified( GPU_DATA );
}
us::Module *mitk::PhotoacousticOCLBeamformer::GetModule()
{
return us::GetModuleContext()->GetModule();
}
bool mitk::PhotoacousticOCLBeamformer::Initialize()
{
bool buildErr = true;
cl_int clErr = 0;
if ( OclFilter::Initialize() )
{
switch (m_Algorithm)
{
case BeamformingAlgorithm::DASQuad:
{
this->m_PixelCalculation = clCreateKernel(this->m_ClProgram, "ckDASQuad", &clErr);
break;
}
case BeamformingAlgorithm::DMASQuad:
{
this->m_PixelCalculation = clCreateKernel(this->m_ClProgram, "ckDMASQuad", &clErr);
break;
}
case BeamformingAlgorithm::DASSphe:
{
this->m_PixelCalculation = clCreateKernel(this->m_ClProgram, "ckDASSphe", &clErr);
break;
}
case BeamformingAlgorithm::DMASSphe:
{
this->m_PixelCalculation = clCreateKernel(this->m_ClProgram, "ckDMASSphe", &clErr);
break;
}
}
buildErr |= CHECK_OCL_ERR( clErr );
}
return (OclFilter::IsInitialized() && buildErr );
}
void mitk::PhotoacousticOCLBeamformer::SetInput(mitk::Image::Pointer image)
{
if(image->GetDimension() != 3)
{
mitkThrowException(mitk::Exception) << "Input for " << this->GetNameOfClass() <<
" is not 3D. The filter only supports 3D. Please change your input.";
}
OclImageToImageFilter::SetInput(image);
}
mitk::Image::Pointer mitk::PhotoacousticOCLBeamformer::GetOutput()
{
if (m_Output->IsModified(GPU_DATA))
{
void* pData = m_Output->TransferDataToCPU(m_CommandQue);
const unsigned int dimension = 3;
unsigned int* dimensions = m_OutputDim;
const mitk::SlicedGeometry3D::Pointer p_slg = m_Input->GetMITKImage()->GetSlicedGeometry();
MITK_DEBUG << "Creating new MITK Image.";
m_Output->GetMITKImage()->Initialize(this->GetOutputType(), dimension, dimensions);
m_Output->GetMITKImage()->SetSpacing(p_slg->GetSpacing());
m_Output->GetMITKImage()->SetGeometry(m_Input->GetMITKImage()->GetGeometry());
m_Output->GetMITKImage()->SetImportVolume(pData, 0, 0, mitk::Image::ReferenceMemory);
}
MITK_DEBUG << "Image Initialized.";
return m_Output->GetMITKImage();
}<commit_msg>#grammarNazi<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkPhotoacousticOCLBeamformer.h"
#include "usServiceReference.h"
mitk::PhotoacousticOCLBeamformer::PhotoacousticOCLBeamformer()
: m_PixelCalculation( NULL )
{
this->AddSourceFile("DASQuadratic.cl");
this->AddSourceFile("DMASQuadratic.cl");
this->AddSourceFile("DASspherical.cl");
this->AddSourceFile("DMASspherical.cl");
this->m_FilterID = "PixelCalculation";
}
mitk::PhotoacousticOCLBeamformer::~PhotoacousticOCLBeamformer()
{
if ( this->m_PixelCalculation )
{
clReleaseKernel( m_PixelCalculation );
}
}
void mitk::PhotoacousticOCLBeamformer::Update()
{
//Check if context & program available
if (!this->Initialize())
{
us::ServiceReference<OclResourceService> ref = GetModuleContext()->GetServiceReference<OclResourceService>();
OclResourceService* resources = GetModuleContext()->GetService<OclResourceService>(ref);
// clean-up also the resources
resources->InvalidateStorage();
mitkThrow() <<"Filter is not initialized. Cannot update.";
}
else{
// Execute
this->Execute();
}
}
void mitk::PhotoacousticOCLBeamformer::Execute()
{
cl_int clErr = 0;
try
{
this->InitExec(this->m_PixelCalculation, m_OutputDim);
}
catch (const mitk::Exception& e)
{
MITK_ERROR << "Caught exception while initializing filter: " << e.what();
return;
}
if (m_Apodisation == nullptr)
{
MITK_INFO << "No apodisation function set; Beamforming will be done without any apodisation.";
m_Apodisation = new float[1];
m_Apodisation[0] = 1;
m_ApodArraySize = 1;
}
us::ServiceReference<OclResourceService> ref = GetModuleContext()->GetServiceReference<OclResourceService>();
OclResourceService* resources = GetModuleContext()->GetService<OclResourceService>(ref);
cl_context gpuContext = resources->GetContext();
cl_mem cl_input = clCreateBuffer(gpuContext, CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, sizeof(float) * m_ApodArraySize, m_Apodisation, &clErr);
CHECK_OCL_ERR(clErr);
// set kernel arguments
clErr = clSetKernelArg( this->m_PixelCalculation, 2, sizeof(cl_mem), &cl_input);
clErr |= clSetKernelArg( this->m_PixelCalculation, 3, sizeof(cl_ushort), &(this->m_ApodArraySize) );
clErr |= clSetKernelArg( this->m_PixelCalculation, 4, sizeof(cl_float), &(this->m_SpeedOfSound) );
clErr |= clSetKernelArg( this->m_PixelCalculation, 5, sizeof(cl_float), &(this->m_TimeSpacing) );
clErr |= clSetKernelArg( this->m_PixelCalculation, 6, sizeof(cl_float), &(this->m_Pitch) );
clErr |= clSetKernelArg( this->m_PixelCalculation, 7, sizeof(cl_float), &(this->m_Angle) );
clErr |= clSetKernelArg( this->m_PixelCalculation, 8, sizeof(cl_ushort), &(this->m_PAImage));
clErr |= clSetKernelArg(this->m_PixelCalculation, 9, sizeof(cl_ushort), &(this->m_TransducerElements));
CHECK_OCL_ERR( clErr );
// execute the filter on a 3D NDRange
this->ExecuteKernel( m_PixelCalculation, 3);
// signalize the GPU-side data changed
m_Output->Modified( GPU_DATA );
}
us::Module *mitk::PhotoacousticOCLBeamformer::GetModule()
{
return us::GetModuleContext()->GetModule();
}
bool mitk::PhotoacousticOCLBeamformer::Initialize()
{
bool buildErr = true;
cl_int clErr = 0;
if ( OclFilter::Initialize() )
{
switch (m_Algorithm)
{
case BeamformingAlgorithm::DASQuad:
{
this->m_PixelCalculation = clCreateKernel(this->m_ClProgram, "ckDASQuad", &clErr);
break;
}
case BeamformingAlgorithm::DMASQuad:
{
this->m_PixelCalculation = clCreateKernel(this->m_ClProgram, "ckDMASQuad", &clErr);
break;
}
case BeamformingAlgorithm::DASSphe:
{
this->m_PixelCalculation = clCreateKernel(this->m_ClProgram, "ckDASSphe", &clErr);
break;
}
case BeamformingAlgorithm::DMASSphe:
{
this->m_PixelCalculation = clCreateKernel(this->m_ClProgram, "ckDMASSphe", &clErr);
break;
}
}
buildErr |= CHECK_OCL_ERR( clErr );
}
return (OclFilter::IsInitialized() && buildErr );
}
void mitk::PhotoacousticOCLBeamformer::SetInput(mitk::Image::Pointer image)
{
if(image->GetDimension() != 3)
{
mitkThrowException(mitk::Exception) << "Input for " << this->GetNameOfClass() <<
" is not 3D. The filter only supports 3D. Please change your input.";
}
OclImageToImageFilter::SetInput(image);
}
mitk::Image::Pointer mitk::PhotoacousticOCLBeamformer::GetOutput()
{
if (m_Output->IsModified(GPU_DATA))
{
void* pData = m_Output->TransferDataToCPU(m_CommandQue);
const unsigned int dimension = 3;
unsigned int* dimensions = m_OutputDim;
const mitk::SlicedGeometry3D::Pointer p_slg = m_Input->GetMITKImage()->GetSlicedGeometry();
MITK_DEBUG << "Creating new MITK Image.";
m_Output->GetMITKImage()->Initialize(this->GetOutputType(), dimension, dimensions);
m_Output->GetMITKImage()->SetSpacing(p_slg->GetSpacing());
m_Output->GetMITKImage()->SetGeometry(m_Input->GetMITKImage()->GetGeometry());
m_Output->GetMITKImage()->SetImportVolume(pData, 0, 0, mitk::Image::ReferenceMemory);
}
MITK_DEBUG << "Image Initialized.";
return m_Output->GetMITKImage();
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2018, Arm Limited and affiliates.
* SPDX-License-Identifier: Apache-2.0
*
* 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 "CppUTest/TestHarness.h"
#include "test_at_cellularstack.h"
#include <string.h>
#include "AT_CellularNetwork.h"
#include "EventQueue.h"
#include "ATHandler.h"
#include "AT_CellularStack.h"
#include "FileHandle_stub.h"
#include "CellularLog.h"
#include "ATHandler_stub.h"
#include "SocketAddress.h"
using namespace mbed;
using namespace events;
class MyStack : public AT_CellularStack {
public:
bool bool_value;
bool max_sock_value;
nsapi_error_t create_error;
int max_packet_size;
MyStack(ATHandler &atr, int cid, nsapi_ip_stack_t typ) : AT_CellularStack(atr, cid, typ)
{
bool_value = false;
max_sock_value = 0;
create_error = NSAPI_ERROR_OK;
max_packet_size = 0;
}
virtual int get_max_socket_count(){return max_sock_value;}
virtual int get_max_packet_size(){return max_packet_size;}
virtual bool is_protocol_supported(nsapi_protocol_t protocol){return bool_value;}
virtual nsapi_error_t socket_close_impl(int sock_id){return NSAPI_ERROR_OK;}
virtual nsapi_error_t create_socket_impl(CellularSocket *socket){return create_error;}
virtual nsapi_size_or_error_t socket_sendto_impl(CellularSocket *socket, const SocketAddress &address,
const void *data, nsapi_size_t size){return NSAPI_ERROR_OK;}
virtual nsapi_size_or_error_t socket_recvfrom_impl(CellularSocket *socket, SocketAddress *address,
void *buffer, nsapi_size_t size) {return NSAPI_ERROR_OK;}
virtual nsapi_error_t socket_open(nsapi_socket_t *handle, nsapi_protocol_t proto) {return AT_CellularStack::socket_open(handle, proto);}
virtual nsapi_error_t socket_close(nsapi_socket_t handle) {return AT_CellularStack::socket_close(handle);}
virtual nsapi_error_t socket_bind(nsapi_socket_t handle, const SocketAddress &address) {return AT_CellularStack::socket_bind(handle, address);}
virtual nsapi_error_t socket_listen(nsapi_socket_t handle, int backlog) {return AT_CellularStack::socket_listen(handle, backlog);}
virtual nsapi_error_t socket_connect(nsapi_socket_t handle, const SocketAddress &address) {return AT_CellularStack::socket_connect(handle, address);}
virtual nsapi_error_t socket_accept(nsapi_socket_t server,
nsapi_socket_t *handle, SocketAddress *address=0) {return AT_CellularStack::socket_accept(server, handle, address);}
virtual nsapi_size_or_error_t socket_send(nsapi_socket_t handle,
const void *data, nsapi_size_t size) {return AT_CellularStack::socket_send(handle, data, size);}
virtual nsapi_size_or_error_t socket_recv(nsapi_socket_t handle,
void *data, nsapi_size_t size) {return AT_CellularStack::socket_recv(handle, data, size);}
virtual nsapi_size_or_error_t socket_sendto(nsapi_socket_t handle, const SocketAddress &address,
const void *data, nsapi_size_t size) {return AT_CellularStack::socket_sendto(handle, address, data, size);}
virtual nsapi_size_or_error_t socket_recvfrom(nsapi_socket_t handle, SocketAddress *address,
void *buffer, nsapi_size_t size) {return AT_CellularStack::socket_recvfrom(handle, address, buffer, size);}
virtual void socket_attach(nsapi_socket_t handle, void (*callback)(void *), void *data) {return AT_CellularStack::socket_attach(handle, callback, data);}
};
Test_AT_CellularStack::Test_AT_CellularStack()
{
ATHandler_stub::ssize_value = 0;
ATHandler_stub::bool_value = false;
ATHandler_stub::read_string_value = NULL;
}
Test_AT_CellularStack::~Test_AT_CellularStack()
{
}
void Test_AT_CellularStack::test_AT_CellularStack_constructor()
{
EventQueue que;
FileHandle_stub fh1;
ATHandler at(&fh1, que, 0, ",");
MyStack *st = new MyStack(at, 0, IPV4_STACK);
delete st;
}
void Test_AT_CellularStack::test_AT_CellularStack_get_ip_address()
{
EventQueue que;
FileHandle_stub fh1;
ATHandler at(&fh1, que, 0, ",");
MyStack st(at, 0, IPV6_STACK);
CHECK(0 == strlen(st.get_ip_address()));
char table[] = "1.2.3.4.5.65.7.8.9.10.11\0";
ATHandler_stub::ssize_value = -1;
ATHandler_stub::bool_value = true;
ATHandler_stub::read_string_value = table;
CHECK(NULL == st.get_ip_address());
ATHandler_stub::ssize_value = strlen(table);
ATHandler_stub::bool_value = true;
ATHandler_stub::read_string_value = table;
CHECK(st.get_ip_address());
}
void Test_AT_CellularStack::test_AT_CellularStack_socket_open()
{
EventQueue que;
FileHandle_stub fh1;
ATHandler at(&fh1, que, 0, ",");
MyStack st(at, 0, IPV6_STACK);
st.bool_value = false;
CHECK(NSAPI_ERROR_UNSUPPORTED == st.socket_open(NULL, NSAPI_TCP));
st.bool_value = true;
st.max_sock_value = 0;
nsapi_socket_t sock;
CHECK(NSAPI_ERROR_NO_SOCKET == st.socket_open(&sock, NSAPI_TCP));
MyStack st2(at, 0, IPV6_STACK);
st2.bool_value = true;
st2.max_sock_value = 1;
nsapi_socket_t sock2;
CHECK(NSAPI_ERROR_OK == st2.socket_open(&sock2, NSAPI_TCP));
}
void Test_AT_CellularStack::test_AT_CellularStack_socket_close()
{
EventQueue que;
FileHandle_stub fh1;
ATHandler at(&fh1, que, 0, ",");
MyStack st(at, 0, IPV6_STACK);
nsapi_socket_t soc = NULL;
CHECK(NSAPI_ERROR_DEVICE_ERROR == st.socket_close(soc));
st.bool_value = true;
st.max_sock_value = 1;
nsapi_socket_t sock;
CHECK(NSAPI_ERROR_OK == st.socket_open(&sock, NSAPI_TCP));
st.max_sock_value = 0;
CHECK(NSAPI_ERROR_DEVICE_ERROR == st.socket_close(sock));
MyStack st2(at, 0, IPV6_STACK);
st2.max_sock_value = 1;
st2.bool_value = true;
nsapi_socket_t sock2;
CHECK(NSAPI_ERROR_OK == st2.socket_open(&sock2, NSAPI_TCP));
CHECK(NSAPI_ERROR_OK == st2.socket_close(sock2));
}
void Test_AT_CellularStack::test_AT_CellularStack_socket_bind()
{
EventQueue que;
FileHandle_stub fh1;
ATHandler at(&fh1, que, 0, ",");
MyStack st(at, 0, IPV6_STACK);
nsapi_socket_t sock;
SocketAddress addr;
ATHandler_stub::nsapi_error_value = NSAPI_ERROR_ALREADY;
CHECK(NSAPI_ERROR_DEVICE_ERROR == st.socket_bind(NULL, addr));
CHECK(NSAPI_ERROR_ALREADY == st.socket_bind(sock, addr));
}
void Test_AT_CellularStack::test_AT_CellularStack_socket_listen()
{
EventQueue que;
FileHandle_stub fh1;
ATHandler at(&fh1, que, 0, ",");
MyStack st(at, 0, IPV6_STACK);
nsapi_socket_t sock;
CHECK(0 == st.socket_listen(sock, 4));
}
void Test_AT_CellularStack::test_AT_CellularStack_socket_connect()
{
EventQueue que;
FileHandle_stub fh1;
ATHandler at(&fh1, que, 0, ",");
MyStack st(at, 0, IPV6_STACK);
SocketAddress addr;
CHECK(NSAPI_ERROR_DEVICE_ERROR == st.socket_connect(NULL, addr));
nsapi_socket_t sock;
CHECK(NSAPI_ERROR_OK == st.socket_connect(sock, addr));
}
void Test_AT_CellularStack::test_AT_CellularStack_socket_accept()
{
EventQueue que;
FileHandle_stub fh1;
ATHandler at(&fh1, que, 0, ",");
MyStack st(at, 0, IPV6_STACK);
nsapi_socket_t sock;
CHECK(0 == st.socket_accept(NULL, &sock));
}
void Test_AT_CellularStack::test_AT_CellularStack_socket_send()
{
EventQueue que;
FileHandle_stub fh1;
ATHandler at(&fh1, que, 0, ",");
MyStack st(at, 0, IPV6_STACK);
CHECK(NSAPI_ERROR_DEVICE_ERROR == st.socket_send(NULL, "addr", 4));
nsapi_socket_t sock;
CHECK(NSAPI_ERROR_DEVICE_ERROR == st.socket_send(sock, "addr", 4));
SocketAddress addr;
st.max_sock_value = 1;
st.bool_value = true;
st.socket_open(&sock, NSAPI_TCP);
st.socket_connect(sock, addr);
CHECK(NSAPI_ERROR_DEVICE_ERROR == st.socket_send(sock, "addr", 4));
}
void Test_AT_CellularStack::test_AT_CellularStack_socket_sendto()
{
EventQueue que;
FileHandle_stub fh1;
ATHandler at(&fh1, que, 0, ",");
MyStack st(at, 0, IPV6_STACK);
nsapi_socket_t sock;
SocketAddress addr;
CHECK(NSAPI_ERROR_DEVICE_ERROR == st.socket_sendto(NULL, addr, "addr", 4));
st.max_sock_value = 1;
st.bool_value = true;
st.socket_open(&sock, NSAPI_TCP);
st.socket_connect(sock, addr);
st.create_error = NSAPI_ERROR_CONNECTION_LOST;
CHECK(NSAPI_ERROR_CONNECTION_LOST == st.socket_sendto(sock, addr, "addr", 4));
st.create_error = NSAPI_ERROR_OK;
st.max_packet_size = 6;
CHECK(NSAPI_ERROR_OK == st.socket_sendto(sock, addr, "addr", 4));
}
void Test_AT_CellularStack::test_AT_CellularStack_socket_recv()
{
EventQueue que;
FileHandle_stub fh1;
ATHandler at(&fh1, que, 0, ",");
MyStack st(at, 0, IPV6_STACK);
char table[4];
CHECK(NSAPI_ERROR_DEVICE_ERROR == st.socket_recv(NULL, table, 4));
}
void Test_AT_CellularStack::test_AT_CellularStack_socket_recvfrom()
{
EventQueue que;
FileHandle_stub fh1;
ATHandler at(&fh1, que, 0, ",");
MyStack st(at, 0, IPV6_STACK);
char table[4];
CHECK(NSAPI_ERROR_DEVICE_ERROR == st.socket_recvfrom(NULL, NULL, table, 4));
nsapi_socket_t sock;
SocketAddress addr;
st.max_sock_value = 1;
st.bool_value = true;
st.socket_open(&sock, NSAPI_TCP);
st.socket_connect(sock, addr);
st.create_error = NSAPI_ERROR_CONNECTION_LOST;
CHECK(NSAPI_ERROR_CONNECTION_LOST == st.socket_recvfrom(sock, &addr, table, 4));
st.create_error = NSAPI_ERROR_OK;
st.max_packet_size = 6;
CHECK(NSAPI_ERROR_OK == st.socket_recvfrom(sock, &addr, table, 4));
}
void Test_AT_CellularStack::test_AT_CellularStack_socket_attach()
{
EventQueue que;
FileHandle_stub fh1;
ATHandler at(&fh1, que, 0, ",");
MyStack st(at, 0, IPV6_STACK);
st.socket_attach(NULL, NULL, NULL);
nsapi_socket_t sock;
st.max_sock_value = 1;
st.bool_value = true;
st.socket_open(&sock, NSAPI_TCP);
st.socket_attach(sock, NULL, NULL);
}
<commit_msg>Cellular tests: nsapi_socket_t errors fixed in unittests<commit_after>/*
* Copyright (c) 2018, Arm Limited and affiliates.
* SPDX-License-Identifier: Apache-2.0
*
* 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 "CppUTest/TestHarness.h"
#include "test_at_cellularstack.h"
#include <string.h>
#include "AT_CellularNetwork.h"
#include "EventQueue.h"
#include "ATHandler.h"
#include "AT_CellularStack.h"
#include "FileHandle_stub.h"
#include "CellularLog.h"
#include "ATHandler_stub.h"
#include "SocketAddress.h"
using namespace mbed;
using namespace events;
class MyStack : public AT_CellularStack {
public:
bool bool_value;
bool max_sock_value;
nsapi_error_t create_error;
int max_packet_size;
CellularSocket socket;
MyStack(ATHandler &atr, int cid, nsapi_ip_stack_t typ) : AT_CellularStack(atr, cid, typ)
{
bool_value = false;
max_sock_value = 0;
create_error = NSAPI_ERROR_OK;
max_packet_size = 0;
}
virtual int get_max_socket_count(){return max_sock_value;}
virtual int get_max_packet_size(){return max_packet_size;}
virtual bool is_protocol_supported(nsapi_protocol_t protocol){return bool_value;}
virtual nsapi_error_t socket_close_impl(int sock_id){return NSAPI_ERROR_OK;}
virtual nsapi_error_t create_socket_impl(CellularSocket *socket){return create_error;}
virtual nsapi_size_or_error_t socket_sendto_impl(CellularSocket *socket, const SocketAddress &address,
const void *data, nsapi_size_t size){return NSAPI_ERROR_OK;}
virtual nsapi_size_or_error_t socket_recvfrom_impl(CellularSocket *socket, SocketAddress *address,
void *buffer, nsapi_size_t size) {return NSAPI_ERROR_OK;}
virtual nsapi_error_t socket_open(nsapi_socket_t *handle, nsapi_protocol_t proto) {return AT_CellularStack::socket_open(handle, proto);}
virtual nsapi_error_t socket_close(nsapi_socket_t handle) {return AT_CellularStack::socket_close(handle);}
virtual nsapi_error_t socket_bind(nsapi_socket_t handle, const SocketAddress &address) {return AT_CellularStack::socket_bind(handle, address);}
virtual nsapi_error_t socket_listen(nsapi_socket_t handle, int backlog) {return AT_CellularStack::socket_listen(handle, backlog);}
virtual nsapi_error_t socket_connect(nsapi_socket_t handle, const SocketAddress &address) {return AT_CellularStack::socket_connect(handle, address);}
virtual nsapi_error_t socket_accept(nsapi_socket_t server,
nsapi_socket_t *handle, SocketAddress *address=0) {return AT_CellularStack::socket_accept(server, handle, address);}
virtual nsapi_size_or_error_t socket_send(nsapi_socket_t handle,
const void *data, nsapi_size_t size) {return AT_CellularStack::socket_send(handle, data, size);}
virtual nsapi_size_or_error_t socket_recv(nsapi_socket_t handle,
void *data, nsapi_size_t size) {return AT_CellularStack::socket_recv(handle, data, size);}
virtual nsapi_size_or_error_t socket_sendto(nsapi_socket_t handle, const SocketAddress &address,
const void *data, nsapi_size_t size) {return AT_CellularStack::socket_sendto(handle, address, data, size);}
virtual nsapi_size_or_error_t socket_recvfrom(nsapi_socket_t handle, SocketAddress *address,
void *buffer, nsapi_size_t size) {return AT_CellularStack::socket_recvfrom(handle, address, buffer, size);}
virtual void socket_attach(nsapi_socket_t handle, void (*callback)(void *), void *data) {return AT_CellularStack::socket_attach(handle, callback, data);}
};
Test_AT_CellularStack::Test_AT_CellularStack()
{
ATHandler_stub::ssize_value = 0;
ATHandler_stub::bool_value = false;
ATHandler_stub::read_string_value = NULL;
}
Test_AT_CellularStack::~Test_AT_CellularStack()
{
}
void Test_AT_CellularStack::test_AT_CellularStack_constructor()
{
EventQueue que;
FileHandle_stub fh1;
ATHandler at(&fh1, que, 0, ",");
MyStack *st = new MyStack(at, 0, IPV4_STACK);
delete st;
}
void Test_AT_CellularStack::test_AT_CellularStack_get_ip_address()
{
EventQueue que;
FileHandle_stub fh1;
ATHandler at(&fh1, que, 0, ",");
MyStack st(at, 0, IPV6_STACK);
CHECK(0 == strlen(st.get_ip_address()));
char table[] = "1.2.3.4.5.65.7.8.9.10.11\0";
ATHandler_stub::ssize_value = -1;
ATHandler_stub::bool_value = true;
ATHandler_stub::read_string_value = table;
CHECK(NULL == st.get_ip_address());
ATHandler_stub::ssize_value = strlen(table);
ATHandler_stub::bool_value = true;
ATHandler_stub::read_string_value = table;
CHECK(st.get_ip_address());
}
void Test_AT_CellularStack::test_AT_CellularStack_socket_open()
{
EventQueue que;
FileHandle_stub fh1;
ATHandler at(&fh1, que, 0, ",");
MyStack st(at, 0, IPV6_STACK);
st.bool_value = false;
CHECK(NSAPI_ERROR_UNSUPPORTED == st.socket_open(NULL, NSAPI_TCP));
st.bool_value = true;
st.max_sock_value = 0;
nsapi_socket_t sock = &st.socket;
CHECK(NSAPI_ERROR_NO_SOCKET == st.socket_open(&sock, NSAPI_TCP));
MyStack st2(at, 0, IPV6_STACK);
st2.bool_value = true;
st2.max_sock_value = 1;
sock = &st2.socket;
CHECK(NSAPI_ERROR_OK == st2.socket_open(&sock, NSAPI_TCP));
}
void Test_AT_CellularStack::test_AT_CellularStack_socket_close()
{
EventQueue que;
FileHandle_stub fh1;
ATHandler at(&fh1, que, 0, ",");
MyStack st(at, 0, IPV6_STACK);
CHECK(NSAPI_ERROR_DEVICE_ERROR == st.socket_close(&st.socket));
nsapi_socket_t sock = &st.socket;
st.bool_value = true;
st.max_sock_value = 1;
CHECK(NSAPI_ERROR_OK == st.socket_open(&sock, NSAPI_TCP));
st.max_sock_value = 0;
CHECK(NSAPI_ERROR_DEVICE_ERROR == st.socket_close(sock));
MyStack st2(at, 0, IPV6_STACK);
st2.max_sock_value = 1;
st2.bool_value = true;
sock = &st2.socket;
CHECK(NSAPI_ERROR_OK == st2.socket_open(&sock, NSAPI_TCP));
CHECK(NSAPI_ERROR_OK == st2.socket_close(sock));
}
void Test_AT_CellularStack::test_AT_CellularStack_socket_bind()
{
EventQueue que;
FileHandle_stub fh1;
ATHandler at(&fh1, que, 0, ",");
MyStack st(at, 0, IPV6_STACK);
SocketAddress addr;
ATHandler_stub::nsapi_error_value = NSAPI_ERROR_ALREADY;
CHECK(NSAPI_ERROR_DEVICE_ERROR == st.socket_bind(NULL, addr));
CHECK(NSAPI_ERROR_ALREADY == st.socket_bind(&st.socket, addr));
}
void Test_AT_CellularStack::test_AT_CellularStack_socket_listen()
{
EventQueue que;
FileHandle_stub fh1;
ATHandler at(&fh1, que, 0, ",");
MyStack st(at, 0, IPV6_STACK);
CHECK(NSAPI_ERROR_UNSUPPORTED == st.socket_listen(&st.socket, 4));
}
void Test_AT_CellularStack::test_AT_CellularStack_socket_connect()
{
EventQueue que;
FileHandle_stub fh1;
ATHandler at(&fh1, que, 0, ",");
MyStack st(at, 0, IPV6_STACK);
SocketAddress addr;
CHECK(NSAPI_ERROR_DEVICE_ERROR == st.socket_connect(NULL, addr));
CHECK(NSAPI_ERROR_OK == st.socket_connect(&st.socket, addr));
}
void Test_AT_CellularStack::test_AT_CellularStack_socket_accept()
{
EventQueue que;
FileHandle_stub fh1;
ATHandler at(&fh1, que, 0, ",");
MyStack st(at, 0, IPV6_STACK);
nsapi_socket_t sock = &st.socket;
CHECK(NSAPI_ERROR_UNSUPPORTED == st.socket_accept(NULL, &sock));
}
void Test_AT_CellularStack::test_AT_CellularStack_socket_send()
{
EventQueue que;
FileHandle_stub fh1;
ATHandler at(&fh1, que, 0, ",");
MyStack st(at, 0, IPV6_STACK);
CHECK(NSAPI_ERROR_DEVICE_ERROR == st.socket_send(NULL, "addr", 4));
CHECK(NSAPI_ERROR_DEVICE_ERROR == st.socket_send(&st.socket, "addr", 4));
SocketAddress addr;
st.max_sock_value = 1;
st.bool_value = true;
nsapi_socket_t sock = &st.socket;
st.socket_open(&sock, NSAPI_TCP);
st.socket_connect(sock, addr);
CHECK(NSAPI_ERROR_DEVICE_ERROR == st.socket_send(sock, "addr", 4));
}
void Test_AT_CellularStack::test_AT_CellularStack_socket_sendto()
{
EventQueue que;
FileHandle_stub fh1;
ATHandler at(&fh1, que, 0, ",");
MyStack st(at, 0, IPV6_STACK);
SocketAddress addr;
CHECK(NSAPI_ERROR_DEVICE_ERROR == st.socket_sendto(NULL, addr, "addr", 4));
st.max_sock_value = 1;
st.bool_value = true;
nsapi_socket_t sock = &st.socket;
st.socket_open(&sock, NSAPI_TCP);
st.socket_connect(sock, addr);
st.create_error = NSAPI_ERROR_CONNECTION_LOST;
CHECK(NSAPI_ERROR_CONNECTION_LOST == st.socket_sendto(sock, addr, "addr", 4));
st.create_error = NSAPI_ERROR_OK;
st.max_packet_size = 6;
CHECK(NSAPI_ERROR_OK == st.socket_sendto(sock, addr, "addr", 4));
}
void Test_AT_CellularStack::test_AT_CellularStack_socket_recv()
{
EventQueue que;
FileHandle_stub fh1;
ATHandler at(&fh1, que, 0, ",");
MyStack st(at, 0, IPV6_STACK);
char table[4];
CHECK(NSAPI_ERROR_DEVICE_ERROR == st.socket_recv(NULL, table, 4));
}
void Test_AT_CellularStack::test_AT_CellularStack_socket_recvfrom()
{
EventQueue que;
FileHandle_stub fh1;
ATHandler at(&fh1, que, 0, ",");
MyStack st(at, 0, IPV6_STACK);
char table[4];
CHECK(NSAPI_ERROR_DEVICE_ERROR == st.socket_recvfrom(NULL, NULL, table, 4));
SocketAddress addr;
st.max_sock_value = 1;
st.bool_value = true;
nsapi_socket_t sock = &st.socket;
st.socket_open(&sock, NSAPI_TCP);
st.socket_connect(sock, addr);
st.create_error = NSAPI_ERROR_CONNECTION_LOST;
CHECK(NSAPI_ERROR_CONNECTION_LOST == st.socket_recvfrom(sock, &addr, table, 4));
st.create_error = NSAPI_ERROR_OK;
st.max_packet_size = 6;
CHECK(NSAPI_ERROR_OK == st.socket_recvfrom(sock, &addr, table, 4));
}
void Test_AT_CellularStack::test_AT_CellularStack_socket_attach()
{
EventQueue que;
FileHandle_stub fh1;
ATHandler at(&fh1, que, 0, ",");
MyStack st(at, 0, IPV6_STACK);
st.socket_attach(NULL, NULL, NULL);
st.max_sock_value = 1;
st.bool_value = true;
nsapi_socket_t sock = &st.socket;
st.socket_open(&sock, NSAPI_TCP);
st.socket_attach(sock, NULL, NULL);
}
<|endoftext|> |
<commit_before>// Copyright 2020 The Wuffs Authors.
//
// 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
//
// https://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.
// ----------------
/*
imageviewer is a simple GUI program for viewing images. On Linux, GUI means
X11. To run:
$CXX imageviewer.cc -lxcb -lxcb-image && \
./a.out ../../test/data/bricks-*.gif; rm -f a.out
for a C++ compiler $CXX, such as clang++ or g++.
The Space and BackSpace keys cycle through the files, if more than one was
given as command line arguments. If none were given, the program reads from
stdin.
The Return key is equivalent to the Space key.
The Escape key quits.
*/
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
// Wuffs ships as a "single file C library" or "header file library" as per
// https://github.com/nothings/stb/blob/master/docs/stb_howto.txt
//
// To use that single file as a "foo.c"-like implementation, instead of a
// "foo.h"-like header, #define WUFFS_IMPLEMENTATION before #include'ing or
// compiling it.
#define WUFFS_IMPLEMENTATION
// Defining the WUFFS_CONFIG__MODULE* macros are optional, but it lets users of
// release/c/etc.c choose which parts of Wuffs to build. That file contains the
// entire Wuffs standard library, implementing a variety of codecs and file
// formats. Without this macro definition, an optimizing compiler or linker may
// very well discard Wuffs code for unused codecs, but listing the Wuffs
// modules we use makes that process explicit. Preprocessing means that such
// code simply isn't compiled.
#define WUFFS_CONFIG__MODULES
#define WUFFS_CONFIG__MODULE__ADLER32
#define WUFFS_CONFIG__MODULE__AUX__BASE
#define WUFFS_CONFIG__MODULE__AUX__IMAGE
#define WUFFS_CONFIG__MODULE__BASE
#define WUFFS_CONFIG__MODULE__BMP
#define WUFFS_CONFIG__MODULE__CRC32
#define WUFFS_CONFIG__MODULE__DEFLATE
#define WUFFS_CONFIG__MODULE__GIF
#define WUFFS_CONFIG__MODULE__LZW
#define WUFFS_CONFIG__MODULE__NIE
#define WUFFS_CONFIG__MODULE__PNG
#define WUFFS_CONFIG__MODULE__WBMP
#define WUFFS_CONFIG__MODULE__ZLIB
// If building this program in an environment that doesn't easily accommodate
// relative includes, you can use the script/inline-c-relative-includes.go
// program to generate a stand-alone C file.
#include "../../release/c/wuffs-unsupported-snapshot.c"
// X11 limits its image dimensions to uint16_t.
#define MAX_INCL_DIMENSION 65535
#define NUM_BACKGROUND_COLORS 3
#define SRC_BUFFER_ARRAY_SIZE (64 * 1024)
wuffs_base__color_u32_argb_premul g_background_colors[NUM_BACKGROUND_COLORS] = {
0xFF000000,
0xFFFFFFFF,
0xFFA9009A,
};
uint32_t g_width = 0;
uint32_t g_height = 0;
wuffs_aux::MemOwner g_pixbuf_mem_owner(nullptr, &free);
wuffs_base__pixel_buffer g_pixbuf = {0};
uint32_t g_background_color_index = 0;
bool //
load_image(const char* filename) {
FILE* file = stdin;
const char* adj_filename = "<stdin>";
if (filename) {
FILE* f = fopen(filename, "rb");
if (f == NULL) {
printf("%s: could not open file\n", filename);
return false;
}
file = f;
adj_filename = filename;
}
g_width = 0;
g_height = 0;
g_pixbuf_mem_owner.reset();
g_pixbuf = wuffs_base__null_pixel_buffer();
wuffs_aux::DecodeImageCallbacks callbacks;
wuffs_aux::sync_io::FileInput input(file);
wuffs_aux::DecodeImageResult res = wuffs_aux::DecodeImage(
callbacks, input,
// Use PIXEL_BLEND__SRC_OVER, not the default PIXEL_BLEND__SRC, because
// we also pass a background color.
WUFFS_BASE__PIXEL_BLEND__SRC_OVER,
g_background_colors[g_background_color_index], MAX_INCL_DIMENSION);
if (filename) {
fclose(file);
}
// wuffs_aux::DecodeImageCallbacks's default implementation should give us an
// interleaved (not multi-planar) pixel buffer, so that all of the pixel data
// is in a single 2-dimensional table (plane 0). Later on, we re-interpret
// that table as XCB image data, which isn't something we could do if we had
// e.g. multi-planar YCbCr.
if (!res.pixbuf.pixcfg.pixel_format().is_interleaved()) {
printf("%s: non-interleaved pixbuf\n", adj_filename);
return false;
}
wuffs_base__table_u8 tab = res.pixbuf.plane(0);
if (tab.width != tab.stride) {
// The xcb_image_create_native call, later on, assumes that (tab.height *
// tab.stride) bytes are readable, which isn't quite the same as what
// wuffs_base__table__flattened_length(tab.width, tab.height, tab.stride)
// returns unless the table is tight (its width equals its stride).
printf("%s: could not allocate tight pixbuf\n", adj_filename);
return false;
}
g_width = res.pixbuf.pixcfg.width();
g_height = res.pixbuf.pixcfg.height();
g_pixbuf_mem_owner = std::move(res.pixbuf_mem_owner);
g_pixbuf = res.pixbuf;
if (res.error_message.empty()) {
printf("%s: ok (%" PRIu32 " x %" PRIu32 ")\n", adj_filename, g_width,
g_height);
} else {
printf("%s: %s\n", adj_filename, res.error_message.c_str());
}
return res.pixbuf.pixcfg.is_valid();
}
// ---------------------------------------------------------------------
#if defined(__linux__)
#define SUPPORTED_OPERATING_SYSTEM
#include <xcb/xcb.h>
#include <xcb/xcb_image.h>
#define XK_BackSpace 0xFF08
#define XK_Escape 0xFF1B
#define XK_Return 0xFF0D
xcb_atom_t g_atom_net_wm_name = XCB_NONE;
xcb_atom_t g_atom_utf8_string = XCB_NONE;
xcb_atom_t g_atom_wm_protocols = XCB_NONE;
xcb_atom_t g_atom_wm_delete_window = XCB_NONE;
xcb_pixmap_t g_pixmap = XCB_NONE;
xcb_keysym_t* g_keysyms = NULL;
xcb_get_keyboard_mapping_reply_t* g_keyboard_mapping = NULL;
void //
init_keymap(xcb_connection_t* c, const xcb_setup_t* z) {
xcb_get_keyboard_mapping_cookie_t cookie = xcb_get_keyboard_mapping(
c, z->min_keycode, z->max_keycode - z->min_keycode + 1);
g_keyboard_mapping = xcb_get_keyboard_mapping_reply(c, cookie, NULL);
g_keysyms = (xcb_keysym_t*)(g_keyboard_mapping + 1);
}
xcb_window_t //
make_window(xcb_connection_t* c, xcb_screen_t* s) {
xcb_window_t w = xcb_generate_id(c);
uint32_t value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK;
uint32_t value_list[2];
value_list[0] = s->black_pixel;
value_list[1] = XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_KEY_PRESS;
xcb_create_window(c, 0, w, s->root, 0, 0, 1024, 768, 0,
XCB_WINDOW_CLASS_INPUT_OUTPUT, s->root_visual, value_mask,
value_list);
xcb_change_property(c, XCB_PROP_MODE_REPLACE, w, g_atom_net_wm_name,
g_atom_utf8_string, 8, 12, "Image Viewer");
xcb_change_property(c, XCB_PROP_MODE_REPLACE, w, g_atom_wm_protocols,
XCB_ATOM_ATOM, 32, 1, &g_atom_wm_delete_window);
xcb_map_window(c, w);
return w;
}
bool //
load(xcb_connection_t* c,
xcb_screen_t* s,
xcb_window_t w,
xcb_gcontext_t g,
const char* filename) {
if (g_pixmap != XCB_NONE) {
xcb_free_pixmap(c, g_pixmap);
}
if (!load_image(filename)) {
return false;
}
wuffs_base__table_u8 tab = g_pixbuf.plane(0);
xcb_create_pixmap(c, s->root_depth, g_pixmap, w, g_width, g_height);
xcb_image_t* image = xcb_image_create_native(
c, g_width, g_height, XCB_IMAGE_FORMAT_Z_PIXMAP, s->root_depth, NULL,
tab.height * tab.stride, tab.ptr);
xcb_image_put(c, g_pixmap, g, image, 0, 0, 0);
xcb_image_destroy(image);
return true;
}
int //
main(int argc, char** argv) {
xcb_connection_t* c = xcb_connect(NULL, NULL);
const xcb_setup_t* z = xcb_get_setup(c);
xcb_screen_t* s = xcb_setup_roots_iterator(z).data;
{
xcb_intern_atom_cookie_t cookie0 =
xcb_intern_atom(c, 1, 12, "_NET_WM_NAME");
xcb_intern_atom_cookie_t cookie1 = xcb_intern_atom(c, 1, 11, "UTF8_STRING");
xcb_intern_atom_cookie_t cookie2 =
xcb_intern_atom(c, 1, 12, "WM_PROTOCOLS");
xcb_intern_atom_cookie_t cookie3 =
xcb_intern_atom(c, 1, 16, "WM_DELETE_WINDOW");
xcb_intern_atom_reply_t* reply0 = xcb_intern_atom_reply(c, cookie0, NULL);
xcb_intern_atom_reply_t* reply1 = xcb_intern_atom_reply(c, cookie1, NULL);
xcb_intern_atom_reply_t* reply2 = xcb_intern_atom_reply(c, cookie2, NULL);
xcb_intern_atom_reply_t* reply3 = xcb_intern_atom_reply(c, cookie3, NULL);
g_atom_net_wm_name = reply0->atom;
g_atom_utf8_string = reply1->atom;
g_atom_wm_protocols = reply2->atom;
g_atom_wm_delete_window = reply3->atom;
free(reply0);
free(reply1);
free(reply2);
free(reply3);
}
xcb_window_t w = make_window(c, s);
xcb_gcontext_t g = xcb_generate_id(c);
xcb_create_gc(c, g, w, 0, NULL);
init_keymap(c, z);
xcb_flush(c);
g_pixmap = xcb_generate_id(c);
bool loaded = load(c, s, w, g, (argc > 1) ? argv[1] : NULL);
int arg = 1;
while (true) {
xcb_generic_event_t* event = xcb_wait_for_event(c);
bool reload = false;
switch (event->response_type & 0x7F) {
case XCB_EXPOSE: {
xcb_expose_event_t* e = (xcb_expose_event_t*)event;
if (loaded && (e->count == 0)) {
xcb_copy_area(c, g_pixmap, w, g, 0, 0, 0, 0, g_width, g_height);
xcb_flush(c);
}
break;
}
case XCB_KEY_PRESS: {
xcb_key_press_event_t* e = (xcb_key_press_event_t*)event;
uint32_t i = e->detail;
if ((z->min_keycode <= i) && (i <= z->max_keycode)) {
i = g_keysyms[(i - z->min_keycode) *
g_keyboard_mapping->keysyms_per_keycode];
switch (i) {
case XK_Escape:
return 0;
case ' ':
case XK_BackSpace:
case XK_Return:
if (argc <= 2) {
break;
}
arg += (i != XK_BackSpace) ? +1 : -1;
if (arg == 0) {
arg = argc - 1;
} else if (arg == argc) {
arg = 1;
}
reload = true;
break;
case ',':
case '.':
g_background_color_index +=
(i == ',') ? (NUM_BACKGROUND_COLORS - 1) : 1;
g_background_color_index %= NUM_BACKGROUND_COLORS;
reload = true;
break;
}
}
break;
}
case XCB_CLIENT_MESSAGE: {
xcb_client_message_event_t* e = (xcb_client_message_event_t*)event;
if (e->data.data32[0] == g_atom_wm_delete_window) {
return 0;
}
break;
}
}
free(event);
if (reload) {
loaded = load(c, s, w, g, argv[arg]);
xcb_clear_area(c, 1, w, 0, 0, 0xFFFF, 0xFFFF);
xcb_flush(c);
}
}
return 0;
}
#endif // defined(__linux__)
// ---------------------------------------------------------------------
#if !defined(SUPPORTED_OPERATING_SYSTEM)
int //
main(int argc, char** argv) {
printf("unsupported operating system\n");
return 1;
}
#endif // !defined(SUPPORTED_OPERATING_SYSTEM)
<commit_msg>Make imageviewer not segfault on XCB errors<commit_after>// Copyright 2020 The Wuffs Authors.
//
// 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
//
// https://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.
// ----------------
/*
imageviewer is a simple GUI program for viewing images. On Linux, GUI means
X11. To run:
$CXX imageviewer.cc -lxcb -lxcb-image && \
./a.out ../../test/data/bricks-*.gif; rm -f a.out
for a C++ compiler $CXX, such as clang++ or g++.
The Space and BackSpace keys cycle through the files, if more than one was
given as command line arguments. If none were given, the program reads from
stdin.
The Return key is equivalent to the Space key.
The Escape key quits.
*/
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
// Wuffs ships as a "single file C library" or "header file library" as per
// https://github.com/nothings/stb/blob/master/docs/stb_howto.txt
//
// To use that single file as a "foo.c"-like implementation, instead of a
// "foo.h"-like header, #define WUFFS_IMPLEMENTATION before #include'ing or
// compiling it.
#define WUFFS_IMPLEMENTATION
// Defining the WUFFS_CONFIG__MODULE* macros are optional, but it lets users of
// release/c/etc.c choose which parts of Wuffs to build. That file contains the
// entire Wuffs standard library, implementing a variety of codecs and file
// formats. Without this macro definition, an optimizing compiler or linker may
// very well discard Wuffs code for unused codecs, but listing the Wuffs
// modules we use makes that process explicit. Preprocessing means that such
// code simply isn't compiled.
#define WUFFS_CONFIG__MODULES
#define WUFFS_CONFIG__MODULE__ADLER32
#define WUFFS_CONFIG__MODULE__AUX__BASE
#define WUFFS_CONFIG__MODULE__AUX__IMAGE
#define WUFFS_CONFIG__MODULE__BASE
#define WUFFS_CONFIG__MODULE__BMP
#define WUFFS_CONFIG__MODULE__CRC32
#define WUFFS_CONFIG__MODULE__DEFLATE
#define WUFFS_CONFIG__MODULE__GIF
#define WUFFS_CONFIG__MODULE__LZW
#define WUFFS_CONFIG__MODULE__NIE
#define WUFFS_CONFIG__MODULE__PNG
#define WUFFS_CONFIG__MODULE__WBMP
#define WUFFS_CONFIG__MODULE__ZLIB
// If building this program in an environment that doesn't easily accommodate
// relative includes, you can use the script/inline-c-relative-includes.go
// program to generate a stand-alone C file.
#include "../../release/c/wuffs-unsupported-snapshot.c"
// X11 limits its image dimensions to uint16_t.
#define MAX_INCL_DIMENSION 65535
#define NUM_BACKGROUND_COLORS 3
#define SRC_BUFFER_ARRAY_SIZE (64 * 1024)
wuffs_base__color_u32_argb_premul g_background_colors[NUM_BACKGROUND_COLORS] = {
0xFF000000,
0xFFFFFFFF,
0xFFA9009A,
};
uint32_t g_width = 0;
uint32_t g_height = 0;
wuffs_aux::MemOwner g_pixbuf_mem_owner(nullptr, &free);
wuffs_base__pixel_buffer g_pixbuf = {0};
uint32_t g_background_color_index = 0;
bool //
load_image(const char* filename) {
FILE* file = stdin;
const char* adj_filename = "<stdin>";
if (filename) {
FILE* f = fopen(filename, "rb");
if (f == NULL) {
printf("%s: could not open file\n", filename);
return false;
}
file = f;
adj_filename = filename;
}
g_width = 0;
g_height = 0;
g_pixbuf_mem_owner.reset();
g_pixbuf = wuffs_base__null_pixel_buffer();
wuffs_aux::DecodeImageCallbacks callbacks;
wuffs_aux::sync_io::FileInput input(file);
wuffs_aux::DecodeImageResult res = wuffs_aux::DecodeImage(
callbacks, input,
// Use PIXEL_BLEND__SRC_OVER, not the default PIXEL_BLEND__SRC, because
// we also pass a background color.
WUFFS_BASE__PIXEL_BLEND__SRC_OVER,
g_background_colors[g_background_color_index], MAX_INCL_DIMENSION);
if (filename) {
fclose(file);
}
// wuffs_aux::DecodeImageCallbacks's default implementation should give us an
// interleaved (not multi-planar) pixel buffer, so that all of the pixel data
// is in a single 2-dimensional table (plane 0). Later on, we re-interpret
// that table as XCB image data, which isn't something we could do if we had
// e.g. multi-planar YCbCr.
if (!res.pixbuf.pixcfg.pixel_format().is_interleaved()) {
printf("%s: non-interleaved pixbuf\n", adj_filename);
return false;
}
wuffs_base__table_u8 tab = res.pixbuf.plane(0);
if (tab.width != tab.stride) {
// The xcb_image_create_native call, later on, assumes that (tab.height *
// tab.stride) bytes are readable, which isn't quite the same as what
// wuffs_base__table__flattened_length(tab.width, tab.height, tab.stride)
// returns unless the table is tight (its width equals its stride).
printf("%s: could not allocate tight pixbuf\n", adj_filename);
return false;
}
g_width = res.pixbuf.pixcfg.width();
g_height = res.pixbuf.pixcfg.height();
g_pixbuf_mem_owner = std::move(res.pixbuf_mem_owner);
g_pixbuf = res.pixbuf;
if (res.error_message.empty()) {
printf("%s: ok (%" PRIu32 " x %" PRIu32 ")\n", adj_filename, g_width,
g_height);
} else {
printf("%s: %s\n", adj_filename, res.error_message.c_str());
}
return res.pixbuf.pixcfg.is_valid();
}
// ---------------------------------------------------------------------
#if defined(__linux__)
#define SUPPORTED_OPERATING_SYSTEM
#include <xcb/xcb.h>
#include <xcb/xcb_image.h>
#define XK_BackSpace 0xFF08
#define XK_Escape 0xFF1B
#define XK_Return 0xFF0D
xcb_atom_t g_atom_net_wm_name = XCB_NONE;
xcb_atom_t g_atom_utf8_string = XCB_NONE;
xcb_atom_t g_atom_wm_protocols = XCB_NONE;
xcb_atom_t g_atom_wm_delete_window = XCB_NONE;
xcb_pixmap_t g_pixmap = XCB_NONE;
xcb_keysym_t* g_keysyms = NULL;
xcb_get_keyboard_mapping_reply_t* g_keyboard_mapping = NULL;
void //
init_keymap(xcb_connection_t* c, const xcb_setup_t* z) {
xcb_get_keyboard_mapping_cookie_t cookie = xcb_get_keyboard_mapping(
c, z->min_keycode, z->max_keycode - z->min_keycode + 1);
g_keyboard_mapping = xcb_get_keyboard_mapping_reply(c, cookie, NULL);
g_keysyms = (xcb_keysym_t*)(g_keyboard_mapping + 1);
}
xcb_window_t //
make_window(xcb_connection_t* c, xcb_screen_t* s) {
xcb_window_t w = xcb_generate_id(c);
uint32_t value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK;
uint32_t value_list[2];
value_list[0] = s->black_pixel;
value_list[1] = XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_KEY_PRESS;
xcb_create_window(c, 0, w, s->root, 0, 0, 1024, 768, 0,
XCB_WINDOW_CLASS_INPUT_OUTPUT, s->root_visual, value_mask,
value_list);
xcb_change_property(c, XCB_PROP_MODE_REPLACE, w, g_atom_net_wm_name,
g_atom_utf8_string, 8, 12, "Image Viewer");
xcb_change_property(c, XCB_PROP_MODE_REPLACE, w, g_atom_wm_protocols,
XCB_ATOM_ATOM, 32, 1, &g_atom_wm_delete_window);
xcb_map_window(c, w);
return w;
}
bool //
load(xcb_connection_t* c,
xcb_screen_t* s,
xcb_window_t w,
xcb_gcontext_t g,
const char* filename) {
if (g_pixmap != XCB_NONE) {
xcb_free_pixmap(c, g_pixmap);
}
if (!load_image(filename)) {
return false;
}
wuffs_base__table_u8 tab = g_pixbuf.plane(0);
xcb_create_pixmap(c, s->root_depth, g_pixmap, w, g_width, g_height);
xcb_image_t* image = xcb_image_create_native(
c, g_width, g_height, XCB_IMAGE_FORMAT_Z_PIXMAP, s->root_depth, NULL,
tab.height * tab.stride, tab.ptr);
xcb_image_put(c, g_pixmap, g, image, 0, 0, 0);
xcb_image_destroy(image);
return true;
}
int //
main(int argc, char** argv) {
xcb_connection_t* c = xcb_connect(NULL, NULL);
const xcb_setup_t* z = xcb_get_setup(c);
xcb_screen_t* s = xcb_setup_roots_iterator(z).data;
{
xcb_intern_atom_cookie_t cookie0 =
xcb_intern_atom(c, 1, 12, "_NET_WM_NAME");
xcb_intern_atom_cookie_t cookie1 = xcb_intern_atom(c, 1, 11, "UTF8_STRING");
xcb_intern_atom_cookie_t cookie2 =
xcb_intern_atom(c, 1, 12, "WM_PROTOCOLS");
xcb_intern_atom_cookie_t cookie3 =
xcb_intern_atom(c, 1, 16, "WM_DELETE_WINDOW");
xcb_intern_atom_reply_t* reply0 = xcb_intern_atom_reply(c, cookie0, NULL);
xcb_intern_atom_reply_t* reply1 = xcb_intern_atom_reply(c, cookie1, NULL);
xcb_intern_atom_reply_t* reply2 = xcb_intern_atom_reply(c, cookie2, NULL);
xcb_intern_atom_reply_t* reply3 = xcb_intern_atom_reply(c, cookie3, NULL);
g_atom_net_wm_name = reply0->atom;
g_atom_utf8_string = reply1->atom;
g_atom_wm_protocols = reply2->atom;
g_atom_wm_delete_window = reply3->atom;
free(reply0);
free(reply1);
free(reply2);
free(reply3);
}
xcb_window_t w = make_window(c, s);
xcb_gcontext_t g = xcb_generate_id(c);
xcb_create_gc(c, g, w, 0, NULL);
init_keymap(c, z);
xcb_flush(c);
g_pixmap = xcb_generate_id(c);
bool loaded = load(c, s, w, g, (argc > 1) ? argv[1] : NULL);
int arg = 1;
while (true) {
xcb_generic_event_t* event = xcb_wait_for_event(c);
// XXX: Large pictures may cause XCB_CONN_CLOSED_REQ_LEN_EXCEED because,
// e.g., 4_194_303 * 4 = 16_777_212 = not nearly enough,
// requiring some trickery to be uploaded to the server.
if (!event) {
printf("XCB failure (error code %d)\n", xcb_connection_has_error(c));
exit(EXIT_FAILURE);
}
bool reload = false;
switch (event->response_type & 0x7F) {
case XCB_EXPOSE: {
xcb_expose_event_t* e = (xcb_expose_event_t*)event;
if (loaded && (e->count == 0)) {
xcb_copy_area(c, g_pixmap, w, g, 0, 0, 0, 0, g_width, g_height);
xcb_flush(c);
}
break;
}
case XCB_KEY_PRESS: {
xcb_key_press_event_t* e = (xcb_key_press_event_t*)event;
uint32_t i = e->detail;
if ((z->min_keycode <= i) && (i <= z->max_keycode)) {
i = g_keysyms[(i - z->min_keycode) *
g_keyboard_mapping->keysyms_per_keycode];
switch (i) {
case XK_Escape:
return 0;
case ' ':
case XK_BackSpace:
case XK_Return:
if (argc <= 2) {
break;
}
arg += (i != XK_BackSpace) ? +1 : -1;
if (arg == 0) {
arg = argc - 1;
} else if (arg == argc) {
arg = 1;
}
reload = true;
break;
case ',':
case '.':
g_background_color_index +=
(i == ',') ? (NUM_BACKGROUND_COLORS - 1) : 1;
g_background_color_index %= NUM_BACKGROUND_COLORS;
reload = true;
break;
}
}
break;
}
case XCB_CLIENT_MESSAGE: {
xcb_client_message_event_t* e = (xcb_client_message_event_t*)event;
if (e->data.data32[0] == g_atom_wm_delete_window) {
return 0;
}
break;
}
}
free(event);
if (reload) {
loaded = load(c, s, w, g, argv[arg]);
xcb_clear_area(c, 1, w, 0, 0, 0xFFFF, 0xFFFF);
xcb_flush(c);
}
}
return 0;
}
#endif // defined(__linux__)
// ---------------------------------------------------------------------
#if !defined(SUPPORTED_OPERATING_SYSTEM)
int //
main(int argc, char** argv) {
printf("unsupported operating system\n");
return 1;
}
#endif // !defined(SUPPORTED_OPERATING_SYSTEM)
<|endoftext|> |
<commit_before>#include "HelloPolycodeApp.h"
HelloPolycodeApp::HelloPolycodeApp(PolycodeView *view) : EventHandler() {
core = new POLYCODE_CORE(view, 640,480,false,false,0,0,90);
CoreServices::getInstance()->getResourceManager()->addArchive("Resources/default.pak");
CoreServices::getInstance()->getResourceManager()->addDirResource("default", false);
screen = new PhysicsScreen(10, 60);
ScreenShape *shape = new ScreenShape(ScreenShape::SHAPE_RECT, 600,30);
shape->setColor(0.0,0.0,0.0,1.0);
shape->setPosition(640/2, 400);
screen->addPhysicsChild(shape, PhysicsScreenEntity::ENTITY_RECT, true);
for(int i=0; i < 50; i++) {
shape = new ScreenShape(ScreenShape::SHAPE_RECT, 20,5);
shape->setRotation(rand() % 360);
shape->setPosition(rand() % 640, rand() % 300);
screen->addPhysicsChild(shape, PhysicsScreenEntity::ENTITY_RECT, false);
}
collisionSound = new Sound("Resources/hit.wav");
screen->addEventListener(this, PhysicsScreenEvent::EVENT_SOLVE_SHAPE_COLLISION);
}
void HelloPolycodeApp::handleEvent(Event *e) {
if(e->getDispatcher() == screen) {
switch(e->getEventCode()) {
case PhysicsScreenEvent::EVENT_SOLVE_SHAPE_COLLISION:
PhysicsScreenEvent *pe = (PhysicsScreenEvent*)e;
if(pe->impactStrength > 5)
collisionSound->Play();
break;
}
}
}
HelloPolycodeApp::~HelloPolycodeApp() {
}
bool HelloPolycodeApp::Update() {
return core->updateAndRender();
}
<commit_msg>Rebased 2DPhysics_Contacts on screenrewrite<commit_after>#include "HelloPolycodeApp.h"
HelloPolycodeApp::HelloPolycodeApp(PolycodeView *view) {
core = new POLYCODE_CORE(view, 640,480,false,false,0,0,90);
PhysicsScene2D *scene = new PhysicsScene2D(10, 60);
ScenePrimitive *shape = new ScenePrimitive(ScenePrimitive::TYPE_VPLANE, 600,30);
shape->setColor(0.0,0.0,0.1,1.0);
shape->setPosition(640/2, 40);
scene->addPhysicsChild(shape, PhysicsScreenEntity::ENTITY_RECT, true);
for(int i=0; i < 200; i++) {
shape = new ScenePrimitive(ScenePrimitive::TYPE_PLANE, 20,5);
shape->setPitch(rand() % 360);
shape->setPosition(rand() % 640, rand() % 300);
scene->addPhysicsChild(shape, PhysicsScreenEntity::ENTITY_RECT, false);
}
}
HelloPolycodeApp::~HelloPolycodeApp() {
}
bool HelloPolycodeApp::Update() {
return core->updateAndRender();
}
<|endoftext|> |
<commit_before>/*
* traywindow.cpp - the KDE system tray applet
* Program: kalarm
* Copyright © 2002-2008 by David Jarvie <[email protected]>
*
* 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" //krazy:exclude=includes (kalarm.h must be first)
#include "traywindow.moc"
#include "alarmcalendar.h"
#include "alarmlistview.h"
#include "alarmresources.h"
#include "alarmtext.h"
#include "functions.h"
#include "kalarmapp.h"
#include "mainwindow.h"
#include "messagewin.h"
#include "newalarmaction.h"
#include "prefdlg.h"
#include "preferences.h"
#include "templatemenuaction.h"
#include <stdlib.h>
#include <QToolTip>
#include <QMouseEvent>
#include <QList>
#include <kactioncollection.h>
#include <ktoggleaction.h>
#include <kapplication.h>
#include <klocale.h>
#include <kaboutdata.h>
#include <kmenu.h>
#include <kmessagebox.h>
#include <kstandarddirs.h>
#include <kstandardaction.h>
#include <kstandardguiitem.h>
#include <kiconeffect.h>
#include <kconfig.h>
#include <kdebug.h>
struct TipItem
{
QDateTime dateTime;
QString text;
};
/*=============================================================================
= Class: TrayWindow
= The KDE system tray window.
=============================================================================*/
TrayWindow::TrayWindow(MainWindow* parent)
: KSystemTrayIcon(parent),
mAssocMainWindow(parent)
{
kDebug();
// Set up GUI icons
mIconEnabled = loadIcon("kalarm");
if (mIconEnabled.isNull())
KMessageBox::sorry(parent, i18nc("@info", "Cannot load system tray icon."));
else
{
KIconLoader loader;
QImage iconDisabled = mIconEnabled.pixmap(loader.currentSize(KIconLoader::Panel)).toImage();
KIconEffect::toGray(iconDisabled, 1.0);
mIconDisabled = QIcon(QPixmap::fromImage(iconDisabled));
}
#ifdef __GNUC__
#warning How to implement drag-and-drop?
#endif
//setAcceptDrops(true); // allow drag-and-drop onto this window
// Set up the context menu
KActionCollection* actions = actionCollection();
KAction* a = KAlarm::createAlarmEnableAction(this);
actions->addAction(QLatin1String("tAlarmsEnable"), a);
contextMenu()->addAction(a);
connect(theApp(), SIGNAL(alarmEnabledToggled(bool)), SLOT(setEnabledStatus(bool)));
mActionNew = new NewAlarmAction(false, i18nc("@action", "&New Alarm"), this);
actions->addAction(QLatin1String("tNew"), mActionNew);
contextMenu()->addAction(mActionNew);
connect(mActionNew, SIGNAL(selected(EditAlarmDlg::Type)), SLOT(slotNewAlarm(EditAlarmDlg::Type)));
mActionNewFromTemplate = KAlarm::createNewFromTemplateAction(i18nc("@action", "New Alarm From &Template"), actions, QLatin1String("tNewFromTempl"));
contextMenu()->addAction(mActionNewFromTemplate);
connect(mActionNewFromTemplate, SIGNAL(selected(const KAEvent*)), SLOT(slotNewFromTemplate(const KAEvent*)));
contextMenu()->addAction(KStandardAction::preferences(this, SLOT(slotPreferences()), actions));
// Replace the default handler for the Quit context menu item
const char* quitName = KStandardAction::name(KStandardAction::Quit);
delete actions->action(quitName);
KStandardAction::quit(this, SLOT(slotQuit()), actions);
// Set icon to correspond with the alarms enabled menu status
setEnabledStatus(theApp()->alarmsEnabled());
connect(AlarmResources::instance(), SIGNAL(resourceStatusChanged(AlarmResource*, AlarmResources::Change)), SLOT(slotResourceStatusChanged()));
connect(this, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), SLOT(slotActivated(QSystemTrayIcon::ActivationReason)));
slotResourceStatusChanged(); // initialise action states
}
TrayWindow::~TrayWindow()
{
kDebug();
theApp()->removeWindow(this);
emit deleted();
}
/******************************************************************************
* Called when the status of a resource has changed.
* Enable or disable actions appropriately.
*/
void TrayWindow::slotResourceStatusChanged()
{
// Find whether there are any writable active alarm resources
bool active = AlarmResources::instance()->activeCount(AlarmResource::ACTIVE, true);
mActionNew->setEnabled(active);
mActionNewFromTemplate->setEnabled(active);
}
/******************************************************************************
* Called when the "New Alarm" menu item is selected to edit a new alarm.
*/
void TrayWindow::slotNewAlarm(EditAlarmDlg::Type type)
{
KAlarm::editNewAlarm(type);
}
/******************************************************************************
* Called when the "New Alarm" menu item is selected to edit a new alarm.
*/
void TrayWindow::slotNewFromTemplate(const KAEvent* event)
{
KAlarm::editNewAlarm(event);
}
/******************************************************************************
* Called when the "Configure KAlarm" menu item is selected.
*/
void TrayWindow::slotPreferences()
{
KAlarmPrefDlg::display();
}
/******************************************************************************
* Called when the Quit context menu item is selected.
*/
void TrayWindow::slotQuit()
{
theApp()->doQuit(parentWidget());
}
/******************************************************************************
* Called when the Alarms Enabled action status has changed.
* Updates the alarms enabled menu item check state, and the icon pixmap.
*/
void TrayWindow::setEnabledStatus(bool status)
{
kDebug() << (int)status;
setIcon(status ? mIconEnabled : mIconDisabled);
}
/******************************************************************************
* Called when the mouse is clicked over the panel icon.
* A left click displays the KAlarm main window.
* A middle button click displays the New Alarm window.
*/
void TrayWindow::slotActivated(QSystemTrayIcon::ActivationReason reason)
{
if (reason == QSystemTrayIcon::Trigger)
{
// Left click: display/hide the first main window
if (mAssocMainWindow && mAssocMainWindow->isVisible())
{
mAssocMainWindow->raise();
mAssocMainWindow->activateWindow();
}
}
else if (reason == QSystemTrayIcon::MiddleClick)
{
if (mActionNew->isEnabled())
mActionNew->trigger(); // display a New Alarm dialog
}
}
/******************************************************************************
* Called when the drag cursor enters the panel icon.
*/
void TrayWindow::dragEnterEvent(QDragEnterEvent* e)
{
MainWindow::executeDragEnterEvent(e, 0);
}
/******************************************************************************
* Called when an object is dropped on the panel icon.
* If the object is recognised, the edit alarm dialog is opened appropriately.
*/
void TrayWindow::dropEvent(QDropEvent* e)
{
MainWindow::executeDropEvent(0, e);
}
/******************************************************************************
* Called when any event occurs.
* If it's a tooltip event, display the tooltip text showing alarms due in the
* next 24 hours. The limit of 24 hours is because only times, not dates, are
* displayed.
*/
bool TrayWindow::event(QEvent* e)
{
if (e->type() != QEvent::ToolTip)
return KSystemTrayIcon::event(e);
QHelpEvent* he = (QHelpEvent*)e;
bool enabled = theApp()->alarmsEnabled();
QString altext;
if (enabled && Preferences::tooltipAlarmCount())
altext = tooltipAlarmText();
QString text;
if (enabled)
text = i18nc("@info:tooltip", "%1%2", KGlobal::mainComponent().aboutData()->programName(), altext);
else
text = i18nc("@info:tooltip 'KAlarm - disabled'", "%1 - disabled", KGlobal::mainComponent().aboutData()->programName());
kDebug() << text;
QToolTip::showText(he->globalPos(), text);
return true;
}
/******************************************************************************
* Return the tooltip text showing alarms due in the next 24 hours.
* The limit of 24 hours is because only times, not dates, are displayed.
*/
QString TrayWindow::tooltipAlarmText() const
{
KAEvent event;
const QString& prefix = Preferences::tooltipTimeToPrefix();
int maxCount = Preferences::tooltipAlarmCount();
KDateTime now = KDateTime::currentLocalDateTime();
KDateTime tomorrow = now.addDays(1);
// Get today's and tomorrow's alarms, sorted in time order
int i, iend;
QList<TipItem> items;
KAEvent::List events = AlarmCalendar::resources()->events(KDateTime(now.date(), QTime(0,0,0), KDateTime::LocalZone), tomorrow, KCalEvent::ACTIVE);
for (i = 0, iend = events.count(); i < iend; ++i)
{
KAEvent* event = events[i];
if (event->enabled() && !event->expired() && event->action() == KAEvent::MESSAGE)
{
TipItem item;
QDateTime dateTime = event->nextTrigger(KAEvent::DISPLAY_TRIGGER).effectiveKDateTime().toLocalZone().dateTime();
if (dateTime > tomorrow.dateTime())
continue; // ignore alarms after tomorrow at the current clock time
item.dateTime = dateTime;
// The alarm is due today, or early tomorrow
if (Preferences::showTooltipAlarmTime())
{
item.text += KGlobal::locale()->formatTime(item.dateTime.time());
item.text += QLatin1Char(' ');
}
if (Preferences::showTooltipTimeToAlarm())
{
int mins = (now.dateTime().secsTo(item.dateTime) + 59) / 60;
if (mins < 0)
mins = 0;
char minutes[3] = "00";
minutes[0] = (mins%60) / 10 + '0';
minutes[1] = (mins%60) % 10 + '0';
if (Preferences::showTooltipAlarmTime())
item.text += i18nc("@info/plain prefix + hours:minutes", "(%1%2:%3)", prefix, mins/60, minutes);
else
item.text += i18nc("@info/plain prefix + hours:minutes", "%1%2:%3", prefix, mins/60, minutes);
item.text += QLatin1Char(' ');
}
item.text += AlarmText::summary(event);
// Insert the item into the list in time-sorted order
int it = 0;
for (int itend = items.count(); it < itend; ++it)
{
if (item.dateTime <= items[it].dateTime)
break;
}
items.insert(it, item);
}
}
kDebug();
QString text;
int count = 0;
for (i = 0, iend = items.count(); i < iend; ++i)
{
kDebug() << "--" << (count+1) << ")" << items[i].text;
text += "<br />" + items[i].text;
if (++count == maxCount)
break;
}
return text;
}
/******************************************************************************
* Called when the associated main window is closed.
*/
void TrayWindow::removeWindow(MainWindow* win)
{
if (win == mAssocMainWindow)
mAssocMainWindow = 0;
}
<commit_msg>Fix warning<commit_after>/*
* traywindow.cpp - the KDE system tray applet
* Program: kalarm
* Copyright © 2002-2008 by David Jarvie <[email protected]>
*
* 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" //krazy:exclude=includes (kalarm.h must be first)
#include "traywindow.moc"
#include "alarmcalendar.h"
#include "alarmlistview.h"
#include "alarmresources.h"
#include "alarmtext.h"
#include "functions.h"
#include "kalarmapp.h"
#include "mainwindow.h"
#include "messagewin.h"
#include "newalarmaction.h"
#include "prefdlg.h"
#include "preferences.h"
#include "templatemenuaction.h"
#include <stdlib.h>
#include <QToolTip>
#include <QMouseEvent>
#include <QList>
#include <kactioncollection.h>
#include <ktoggleaction.h>
#include <kapplication.h>
#include <klocale.h>
#include <kaboutdata.h>
#include <kmenu.h>
#include <kmessagebox.h>
#include <kstandarddirs.h>
#include <kstandardaction.h>
#include <kstandardguiitem.h>
#include <kiconeffect.h>
#include <kconfig.h>
#include <kdebug.h>
struct TipItem
{
QDateTime dateTime;
QString text;
};
/*=============================================================================
= Class: TrayWindow
= The KDE system tray window.
=============================================================================*/
TrayWindow::TrayWindow(MainWindow* parent)
: KSystemTrayIcon(parent),
mAssocMainWindow(parent)
{
kDebug();
// Set up GUI icons
mIconEnabled = loadIcon("kalarm");
if (mIconEnabled.isNull())
KMessageBox::sorry(parent, i18nc("@info", "Cannot load system tray icon."));
else
{
KIconLoader loader;
QImage iconDisabled = mIconEnabled.pixmap(loader.currentSize(KIconLoader::Panel)).toImage();
KIconEffect::toGray(iconDisabled, 1.0);
mIconDisabled = QIcon(QPixmap::fromImage(iconDisabled));
}
#ifdef __GNUC__
#warning How to implement drag-and-drop?
#endif
//setAcceptDrops(true); // allow drag-and-drop onto this window
// Set up the context menu
KActionCollection* actions = actionCollection();
KAction* a = KAlarm::createAlarmEnableAction(this);
actions->addAction(QLatin1String("tAlarmsEnable"), a);
contextMenu()->addAction(a);
connect(theApp(), SIGNAL(alarmEnabledToggled(bool)), SLOT(setEnabledStatus(bool)));
mActionNew = new NewAlarmAction(false, i18nc("@action", "&New Alarm"), this);
actions->addAction(QLatin1String("tNew"), mActionNew);
contextMenu()->addAction(mActionNew);
connect(mActionNew, SIGNAL(selected(EditAlarmDlg::Type)), SLOT(slotNewAlarm(EditAlarmDlg::Type)));
mActionNewFromTemplate = KAlarm::createNewFromTemplateAction(i18nc("@action", "New Alarm From &Template"), actions, QLatin1String("tNewFromTempl"));
contextMenu()->addAction(mActionNewFromTemplate);
connect(mActionNewFromTemplate, SIGNAL(selected(const KAEvent*)), SLOT(slotNewFromTemplate(const KAEvent*)));
contextMenu()->addAction(KStandardAction::preferences(this, SLOT(slotPreferences()), actions));
// Replace the default handler for the Quit context menu item
const char* quitName = KStandardAction::name(KStandardAction::Quit);
delete actions->action(quitName);
KStandardAction::quit(this, SLOT(slotQuit()), actions);
// Set icon to correspond with the alarms enabled menu status
setEnabledStatus(theApp()->alarmsEnabled());
connect(AlarmResources::instance(), SIGNAL(resourceStatusChanged(AlarmResource*, AlarmResources::Change)), SLOT(slotResourceStatusChanged()));
connect(this, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), SLOT(slotActivated(QSystemTrayIcon::ActivationReason)));
slotResourceStatusChanged(); // initialise action states
}
TrayWindow::~TrayWindow()
{
kDebug();
theApp()->removeWindow(this);
emit deleted();
}
/******************************************************************************
* Called when the status of a resource has changed.
* Enable or disable actions appropriately.
*/
void TrayWindow::slotResourceStatusChanged()
{
// Find whether there are any writable active alarm resources
bool active = AlarmResources::instance()->activeCount(AlarmResource::ACTIVE, true);
mActionNew->setEnabled(active);
mActionNewFromTemplate->setEnabled(active);
}
/******************************************************************************
* Called when the "New Alarm" menu item is selected to edit a new alarm.
*/
void TrayWindow::slotNewAlarm(EditAlarmDlg::Type type)
{
KAlarm::editNewAlarm(type);
}
/******************************************************************************
* Called when the "New Alarm" menu item is selected to edit a new alarm.
*/
void TrayWindow::slotNewFromTemplate(const KAEvent* event)
{
KAlarm::editNewAlarm(event);
}
/******************************************************************************
* Called when the "Configure KAlarm" menu item is selected.
*/
void TrayWindow::slotPreferences()
{
KAlarmPrefDlg::display();
}
/******************************************************************************
* Called when the Quit context menu item is selected.
*/
void TrayWindow::slotQuit()
{
theApp()->doQuit(parentWidget());
}
/******************************************************************************
* Called when the Alarms Enabled action status has changed.
* Updates the alarms enabled menu item check state, and the icon pixmap.
*/
void TrayWindow::setEnabledStatus(bool status)
{
kDebug() << (int)status;
setIcon(status ? mIconEnabled : mIconDisabled);
}
/******************************************************************************
* Called when the mouse is clicked over the panel icon.
* A left click displays the KAlarm main window.
* A middle button click displays the New Alarm window.
*/
void TrayWindow::slotActivated(QSystemTrayIcon::ActivationReason reason)
{
if (reason == QSystemTrayIcon::Trigger)
{
// Left click: display/hide the first main window
if (mAssocMainWindow && mAssocMainWindow->isVisible())
{
mAssocMainWindow->raise();
mAssocMainWindow->activateWindow();
}
}
else if (reason == QSystemTrayIcon::MiddleClick)
{
if (mActionNew->isEnabled())
mActionNew->trigger(); // display a New Alarm dialog
}
}
/******************************************************************************
* Called when the drag cursor enters the panel icon.
*/
void TrayWindow::dragEnterEvent(QDragEnterEvent* e)
{
MainWindow::executeDragEnterEvent(e, 0);
}
/******************************************************************************
* Called when an object is dropped on the panel icon.
* If the object is recognised, the edit alarm dialog is opened appropriately.
*/
void TrayWindow::dropEvent(QDropEvent* e)
{
MainWindow::executeDropEvent(0, e);
}
/******************************************************************************
* Called when any event occurs.
* If it's a tooltip event, display the tooltip text showing alarms due in the
* next 24 hours. The limit of 24 hours is because only times, not dates, are
* displayed.
*/
bool TrayWindow::event(QEvent* e)
{
if (e->type() != QEvent::ToolTip)
return KSystemTrayIcon::event(e);
QHelpEvent* he = (QHelpEvent*)e;
bool enabled = theApp()->alarmsEnabled();
QString altext;
if (enabled && Preferences::tooltipAlarmCount())
altext = tooltipAlarmText();
QString text;
if (enabled)
text = i18nc("@info:tooltip", "%1%2", KGlobal::mainComponent().aboutData()->programName(), altext);
else
text = i18nc("@info:tooltip 'KAlarm - disabled'", "%1 - disabled", KGlobal::mainComponent().aboutData()->programName());
kDebug() << text;
QToolTip::showText(he->globalPos(), text);
return true;
}
/******************************************************************************
* Return the tooltip text showing alarms due in the next 24 hours.
* The limit of 24 hours is because only times, not dates, are displayed.
*/
QString TrayWindow::tooltipAlarmText() const
{
KAEvent event;
const QString& prefix = Preferences::tooltipTimeToPrefix();
int maxCount = Preferences::tooltipAlarmCount();
KDateTime now = KDateTime::currentLocalDateTime();
KDateTime tomorrow = now.addDays(1);
// Get today's and tomorrow's alarms, sorted in time order
int i, iend;
QList<TipItem> items;
KAEvent::List events = AlarmCalendar::resources()->events(KDateTime(now.date(), QTime(0,0,0), KDateTime::LocalZone), tomorrow, KCalEvent::ACTIVE);
for (i = 0, iend = events.count(); i < iend; ++i)
{
KAEvent* event = events[i];
if (event->enabled() && !event->expired() && event->action() == KAEvent::MESSAGE)
{
TipItem item;
QDateTime dateTime = event->nextTrigger(KAEvent::DISPLAY_TRIGGER).effectiveKDateTime().toLocalZone().dateTime();
if (dateTime > tomorrow.dateTime())
continue; // ignore alarms after tomorrow at the current clock time
item.dateTime = dateTime;
// The alarm is due today, or early tomorrow
if (Preferences::showTooltipAlarmTime())
{
item.text += KGlobal::locale()->formatTime(item.dateTime.time());
item.text += QLatin1Char(' ');
}
if (Preferences::showTooltipTimeToAlarm())
{
int mins = (now.dateTime().secsTo(item.dateTime) + 59) / 60;
if (mins < 0)
mins = 0;
char minutes[3] = "00";
minutes[0] = static_cast<char>((mins%60) / 10 + '0');
minutes[1] = static_cast<char>((mins%60) % 10 + '0');
if (Preferences::showTooltipAlarmTime())
item.text += i18nc("@info/plain prefix + hours:minutes", "(%1%2:%3)", prefix, mins/60, minutes);
else
item.text += i18nc("@info/plain prefix + hours:minutes", "%1%2:%3", prefix, mins/60, minutes);
item.text += QLatin1Char(' ');
}
item.text += AlarmText::summary(event);
// Insert the item into the list in time-sorted order
int it = 0;
for (int itend = items.count(); it < itend; ++it)
{
if (item.dateTime <= items[it].dateTime)
break;
}
items.insert(it, item);
}
}
kDebug();
QString text;
int count = 0;
for (i = 0, iend = items.count(); i < iend; ++i)
{
kDebug() << "--" << (count+1) << ")" << items[i].text;
text += "<br />" + items[i].text;
if (++count == maxCount)
break;
}
return text;
}
/******************************************************************************
* Called when the associated main window is closed.
*/
void TrayWindow::removeWindow(MainWindow* win)
{
if (win == mAssocMainWindow)
mAssocMainWindow = 0;
}
<|endoftext|> |
<commit_before>/**
* @file Fullscreen.cpp
* @brief Tests of glfw fullscreen mode.
*
* Copyright (c) 2014 Sebastien Rombauts ([email protected])
*
* Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
* or copy at http://opensource.org/licenses/MIT)
*/
#include <GLFW/glfw3.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
static void error_callback(int error, const char* description) {
fputs(description, stderr);
}
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) {
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) {
glfwSetWindowShouldClose(window, GL_TRUE);
}
}
int main(void) {
GLFWwindow* window;
glfwSetErrorCallback(error_callback);
if (!glfwInit()) {
exit(EXIT_FAILURE);
}
glfwWindowHint(GLFW_SRGB_CAPABLE, GL_TRUE);
// get the current Desktop screen resolution and colour depth
const GLFWvidmode* pCurrentVideoMod = glfwGetVideoMode(glfwGetPrimaryMonitor());
int width = pCurrentVideoMod->width;
int height = pCurrentVideoMod->height;
std::cout << "fullscreen (" << width << " x " << height << ")\n";
// Open a fullscreen window on the first monitor
window = glfwCreateWindow(width, height, "Simple example", glfwGetPrimaryMonitor(), NULL);
if (!window) {
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwMakeContextCurrent(window);
glfwSetKeyCallback(window, key_callback);
glfwGetFramebufferSize(window, &width, &height);
glViewport(0, 0, width, height);
std::cout << "fullscreen (" << width << " x " << height << ")\n";
// configure projection matrix with the ratio of the windows
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
float ratio = width / (float)height;
glOrtho(-ratio, ratio, -1.0f, 1.0f, 1.0f, -1.0f);
while (!glfwWindowShouldClose(window)) {
// clear the buffer
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
// configure model view matrix, with timed rotation
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glRotatef((float) glfwGetTime() * 50.0f, 0.0f, 0.0f, 1.0f);
// draw a triangle
glBegin(GL_TRIANGLES);
glColor3f(1.0f, 0.0f, 0.0f);
glVertex3f(-0.6f, -0.4f, 0.0f);
glColor3f(0.0f, 1.0f, 0.0f);
glVertex3f(0.6f, -0.4f, 0.0f);
glColor3f(0.0f, 0.0f, 1.0f);
glVertex3f(0.0f, 0.6f, 0.0f);
glEnd();
// Swap back & front buffers
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwDestroyWindow(window);
glfwTerminate();
exit(EXIT_SUCCESS);
}
<commit_msg>Added a moving rectangle<commit_after>/**
* @file Fullscreen.cpp
* @brief Tests of glfw fullscreen mode.
*
* Copyright (c) 2014 Sebastien Rombauts ([email protected])
*
* Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
* or copy at http://opensource.org/licenses/MIT)
*/
#include <GLFW/glfw3.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <cassert>
#include <vector>
class Color {
public:
Color(float aR, float aG, float aB, float aA) :
mR(aR), mG(aG), mB(aB), mA(aA)
{
assert(0.0f <= mR); assert(1.0f >= mR);
assert(0.0f <= mG); assert(1.0f >= mG);
assert(0.0f <= mB); assert(1.0f >= mB);
assert(0.0f <= mA); assert(1.0f >= mA);
}
inline const float r() {
return mR;
}
inline const float g() {
return mG;
}
inline const float b() {
return mB;
}
inline const float a() {
return mA;
}
private:
float mR;
float mG;
float mB;
float mA;
};
class vect2d {
public:
vect2d(float aX, float aY) :
mX(aX), mY(aY)
{
}
const float x() {
return mX;
}
const float y() {
return mY;
}
const float w() {
return mX;
}
const float h() {
return mY;
}
void x(float aX) {
mX = aX;
}
void y(float aY) {
mY = aY;
}
private:
float mX;
float mY;
};
typedef vect2d Position;
typedef vect2d Dimension;
typedef vect2d Speed;
/**
* @brief Manage the animation and rendering of a rectangle
*/
class Rectangle {
public:
typedef std::vector<Rectangle> Vector;
public:
/**
* @brief Build a rectangle that must fit into the [(-1.0f, -1.0f), (1.0f, 1.0f)] screen
*/
Rectangle(const Position& aPosition, const Dimension& aDimension, const Speed& aSpeed, const Color& aColor) :
mPosition(aPosition), mDimension(aDimension), mSpeed(aSpeed), mColor(aColor)
{
assert(0.0f <= mDimension.w()); assert(2.0f >= mDimension.w());
assert(0.0f <= mDimension.h()); assert(2.0f >= mDimension.h());
assert(-1.0f <= left()); assert(left() < 1.0f);
assert(-1.0f < right()); assert(right() < 1.0f);
assert(-1.0f <= bottom()); assert(bottom() < 1.0f);
assert(-1.0f < top()); assert(top() < 1.0f);
}
inline const float left() {
return (mPosition.x());
}
inline const float right() {
return (mPosition.x() + mDimension.w());
}
inline const float bottom() {
return (mPosition.y());
}
inline const float top() {
return (mPosition.y() + mDimension.h());
}
/**
* @brief Move the rectangle according to its position, its speed, and the ellapsed time since previous frame
*
* Reposition the rectangle to the bottom/left when it reach the screen top/right (or reverse)
*/
void move(float aDeltaTime) {
mPosition.x(mPosition.x() + (mSpeed.x() * aDeltaTime));
mPosition.y(mPosition.y() + (mSpeed.y() * aDeltaTime));
if (left() < -1.0f) {
mPosition.x(1.0f);
}
if (right() > 1.0f) {
mPosition.x(1.0f);
}
if (bottom() < -1.0f) {
mPosition.y(1.0f);
}
if (top() > 1.0f) {
mPosition.y(-1.0f);
}
}
// draw a rectangle polygon
void render() {
glBegin(GL_POLYGON);
glColor4f(mColor.r(), mColor.g(), mColor.b(), mColor.a());
glVertex2f(left(), bottom());
glColor4f(mColor.r(), mColor.g(), mColor.b(), mColor.a());
glVertex2f(left(), top());
glColor4f(mColor.r(), mColor.g(), mColor.b(), mColor.a());
glVertex2f(right(), top());
glColor4f(mColor.r(), mColor.g(), mColor.b(), mColor.a());
glVertex2f(right(), bottom());
glEnd();
}
private:
Position mPosition;
Dimension mDimension;
Speed mSpeed;
Color mColor;
};
static void error_callback(int error, const char* description) {
fputs(description, stderr);
}
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) {
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) {
glfwSetWindowShouldClose(window, GL_TRUE);
}
}
int main(void) {
Rectangle::Vector rectangles;
rectangles.push_back(Rectangle(Position(-1.0f, -0.0f),
Dimension(1.0f, 0.2f),
Speed(0.1f, 0.0f),
Color(1.0f, 0.0f, 0.0f, 1.0f)));
GLFWwindow* window;
glfwSetErrorCallback(error_callback);
if (!glfwInit()) {
exit(EXIT_FAILURE);
}
glfwWindowHint(GLFW_SRGB_CAPABLE, GL_TRUE);
// get the current Desktop screen resolution and colour depth
const GLFWvidmode* pCurrentVideoMod = glfwGetVideoMode(glfwGetPrimaryMonitor());
int width = pCurrentVideoMod->width;
int height = pCurrentVideoMod->height;
std::cout << "fullscreen (" << width << " x " << height << ")\n";
// Open a fullscreen window on the first monitor
window = glfwCreateWindow(width, height, "Simple example", glfwGetPrimaryMonitor(), NULL);
if (!window) {
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwMakeContextCurrent(window);
glfwSetKeyCallback(window, key_callback);
glfwGetFramebufferSize(window, &width, &height);
glViewport(0, 0, width, height);
std::cout << "fullscreen (" << width << " x " << height << ")\n";
double currTime = glfwGetTime();
double prevTime = currTime;
while (!glfwWindowShouldClose(window)) {
// clear the buffer
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
currTime = glfwGetTime();
float ellapsedTime = static_cast<float>(currTime - prevTime);
std::cout << "ellapsedTime=" << ellapsedTime << std::endl;
// move the rectangles based on ellapsed time
for (Rectangle::Vector::iterator iRectangle = rectangles.begin();
iRectangle != rectangles.end();
++iRectangle) {
iRectangle->move(ellapsedTime);
}
// draw the rectangles
for (Rectangle::Vector::iterator iRectangle = rectangles.begin();
iRectangle != rectangles.end();
++iRectangle) {
iRectangle->render();
}
// Swap back & front buffers
glfwSwapBuffers(window);
glfwPollEvents();
prevTime = currTime;
}
glfwDestroyWindow(window);
glfwTerminate();
exit(EXIT_SUCCESS);
}
<|endoftext|> |
<commit_before>/***********************************************************************
multiquery.cpp - Example showing how to iterate over result sets upon
execution of a query that returns more than one result set. You can
get multiple result sets when executing multiple separate SQL
statments in a single query, or when dealing with the results of
calling a stored procedure.
Copyright (c) 1998 by Kevin Atkinson, (c) 1999-2001 by MySQL AB,
(c) 2004-2009 by Educational Technology Resources, Inc., and (c)
2005 by Arnon Jalon. Others may also hold copyrights on code in
this file. See the CREDITS.txt file in the top directory of the
distribution for details.
This file is part of MySQL++.
MySQL++ 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.
MySQL++ 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 MySQL++; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
***********************************************************************/
#include "cmdline.h"
#include "printdata.h"
#include <mysql++.h>
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
using namespace mysqlpp;
typedef vector<size_t> IntVectorType;
static void
print_header(IntVectorType& widths, StoreQueryResult& res)
{
cout << " |" << setfill(' ');
for (size_t i = 0; i < res.field_names()->size(); i++) {
cout << " " << setw(widths.at(i)) << res.field_name(int(i)) << " |";
}
cout << endl;
}
static void
print_row(IntVectorType& widths, Row& row)
{
cout << " |" << setfill(' ');
for (size_t i = 0; i < row.size(); ++i) {
cout << " " << setw(widths.at(i)) << row[int(i)] << " |";
}
cout << endl;
}
static void
print_row_separator(IntVectorType& widths)
{
cout << " +" << setfill('-');
for (size_t i = 0; i < widths.size(); i++) {
cout << "-" << setw(widths.at(i)) << '-' << "-+";
}
cout << endl;
}
static void
print_result(StoreQueryResult& res, int index)
{
// Show how many rows are in result, if any
StoreQueryResult::size_type num_results = res.size();
if (res && (num_results > 0)) {
cout << "Result set " << index << " has " << num_results <<
" row" << (num_results == 1 ? "" : "s") << ':' << endl;
}
else {
cout << "Result set " << index << " is empty." << endl;
return;
}
// Figure out the widths of the result set's columns
IntVectorType widths;
size_t size = res.num_fields();
for (size_t i = 0; i < size; i++) {
widths.push_back(max(
res.field(i).max_length(),
res.field_name(i).size()));
}
// Print result set header
print_row_separator(widths);
print_header(widths, res);
print_row_separator(widths);
// Display the result set contents
for (StoreQueryResult::size_type i = 0; i < num_results; ++i) {
print_row(widths, res[i]);
}
// Print result set footer
print_row_separator(widths);
}
static void
print_multiple_results(Query& query)
{
// Execute query and print all result sets
StoreQueryResult res = query.store();
print_result(res, 0);
for (int i = 1; query.more_results(); ++i) {
res = query.store_next();
print_result(res, i);
}
}
int
main(int argc, char *argv[])
{
// Get connection parameters from command line
mysqlpp::examples::CommandLine cmdline(argc, argv);
if (!cmdline) {
return 1;
}
try {
// Enable multi-queries. Notice that you almost always set
// MySQL++ connection options before establishing the server
// connection, and options are always set using this one
// interface. If you're familiar with the underlying C API,
// you know that there is poor consistency on these matters;
// MySQL++ abstracts these differences away.
Connection con;
con.set_option(new MultiStatementsOption(true));
// Connect to the database
if (!con.connect(mysqlpp::examples::db_name, cmdline.server(),
cmdline.user(), cmdline.pass())) {
return 1;
}
// Set up query with multiple queries.
Query query = con.query();
query << "DROP TABLE IF EXISTS test_table; " <<
"CREATE TABLE test_table(id INT); " <<
"INSERT INTO test_table VALUES(10); " <<
"UPDATE test_table SET id=20 WHERE id=10; " <<
"SELECT * FROM test_table; " <<
"DROP TABLE test_table";
cout << "Multi-query: " << endl << query << endl;
// Execute statement and display all result sets.
print_multiple_results(query);
#if MYSQL_VERSION_ID >= 50000
// If it's MySQL v5.0 or higher, also test stored procedures, which
// return their results the same way multi-queries do.
query << "DROP PROCEDURE IF EXISTS get_stock; " <<
"CREATE PROCEDURE get_stock" <<
"( i_item varchar(20) ) " <<
"BEGIN " <<
"SET i_item = concat('%', i_item, '%'); " <<
"SELECT * FROM stock WHERE lower(item) like lower(i_item); " <<
"END;";
cout << "Stored procedure query: " << endl << query << endl;
// Create the stored procedure.
print_multiple_results(query);
// Call the stored procedure and display its results.
query << "CALL get_stock('relish')";
cout << "Query: " << query << endl;
print_multiple_results(query);
#endif
return 0;
}
catch (const BadOption& err) {
cerr << err.what() << endl;
cerr << "This example requires MySQL 4.1.1 or later." << endl;
return 1;
}
catch (const ConnectionFailed& err) {
cerr << "Failed to connect to database server: " <<
err.what() << endl;
return 1;
}
catch (const Exception& er) {
// Catch-all for any other MySQL++ exceptions
cerr << "Error: " << er.what() << endl;
return 1;
}
}
<commit_msg>#including algorithm.h in examples/multiquery.cpp for std::max(). Didn't need it before because we were apparently getting another version via another #include path. Probably either the windows.h macro or the one in stdlib.h.<commit_after>/***********************************************************************
multiquery.cpp - Example showing how to iterate over result sets upon
execution of a query that returns more than one result set. You can
get multiple result sets when executing multiple separate SQL
statments in a single query, or when dealing with the results of
calling a stored procedure.
Copyright (c) 1998 by Kevin Atkinson, (c) 1999-2001 by MySQL AB,
(c) 2004-2009 by Educational Technology Resources, Inc., and (c)
2005 by Arnon Jalon. Others may also hold copyrights on code in
this file. See the CREDITS.txt file in the top directory of the
distribution for details.
This file is part of MySQL++.
MySQL++ 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.
MySQL++ 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 MySQL++; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
***********************************************************************/
#include "cmdline.h"
#include "printdata.h"
#include <mysql++.h>
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
using namespace mysqlpp;
typedef vector<size_t> IntVectorType;
static void
print_header(IntVectorType& widths, StoreQueryResult& res)
{
cout << " |" << setfill(' ');
for (size_t i = 0; i < res.field_names()->size(); i++) {
cout << " " << setw(widths.at(i)) << res.field_name(int(i)) << " |";
}
cout << endl;
}
static void
print_row(IntVectorType& widths, Row& row)
{
cout << " |" << setfill(' ');
for (size_t i = 0; i < row.size(); ++i) {
cout << " " << setw(widths.at(i)) << row[int(i)] << " |";
}
cout << endl;
}
static void
print_row_separator(IntVectorType& widths)
{
cout << " +" << setfill('-');
for (size_t i = 0; i < widths.size(); i++) {
cout << "-" << setw(widths.at(i)) << '-' << "-+";
}
cout << endl;
}
static void
print_result(StoreQueryResult& res, int index)
{
// Show how many rows are in result, if any
StoreQueryResult::size_type num_results = res.size();
if (res && (num_results > 0)) {
cout << "Result set " << index << " has " << num_results <<
" row" << (num_results == 1 ? "" : "s") << ':' << endl;
}
else {
cout << "Result set " << index << " is empty." << endl;
return;
}
// Figure out the widths of the result set's columns
IntVectorType widths;
size_t size = res.num_fields();
for (size_t i = 0; i < size; i++) {
widths.push_back(max(
res.field(i).max_length(),
res.field_name(i).size()));
}
// Print result set header
print_row_separator(widths);
print_header(widths, res);
print_row_separator(widths);
// Display the result set contents
for (StoreQueryResult::size_type i = 0; i < num_results; ++i) {
print_row(widths, res[i]);
}
// Print result set footer
print_row_separator(widths);
}
static void
print_multiple_results(Query& query)
{
// Execute query and print all result sets
StoreQueryResult res = query.store();
print_result(res, 0);
for (int i = 1; query.more_results(); ++i) {
res = query.store_next();
print_result(res, i);
}
}
int
main(int argc, char *argv[])
{
// Get connection parameters from command line
mysqlpp::examples::CommandLine cmdline(argc, argv);
if (!cmdline) {
return 1;
}
try {
// Enable multi-queries. Notice that you almost always set
// MySQL++ connection options before establishing the server
// connection, and options are always set using this one
// interface. If you're familiar with the underlying C API,
// you know that there is poor consistency on these matters;
// MySQL++ abstracts these differences away.
Connection con;
con.set_option(new MultiStatementsOption(true));
// Connect to the database
if (!con.connect(mysqlpp::examples::db_name, cmdline.server(),
cmdline.user(), cmdline.pass())) {
return 1;
}
// Set up query with multiple queries.
Query query = con.query();
query << "DROP TABLE IF EXISTS test_table; " <<
"CREATE TABLE test_table(id INT); " <<
"INSERT INTO test_table VALUES(10); " <<
"UPDATE test_table SET id=20 WHERE id=10; " <<
"SELECT * FROM test_table; " <<
"DROP TABLE test_table";
cout << "Multi-query: " << endl << query << endl;
// Execute statement and display all result sets.
print_multiple_results(query);
#if MYSQL_VERSION_ID >= 50000
// If it's MySQL v5.0 or higher, also test stored procedures, which
// return their results the same way multi-queries do.
query << "DROP PROCEDURE IF EXISTS get_stock; " <<
"CREATE PROCEDURE get_stock" <<
"( i_item varchar(20) ) " <<
"BEGIN " <<
"SET i_item = concat('%', i_item, '%'); " <<
"SELECT * FROM stock WHERE lower(item) like lower(i_item); " <<
"END;";
cout << "Stored procedure query: " << endl << query << endl;
// Create the stored procedure.
print_multiple_results(query);
// Call the stored procedure and display its results.
query << "CALL get_stock('relish')";
cout << "Query: " << query << endl;
print_multiple_results(query);
#endif
return 0;
}
catch (const BadOption& err) {
cerr << err.what() << endl;
cerr << "This example requires MySQL 4.1.1 or later." << endl;
return 1;
}
catch (const ConnectionFailed& err) {
cerr << "Failed to connect to database server: " <<
err.what() << endl;
return 1;
}
catch (const Exception& er) {
// Catch-all for any other MySQL++ exceptions
cerr << "Error: " << er.what() << endl;
return 1;
}
}
<|endoftext|> |
<commit_before>// ========================================================================== //
// This file is part of DO++, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2013 David Ok <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //
//! @file
#ifndef DO_DEBUG_UTILITIES
#define DO_DEBUG_UTILITIES
#include <iostream>
#define CHECK(x) std::cout << #x << " = " << x << std::endl
namespace DO {
//! \ingroup Utility
//! \brief Outputting program stage description on console.
inline void printStage(const std::string& stageName)
{
std::cout << std::endl;
std::cout << "// ======================================================================= //" << std::endl;
std::cout << "// " << stageName << std::endl;
}
//! \ingroup Utility
//! \brief Wait for return key on the console.
inline void waitReturnKey()
{
std::cout << "Press RETURN key to continue...";
std::cin.ignore();
}
} /* namespace DO */
#endif /* DO_DEBUG_UTILITIES */<commit_msg>STY: rename functions.<commit_after>// ========================================================================== //
// This file is part of DO++, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2013 David Ok <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //
//! @file
#ifndef DO_DEBUG_UTILITIES_HPP
#define DO_DEBUG_UTILITIES_HPP
#include <iostream>
#define CHECK(x) std::cout << #x << " = " << x << std::endl
namespace DO {
//! \ingroup Utility
//! \brief Outputting program stage description on console.
inline void print_stage(const std::string& stageName)
{
std::cout << std::endl;
std::cout << "// ======================================================================= //" << std::endl;
std::cout << "// " << stageName << std::endl;
}
//! \ingroup Utility
//! \brief Wait for return key on the console.
inline void wait_return_key()
{
std::cout << "Press RETURN key to continue...";
std::cin.ignore();
}
} /* namespace DO */
#endif /* DO_DEBUG_UTILITIES_HPP */
<|endoftext|> |
<commit_before>#include "Game/Piece.h"
#include <cctype>
#include <algorithm>
#include <cassert>
#include <array>
#include <cctype>
#include "Game/Square.h"
#include "Game/Color.h"
#include "Moves/Move.h"
#include "Moves/Direction.h"
#include "Moves/Pawn_Move.h"
#include "Moves/Pawn_Double_Move.h"
#include "Moves/Pawn_Promotion.h"
#include "Moves/En_Passant.h"
#include "Moves/Castle.h"
#include "Utility/Fixed_Capacity_Vector.h"
const Piece::piece_code_t Piece::invalid_code = Piece{Piece_Color::BLACK, Piece_Type::KING}.index() + 1;
namespace
{
const std::string pgn_symbols = "PRNBQK";
using indexed_move_array = std::array<std::array<Fixed_Capacity_Vector<Fixed_Capacity_Vector<const Move*, 7>, 12>, 64>, 12>;
void add_pawn_moves(indexed_move_array& out, Piece_Color color) noexcept;
void add_rook_moves(indexed_move_array& out, Piece_Color color, Piece_Type type = Piece_Type::ROOK) noexcept;
void add_knight_moves(indexed_move_array& out, Piece_Color color) noexcept;
void add_bishop_moves(indexed_move_array& out, Piece_Color color, Piece_Type type = Piece_Type::BISHOP) noexcept;
void add_queen_moves(indexed_move_array& out, Piece_Color color) noexcept;
void add_king_moves(indexed_move_array& out, Piece_Color color) noexcept;
const auto legal_moves =
[]()
{
indexed_move_array result;
for(auto color : {Piece_Color::WHITE, Piece_Color::BLACK})
{
add_pawn_moves(result, color);
add_rook_moves(result, color);
add_knight_moves(result, color);
add_bishop_moves(result, color);
add_queen_moves(result, color);
add_king_moves(result, color);
}
return result;
}();
const auto attack_moves =
[]()
{
indexed_move_array result;
for(auto color : {Piece_Color::WHITE, Piece_Color::BLACK})
{
for(auto type_index = 0; type_index <= static_cast<int>(Piece_Type::KING); ++type_index)
{
auto piece = Piece{color, static_cast<Piece_Type>(type_index)};
for(size_t index = 0; index < 64; ++index)
{
for(const auto& move_list : legal_moves[piece.index()][index])
{
result[piece.index()][index].push_back({});
for(auto move : move_list)
{
// Make list of all capturing moves, excluding all but one type of pawn capture per square.
if(move->can_capture()
&& ! move->is_en_passant()
&& (move->promotion_piece_symbol() == 'Q' || move->promotion_piece_symbol() == '\0'))
{
result[piece.index()][index].back().push_back(move);
}
}
}
}
}
}
return result;
}();
// Add a move to the list that is only legal when starting from a certain square
// (e.g., castling, pawn double move, promotion, etc.)
template<typename Move_Type, typename ...Parameters>
void add_legal_move(indexed_move_array& out, Piece piece, bool blockable, Parameters ... parameters) noexcept
{
auto move = new Move_Type(parameters...);
auto& lists = out[piece.index()][move->start().index()];
if(lists.empty() || ! blockable)
{
lists.push_back({});
}
if( ! lists.back().empty() && ! same_direction(move->movement(), lists.back().back()->movement()))
{
lists.push_back({});
}
lists.back().push_back(move);
}
void add_standard_legal_move(indexed_move_array& out, Piece piece, int file_step, int rank_step, bool blockable) noexcept
{
for(auto start : Square::all_squares())
{
auto end = start + Square_Difference{file_step, rank_step};
if(end.inside_board())
{
add_legal_move<Move>(out, piece, blockable, start, end);
}
}
}
void add_pawn_moves(indexed_move_array& out, Piece_Color color) noexcept
{
auto pawn = Piece{color, Piece_Type::PAWN};
auto base_rank = (color == Piece_Color::WHITE ? 2 : 7);
auto no_normal_move_rank = (color == Piece_Color::WHITE ? 7 : 2);
auto rank_change = (color == Piece_Color::WHITE ? 1 : -1);
for(char file = 'a'; file <= 'h'; ++file)
{
for(int rank = base_rank; rank != no_normal_move_rank; rank += rank_change)
{
add_legal_move<Pawn_Move>(out, pawn, true, color, Square{file, rank});
}
}
for(char file = 'a'; file <= 'h'; ++file)
{
add_legal_move<Pawn_Double_Move>(out, pawn, true, color, file);
}
std::vector<Piece_Type> possible_promotions;
for(auto type_index = 0; type_index <= static_cast<int>(Piece_Type::KING); ++type_index)
{
auto type = static_cast<Piece_Type>(type_index);
if(type == Piece_Type::PAWN || type == Piece_Type::KING)
{
continue;
}
possible_promotions.push_back(type);
}
for(auto dir : {Direction::RIGHT, Direction::LEFT})
{
auto first_file = (dir == Direction::RIGHT ? 'a' : 'b');
auto last_file = (dir == Direction::RIGHT ? 'g' : 'h');
for(char file = first_file; file <= last_file; ++file)
{
for(int rank = base_rank; rank != no_normal_move_rank; rank += rank_change)
{
add_legal_move<Pawn_Move>(out, pawn, true, color, Square{file, rank}, dir);
}
}
for(char file = first_file; file <= last_file; ++file)
{
add_legal_move<En_Passant>(out, pawn, true, color, dir, file);
}
for(auto promote : possible_promotions)
{
for(auto file = first_file; file <= last_file; ++file)
{
add_legal_move<Pawn_Promotion>(out, pawn, false, promote, color, file, dir);
}
}
}
for(auto promote : possible_promotions)
{
for(auto file = 'a'; file <= 'h'; ++file)
{
add_legal_move<Pawn_Promotion>(out, pawn, false, promote, color, file);
}
}
}
void add_rook_moves(indexed_move_array& out, Piece_Color color, Piece_Type type) noexcept
{
for(int d_file = -1; d_file <= 1; ++d_file)
{
for(int d_rank = -1; d_rank <= 1; ++d_rank)
{
if(d_file == 0 && d_rank == 0) { continue; }
if(d_file != 0 && d_rank != 0) { continue; }
for(int move_size = 1; move_size <= 7; ++move_size)
{
add_standard_legal_move(out, {color, type}, move_size*d_file, move_size*d_rank, true);
}
}
}
}
void add_knight_moves(indexed_move_array& out, Piece_Color color) noexcept
{
for(auto d_file : {1, 2})
{
auto d_rank = 3 - d_file;
for(auto file_direction : {-1, 1})
{
for(auto rank_direction : {-1, 1})
{
add_standard_legal_move(out, {color, Piece_Type::KNIGHT}, d_file*file_direction, d_rank*rank_direction, false);
}
}
}
}
void add_bishop_moves(indexed_move_array& out, Piece_Color color, Piece_Type type) noexcept
{
for(int d_rank : {-1, 1})
{
for(int d_file : {-1, 1})
{
for(int move_size = 1; move_size <= 7; ++move_size)
{
add_standard_legal_move(out, {color, type}, move_size*d_file, move_size*d_rank, true);
}
}
}
}
void add_queen_moves(indexed_move_array& out, Piece_Color color) noexcept
{
add_bishop_moves(out, color, Piece_Type::QUEEN);
add_rook_moves(out, color, Piece_Type::QUEEN);
}
void add_king_moves(indexed_move_array& out, Piece_Color color) noexcept
{
auto king = Piece{color, Piece_Type::KING};
auto kingside_castle_added = false;
auto queenside_castle_added = false;
int base_rank = (color == Piece_Color::WHITE ? 1 : 8);
for(int d_rank = -1; d_rank <= 1; ++d_rank)
{
for(int d_file = -1; d_file <= 1; ++d_file)
{
if(d_rank == 0 && d_file == 0) { continue; }
add_standard_legal_move(out, king, d_file, d_rank, true);
if(d_rank == 0)
{
if(d_file > 0)
{
if( ! kingside_castle_added)
{
add_legal_move<Castle>(out, king, true, base_rank, Direction::RIGHT);
kingside_castle_added = true;
}
}
else
{
if( ! queenside_castle_added)
{
add_legal_move<Castle>(out, king, true, base_rank, Direction::LEFT);
}
}
}
}
}
}
Piece_Type piece_type_from_char(char pgn_symbol)
{
auto i = pgn_symbols.find(std::toupper(pgn_symbol));
if(i == std::string::npos)
{
throw std::invalid_argument(pgn_symbol + std::string{" is not a valid piece PGN symbol."});
}
return static_cast<Piece_Type>(i);
}
}
Piece::Piece() noexcept : piece_code(invalid_code)
{
}
Piece::Piece(Piece_Color color, Piece_Type type) noexcept :
piece_code((static_cast<int>(type) << 1) | static_cast<int>(color))
{
// piece_code layout: 4 bits
// 3 most significant bits = Piece_Type (values 0-5)
// least significant bit = Piece_Color (0 or 1)
//
// 101 1
// ^^^ ^-- Piece_Color::BLACK
// +--- Piece_Type::KING
}
Piece::Piece(char pgn_symbol) : Piece(std::isupper(pgn_symbol) ? Piece_Color::WHITE : Piece_Color::BLACK,
piece_type_from_char(pgn_symbol))
{
}
Piece_Color Piece::color() const noexcept
{
assert(*this);
return static_cast<Piece_Color>(piece_code & 1);
}
std::string Piece::pgn_symbol() const noexcept
{
assert(*this);
return type() == Piece_Type::PAWN ? std::string{} : std::string(1, std::toupper(fen_symbol()));
}
char Piece::fen_symbol() const noexcept
{
assert(*this);
auto symbol = pgn_symbols[static_cast<int>(type())];
return (color() == Piece_Color::WHITE ? symbol : std::tolower(symbol));
}
bool Piece::can_move(const Move* move) const noexcept
{
assert(*this);
for(const auto& moves : move_lists(move->start()))
{
if(std::find(moves.begin(), moves.end(), move) != moves.end())
{
return true;
}
}
return false;
}
const Piece::list_of_move_lists& Piece::move_lists(Square square) const noexcept
{
assert(*this);
return legal_moves[index()][square.index()];
}
Piece_Type Piece::type() const noexcept
{
assert(*this);
return static_cast<Piece_Type>(piece_code >> 1);
}
Piece::operator bool() const noexcept
{
return piece_code != invalid_code;
}
Piece::piece_code_t Piece::index() const noexcept
{
return piece_code;
}
const Piece::list_of_move_lists& Piece::attacking_move_lists(Square square) const noexcept
{
assert(*this);
return attack_moves[index()][square.index()];
}
bool operator==(Piece a, Piece b) noexcept
{
return a.index() == b.index();
}
bool operator!=(Piece a, Piece b) noexcept
{
return !(a == b);
}
<commit_msg>Remove redundant checks in Castle creation<commit_after>#include "Game/Piece.h"
#include <cctype>
#include <algorithm>
#include <cassert>
#include <array>
#include <cctype>
#include "Game/Square.h"
#include "Game/Color.h"
#include "Moves/Move.h"
#include "Moves/Direction.h"
#include "Moves/Pawn_Move.h"
#include "Moves/Pawn_Double_Move.h"
#include "Moves/Pawn_Promotion.h"
#include "Moves/En_Passant.h"
#include "Moves/Castle.h"
#include "Utility/Fixed_Capacity_Vector.h"
const Piece::piece_code_t Piece::invalid_code = Piece{Piece_Color::BLACK, Piece_Type::KING}.index() + 1;
namespace
{
const std::string pgn_symbols = "PRNBQK";
using indexed_move_array = std::array<std::array<Fixed_Capacity_Vector<Fixed_Capacity_Vector<const Move*, 7>, 12>, 64>, 12>;
void add_pawn_moves(indexed_move_array& out, Piece_Color color) noexcept;
void add_rook_moves(indexed_move_array& out, Piece_Color color, Piece_Type type = Piece_Type::ROOK) noexcept;
void add_knight_moves(indexed_move_array& out, Piece_Color color) noexcept;
void add_bishop_moves(indexed_move_array& out, Piece_Color color, Piece_Type type = Piece_Type::BISHOP) noexcept;
void add_queen_moves(indexed_move_array& out, Piece_Color color) noexcept;
void add_king_moves(indexed_move_array& out, Piece_Color color) noexcept;
const auto legal_moves =
[]()
{
indexed_move_array result;
for(auto color : {Piece_Color::WHITE, Piece_Color::BLACK})
{
add_pawn_moves(result, color);
add_rook_moves(result, color);
add_knight_moves(result, color);
add_bishop_moves(result, color);
add_queen_moves(result, color);
add_king_moves(result, color);
}
return result;
}();
const auto attack_moves =
[]()
{
indexed_move_array result;
for(auto color : {Piece_Color::WHITE, Piece_Color::BLACK})
{
for(auto type_index = 0; type_index <= static_cast<int>(Piece_Type::KING); ++type_index)
{
auto piece = Piece{color, static_cast<Piece_Type>(type_index)};
for(size_t index = 0; index < 64; ++index)
{
for(const auto& move_list : legal_moves[piece.index()][index])
{
result[piece.index()][index].push_back({});
for(auto move : move_list)
{
// Make list of all capturing moves, excluding all but one type of pawn capture per square.
if(move->can_capture()
&& ! move->is_en_passant()
&& (move->promotion_piece_symbol() == 'Q' || move->promotion_piece_symbol() == '\0'))
{
result[piece.index()][index].back().push_back(move);
}
}
}
}
}
}
return result;
}();
// Add a move to the list that is only legal when starting from a certain square
// (e.g., castling, pawn double move, promotion, etc.)
template<typename Move_Type, typename ...Parameters>
void add_legal_move(indexed_move_array& out, Piece piece, bool blockable, Parameters ... parameters) noexcept
{
auto move = new Move_Type(parameters...);
auto& lists = out[piece.index()][move->start().index()];
if(lists.empty() || ! blockable)
{
lists.push_back({});
}
if( ! lists.back().empty() && ! same_direction(move->movement(), lists.back().back()->movement()))
{
lists.push_back({});
}
lists.back().push_back(move);
}
void add_standard_legal_move(indexed_move_array& out, Piece piece, int file_step, int rank_step, bool blockable) noexcept
{
for(auto start : Square::all_squares())
{
auto end = start + Square_Difference{file_step, rank_step};
if(end.inside_board())
{
add_legal_move<Move>(out, piece, blockable, start, end);
}
}
}
void add_pawn_moves(indexed_move_array& out, Piece_Color color) noexcept
{
auto pawn = Piece{color, Piece_Type::PAWN};
auto base_rank = (color == Piece_Color::WHITE ? 2 : 7);
auto no_normal_move_rank = (color == Piece_Color::WHITE ? 7 : 2);
auto rank_change = (color == Piece_Color::WHITE ? 1 : -1);
for(char file = 'a'; file <= 'h'; ++file)
{
for(int rank = base_rank; rank != no_normal_move_rank; rank += rank_change)
{
add_legal_move<Pawn_Move>(out, pawn, true, color, Square{file, rank});
}
}
for(char file = 'a'; file <= 'h'; ++file)
{
add_legal_move<Pawn_Double_Move>(out, pawn, true, color, file);
}
std::vector<Piece_Type> possible_promotions;
for(auto type_index = 0; type_index <= static_cast<int>(Piece_Type::KING); ++type_index)
{
auto type = static_cast<Piece_Type>(type_index);
if(type == Piece_Type::PAWN || type == Piece_Type::KING)
{
continue;
}
possible_promotions.push_back(type);
}
for(auto dir : {Direction::RIGHT, Direction::LEFT})
{
auto first_file = (dir == Direction::RIGHT ? 'a' : 'b');
auto last_file = (dir == Direction::RIGHT ? 'g' : 'h');
for(char file = first_file; file <= last_file; ++file)
{
for(int rank = base_rank; rank != no_normal_move_rank; rank += rank_change)
{
add_legal_move<Pawn_Move>(out, pawn, true, color, Square{file, rank}, dir);
}
}
for(char file = first_file; file <= last_file; ++file)
{
add_legal_move<En_Passant>(out, pawn, true, color, dir, file);
}
for(auto promote : possible_promotions)
{
for(auto file = first_file; file <= last_file; ++file)
{
add_legal_move<Pawn_Promotion>(out, pawn, false, promote, color, file, dir);
}
}
}
for(auto promote : possible_promotions)
{
for(auto file = 'a'; file <= 'h'; ++file)
{
add_legal_move<Pawn_Promotion>(out, pawn, false, promote, color, file);
}
}
}
void add_rook_moves(indexed_move_array& out, Piece_Color color, Piece_Type type) noexcept
{
for(int d_file = -1; d_file <= 1; ++d_file)
{
for(int d_rank = -1; d_rank <= 1; ++d_rank)
{
if(d_file == 0 && d_rank == 0) { continue; }
if(d_file != 0 && d_rank != 0) { continue; }
for(int move_size = 1; move_size <= 7; ++move_size)
{
add_standard_legal_move(out, {color, type}, move_size*d_file, move_size*d_rank, true);
}
}
}
}
void add_knight_moves(indexed_move_array& out, Piece_Color color) noexcept
{
for(auto d_file : {1, 2})
{
auto d_rank = 3 - d_file;
for(auto file_direction : {-1, 1})
{
for(auto rank_direction : {-1, 1})
{
add_standard_legal_move(out, {color, Piece_Type::KNIGHT}, d_file*file_direction, d_rank*rank_direction, false);
}
}
}
}
void add_bishop_moves(indexed_move_array& out, Piece_Color color, Piece_Type type) noexcept
{
for(int d_rank : {-1, 1})
{
for(int d_file : {-1, 1})
{
for(int move_size = 1; move_size <= 7; ++move_size)
{
add_standard_legal_move(out, {color, type}, move_size*d_file, move_size*d_rank, true);
}
}
}
}
void add_queen_moves(indexed_move_array& out, Piece_Color color) noexcept
{
add_bishop_moves(out, color, Piece_Type::QUEEN);
add_rook_moves(out, color, Piece_Type::QUEEN);
}
void add_king_moves(indexed_move_array& out, Piece_Color color) noexcept
{
auto king = Piece{color, Piece_Type::KING};
int base_rank = (color == Piece_Color::WHITE ? 1 : 8);
for(int d_rank = -1; d_rank <= 1; ++d_rank)
{
for(int d_file = -1; d_file <= 1; ++d_file)
{
if(d_rank == 0 && d_file == 0) { continue; }
add_standard_legal_move(out, king, d_file, d_rank, true);
if(d_rank == 0)
{
if(d_file > 0)
{
add_legal_move<Castle>(out, king, true, base_rank, Direction::RIGHT);
}
else
{
add_legal_move<Castle>(out, king, true, base_rank, Direction::LEFT);
}
}
}
}
}
Piece_Type piece_type_from_char(char pgn_symbol)
{
auto i = pgn_symbols.find(std::toupper(pgn_symbol));
if(i == std::string::npos)
{
throw std::invalid_argument(pgn_symbol + std::string{" is not a valid piece PGN symbol."});
}
return static_cast<Piece_Type>(i);
}
}
Piece::Piece() noexcept : piece_code(invalid_code)
{
}
Piece::Piece(Piece_Color color, Piece_Type type) noexcept :
piece_code((static_cast<int>(type) << 1) | static_cast<int>(color))
{
// piece_code layout: 4 bits
// 3 most significant bits = Piece_Type (values 0-5)
// least significant bit = Piece_Color (0 or 1)
//
// 101 1
// ^^^ ^-- Piece_Color::BLACK
// +--- Piece_Type::KING
}
Piece::Piece(char pgn_symbol) : Piece(std::isupper(pgn_symbol) ? Piece_Color::WHITE : Piece_Color::BLACK,
piece_type_from_char(pgn_symbol))
{
}
Piece_Color Piece::color() const noexcept
{
assert(*this);
return static_cast<Piece_Color>(piece_code & 1);
}
std::string Piece::pgn_symbol() const noexcept
{
assert(*this);
return type() == Piece_Type::PAWN ? std::string{} : std::string(1, std::toupper(fen_symbol()));
}
char Piece::fen_symbol() const noexcept
{
assert(*this);
auto symbol = pgn_symbols[static_cast<int>(type())];
return (color() == Piece_Color::WHITE ? symbol : std::tolower(symbol));
}
bool Piece::can_move(const Move* move) const noexcept
{
assert(*this);
for(const auto& moves : move_lists(move->start()))
{
if(std::find(moves.begin(), moves.end(), move) != moves.end())
{
return true;
}
}
return false;
}
const Piece::list_of_move_lists& Piece::move_lists(Square square) const noexcept
{
assert(*this);
return legal_moves[index()][square.index()];
}
Piece_Type Piece::type() const noexcept
{
assert(*this);
return static_cast<Piece_Type>(piece_code >> 1);
}
Piece::operator bool() const noexcept
{
return piece_code != invalid_code;
}
Piece::piece_code_t Piece::index() const noexcept
{
return piece_code;
}
const Piece::list_of_move_lists& Piece::attacking_move_lists(Square square) const noexcept
{
assert(*this);
return attack_moves[index()][square.index()];
}
bool operator==(Piece a, Piece b) noexcept
{
return a.index() == b.index();
}
bool operator!=(Piece a, Piece b) noexcept
{
return !(a == b);
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkSampleSelectiveMeanShiftBlurringFilterTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkImageFileReader.h"
#include "itkImageRegionIterator.h"
#include "itkJointDomainImageToListAdaptor.h"
#include "itkSampleSelectiveMeanShiftBlurringFilter.h"
#include "itkHypersphereKernelMeanShiftModeSeeker.h"
int itkSampleSelectiveMeanShiftBlurringFilterTest(int argc, char* argv[] )
{
std::cout << "SampleSelectiveMeanShiftBlurringFilter Test \n \n";
if (argc < 2)
{
std::cout << "ERROR: data file name argument missing."
<< std::endl ;
return EXIT_FAILURE;
}
typedef itk::Image< unsigned char, 2 > ImageType ;
typedef itk::ImageFileReader< ImageType > ImageReaderType ;
ImageReaderType::Pointer imageReader = ImageReaderType::New() ;
imageReader->SetFileName( argv[1] ) ;
imageReader->Update() ;
ImageType::Pointer image = imageReader->GetOutput() ;
typedef itk::Statistics::JointDomainImageToListAdaptor< ImageType >
ListSampleType ;
ListSampleType::Pointer listSample = ListSampleType::New() ;
listSample->SetImage( image ) ;
ListSampleType::NormalizationFactorsType factors ;
factors[0] = 4 ;
factors[1] = 4 ;
factors[2] = 8 ;
listSample->SetNormalizationFactors( factors ) ;
typedef itk::Statistics::HypersphereKernelMeanShiftModeSeeker<
ListSampleType > ModeSeekerType ;
ModeSeekerType::Pointer modeSeeker = ModeSeekerType::New() ;
modeSeeker->SetInputSample( listSample ) ;
modeSeeker->SetSearchRadius( 1.0 ) ;
typedef itk::Statistics::SampleSelectiveMeanShiftBlurringFilter<
ListSampleType > FilterType ;
FilterType::Pointer filter = FilterType::New() ;
filter->SetInputSample( listSample ) ;
filter->SetMeanShiftModeSeeker( modeSeeker ) ;
FilterType::ComponentSelectionsType componentSelections ;
componentSelections.Fill( false ) ;
componentSelections[2] = true ;
filter->SetComponentSelections( componentSelections ) ;
try
{
filter->Update() ;
}
catch ( ... )
{
std::cout << "Test failed." << std::endl;
return EXIT_FAILURE;
}
std::cout << "Test passed." << std::endl;
return EXIT_SUCCESS;
}
<commit_msg><commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkSampleSelectiveMeanShiftBlurringFilterTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkImageRegionIterator.h"
#include "itkJointDomainImageToListAdaptor.h"
#include "itkSampleSelectiveMeanShiftBlurringFilter.h"
#include "itkHypersphereKernelMeanShiftModeSeeker.h"
int itkSampleSelectiveMeanShiftBlurringFilterTest(int argc, char* argv[] )
{
std::cout << "SampleSelectiveMeanShiftBlurringFilter Test \n \n";
if (argc < 2)
{
std::cout << "ERROR: data file name argument missing."
<< std::endl ;
return EXIT_FAILURE;
}
typedef itk::Image< unsigned char, 2 > ImageType ;
typedef itk::ImageFileReader< ImageType > ImageReaderType ;
ImageReaderType::Pointer imageReader = ImageReaderType::New() ;
imageReader->SetFileName( argv[1] ) ;
imageReader->Update() ;
ImageType::Pointer image = imageReader->GetOutput() ;
typedef itk::Statistics::JointDomainImageToListAdaptor< ImageType >
ListSampleType ;
ListSampleType::Pointer listSample = ListSampleType::New() ;
listSample->SetImage( image ) ;
ListSampleType::NormalizationFactorsType factors ;
factors[0] = 4 ;
factors[1] = 4 ;
factors[2] = 8 ;
listSample->SetNormalizationFactors( factors ) ;
typedef itk::Statistics::HypersphereKernelMeanShiftModeSeeker<
ListSampleType > ModeSeekerType ;
ModeSeekerType::Pointer modeSeeker = ModeSeekerType::New() ;
modeSeeker->SetInputSample( listSample ) ;
modeSeeker->SetSearchRadius( 1.0 ) ;
typedef itk::Statistics::SampleSelectiveMeanShiftBlurringFilter<
ListSampleType > FilterType ;
FilterType::Pointer filter = FilterType::New() ;
filter->SetInputSample( listSample ) ;
filter->SetMeanShiftModeSeeker( modeSeeker ) ;
FilterType::ComponentSelectionsType componentSelections ;
componentSelections.Fill( false ) ;
componentSelections[2] = true ;
filter->SetComponentSelections( componentSelections ) ;
try
{
filter->Update() ;
}
catch ( ... )
{
std::cout << "Test failed." << std::endl;
return EXIT_FAILURE;
}
// if you want to see the blurred image, change the following
// variable value to true.
bool saveOutputImage = false ;
if ( saveOutputImage )
{
typedef ImageType OutputImageType ;
typedef itk::ImageRegionIterator< OutputImageType > ImageIteratorType ;
typedef ImageType::PixelType PixelType ;
typedef itk::ImageFileWriter< OutputImageType > ImageWriterType ;
OutputImageType::Pointer outputImage = OutputImageType::New() ;
outputImage->SetRegions( image->GetLargestPossibleRegion() ) ;
outputImage->Allocate() ;
ImageIteratorType io_iter( outputImage,
outputImage->GetLargestPossibleRegion() ) ;
io_iter.GoToBegin() ;
FilterType::OutputType::Pointer output = filter->GetOutput() ;
FilterType::OutputType::Iterator fo_iter = output->Begin() ;
FilterType::OutputType::Iterator fo_end = output->End() ;
while ( fo_iter != fo_end )
{
io_iter.Set
((PixelType) (factors[2] * fo_iter.GetMeasurementVector()[2])) ;
++fo_iter ;
++io_iter ;
}
ImageWriterType::Pointer writer = ImageWriterType::New() ;
writer->SetFileName("blurred_sf4.png") ;
writer->SetInput( outputImage ) ;
writer->Update() ;
}
std::cout << "Test passed." << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbStreamingImageFileWriter.h"
#include "otbPrintableImageFilter.h"
// Software Guide : BeginCommandLineArgs
// INPUTS: {Spot5-Gloucester-before.tif}, {Spot5-Gloucester-after.tif}
// OUTPUTS: {MADOutput.tif}, {mad-input1.png}, {mad-input2.png}, {mad-output.png}
//
// Software Guide : EndCommandLineArgs
// Software Guide : BeginLatex
// This example illustrates the class
// \doxygen{otb}{MultivariateAlterationChangeDetectorImageFilter},
// which implements the Multivariate Alteration Change Detector
// algorithm \cite{nielsen2007regularized}. This algorihtm allows to
// perform change detection from a pair multi-band images, including
// images with different number of bands or modalities. Its output is
// a a multi-band image of change maps, each one being unccorrelated
// with the remaining. The number of bands of the output image is the
// minimum number of bands between the two input images.
//
// The algorithm works as follows. It tries to find two linear
// combinations of bands (one for each input images) which maximize
// correlation, and subtract these two linear combinitation, leading
// to the first change map. Then, it looks for a second set of linear
// combinations which are orthogonal to the first ones, a which
// maximize correlation, and use it as the second change map. This
// process is iterated until no more orthogonal linear combinations
// can be found.
//
// This algorithms has numerous advantages, such as radiometry scaling
// and shifting invariance and absence of parameters, but it can not
// be used on a pair of single band images (in this case the output is
// simply the difference between the two images).
//
// We start by including the corresponding header file.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "otbMultivariateAlterationDetectorImageFilter.h"
// Software Guide : EndCodeSnippet
int main(int argc, char* argv[])
{
if (argc < 6)
{
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0] << " inputImageFile1 inputImageFile2 outIn1Pretty outIn2Pretty outPretty"
<< "outputImageFile" << std::endl;
return -1;
}
// Define the dimension of the images
const unsigned int Dimension = 2;
// Software Guide : BeginLatex
// We then define the types for the input images, of the
// change image and of the image to be stored in a file for visualization.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef unsigned short InputPixelType;
typedef float OutputPixelType;
typedef otb::VectorImage<InputPixelType, Dimension> InputImageType;
typedef otb::VectorImage<OutputPixelType, Dimension> OutputImageType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We can now declare the types for the reader. Since the images
// can be vey large, we will force the pipeline to use
// streaming. For this purpose, the file writer will be
// streamed. This is achieved by using the
// \doxygen{otb}{StreamingImageFileWriter} class.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::ImageFileReader<InputImageType> ReaderType;
typedef otb::StreamingImageFileWriter<OutputImageType> WriterType;
// Software Guide : EndCodeSnippet
// This is for rendering in software guide
typedef otb::PrintableImageFilter<InputImageType,InputImageType> InputPrintFilterType;
typedef otb::PrintableImageFilter<OutputImageType,OutputImageType> OutputPrintFilterType;
typedef InputPrintFilterType::OutputImageType VisuImageType;
typedef otb::StreamingImageFileWriter<VisuImageType> VisuWriterType;
// The \doxygen{otb}{MultivariateAlterationDetectorImageFilter} is templated over
// the type of the input images and the type of the generated change
// image.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::MultivariateAlterationDetectorImageFilter<
InputImageType,OutputImageType> MADFilterType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The different elements of the pipeline can now be instantiated.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
ReaderType::Pointer reader1 = ReaderType::New();
ReaderType::Pointer reader2 = ReaderType::New();
WriterType::Pointer writer = WriterType::New();
MADFilterType::Pointer madFilter = MADFilterType::New();
// Software Guide : EndCodeSnippet
const char * inputFilename1 = argv[1];
const char * inputFilename2 = argv[2];
const char * outputFilename = argv[3];
const char * in1pretty = argv[4];
const char * in2pretty = argv[5];
const char * outpretty = argv[6];
// Software Guide : BeginLatex
//
// We set the parameters of the different elements of the pipeline.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
reader1->SetFileName(inputFilename1);
reader2->SetFileName(inputFilename2);
writer->SetFileName(outputFilename);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We build the pipeline by plugging all the elements together.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
madFilter->SetInput1(reader1->GetOutput());
madFilter->SetInput2(reader2->GetOutput());
writer->SetInput(madFilter->GetOutput());
// Software Guide : EndCodeSnippet
try
{
// Software Guide : BeginLatex
//
// And then we can trigger the pipeline update, as usual.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
writer->Update();
// Software Guide : EndCodeSnippet
}
catch (itk::ExceptionObject& err)
{
std::cout << "ExceptionObject caught !" << std::endl;
std::cout << err << std::endl;
return -1;
}
// Here we generate the figures
InputPrintFilterType::Pointer input1PrintFilter = InputPrintFilterType::New();
InputPrintFilterType::Pointer input2PrintFilter = InputPrintFilterType::New();
OutputPrintFilterType::Pointer outputPrintFilter = OutputPrintFilterType::New();
VisuWriterType::Pointer input1VisuWriter = VisuWriterType::New();
VisuWriterType::Pointer input2VisuWriter = VisuWriterType::New();
VisuWriterType::Pointer outputVisuWriter = VisuWriterType::New();
input1PrintFilter->SetInput(reader1->GetOutput());
input1PrintFilter->SetChannel(3);
input1PrintFilter->SetChannel(2);
input1PrintFilter->SetChannel(1);
input2PrintFilter->SetInput(reader2->GetOutput());
input2PrintFilter->SetChannel(3);
input2PrintFilter->SetChannel(2);
input2PrintFilter->SetChannel(1);
outputPrintFilter->SetInput(madFilter->GetOutput());
outputPrintFilter->SetChannel(3);
outputPrintFilter->SetChannel(2);
outputPrintFilter->SetChannel(1);
input1VisuWriter->SetInput(input1PrintFilter->GetOutput());
input2VisuWriter->SetInput(input2PrintFilter->GetOutput());
outputVisuWriter->SetInput(outputPrintFilter->GetOutput());
input1VisuWriter->SetFileName(in1pretty);
input2VisuWriter->SetFileName(in2pretty);
outputVisuWriter->SetFileName(outpretty);
input1VisuWriter->Update();
input2VisuWriter->Update();
outputVisuWriter->Update();
// Software Guide : BeginLatex
// Figure \ref{fig:MADCHDET} shows the
// results of Multivariate Alteration Detector applied to a pair of
// SPOT5 images before and after a flooding event.
// \begin{figure}
// \center \includegraphics[width=0.32\textwidth]{mad-input1.eps}
// \includegraphics[width=0.32\textwidth]{mad-input2.eps}
// \includegraphics[width=0.32\textwidth]{mad-output.eps}
// \itkcaption[CorrelationMultivariate Alteration Detection
// Results]{Result of the Multivariate Alteration Detector results on
// SPOT5 data before and after flooding.} \label{fig:MADCHDET}
// \end{figure}
// Software Guide : EndLatex
return EXIT_SUCCESS;
}
<commit_msg>STYLE<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbStreamingImageFileWriter.h"
#include "otbPrintableImageFilter.h"
// Software Guide : BeginCommandLineArgs
// INPUTS: {Spot5-Gloucester-before.tif}, {Spot5-Gloucester-after.tif}
// OUTPUTS: {MADOutput.tif}, {mad-input1.png}, {mad-input2.png}, {mad-output.png}
//
// Software Guide : EndCommandLineArgs
// Software Guide : BeginLatex
// This example illustrates the class
// \doxygen{otb}{MultivariateAlterationChangeDetectorImageFilter},
// which implements the Multivariate Alteration Change Detector
// algorithm \cite{nielsen2007regularized}. This algorihtm allows to
// perform change detection from a pair multi-band images, including
// images with different number of bands or modalities. Its output is
// a a multi-band image of change maps, each one being unccorrelated
// with the remaining. The number of bands of the output image is the
// minimum number of bands between the two input images.
//
// The algorithm works as follows. It tries to find two linear
// combinations of bands (one for each input images) which maximize
// correlation, and subtract these two linear combinitation, leading
// to the first change map. Then, it looks for a second set of linear
// combinations which are orthogonal to the first ones, a which
// maximize correlation, and use it as the second change map. This
// process is iterated until no more orthogonal linear combinations
// can be found.
//
// This algorithms has numerous advantages, such as radiometry scaling
// and shifting invariance and absence of parameters, but it can not
// be used on a pair of single band images (in this case the output is
// simply the difference between the two images).
//
// We start by including the corresponding header file.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "otbMultivariateAlterationDetectorImageFilter.h"
// Software Guide : EndCodeSnippet
int main(int argc, char* argv[])
{
if (argc < 6)
{
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0] << " inputImageFile1 inputImageFile2 outIn1Pretty outIn2Pretty outPretty"
<< "outputImageFile" << std::endl;
return -1;
}
// Define the dimension of the images
const unsigned int Dimension = 2;
// Software Guide : BeginLatex
// We then define the types for the input images, of the
// change image and of the image to be stored in a file for visualization.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef unsigned short InputPixelType;
typedef float OutputPixelType;
typedef otb::VectorImage<InputPixelType, Dimension> InputImageType;
typedef otb::VectorImage<OutputPixelType, Dimension> OutputImageType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We can now declare the types for the reader. Since the images
// can be vey large, we will force the pipeline to use
// streaming. For this purpose, the file writer will be
// streamed. This is achieved by using the
// \doxygen{otb}{StreamingImageFileWriter} class.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::ImageFileReader<InputImageType> ReaderType;
typedef otb::StreamingImageFileWriter<OutputImageType> WriterType;
// Software Guide : EndCodeSnippet
// This is for rendering in software guide
typedef otb::PrintableImageFilter<InputImageType,InputImageType> InputPrintFilterType;
typedef otb::PrintableImageFilter<OutputImageType,OutputImageType> OutputPrintFilterType;
typedef InputPrintFilterType::OutputImageType VisuImageType;
typedef otb::StreamingImageFileWriter<VisuImageType> VisuWriterType;
// The \doxygen{otb}{MultivariateAlterationDetectorImageFilter} is templated over
// the type of the input images and the type of the generated change
// image.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::MultivariateAlterationDetectorImageFilter<
InputImageType,OutputImageType> MADFilterType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The different elements of the pipeline can now be instantiated.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
ReaderType::Pointer reader1 = ReaderType::New();
ReaderType::Pointer reader2 = ReaderType::New();
WriterType::Pointer writer = WriterType::New();
MADFilterType::Pointer madFilter = MADFilterType::New();
// Software Guide : EndCodeSnippet
const char * inputFilename1 = argv[1];
const char * inputFilename2 = argv[2];
const char * outputFilename = argv[3];
const char * in1pretty = argv[4];
const char * in2pretty = argv[5];
const char * outpretty = argv[6];
// Software Guide : BeginLatex
//
// We set the parameters of the different elements of the pipeline.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
reader1->SetFileName(inputFilename1);
reader2->SetFileName(inputFilename2);
writer->SetFileName(outputFilename);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We build the pipeline by plugging all the elements together.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
madFilter->SetInput1(reader1->GetOutput());
madFilter->SetInput2(reader2->GetOutput());
writer->SetInput(madFilter->GetOutput());
// Software Guide : EndCodeSnippet
try
{
// Software Guide : BeginLatex
//
// And then we can trigger the pipeline update, as usual.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
writer->Update();
// Software Guide : EndCodeSnippet
}
catch (itk::ExceptionObject& err)
{
std::cout << "ExceptionObject caught !" << std::endl;
std::cout << err << std::endl;
return -1;
}
// Here we generate the figures
InputPrintFilterType::Pointer input1PrintFilter = InputPrintFilterType::New();
InputPrintFilterType::Pointer input2PrintFilter = InputPrintFilterType::New();
OutputPrintFilterType::Pointer outputPrintFilter = OutputPrintFilterType::New();
VisuWriterType::Pointer input1VisuWriter = VisuWriterType::New();
VisuWriterType::Pointer input2VisuWriter = VisuWriterType::New();
VisuWriterType::Pointer outputVisuWriter = VisuWriterType::New();
input1PrintFilter->SetInput(reader1->GetOutput());
input1PrintFilter->SetChannel(3);
input1PrintFilter->SetChannel(2);
input1PrintFilter->SetChannel(1);
input2PrintFilter->SetInput(reader2->GetOutput());
input2PrintFilter->SetChannel(3);
input2PrintFilter->SetChannel(2);
input2PrintFilter->SetChannel(1);
outputPrintFilter->SetInput(madFilter->GetOutput());
outputPrintFilter->SetChannel(3);
outputPrintFilter->SetChannel(2);
outputPrintFilter->SetChannel(1);
input1VisuWriter->SetInput(input1PrintFilter->GetOutput());
input2VisuWriter->SetInput(input2PrintFilter->GetOutput());
outputVisuWriter->SetInput(outputPrintFilter->GetOutput());
input1VisuWriter->SetFileName(in1pretty);
input2VisuWriter->SetFileName(in2pretty);
outputVisuWriter->SetFileName(outpretty);
input1VisuWriter->Update();
input2VisuWriter->Update();
outputVisuWriter->Update();
// Software Guide : BeginLatex
// Figure \ref{fig:MADCHDET} shows the
// results of Multivariate Alteration Detector applied to a pair of
// SPOT5 images before and after a flooding event.
// \begin{figure}
// \center \includegraphics[width=0.32\textwidth]{mad-input1.eps}
// \includegraphics[width=0.32\textwidth]{mad-input2.eps}
// \includegraphics[width=0.32\textwidth]{mad-output.eps}
// \itkcaption[CorrelationMultivariate Alteration Detection
// Results]{Result of the Multivariate Alteration Detector results on
// SPOT5 data before and after flooding.} \label{fig:MADCHDET}
// \end{figure}
// Software Guide : EndLatex
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*=============================================================================
Library: CTK
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics
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 "ctkCMEventDispatcher_p.h"
#include <service/log/ctkLogService.h>
#include <service/cm/ctkConfigurationListener.h>
#include <QRunnable>
class _DispatchEventRunnable : public QRunnable
{
public:
_DispatchEventRunnable(ctkServiceTracker<ctkConfigurationListener*>* tracker,
ctkLogService* log, const ctkConfigurationEvent& event,
const ctkServiceReference& ref)
: tracker(tracker), log(log), event(event), ref(ref)
{
}
void run()
{
ctkConfigurationListener* listener = tracker->getService(ref);
if (listener == 0)
{
return;
}
try
{
listener->configurationEvent(event);
}
catch (const std::exception& e)
{
log->log(ctkLogService::LOG_ERROR, e.what());
}
catch (...)
{
log->log(ctkLogService::LOG_ERROR, "Unspecified exception");
}
}
private:
ctkServiceTracker<ctkConfigurationListener*>* tracker;
ctkLogService* log;
ctkConfigurationEvent event;
ctkServiceReference ref;
};
ctkCMEventDispatcher::ctkCMEventDispatcher(ctkPluginContext* context, ctkLogService* log)
: tracker(context), queue("ctkConfigurationListener Event Queue"), log(log)
{
}
void ctkCMEventDispatcher::start()
{
tracker.open();
}
void ctkCMEventDispatcher::stop()
{
tracker.close();
{
QMutexLocker lock(&mutex);
configAdminReference = ctkServiceReference();
}
}
void ctkCMEventDispatcher::setServiceReference(const ctkServiceReference& reference)
{
QMutexLocker lock(&mutex);
if (!configAdminReference)
{
configAdminReference = reference;
}
}
void ctkCMEventDispatcher::dispatchEvent(ctkConfigurationEvent::Type type, const QString& factoryPid, const QString& pid)
{
const ctkConfigurationEvent event = createConfigurationEvent(type, factoryPid, pid);
if (event.isNull())
return;
QList<ctkServiceReference> refs = tracker.getServiceReferences();
foreach (ctkServiceReference ref, refs)
{
queue.put(new _DispatchEventRunnable(&tracker, log, event, ref));
}
}
ctkConfigurationEvent ctkCMEventDispatcher::createConfigurationEvent(ctkConfigurationEvent::Type type, const QString& factoryPid, const QString& pid)
{
if (!configAdminReference)
{
return ctkConfigurationEvent();
}
return ctkConfigurationEvent(configAdminReference, type, factoryPid, pid);
}
<commit_msg>Using operator=(int) to reset service reference.<commit_after>/*=============================================================================
Library: CTK
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics
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 "ctkCMEventDispatcher_p.h"
#include <service/log/ctkLogService.h>
#include <service/cm/ctkConfigurationListener.h>
#include <QRunnable>
class _DispatchEventRunnable : public QRunnable
{
public:
_DispatchEventRunnable(ctkServiceTracker<ctkConfigurationListener*>* tracker,
ctkLogService* log, const ctkConfigurationEvent& event,
const ctkServiceReference& ref)
: tracker(tracker), log(log), event(event), ref(ref)
{
}
void run()
{
ctkConfigurationListener* listener = tracker->getService(ref);
if (listener == 0)
{
return;
}
try
{
listener->configurationEvent(event);
}
catch (const std::exception& e)
{
log->log(ctkLogService::LOG_ERROR, e.what());
}
catch (...)
{
log->log(ctkLogService::LOG_ERROR, "Unspecified exception");
}
}
private:
ctkServiceTracker<ctkConfigurationListener*>* tracker;
ctkLogService* log;
ctkConfigurationEvent event;
ctkServiceReference ref;
};
ctkCMEventDispatcher::ctkCMEventDispatcher(ctkPluginContext* context, ctkLogService* log)
: tracker(context), queue("ctkConfigurationListener Event Queue"), log(log)
{
}
void ctkCMEventDispatcher::start()
{
tracker.open();
}
void ctkCMEventDispatcher::stop()
{
tracker.close();
{
QMutexLocker lock(&mutex);
configAdminReference = 0;
}
}
void ctkCMEventDispatcher::setServiceReference(const ctkServiceReference& reference)
{
QMutexLocker lock(&mutex);
if (!configAdminReference)
{
configAdminReference = reference;
}
}
void ctkCMEventDispatcher::dispatchEvent(ctkConfigurationEvent::Type type, const QString& factoryPid, const QString& pid)
{
const ctkConfigurationEvent event = createConfigurationEvent(type, factoryPid, pid);
if (event.isNull())
return;
QList<ctkServiceReference> refs = tracker.getServiceReferences();
foreach (ctkServiceReference ref, refs)
{
queue.put(new _DispatchEventRunnable(&tracker, log, event, ref));
}
}
ctkConfigurationEvent ctkCMEventDispatcher::createConfigurationEvent(ctkConfigurationEvent::Type type, const QString& factoryPid, const QString& pid)
{
if (!configAdminReference)
{
return ctkConfigurationEvent();
}
return ctkConfigurationEvent(configAdminReference, type, factoryPid, pid);
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015, 2016, 2017, 2018, Intel Corporation
*
* 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 Intel Corporation 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 LOG OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "geopm_env.h"
#include "geopm_signal_handler.h"
#include "geopm_message.h"
#include "geopm_time.h"
#include "Kontroller.hpp"
#include "ApplicationIO.hpp"
#include "Reporter.hpp"
#include "Tracer.hpp"
#include "Exception.hpp"
#include "Comm.hpp"
#include "PlatformTopo.hpp"
#include "PlatformIO.hpp"
#include "Agent.hpp"
#include "TreeComm.hpp"
#include "ManagerIO.hpp"
#include "config.h"
extern "C"
{
static void *geopm_threaded_run(void *args)
{
long err = 0;
geopm::Kontroller *ctl = (geopm::Kontroller *)args;
try {
ctl->run();
}
catch (...) {
err = geopm::exception_handler(std::current_exception());
}
return (void *)err;
}
}
namespace geopm
{
Kontroller::Kontroller(std::shared_ptr<IComm> ppn1_comm,
const std::string &global_policy_path)
: Kontroller(ppn1_comm,
platform_topo(),
platform_io(),
geopm_env_agent(),
IAgent::num_policy(agent_factory().dictionary(geopm_env_agent())),
IAgent::num_sample(agent_factory().dictionary(geopm_env_agent())),
std::unique_ptr<ITreeComm>(new TreeComm(ppn1_comm,
IAgent::num_policy(agent_factory().dictionary(geopm_env_agent())),
IAgent::num_sample(agent_factory().dictionary(geopm_env_agent())))),
std::shared_ptr<IApplicationIO>(new ApplicationIO(geopm_env_shmkey())),
std::unique_ptr<IReporter>(new Reporter(geopm_env_report(), platform_io(), ppn1_comm->rank())),
std::unique_ptr<ITracer>(new Tracer()),
std::vector<std::unique_ptr<IAgent> >{},
std::unique_ptr<IManagerIOSampler>(new ManagerIOSampler(global_policy_path, true)))
{
}
Kontroller::Kontroller(std::shared_ptr<IComm> comm,
IPlatformTopo &plat_topo,
IPlatformIO &plat_io,
const std::string &agent_name,
int num_send_down,
int num_send_up,
std::unique_ptr<ITreeComm> tree_comm,
std::shared_ptr<IApplicationIO> application_io,
std::unique_ptr<IReporter> reporter,
std::unique_ptr<ITracer> tracer,
std::vector<std::unique_ptr<IAgent> > level_agent,
std::unique_ptr<IManagerIOSampler> manager_io_sampler)
: m_comm(comm)
, m_platform_topo(plat_topo)
, m_platform_io(plat_io)
, m_agent_name(agent_name)
, m_num_send_down(num_send_down)
, m_num_send_up(num_send_up)
, m_tree_comm(std::move(tree_comm))
, m_num_level_ctl(m_tree_comm->num_level_controlled())
, m_max_level(m_num_level_ctl + 1)
, m_root_level(m_tree_comm->root_level())
, m_application_io(std::move(application_io))
, m_reporter(std::move(reporter))
, m_tracer(std::move(tracer))
, m_agent(std::move(level_agent))
, m_is_root(m_num_level_ctl == m_root_level)
, m_in_policy(m_num_send_down)
, m_out_policy(m_num_level_ctl)
, m_in_sample(m_num_level_ctl)
, m_out_sample(m_num_send_up)
, m_manager_io_sampler(std::move(manager_io_sampler))
{
// Three dimensional vector over levels, children, and message
// index. These are used as temporary storage when passing
// messages up and down the tree.
for (int level = 0; level != m_num_level_ctl; ++level) {
int num_children = m_tree_comm->level_size(level);
m_out_policy[level] = std::vector<std::vector<double> >(num_children,
std::vector<double>(m_num_send_down));
m_in_sample[level] = std::vector<std::vector<double> >(num_children,
std::vector<double>(m_num_send_up));
}
if (m_agent.size() == 0) {
m_agent.push_back(agent_factory().make_plugin(m_agent_name));
m_agent.back()->init(0, m_tree_comm->level_num_leaf(0));
for (int level = 1; level < m_max_level; ++level) {
m_agent.push_back(agent_factory().make_plugin(m_agent_name));
m_agent.back()->init(level, m_tree_comm->level_num_leaf(level));
}
}
/// @todo move somewhere else: need to happen after Agents are constructed
// sanity checks
if (m_agent.size() == 0) {
throw Exception("Kontroller requires at least one Agent",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
if (m_max_level != (int)m_agent.size()) {
throw Exception("Kontroller number of agents is incorrect",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
}
Kontroller::~Kontroller()
{
geopm_signal_handler_check();
geopm_signal_handler_revert();
}
void Kontroller::run(void)
{
m_reporter->init();
setup_trace();
m_application_io->controller_ready();
m_application_io->update(m_comm);
m_platform_io.read_batch();
m_tracer->update(m_trace_sample, m_application_io->region_info());
m_application_io->clear_region_info();
while (!m_application_io->do_shutdown()) {
step();
}
m_application_io->update(m_comm);
m_platform_io.read_batch();
m_tracer->update(m_trace_sample, m_application_io->region_info());
m_application_io->clear_region_info();
generate();
}
void Kontroller::generate(void)
{
std::vector<std::pair<std::string, std::string> > agent_report_header;
if (m_is_root) {
agent_report_header = m_agent[m_root_level]->report_header();
}
auto agent_node_report = m_agent[0]->report_node();
m_reporter->generate(m_agent_name,
agent_report_header,
agent_node_report,
m_agent[0]->report_region(),
*m_application_io,
m_comm,
*m_tree_comm);
m_tracer->flush();
}
void Kontroller::step(void)
{
walk_down();
geopm_signal_handler_check();
walk_up();
geopm_signal_handler_check();
m_agent[0]->wait();
geopm_signal_handler_check();
}
void Kontroller::walk_down(void)
{
bool do_send = false;
if (m_is_root) {
/// @todo Pass m_in_policy by reference into the sampler, and return an is_updated bool.
m_in_policy = m_manager_io_sampler->sample();
do_send = true;
}
else {
do_send = m_tree_comm->receive_down(m_num_level_ctl, m_in_policy);
}
for (int level = m_num_level_ctl - 1; level != -1; --level) {
do_send = m_agent[level]->descend(m_in_policy, m_out_policy[level]);
if (do_send) {
m_tree_comm->send_down(level, m_out_policy[level]);
do_send = m_tree_comm->receive_down(level, m_in_policy);
}
}
if (do_send &&
m_agent[0]->adjust_platform(m_in_policy)) {
m_platform_io.write_batch();
}
}
void Kontroller::walk_up(void)
{
m_application_io->update(m_comm);
m_platform_io.read_batch();
bool do_send = m_agent[0]->sample_platform(m_out_sample);
m_agent[0]->trace_values(m_trace_sample);
m_tracer->update(m_trace_sample, m_application_io->region_info());
m_application_io->clear_region_info();
for (int level = 0; level != m_num_level_ctl; ++level) {
m_tree_comm->send_up(level, m_out_sample);
do_send = m_tree_comm->receive_up(level, m_in_sample[level]);
if (do_send) {
do_send = m_agent[level]->ascend(m_in_sample[level], m_out_sample);
}
}
if (do_send) {
if (!m_is_root) {
m_tree_comm->send_up(m_num_level_ctl, m_out_sample);
}
else {
/// @todo At the root of the tree, send signals up to the
/// resource manager.
}
}
}
void Kontroller::pthread(const pthread_attr_t *attr, pthread_t *thread)
{
int err = pthread_create(thread, attr, geopm_threaded_run, (void *)this);
if (err) {
throw Exception("Controller::pthread(): pthread_create() failed",
err, __FILE__, __LINE__);
}
}
void Kontroller::setup_trace(void)
{
auto agent_cols = m_agent[0]->trace_names();
m_tracer->columns(agent_cols);
m_trace_sample.resize(agent_cols.size());
}
}
<commit_msg>Use return value from sample_platform() and last call to recieve_down().<commit_after>/*
* Copyright (c) 2015, 2016, 2017, 2018, Intel Corporation
*
* 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 Intel Corporation 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 LOG OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "geopm_env.h"
#include "geopm_signal_handler.h"
#include "geopm_message.h"
#include "geopm_time.h"
#include "Kontroller.hpp"
#include "ApplicationIO.hpp"
#include "Reporter.hpp"
#include "Tracer.hpp"
#include "Exception.hpp"
#include "Comm.hpp"
#include "PlatformTopo.hpp"
#include "PlatformIO.hpp"
#include "Agent.hpp"
#include "TreeComm.hpp"
#include "ManagerIO.hpp"
#include "config.h"
extern "C"
{
static void *geopm_threaded_run(void *args)
{
long err = 0;
geopm::Kontroller *ctl = (geopm::Kontroller *)args;
try {
ctl->run();
}
catch (...) {
err = geopm::exception_handler(std::current_exception());
}
return (void *)err;
}
}
namespace geopm
{
Kontroller::Kontroller(std::shared_ptr<IComm> ppn1_comm,
const std::string &global_policy_path)
: Kontroller(ppn1_comm,
platform_topo(),
platform_io(),
geopm_env_agent(),
IAgent::num_policy(agent_factory().dictionary(geopm_env_agent())),
IAgent::num_sample(agent_factory().dictionary(geopm_env_agent())),
std::unique_ptr<ITreeComm>(new TreeComm(ppn1_comm,
IAgent::num_policy(agent_factory().dictionary(geopm_env_agent())),
IAgent::num_sample(agent_factory().dictionary(geopm_env_agent())))),
std::shared_ptr<IApplicationIO>(new ApplicationIO(geopm_env_shmkey())),
std::unique_ptr<IReporter>(new Reporter(geopm_env_report(), platform_io(), ppn1_comm->rank())),
std::unique_ptr<ITracer>(new Tracer()),
std::vector<std::unique_ptr<IAgent> >{},
std::unique_ptr<IManagerIOSampler>(new ManagerIOSampler(global_policy_path, true)))
{
}
Kontroller::Kontroller(std::shared_ptr<IComm> comm,
IPlatformTopo &plat_topo,
IPlatformIO &plat_io,
const std::string &agent_name,
int num_send_down,
int num_send_up,
std::unique_ptr<ITreeComm> tree_comm,
std::shared_ptr<IApplicationIO> application_io,
std::unique_ptr<IReporter> reporter,
std::unique_ptr<ITracer> tracer,
std::vector<std::unique_ptr<IAgent> > level_agent,
std::unique_ptr<IManagerIOSampler> manager_io_sampler)
: m_comm(comm)
, m_platform_topo(plat_topo)
, m_platform_io(plat_io)
, m_agent_name(agent_name)
, m_num_send_down(num_send_down)
, m_num_send_up(num_send_up)
, m_tree_comm(std::move(tree_comm))
, m_num_level_ctl(m_tree_comm->num_level_controlled())
, m_max_level(m_num_level_ctl + 1)
, m_root_level(m_tree_comm->root_level())
, m_application_io(std::move(application_io))
, m_reporter(std::move(reporter))
, m_tracer(std::move(tracer))
, m_agent(std::move(level_agent))
, m_is_root(m_num_level_ctl == m_root_level)
, m_in_policy(m_num_send_down)
, m_out_policy(m_num_level_ctl)
, m_in_sample(m_num_level_ctl)
, m_out_sample(m_num_send_up)
, m_manager_io_sampler(std::move(manager_io_sampler))
{
// Three dimensional vector over levels, children, and message
// index. These are used as temporary storage when passing
// messages up and down the tree.
for (int level = 0; level != m_num_level_ctl; ++level) {
int num_children = m_tree_comm->level_size(level);
m_out_policy[level] = std::vector<std::vector<double> >(num_children,
std::vector<double>(m_num_send_down));
m_in_sample[level] = std::vector<std::vector<double> >(num_children,
std::vector<double>(m_num_send_up));
}
if (m_agent.size() == 0) {
m_agent.push_back(agent_factory().make_plugin(m_agent_name));
m_agent.back()->init(0, m_tree_comm->level_num_leaf(0));
for (int level = 1; level < m_max_level; ++level) {
m_agent.push_back(agent_factory().make_plugin(m_agent_name));
m_agent.back()->init(level, m_tree_comm->level_num_leaf(level));
}
}
/// @todo move somewhere else: need to happen after Agents are constructed
// sanity checks
if (m_agent.size() == 0) {
throw Exception("Kontroller requires at least one Agent",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
if (m_max_level != (int)m_agent.size()) {
throw Exception("Kontroller number of agents is incorrect",
GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
}
Kontroller::~Kontroller()
{
geopm_signal_handler_check();
geopm_signal_handler_revert();
}
void Kontroller::run(void)
{
m_reporter->init();
setup_trace();
m_application_io->controller_ready();
m_application_io->update(m_comm);
m_platform_io.read_batch();
m_tracer->update(m_trace_sample, m_application_io->region_info());
m_application_io->clear_region_info();
while (!m_application_io->do_shutdown()) {
step();
}
m_application_io->update(m_comm);
m_platform_io.read_batch();
m_tracer->update(m_trace_sample, m_application_io->region_info());
m_application_io->clear_region_info();
generate();
}
void Kontroller::generate(void)
{
std::vector<std::pair<std::string, std::string> > agent_report_header;
if (m_is_root) {
agent_report_header = m_agent[m_root_level]->report_header();
}
auto agent_node_report = m_agent[0]->report_node();
m_reporter->generate(m_agent_name,
agent_report_header,
agent_node_report,
m_agent[0]->report_region(),
*m_application_io,
m_comm,
*m_tree_comm);
m_tracer->flush();
}
void Kontroller::step(void)
{
walk_down();
geopm_signal_handler_check();
walk_up();
geopm_signal_handler_check();
m_agent[0]->wait();
geopm_signal_handler_check();
}
void Kontroller::walk_down(void)
{
bool do_send = false;
if (m_is_root) {
/// @todo Pass m_in_policy by reference into the sampler, and return an is_updated bool.
m_in_policy = m_manager_io_sampler->sample();
do_send = true;
}
else {
do_send = m_tree_comm->receive_down(m_num_level_ctl, m_in_policy);
}
for (int level = m_num_level_ctl - 1; level != -1; --level) {
if (do_send) {
do_send = m_agent[level]->descend(m_in_policy, m_out_policy[level]);
}
if (do_send) {
m_tree_comm->send_down(level, m_out_policy[level]);
}
do_send = m_tree_comm->receive_down(level, m_in_policy);
}
if (do_send &&
m_agent[0]->adjust_platform(m_in_policy)) {
m_platform_io.write_batch();
}
}
void Kontroller::walk_up(void)
{
m_application_io->update(m_comm);
m_platform_io.read_batch();
bool do_send = m_agent[0]->sample_platform(m_out_sample);
m_agent[0]->trace_values(m_trace_sample);
m_tracer->update(m_trace_sample, m_application_io->region_info());
m_application_io->clear_region_info();
for (int level = 0; level != m_num_level_ctl; ++level) {
if (do_send) {
m_tree_comm->send_up(level, m_out_sample);
}
do_send = m_tree_comm->receive_up(level, m_in_sample[level]);
if (do_send) {
do_send = m_agent[level]->ascend(m_in_sample[level], m_out_sample);
}
}
if (do_send) {
if (!m_is_root) {
m_tree_comm->send_up(m_num_level_ctl, m_out_sample);
}
else {
/// @todo At the root of the tree, send signals up to the
/// resource manager.
}
}
}
void Kontroller::pthread(const pthread_attr_t *attr, pthread_t *thread)
{
int err = pthread_create(thread, attr, geopm_threaded_run, (void *)this);
if (err) {
throw Exception("Controller::pthread(): pthread_create() failed",
err, __FILE__, __LINE__);
}
}
void Kontroller::setup_trace(void)
{
auto agent_cols = m_agent[0]->trace_names();
m_tracer->columns(agent_cols);
m_trace_sample.resize(agent_cols.size());
}
}
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2012, John Haddon. All rights reserved.
// Copyright (c) 2013, 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 John Haddon 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 "GafferScene/Attributes.h"
#include "boost/bind.hpp"
#include "boost/logic/tribool.hpp"
using namespace IECore;
using namespace Gaffer;
using namespace GafferScene;
GAFFER_NODE_DEFINE_TYPE( Attributes );
size_t Attributes::g_firstPlugIndex = 0;
Attributes::Attributes( const std::string &name )
: AttributeProcessor( name, PathMatcher::EveryMatch )
{
storeIndexOfNextChild( g_firstPlugIndex );
addChild( new CompoundDataPlug( "attributes" ) );
addChild( new BoolPlug( "global", Plug::In, false ) );
addChild( new AtomicCompoundDataPlug( "extraAttributes", Plug::In, new IECore::CompoundData ) );
// Connect to signals we use to manage pass-throughs for globals
// and attributes based on the value of globalPlug().
plugSetSignal().connect( boost::bind( &Attributes::plugSet, this, ::_1 ) );
plugInputChangedSignal().connect( boost::bind( &Attributes::plugInputChanged, this, ::_1 ) );
}
Attributes::~Attributes()
{
}
Gaffer::CompoundDataPlug *Attributes::attributesPlug()
{
return getChild<Gaffer::CompoundDataPlug>( g_firstPlugIndex );
}
const Gaffer::CompoundDataPlug *Attributes::attributesPlug() const
{
return getChild<Gaffer::CompoundDataPlug>( g_firstPlugIndex );
}
Gaffer::BoolPlug *Attributes::globalPlug()
{
return getChild<Gaffer::BoolPlug>( g_firstPlugIndex + 1 );
}
const Gaffer::BoolPlug *Attributes::globalPlug() const
{
return getChild<Gaffer::BoolPlug>( g_firstPlugIndex + 1 );
}
Gaffer::AtomicCompoundDataPlug *Attributes::extraAttributesPlug()
{
return getChild<Gaffer::AtomicCompoundDataPlug>( g_firstPlugIndex + 2 );
}
const Gaffer::AtomicCompoundDataPlug *Attributes::extraAttributesPlug() const
{
return getChild<Gaffer::AtomicCompoundDataPlug>( g_firstPlugIndex + 2 );
}
void Attributes::affects( const Gaffer::Plug *input, AffectedPlugsContainer &outputs ) const
{
AttributeProcessor::affects( input, outputs );
if(
input == globalPlug() ||
input == inPlug()->globalsPlug() ||
attributesPlug()->isAncestorOf( input ) ||
input == extraAttributesPlug()
)
{
// We can only affect a particular output if we haven't
// connected it as a pass-through in updateInternalConnections().
if( !outPlug()->globalsPlug()->getInput() )
{
outputs.push_back( outPlug()->globalsPlug() );
}
}
}
void Attributes::hashGlobals( const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const
{
if( globalPlug()->getValue() )
{
// We will modify the globals.
AttributeProcessor::hashGlobals( context, parent, h );
inPlug()->globalsPlug()->hash( h );
attributesPlug()->hash( h );
extraAttributesPlug()->hash( h );
}
else
{
// We won't modify the globals - pass through the hash.
h = inPlug()->globalsPlug()->hash();
}
}
IECore::ConstCompoundObjectPtr Attributes::computeGlobals( const Gaffer::Context *context, const ScenePlug *parent ) const
{
ConstCompoundObjectPtr inputGlobals = inPlug()->globalsPlug()->getValue();
if( !globalPlug()->getValue() )
{
return inputGlobals;
}
const CompoundDataPlug *p = attributesPlug();
IECore::CompoundObjectPtr result = new CompoundObject;
// Since we're not going to modify any existing members (only add new ones),
// and our result becomes const on returning it, we can directly reference
// the input members in our result without copying. Be careful not to modify
// them though!
result->members() = inputGlobals->members();
std::string name;
for( NameValuePlugIterator it( p ); !it.done(); ++it )
{
IECore::DataPtr d = p->memberDataAndName( it->get(), name );
if( d )
{
result->members()["attribute:" + name] = d;
}
}
IECore::ConstCompoundDataPtr extraAttributesData = extraAttributesPlug()->getValue();
const IECore::CompoundDataMap &extraAttributes = extraAttributesData->readable();
for( IECore::CompoundDataMap::const_iterator it = extraAttributes.begin(), eIt = extraAttributes.end(); it != eIt; ++it )
{
result->members()["attribute:" + it->first.string()] = it->second.get();
}
return result;
}
bool Attributes::affectsProcessedAttributes( const Gaffer::Plug *input ) const
{
if( outPlug()->attributesPlug()->getInput() )
{
// We've made a pass-through connection
return false;
}
return
AttributeProcessor::affectsProcessedAttributes( input ) ||
attributesPlug()->isAncestorOf( input ) ||
input == globalPlug() ||
input == extraAttributesPlug()
;
}
void Attributes::hashProcessedAttributes( const ScenePath &path, const Gaffer::Context *context, IECore::MurmurHash &h ) const
{
if( ( attributesPlug()->children().empty() && extraAttributesPlug()->isSetToDefault() ) || globalPlug()->getValue() )
{
h = inPlug()->attributesPlug()->hash();
}
else
{
AttributeProcessor::hashProcessedAttributes( path, context, h );
attributesPlug()->hash( h );
extraAttributesPlug()->hash( h );
}
}
IECore::ConstCompoundObjectPtr Attributes::computeProcessedAttributes( const ScenePath &path, const Gaffer::Context *context, const IECore::CompoundObject *inputAttributes ) const
{
const CompoundDataPlug *ap = attributesPlug();
IECore::ConstCompoundDataPtr extraAttributesData = extraAttributesPlug()->getValue();
const IECore::CompoundDataMap &extraAttributes = extraAttributesData->readable();
if( !ap->children().size() && extraAttributes.empty() )
{
return inputAttributes;
}
/// \todo You might think that we wouldn't have to check this again
/// because the base class would have used processesAttributes()
/// to avoid even calling this function. But that isn't the case for
/// some reason.
if( globalPlug()->getValue() )
{
return inputAttributes;
}
CompoundObjectPtr result = new CompoundObject;
// Since we're not going to modify any existing members (only add new ones),
// and our result becomes const on returning it, we can directly reference
// the input members in our result without copying. Be careful not to modify
// them though!
result->members() = inputAttributes->members();
ap->fillCompoundObject( result->members() );
for( IECore::CompoundDataMap::const_iterator it = extraAttributes.begin(), eIt = extraAttributes.end(); it != eIt; ++it )
{
result->members()[it->first] = it->second.get();
}
return result;
}
void Attributes::plugSet( Gaffer::Plug *plug )
{
if( plug == globalPlug() )
{
updateInternalConnections();
}
}
void Attributes::plugInputChanged( Gaffer::Plug *plug )
{
if( plug == globalPlug() )
{
updateInternalConnections();
}
}
void Attributes::updateInternalConnections()
{
// Manage internal pass-throughs based on the value of the globalPlug().
const Plug *p = globalPlug()->source<Gaffer::Plug>();
boost::tribool global;
if( p->direction() == Plug::Out && runTimeCast<const ComputeNode>( p->node() ) )
{
// Can vary from compute to compute.
global = boost::indeterminate;
}
else
{
global = globalPlug()->getValue();
}
outPlug()->globalsPlug()->setInput(
global || boost::indeterminate( global ) ? nullptr : inPlug()->globalsPlug()
);
outPlug()->attributesPlug()->setInput(
!global || boost::indeterminate( global ) ? nullptr : inPlug()->attributesPlug()
);
}
<commit_msg>Attributes : Remove bogus comment<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2012, John Haddon. All rights reserved.
// Copyright (c) 2013, 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 John Haddon 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 "GafferScene/Attributes.h"
#include "boost/bind.hpp"
#include "boost/logic/tribool.hpp"
using namespace IECore;
using namespace Gaffer;
using namespace GafferScene;
GAFFER_NODE_DEFINE_TYPE( Attributes );
size_t Attributes::g_firstPlugIndex = 0;
Attributes::Attributes( const std::string &name )
: AttributeProcessor( name, PathMatcher::EveryMatch )
{
storeIndexOfNextChild( g_firstPlugIndex );
addChild( new CompoundDataPlug( "attributes" ) );
addChild( new BoolPlug( "global", Plug::In, false ) );
addChild( new AtomicCompoundDataPlug( "extraAttributes", Plug::In, new IECore::CompoundData ) );
// Connect to signals we use to manage pass-throughs for globals
// and attributes based on the value of globalPlug().
plugSetSignal().connect( boost::bind( &Attributes::plugSet, this, ::_1 ) );
plugInputChangedSignal().connect( boost::bind( &Attributes::plugInputChanged, this, ::_1 ) );
}
Attributes::~Attributes()
{
}
Gaffer::CompoundDataPlug *Attributes::attributesPlug()
{
return getChild<Gaffer::CompoundDataPlug>( g_firstPlugIndex );
}
const Gaffer::CompoundDataPlug *Attributes::attributesPlug() const
{
return getChild<Gaffer::CompoundDataPlug>( g_firstPlugIndex );
}
Gaffer::BoolPlug *Attributes::globalPlug()
{
return getChild<Gaffer::BoolPlug>( g_firstPlugIndex + 1 );
}
const Gaffer::BoolPlug *Attributes::globalPlug() const
{
return getChild<Gaffer::BoolPlug>( g_firstPlugIndex + 1 );
}
Gaffer::AtomicCompoundDataPlug *Attributes::extraAttributesPlug()
{
return getChild<Gaffer::AtomicCompoundDataPlug>( g_firstPlugIndex + 2 );
}
const Gaffer::AtomicCompoundDataPlug *Attributes::extraAttributesPlug() const
{
return getChild<Gaffer::AtomicCompoundDataPlug>( g_firstPlugIndex + 2 );
}
void Attributes::affects( const Gaffer::Plug *input, AffectedPlugsContainer &outputs ) const
{
AttributeProcessor::affects( input, outputs );
if(
input == globalPlug() ||
input == inPlug()->globalsPlug() ||
attributesPlug()->isAncestorOf( input ) ||
input == extraAttributesPlug()
)
{
// We can only affect a particular output if we haven't
// connected it as a pass-through in updateInternalConnections().
if( !outPlug()->globalsPlug()->getInput() )
{
outputs.push_back( outPlug()->globalsPlug() );
}
}
}
void Attributes::hashGlobals( const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const
{
if( globalPlug()->getValue() )
{
// We will modify the globals.
AttributeProcessor::hashGlobals( context, parent, h );
inPlug()->globalsPlug()->hash( h );
attributesPlug()->hash( h );
extraAttributesPlug()->hash( h );
}
else
{
// We won't modify the globals - pass through the hash.
h = inPlug()->globalsPlug()->hash();
}
}
IECore::ConstCompoundObjectPtr Attributes::computeGlobals( const Gaffer::Context *context, const ScenePlug *parent ) const
{
ConstCompoundObjectPtr inputGlobals = inPlug()->globalsPlug()->getValue();
if( !globalPlug()->getValue() )
{
return inputGlobals;
}
const CompoundDataPlug *p = attributesPlug();
IECore::CompoundObjectPtr result = new CompoundObject;
// Since we're not going to modify any existing members (only add new ones),
// and our result becomes const on returning it, we can directly reference
// the input members in our result without copying. Be careful not to modify
// them though!
result->members() = inputGlobals->members();
std::string name;
for( NameValuePlugIterator it( p ); !it.done(); ++it )
{
IECore::DataPtr d = p->memberDataAndName( it->get(), name );
if( d )
{
result->members()["attribute:" + name] = d;
}
}
IECore::ConstCompoundDataPtr extraAttributesData = extraAttributesPlug()->getValue();
const IECore::CompoundDataMap &extraAttributes = extraAttributesData->readable();
for( IECore::CompoundDataMap::const_iterator it = extraAttributes.begin(), eIt = extraAttributes.end(); it != eIt; ++it )
{
result->members()["attribute:" + it->first.string()] = it->second.get();
}
return result;
}
bool Attributes::affectsProcessedAttributes( const Gaffer::Plug *input ) const
{
if( outPlug()->attributesPlug()->getInput() )
{
// We've made a pass-through connection
return false;
}
return
AttributeProcessor::affectsProcessedAttributes( input ) ||
attributesPlug()->isAncestorOf( input ) ||
input == globalPlug() ||
input == extraAttributesPlug()
;
}
void Attributes::hashProcessedAttributes( const ScenePath &path, const Gaffer::Context *context, IECore::MurmurHash &h ) const
{
if( ( attributesPlug()->children().empty() && extraAttributesPlug()->isSetToDefault() ) || globalPlug()->getValue() )
{
h = inPlug()->attributesPlug()->hash();
}
else
{
AttributeProcessor::hashProcessedAttributes( path, context, h );
attributesPlug()->hash( h );
extraAttributesPlug()->hash( h );
}
}
IECore::ConstCompoundObjectPtr Attributes::computeProcessedAttributes( const ScenePath &path, const Gaffer::Context *context, const IECore::CompoundObject *inputAttributes ) const
{
const CompoundDataPlug *ap = attributesPlug();
IECore::ConstCompoundDataPtr extraAttributesData = extraAttributesPlug()->getValue();
const IECore::CompoundDataMap &extraAttributes = extraAttributesData->readable();
if( !ap->children().size() && extraAttributes.empty() )
{
return inputAttributes;
}
if( globalPlug()->getValue() )
{
return inputAttributes;
}
CompoundObjectPtr result = new CompoundObject;
// Since we're not going to modify any existing members (only add new ones),
// and our result becomes const on returning it, we can directly reference
// the input members in our result without copying. Be careful not to modify
// them though!
result->members() = inputAttributes->members();
ap->fillCompoundObject( result->members() );
for( IECore::CompoundDataMap::const_iterator it = extraAttributes.begin(), eIt = extraAttributes.end(); it != eIt; ++it )
{
result->members()[it->first] = it->second.get();
}
return result;
}
void Attributes::plugSet( Gaffer::Plug *plug )
{
if( plug == globalPlug() )
{
updateInternalConnections();
}
}
void Attributes::plugInputChanged( Gaffer::Plug *plug )
{
if( plug == globalPlug() )
{
updateInternalConnections();
}
}
void Attributes::updateInternalConnections()
{
// Manage internal pass-throughs based on the value of the globalPlug().
const Plug *p = globalPlug()->source<Gaffer::Plug>();
boost::tribool global;
if( p->direction() == Plug::Out && runTimeCast<const ComputeNode>( p->node() ) )
{
// Can vary from compute to compute.
global = boost::indeterminate;
}
else
{
global = globalPlug()->getValue();
}
outPlug()->globalsPlug()->setInput(
global || boost::indeterminate( global ) ? nullptr : inPlug()->globalsPlug()
);
outPlug()->attributesPlug()->setInput(
!global || boost::indeterminate( global ) ? nullptr : inPlug()->attributesPlug()
);
}
<|endoftext|> |
<commit_before>#include <assert.h>
#include <math.h>
#include <vector>
#include "common_header.h"
#include "converter.h"
static std::vector<float> s_normal_temp;
static uint _get_image_stride(uint width, uint bpp) {
assert(bpp % 8 == 0);
uint byteCount = bpp / 8;
uint stride = (width * byteCount + 3) & ~3;
return stride;
}
static inline int _combine_rgb(uchar r, uchar g, uchar b) {
return ((r << 16) & 0xff0000) +
((g << 8) & 0x00ff00) +
(b & 0x0000ff);
}
static void _convert_rgb(image_data *height_img) {
uchar *pixels = height_img->pixels;
uint stride = _get_image_stride(height_img->width, 24);
for (int row = 0; row < height_img->height; row++) {
for (int col = 0; col < stride; col++) {
if (col + 3 > stride)
continue;
int i = row * stride + col;
uchar r = pixels[i];
uchar g = pixels[i + 1];
uchar b = pixels[i + 2];
int hg = _combine_rgb(r, g, b);
//above.
int ha = 0;
if (row == 0) {
ha = hg;
}
else {
i = (row - 1) * stride + col;
uchar r = pixels[i];
uchar g = pixels[i + 1];
uchar b = pixels[i + 2];
ha = _combine_rgb(r, g, b);
}
//right.
int hr = 0;
if (col + 6 > stride) {
hr = hg;
}
else {
i = row * stride + col + 1;
uchar r = pixels[i];
uchar g = pixels[i + 1];
uchar b = pixels[i + 2];
hr = _combine_rgb(r, g, b);
}
int diff_ga = hg - ha;
int diff_gr = hg - hr;
float vl = sqrt(diff_ga * diff_ga + diff_gr * diff_gr + 1);
s_normal_temp.push_back(diff_ga / vl);
s_normal_temp.push_back(diff_gr / vl);
s_normal_temp.push_back(1 / vl);
}
}
}
static void _convert_bgr(image_data *height_img) {
uchar *pixels = height_img->pixels;
uint stride = _get_image_stride(height_img->width, 24);
for (int row = 0; row < height_img->height; row++) {
for (int col = 0; col < stride; col++) {
if (col + 3 > stride)
continue;
int i = row * stride + col;
uchar b = pixels[i];
uchar g = pixels[i + 1];
uchar r = pixels[i + 2];
int hg = _combine_rgb(b, g, r);
//above.
int ha = 0;
if (row == 0) {
ha = hg;
}
else {
i = (row - 1) * stride + col;
uchar b = pixels[i];
uchar g = pixels[i + 1];
uchar r = pixels[i + 2];
ha = _combine_rgb(b, g, r);
}
//right.
int hr = 0;
if (col + 6 > stride) {
hr = hg;
}
else {
i = row * stride + col + 1;
uchar b = pixels[i];
uchar g = pixels[i + 1];
uchar r = pixels[i + 2];
hr = _combine_rgb(b, g, r);
}
int diff_ga = hg - ha;
int diff_gr = hg - hr;
float vl = sqrt(diff_ga * diff_ga + diff_gr * diff_gr + 1);
s_normal_temp.push_back(1 / vl);
s_normal_temp.push_back(diff_gr / vl);
s_normal_temp.push_back(diff_ga / vl);
}
}
}
static void _convert_rgba(image_data *height_img) {
//TODO...
}
static void _convert_bgra(image_data *height_img) {
//TODO...
}
image_data * convert(image_data *height_img) {
image_data *normal_img = new image_data();
normal_img->width = height_img->width;
normal_img->height = height_img->height;
uint stride = _get_image_stride(normal_img->width, 24);
uint size = normal_img->height * stride;
normal_img->pixels = new uchar[size];
s_normal_temp.clear();
img_gray_scale(height_img);
switch (height_img->format) {
case IMG_FORMAT_RGB:
_convert_rgb(height_img);
break;
case IMG_FORMAT_BGR:
_convert_bgr(height_img);
break;
case IMG_FORMAT_RGBA:
//TODO...
assert(false);
break;
case IMG_FORMAT_BGRA:
//TODO...
assert(false);
break;
default:
assert(false);
break;
}
uchar *pixels = normal_img->pixels;
for (int row = 0; row < normal_img->height; row++) {
for (int col = 0; col < stride; col++) {
int i = row * stride + col;
pixels[i] = (s_normal_temp[i] + 1) * 125;
pixels[i + 1] = (s_normal_temp[i + 1] + 1) * 125;
pixels[i + 2] = (s_normal_temp[i + 2] + 1) * 125;
}
}
return normal_img;
}<commit_msg>bug fixed.<commit_after>#include <assert.h>
#include <math.h>
#include <vector>
#include "common_header.h"
#include "converter.h"
static std::vector<float> s_normal_temp;
static uint _get_image_stride(uint width, uint bpp) {
assert(bpp % 8 == 0);
uint byteCount = bpp / 8;
uint stride = (width * byteCount + 3) & ~3;
return stride;
}
static inline int _combine_rgb(uchar r, uchar g, uchar b) {
return ((r << 16) & 0xff0000) +
((g << 8) & 0x00ff00) +
(b & 0x0000ff);
}
static void _convert_rgb(image_data *height_img) {
uchar *pixels = height_img->pixels;
uint stride = _get_image_stride(height_img->width, 24);
for (int row = 0; row < height_img->height; row++) {
for (int col = 0; col < stride; col+=3) {
if (col + 3 > stride)
continue;
int i = row * stride + col;
uchar r = pixels[i];
uchar g = pixels[i + 1];
uchar b = pixels[i + 2];
int hg = _combine_rgb(r, g, b);
//above.
int ha = 0;
if (row == 0) {
ha = hg;
}
else {
i = (row - 1) * stride + col;
uchar r = pixels[i];
uchar g = pixels[i + 1];
uchar b = pixels[i + 2];
ha = _combine_rgb(r, g, b);
}
//right.
int hr = 0;
if (col + 6 > stride) {
hr = hg;
}
else {
i = row * stride + col + 1;
uchar r = pixels[i];
uchar g = pixels[i + 1];
uchar b = pixels[i + 2];
hr = _combine_rgb(r, g, b);
}
int diff_ga = hg - ha;
int diff_gr = hg - hr;
float vl = sqrt(diff_ga * diff_ga + diff_gr * diff_gr + 1);
s_normal_temp.push_back(diff_ga / vl);
s_normal_temp.push_back(diff_gr / vl);
s_normal_temp.push_back(1 / vl);
}
}
}
static void _convert_bgr(image_data *height_img) {
uchar *pixels = height_img->pixels;
uint stride = _get_image_stride(height_img->width, 24);
for (int row = 0; row < height_img->height; row++) {
for (int col = 0; col < stride; col+=3) {
if (col + 3 > stride)
continue;
int i = row * stride + col;
uchar b = pixels[i];
uchar g = pixels[i + 1];
uchar r = pixels[i + 2];
int hg = _combine_rgb(b, g, r);
//above.
int ha = 0;
if (row == 0) {
ha = hg;
}
else {
i = (row - 1) * stride + col;
uchar b = pixels[i];
uchar g = pixels[i + 1];
uchar r = pixels[i + 2];
ha = _combine_rgb(b, g, r);
}
//right.
int hr = 0;
if (col + 6 > stride) {
hr = hg;
}
else {
i = row * stride + col + 1;
uchar b = pixels[i];
uchar g = pixels[i + 1];
uchar r = pixels[i + 2];
hr = _combine_rgb(b, g, r);
}
int diff_ga = hg - ha;
int diff_gr = hg - hr;
float vl = sqrt(diff_ga * diff_ga + diff_gr * diff_gr + 1);
s_normal_temp.push_back(1 / vl);
s_normal_temp.push_back(diff_gr / vl);
s_normal_temp.push_back(diff_ga / vl);
}
}
}
static void _convert_rgba(image_data *height_img) {
//TODO...
}
static void _convert_bgra(image_data *height_img) {
//TODO...
}
image_data * convert(image_data *height_img) {
image_data *normal_img = new image_data();
normal_img->width = height_img->width;
normal_img->height = height_img->height;
uint stride = _get_image_stride(normal_img->width, 24);
uint size = normal_img->height * stride;
normal_img->pixels = new uchar[size];
s_normal_temp.clear();
img_gray_scale(height_img);
switch (height_img->format) {
case IMG_FORMAT_RGB:
_convert_rgb(height_img);
break;
case IMG_FORMAT_BGR:
_convert_bgr(height_img);
break;
case IMG_FORMAT_RGBA:
//TODO...
assert(false);
break;
case IMG_FORMAT_BGRA:
//TODO...
assert(false);
break;
default:
assert(false);
break;
}
uchar *pixels = normal_img->pixels;
for (int row = 0; row < normal_img->height; row++) {
for (int col = 0; col < stride; col+=3) {
if (col + 3 > stride)
continue;
int i = row * stride + col;
pixels[i] = (s_normal_temp[i] + 1) * 127;
pixels[i + 1] = (s_normal_temp[i + 1] + 1) * 127;
pixels[i + 2] = (s_normal_temp[i + 2] + 1) * 127;
}
}
return normal_img;
}<|endoftext|> |
<commit_before>#include "xml_doc.hpp"
#include "xml_parser_ctxt.hpp"
#include <string>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <utility>
#include <libxml/parser.h>
// #include "bilanz.hpp"
static auto loadXml( std::istream &is, XmlErrorHandler &handler )
-> std::shared_ptr<xmlDoc>;
typedef enum { NON_RECURSIVE = 0, RECURSIVE = 1 } XmlCopy;
typedef enum { KEEP_BLANKS = 0, INDENT = 1 } XmlFormat;
XmlDoc::XmlDoc( ) : xmlDoc_{nullptr} {}
XmlDoc::XmlDoc( std::istream &is ) : xmlDoc_{nullptr} {
xmlDoc_ = loadXml( is, xmlHandler_ );
}
// XmlDoc::XmlDoc( xmlDocPtr xml ) : xmlDoc_{xml} {
// pathname_ = ( xml->name ) ? Pathname{std::string{xml->name}} : Pathname{};
// }
XmlDoc::XmlDoc( const XmlDoc &doc )
: xmlDoc_{doc.xmlDoc_} {}
XmlDoc::XmlDoc( XmlDoc &&doc )
: xmlDoc_{std::move( doc.xmlDoc_ )}, xmlHandler_{std::move( doc.xmlHandler_ )} {}
auto XmlDoc::operator=( const XmlDoc &rhs ) -> XmlDoc & {
if ( this != &rhs ) {
xmlDoc_ = rhs.xmlDoc_;
}
return *this;
}
auto XmlDoc::operator=( XmlDoc &&rhs ) -> XmlDoc & {
xmlDoc_ = std::move( rhs.xmlDoc_ );
xmlHandler_ = std::move( rhs.xmlHandler_ );
return *this;
}
XmlDoc::operator bool( ) const { return ( xmlDoc_.get( ) != nullptr ); }
auto XmlDoc::swap( XmlDoc &other ) -> void { std::swap( xmlDoc_, other.xmlDoc_ ); }
auto XmlDoc::toString( ) const -> std::string {
if ( xmlDoc_ ) {
xmlChar *buff;
int size;
xmlDocDumpFormatMemory( xmlDoc_.get( ), &buff, &size, INDENT );
std::string strbuff{( char * )buff, static_cast<size_t>( size )};
xmlFree( buff ); // free buff
return strbuff;
}
return std::string{};
}
static auto loadXml( std::istream &is, XmlErrorHandler &handler )
-> std::shared_ptr<xmlDoc> {
std::istreambuf_iterator<char> eos;
std::string fbuff{std::istreambuf_iterator<char>{is}, eos};
handler.registerHandler( );
XmlParserCtxt parser;
return std::shared_ptr<xmlDoc>{
xmlCtxtReadMemory( parser.get( ), fbuff.data( ), fbuff.size( ), NULL, NULL,
XML_PARSE_NONET | XML_PARSE_NOWARNING ),
FreeXmlDoc( )};
}
auto operator>>( std::istream &is, XmlDoc &doc ) -> std::istream & {
doc.xmlDoc_ = loadXml( is, doc.xmlHandler_ );
return is;
}
auto fileToString( const std::string &path ) -> std::string {
std::ifstream in;
in.exceptions( std::ifstream::failbit | std::ifstream::badbit );
in.open( path.data( ), std::ios::in | std::ios::binary );
std::ostringstream contents;
contents << in.rdbuf( );
in.close( );
return contents.str( );
}
template <>
void std::swap( XmlDoc &lhs, XmlDoc &rhs ) {
lhs.swap( rhs );
}
<commit_msg>XmlDoc#toString uses XmlString<commit_after>#include "xml_doc.hpp"
#include "xml_parser_ctxt.hpp"
#include "xml_string.hpp"
#include <string>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <utility>
#include <libxml/parser.h>
// #include "bilanz.hpp"
static auto loadXml( std::istream &is, XmlErrorHandler &handler )
-> std::shared_ptr<xmlDoc>;
typedef enum { NON_RECURSIVE = 0, RECURSIVE = 1 } XmlCopy;
typedef enum { KEEP_BLANKS = 0, INDENT = 1 } XmlFormat;
XmlDoc::XmlDoc( ) : xmlDoc_{nullptr} {}
XmlDoc::XmlDoc( std::istream &is ) : xmlDoc_{nullptr} {
xmlDoc_ = loadXml( is, xmlHandler_ );
}
// XmlDoc::XmlDoc( xmlDocPtr xml ) : xmlDoc_{xml} {
// pathname_ = ( xml->name ) ? Pathname{std::string{xml->name}} : Pathname{};
// }
XmlDoc::XmlDoc( const XmlDoc &doc ) : xmlDoc_{doc.xmlDoc_} {}
XmlDoc::XmlDoc( XmlDoc &&doc )
: xmlDoc_{std::move( doc.xmlDoc_ )}, xmlHandler_{std::move( doc.xmlHandler_ )} {}
auto XmlDoc::operator=( const XmlDoc &rhs ) -> XmlDoc & {
if ( this != &rhs ) {
xmlDoc_ = rhs.xmlDoc_;
}
return *this;
}
auto XmlDoc::operator=( XmlDoc &&rhs ) -> XmlDoc & {
xmlDoc_ = std::move( rhs.xmlDoc_ );
xmlHandler_ = std::move( rhs.xmlHandler_ );
return *this;
}
XmlDoc::operator bool( ) const { return ( xmlDoc_.get( ) != nullptr ); }
auto XmlDoc::swap( XmlDoc &other ) -> void { std::swap( xmlDoc_, other.xmlDoc_ ); }
auto XmlDoc::toString( ) const -> std::string {
if ( xmlDoc_ ) {
xmlChar *buff;
int size;
xmlDocDumpFormatMemory( xmlDoc_.get( ), &buff, &size, INDENT );
XmlString str{buff};
return str.toString( );
}
return std::string{};
}
static auto loadXml( std::istream &is, XmlErrorHandler &handler )
-> std::shared_ptr<xmlDoc> {
std::istreambuf_iterator<char> eos;
std::string fbuff{std::istreambuf_iterator<char>{is}, eos};
handler.registerHandler( );
XmlParserCtxt parser;
return std::shared_ptr<xmlDoc>{
xmlCtxtReadMemory( parser.get( ), fbuff.data( ), fbuff.size( ), NULL, NULL,
XML_PARSE_NONET | XML_PARSE_NOWARNING ),
FreeXmlDoc( )};
}
auto operator>>( std::istream &is, XmlDoc &doc ) -> std::istream & {
doc.xmlDoc_ = loadXml( is, doc.xmlHandler_ );
return is;
}
auto fileToString( const std::string &path ) -> std::string {
std::ifstream in;
in.exceptions( std::ifstream::failbit | std::ifstream::badbit );
in.open( path.data( ), std::ios::in | std::ios::binary );
std::ostringstream contents;
contents << in.rdbuf( );
in.close( );
return contents.str( );
}
template <>
void std::swap( XmlDoc &lhs, XmlDoc &rhs ) {
lhs.swap( rhs );
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include <QmitkColorPropertyEditor.h>
#include <qlayout.h>
#include <qpainter.h>
#include <qapplication.h>
//----- QmitkPopupColorChooser ---------------------------------------------------------
QmitkPopupColorChooser::QmitkPopupColorChooser(QWidget* parent, unsigned int steps, unsigned int size, const char* name)
: QFrame (parent, name, WStyle_StaysOnTop | WStyle_Customize | WStyle_NoBorder | WStyle_Tool | WX11BypassWM),
my_parent(parent)
{
setSteps(steps);
setLineWidth(2);
setMouseTracking ( TRUE );
setMargin(0);
setAutoMask( FALSE );
setFrameStyle ( QFrame::Panel | QFrame::Raised );
setLineWidth( 1 );
polish();
resize(size, size);
hide();
}
QmitkPopupColorChooser::~QmitkPopupColorChooser()
{
}
void QmitkPopupColorChooser::setSteps(int steps)
{
m_Steps = steps;
m_Steps2 = m_Steps / 2;
m_HStep = 360 / m_Steps;
m_SStep = 512 / m_Steps;
m_VStep = 512 / m_Steps;
}
void QmitkPopupColorChooser::keyReleaseEvent(QKeyEvent*)
{
emit colorSelected( m_OriginalColor );
close();
}
void QmitkPopupColorChooser::mouseMoveEvent (QMouseEvent* e)
{
double x(e->pos().x());
double y(e->pos().y());
x /= width();
if ( x >= 0.0 )
{
//x = (int)(x / (1.0/m_Steps)) * (1.0/m_Steps); // div stepsize * stepsize
x = (int)(x * (float)(m_Steps-1)) / (float)(m_Steps-1); // same as above
if (x > 1.0) x = 1.0;
if (x < 0.0) x = 0.0;
}
y /= height();
if (y >= 1.0) y = 0.9;
if (y < 0.0) y = 0.0;
y = (int)(y * (float)m_Steps) / (float)m_Steps;
m_H = static_cast<int>( y * 359.0 );
if ( x >= 0.5 )
{
m_S = static_cast<int>( (1.0 - x) * 511.0 );
if ( m_S > 255 ) m_S = 255;
m_V = 255;
}
else
{
m_S = 255;
if ( x < 0.0 )
m_V = 0;
else
{
m_V = static_cast<int>( x * 511.0 + 511.0 / (float)(m_Steps-1) );
if ( m_V > 255 ) m_V = 255;
}
}
QColor color;
color.setHsv(m_H, m_S, m_V);
emit colorSelected( color );
}
void QmitkPopupColorChooser::mouseReleaseEvent (QMouseEvent*)
{
close ();
}
void QmitkPopupColorChooser::closeEvent (QCloseEvent*e)
{
e->accept ();
releaseKeyboard();
releaseMouse();
if (!m_popupParent) return;
// remember that we (as a popup) might recieve the mouse release
// event instead of the popupParent. This is due to the fact that
// the popupParent popped us up in its mousePressEvent handler. To
// avoid the button remaining in pressed state we simply send a
// faked mouse button release event to it.
// Maleike: parent should not pop us on MouseRelease!
QMouseEvent me( QEvent::MouseButtonRelease, QPoint(0,0), QPoint(0,0), QMouseEvent::LeftButton, QMouseEvent::NoButton);
QApplication::sendEvent ( m_popupParent, &me );
}
void QmitkPopupColorChooser::popup(QWidget* parent, const QPoint& point, const mitk::Color* color)
{
m_popupParent = parent;
if (m_popupParent)
{
QPoint newPos;
if (color)
{
QColor qcolor( (int)((*color)[0] * 255.0) , (int)((*color)[1] * 255.0) , (int)((*color)[2] * 255.0) );
int h,s,v;
qcolor.getHsv(&h, &s, &v);
if ( h == -1 ) // set by Qt if color is achromatic ( but this widget does not display grays )
h = 10; // red
int x, y;
float cellwidth = (float)width() / (float)(m_Steps);
if ( s > v ) // restrict to the colors we can display
{ // left side, ramp from v = 255/m_Steps to v = 255
s = 255;
x = (int)(
(
((float)v / 255.0)
*
((float)m_Steps2)
-
1.0
)
*
cellwidth
+ cellwidth/2
);
}
else
{
v = 255;
x = (int)(
(
(1.0 - ((float)s / 255.0))
*
((float)m_Steps2)
)
*
cellwidth
+ cellwidth/2
+ width() / 2
);
}
y = (int)( (float)h/360.0 * (float)m_Steps * cellwidth );
m_OriginalColor.setHsv(h,s,v);
// move to color
newPos.setX( point.x() - x );
newPos.setY( point.y() - y );
}
else
{
// center widget
m_OriginalColor.setHsv(-1, 0, 0);
newPos.setX( point.x() - width() / 2 );
newPos.setY( point.y() - height() / 2 );
}
move ( m_popupParent->mapToGlobal( newPos ) );
}
show();
raise();
grabMouse();
grabKeyboard();
}
void QmitkPopupColorChooser::paintEvent(QPaintEvent*)
{
QPainter painter(this);
drawGradient( &painter );
}
void QmitkPopupColorChooser::drawGradient( QPainter* p)
{
p->setWindow( 0, 0, m_Steps-1, m_Steps ); // defines coordinate system
p->setPen( Qt::NoPen );
QColor c;
for ( unsigned int h = 0; h < m_Steps; ++h )
{
for ( unsigned int v = 1; v < m_Steps2; ++v )
{
c.setHsv( h*m_HStep, 255, v*m_VStep ); // rainbow effect
p->setBrush( c ); // solid fill with color c
p->drawRect( v-1, h, m_Steps2, m_Steps ); // draw the rectangle
}
for ( unsigned int s = 0; s < m_Steps2; ++s )
{
c.setHsv( h*m_HStep, 255 - s*m_SStep, 255 ); // rainbow effect
p->setBrush( c ); // solid fill with color c
p->drawRect( m_Steps2+s-1, h, m_Steps2, m_Steps ); // draw the rectangle
}
}
}
//----- QmitkColorPropertyEditor --------------------------------------------------
// initialization of static pointer to color picker widget
QmitkPopupColorChooser* QmitkColorPropertyEditor::colorChooser = NULL;
int QmitkColorPropertyEditor::colorChooserRefCount = 0;
QmitkColorPropertyEditor::QmitkColorPropertyEditor( const mitk::ColorProperty* property, QWidget* parent, const char* name )
: QmitkColorPropertyView( property, parent, name )
{
// our popup belongs to the whole screen, so it could be drawn outside the toplevel window's borders
int scr;
if ( QApplication::desktop()->isVirtualDesktop() )
scr = QApplication::desktop()->screenNumber( parent->mapToGlobal( pos() ) );
else
scr = QApplication::desktop()->screenNumber( parent );
if ( colorChooserRefCount == 0 )
{
colorChooser = new QmitkPopupColorChooser( QApplication::desktop()->screen( scr ), 50 );
}
++colorChooserRefCount;
}
QmitkColorPropertyEditor::~QmitkColorPropertyEditor()
{
--colorChooserRefCount;
if (!colorChooserRefCount)
{
delete colorChooser;
colorChooser = NULL;
}
}
void QmitkColorPropertyEditor::mousePressEvent(QMouseEvent* e)
{
connect( colorChooser, SIGNAL(colorSelected(QColor)), this, SLOT(onColorSelected(QColor)) );
if (m_ColorProperty)
{
colorChooser->popup( this, e->pos(), &(m_ColorProperty->GetColor()) );
}
}
void QmitkColorPropertyEditor::mouseReleaseEvent(QMouseEvent*)
{
disconnect( colorChooser, SIGNAL(colorSelected(QColor)), this, SLOT(onColorSelected(QColor)) );
}
void QmitkColorPropertyEditor::onColorSelected(QColor c)
{
if (m_ColorProperty)
{
int r,g,b;
c.getRgb( &r, &g, &b );
const_cast<mitk::ColorProperty*>(m_ColorProperty)->SetColor( r / 255.0, g / 255.0, b / 255.0 );
const_cast<mitk::ColorProperty*>(m_ColorProperty)->Modified();
}
}
<commit_msg>update rendering after color change<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include <QmitkColorPropertyEditor.h>
#include <qlayout.h>
#include <qpainter.h>
#include <qapplication.h>
#include <mitkRenderingManager.h>
//----- QmitkPopupColorChooser ---------------------------------------------------------
QmitkPopupColorChooser::QmitkPopupColorChooser(QWidget* parent, unsigned int steps, unsigned int size, const char* name)
: QFrame (parent, name, WStyle_StaysOnTop | WStyle_Customize | WStyle_NoBorder | WStyle_Tool | WX11BypassWM),
my_parent(parent)
{
setSteps(steps);
setLineWidth(2);
setMouseTracking ( TRUE );
setMargin(0);
setAutoMask( FALSE );
setFrameStyle ( QFrame::Panel | QFrame::Raised );
setLineWidth( 1 );
polish();
resize(size, size);
hide();
}
QmitkPopupColorChooser::~QmitkPopupColorChooser()
{
}
void QmitkPopupColorChooser::setSteps(int steps)
{
m_Steps = steps;
m_Steps2 = m_Steps / 2;
m_HStep = 360 / m_Steps;
m_SStep = 512 / m_Steps;
m_VStep = 512 / m_Steps;
}
void QmitkPopupColorChooser::keyReleaseEvent(QKeyEvent*)
{
emit colorSelected( m_OriginalColor );
close();
}
void QmitkPopupColorChooser::mouseMoveEvent (QMouseEvent* e)
{
double x(e->pos().x());
double y(e->pos().y());
x /= width();
if ( x >= 0.0 )
{
//x = (int)(x / (1.0/m_Steps)) * (1.0/m_Steps); // div stepsize * stepsize
x = (int)(x * (float)(m_Steps-1)) / (float)(m_Steps-1); // same as above
if (x > 1.0) x = 1.0;
if (x < 0.0) x = 0.0;
}
y /= height();
if (y >= 1.0) y = 0.9;
if (y < 0.0) y = 0.0;
y = (int)(y * (float)m_Steps) / (float)m_Steps;
m_H = static_cast<int>( y * 359.0 );
if ( x >= 0.5 )
{
m_S = static_cast<int>( (1.0 - x) * 511.0 );
if ( m_S > 255 ) m_S = 255;
m_V = 255;
}
else
{
m_S = 255;
if ( x < 0.0 )
m_V = 0;
else
{
m_V = static_cast<int>( x * 511.0 + 511.0 / (float)(m_Steps-1) );
if ( m_V > 255 ) m_V = 255;
}
}
QColor color;
color.setHsv(m_H, m_S, m_V);
emit colorSelected( color );
}
void QmitkPopupColorChooser::mouseReleaseEvent (QMouseEvent*)
{
close ();
}
void QmitkPopupColorChooser::closeEvent (QCloseEvent*e)
{
e->accept ();
releaseKeyboard();
releaseMouse();
if (!m_popupParent) return;
// remember that we (as a popup) might recieve the mouse release
// event instead of the popupParent. This is due to the fact that
// the popupParent popped us up in its mousePressEvent handler. To
// avoid the button remaining in pressed state we simply send a
// faked mouse button release event to it.
// Maleike: parent should not pop us on MouseRelease!
QMouseEvent me( QEvent::MouseButtonRelease, QPoint(0,0), QPoint(0,0), QMouseEvent::LeftButton, QMouseEvent::NoButton);
QApplication::sendEvent ( m_popupParent, &me );
}
void QmitkPopupColorChooser::popup(QWidget* parent, const QPoint& point, const mitk::Color* color)
{
m_popupParent = parent;
if (m_popupParent)
{
QPoint newPos;
if (color)
{
QColor qcolor( (int)((*color)[0] * 255.0) , (int)((*color)[1] * 255.0) , (int)((*color)[2] * 255.0) );
int h,s,v;
qcolor.getHsv(&h, &s, &v);
if ( h == -1 ) // set by Qt if color is achromatic ( but this widget does not display grays )
h = 10; // red
int x, y;
float cellwidth = (float)width() / (float)(m_Steps);
if ( s > v ) // restrict to the colors we can display
{ // left side, ramp from v = 255/m_Steps to v = 255
s = 255;
x = (int)(
(
((float)v / 255.0)
*
((float)m_Steps2)
-
1.0
)
*
cellwidth
+ cellwidth/2
);
}
else
{
v = 255;
x = (int)(
(
(1.0 - ((float)s / 255.0))
*
((float)m_Steps2)
)
*
cellwidth
+ cellwidth/2
+ width() / 2
);
}
y = (int)( (float)h/360.0 * (float)m_Steps * cellwidth );
m_OriginalColor.setHsv(h,s,v);
// move to color
newPos.setX( point.x() - x );
newPos.setY( point.y() - y );
}
else
{
// center widget
m_OriginalColor.setHsv(-1, 0, 0);
newPos.setX( point.x() - width() / 2 );
newPos.setY( point.y() - height() / 2 );
}
move ( m_popupParent->mapToGlobal( newPos ) );
}
show();
raise();
grabMouse();
grabKeyboard();
}
void QmitkPopupColorChooser::paintEvent(QPaintEvent*)
{
QPainter painter(this);
drawGradient( &painter );
}
void QmitkPopupColorChooser::drawGradient( QPainter* p)
{
p->setWindow( 0, 0, m_Steps-1, m_Steps ); // defines coordinate system
p->setPen( Qt::NoPen );
QColor c;
for ( unsigned int h = 0; h < m_Steps; ++h )
{
for ( unsigned int v = 1; v < m_Steps2; ++v )
{
c.setHsv( h*m_HStep, 255, v*m_VStep ); // rainbow effect
p->setBrush( c ); // solid fill with color c
p->drawRect( v-1, h, m_Steps2, m_Steps ); // draw the rectangle
}
for ( unsigned int s = 0; s < m_Steps2; ++s )
{
c.setHsv( h*m_HStep, 255 - s*m_SStep, 255 ); // rainbow effect
p->setBrush( c ); // solid fill with color c
p->drawRect( m_Steps2+s-1, h, m_Steps2, m_Steps ); // draw the rectangle
}
}
}
//----- QmitkColorPropertyEditor --------------------------------------------------
// initialization of static pointer to color picker widget
QmitkPopupColorChooser* QmitkColorPropertyEditor::colorChooser = NULL;
int QmitkColorPropertyEditor::colorChooserRefCount = 0;
QmitkColorPropertyEditor::QmitkColorPropertyEditor( const mitk::ColorProperty* property, QWidget* parent, const char* name )
: QmitkColorPropertyView( property, parent, name )
{
// our popup belongs to the whole screen, so it could be drawn outside the toplevel window's borders
int scr;
if ( QApplication::desktop()->isVirtualDesktop() )
scr = QApplication::desktop()->screenNumber( parent->mapToGlobal( pos() ) );
else
scr = QApplication::desktop()->screenNumber( parent );
if ( colorChooserRefCount == 0 )
{
colorChooser = new QmitkPopupColorChooser( QApplication::desktop()->screen( scr ), 50 );
}
++colorChooserRefCount;
}
QmitkColorPropertyEditor::~QmitkColorPropertyEditor()
{
--colorChooserRefCount;
if (!colorChooserRefCount)
{
delete colorChooser;
colorChooser = NULL;
}
}
void QmitkColorPropertyEditor::mousePressEvent(QMouseEvent* e)
{
connect( colorChooser, SIGNAL(colorSelected(QColor)), this, SLOT(onColorSelected(QColor)) );
if (m_ColorProperty)
{
colorChooser->popup( this, e->pos(), &(m_ColorProperty->GetColor()) );
}
}
void QmitkColorPropertyEditor::mouseReleaseEvent(QMouseEvent*)
{
disconnect( colorChooser, SIGNAL(colorSelected(QColor)), this, SLOT(onColorSelected(QColor)) );
}
void QmitkColorPropertyEditor::onColorSelected(QColor c)
{
if (m_ColorProperty)
{
int r,g,b;
c.getRgb( &r, &g, &b );
const_cast<mitk::ColorProperty*>(m_ColorProperty)->SetColor( r / 255.0, g / 255.0, b / 255.0 );
const_cast<mitk::ColorProperty*>(m_ColorProperty)->Modified();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
}
<|endoftext|> |
<commit_before>#ifndef COM_MASAERS_POLYSET_HPP
#define COM_MASAERS_POLYSET_HPP
#include "pointer_union.hpp"
#include <utility>
#include <set>
namespace com_masaers {
template<typename...>
class polyset;
template<>
class polyset<> {
protected:
template<typename T> const void* do_find(const T& value) const {
static_assert(std::is_same<T, void>::value, "Cannot find unsupported type in a polyset.");
return NULL;
}
template<typename T> std::pair<const void*, bool> do_insert(const T& value) {
static_assert(std::is_same<T, void>::value, "Cannot insert unsupported type into a polyset.");
return std::pair<const void*, bool>(NULL, false);
}
public:
template<typename T> void erase(T&& value) {
static_assert(std::is_same<T, void>::value, "Cannot erase unsupported type in a polyset.");
}
bool empty() const { return true; }
std::size_t size() const { return 0; }
void clear() {}
}; // polyset base case
template<typename Value, typename... Values>
class polyset<Value, Values...> : public polyset<Values...> {
protected:
typedef polyset<Values...> base_type;
typedef std::set<Value> store_type;
typedef ptrunion<typename std::add_const<Value>::type, typename std::add_const<Values>::type...> ptr_type;
store_type store_m;
const void* do_find(const Value& value) const {
const void* result = NULL;
auto it = store_m.find(value);
if (it != store_m.end()) {
result = static_cast<const void*>(&*it);
}
return result;
}
template<typename T> const void* do_find(const T& value) const {
return base_type::do_find(value);
}
std::pair<typename store_type::iterator, bool> do_insert(const Value& value) {
return store_m.insert(value);
}
template<typename T> auto do_insert(const T& value) -> decltype(base_type::do_insert(value)) {
return base_type::do_insert(value);
}
public:
template<typename T> ptr_type find(const T& value) const {
return ptr_type(static_cast<const typename std::decay<T>::type*>(do_find(value)));
}
template<typename T> std::pair<ptr_type, bool> insert(const T& value) {
auto p = do_insert(value);
return std::pair<ptr_type, bool>(static_cast<const typename std::decay<T>::type*>(&*p.first), p.second);
}
decltype(std::declval<store_type>().erase(std::declval<const Value&>()))
erase(const Value& value) {
return store_m.erase(value);
}
template<typename T> auto erase(const T& value) -> decltype(base_type::erase(value)) {
return base_type::erase(value);
}
bool empty() const { return store_m.empty() && base_type::empty(); }
std::size_t size() const { return store_m.size() + base_type::size(); }
void clear() { store_m.clear(); base_type::clear(); }
}; // polyset inductive case
} // namespace com_masaers
#endif
<commit_msg>Fixed do_find.<commit_after>#ifndef COM_MASAERS_POLYSET_HPP
#define COM_MASAERS_POLYSET_HPP
#include "pointer_union.hpp"
#include <utility>
#include <set>
namespace com_masaers {
template<typename...>
class polyset;
template<>
class polyset<> {
protected:
template<typename T> const void* do_find(const T& value) const {
static_assert(std::is_same<T, void>::value, "Cannot find unsupported type in a polyset.");
return NULL;
}
template<typename T> std::pair<const void*, bool> do_insert(const T& value) {
static_assert(std::is_same<T, void>::value, "Cannot insert unsupported type into a polyset.");
return std::pair<const void*, bool>(NULL, false);
}
public:
template<typename T> void erase(T&& value) {
static_assert(std::is_same<T, void>::value, "Cannot erase unsupported type from a polyset.");
}
bool empty() const { return true; }
std::size_t size() const { return 0; }
void clear() {}
}; // polyset base case
template<typename Value, typename... Values>
class polyset<Value, Values...> : public polyset<Values...> {
protected:
typedef polyset<Values...> base_type;
typedef std::set<Value> store_type;
typedef ptrunion<typename std::add_const<Value>::type, typename std::add_const<Values>::type...> ptr_type;
store_type store_m;
const void* do_find(const Value& value) const {
const void* result = NULL;
auto it = store_m.find(value);
if (it != store_m.end()) {
result = static_cast<const void*>(&*it);
}
return result;
}
template<typename T> auto do_find(const T& value) const -> decltype(base_type::do_find(value)) {
return base_type::do_find(value);
}
std::pair<typename store_type::iterator, bool> do_insert(const Value& value) {
return store_m.insert(value);
}
template<typename T> auto do_insert(const T& value) -> decltype(base_type::do_insert(value)) {
return base_type::do_insert(value);
}
public:
template<typename T> ptr_type find(const T& value) const {
return ptr_type(static_cast<const typename std::decay<T>::type*>(do_find(value)));
}
template<typename T> std::pair<ptr_type, bool> insert(const T& value) {
auto p = do_insert(value);
return std::pair<ptr_type, bool>(static_cast<const typename std::decay<T>::type*>(&*p.first), p.second);
}
decltype(std::declval<store_type>().erase(std::declval<const Value&>()))
erase(const Value& value) {
return store_m.erase(value);
}
template<typename T> auto erase(const T& value) -> decltype(base_type::erase(value)) {
return base_type::erase(value);
}
bool empty() const { return store_m.empty() && base_type::empty(); }
std::size_t size() const { return store_m.size() + base_type::size(); }
void clear() { store_m.clear(); base_type::clear(); }
}; // polyset inductive case
} // namespace com_masaers
#endif
<|endoftext|> |
<commit_before>#include "z80.h"
#include <cassert>
z80::z80() {
reset();
}
void z80::cycle() {
pc += 1;
int op = mmu.readbyte(pc.getfull());
call(op);
if (!setticks) assert(false && "No ticks added! (incorrect or no instruction)");
setticks = false;
}
void z80::reset() {
clock_m = 0;
clock_t = 0;
setticks = false;
iff = false;
af.reset();
bc.reset();
de.reset();
hl.reset();
pc.reset();
sp.reset();
alu.setflagregister(&af);
}
quint8 z80::getbyteregisterval(int code) {
switch (code) {
case 7: return af.gethi();
case 0: return bc.gethi();
case 1: return bc.getlo();
case 2: return de.gethi();
case 3: return de.getlo();
case 4: return hl.gethi();
case 5: return hl.getlo();
}
return 0;
}
void z80::setbyteregisterval(int code, quint8 val) {
switch (code) {
case 7: af.sethi(val); break;
case 0: bc.sethi(val); break;
case 1: bc.setlo(val); break;
case 2: de.sethi(val); break;
case 3: de.setlo(val); break;
case 4: hl.sethi(val); break;
case 5: hl.setlo(val); break;
}
}
quint16 z80::getwordregisterval(int code, bool lastsp) {
switch (code) {
case 0: return bc.getfull();
case 1: return de.getfull();
case 2: return hl.getfull();
case 3: return (lastsp) ? sp.getfull() : af.getfull();
}
return 0;
}
void z80::setwordregisterval(int code, bool lastsp, quint16 val) {
switch (code) {
case 0: bc.setfull(val); break;
case 1: de.setfull(val); break;
case 2: hl.setfull(val); break;
case 3: if (lastsp) sp.setfull(val); else af.setfull(val); break;
}
}
quint8 z80::getbytearg() {
quint8 retval = mmu.readbyte(pc.getfull());
pc += 1;
return retval;
}
quint16 z80::getwordarg() {
quint16 retval;
retval = mmu.readbyte(pc.getfull()) << 8;
pc += 1;
retval |= mmu.readbyte(pc.getfull());
pc += 1;
return retval;
}
void z80::addticks(int m, int t) {
clock_m += m;
clock_t += t;
setticks = true;
}
void z80::call(quint8 opcode) {
int hi2 = opcode >> 6;
int mid3 = (opcode >> 3) & 7;
int low3 = opcode & 7;
int mid2 = (opcode >> 4) & 3;
int low4 = opcode & 15;
switch (hi2) {
case 0:
switch (low3) {
case 0:
if (mid3 == 0) op_nop();
break;
case 1:
if ((mid3 & 1) == 0) op_ld_dd_nn(mid2); break;
case 2:
op_ld_ahl_nn(mid3); break;
case 4:
op_inc_r(mid3); break;
case 5:
op_dec_r(mid3); break;
case 6:
op_ld_r_n(mid3); break;
case 7:
switch (mid3) {
case 5:
op_cpl(); break;
case 6:
op_scf(); break;
case 7:
op_ccf(); break;
}
break;
}
break;
case 1:
if (mid3 == 6 && low3 == 6) op_halt();
else op_ld_r_r(mid3, low3);
break;
case 2:
switch (mid3) {
case 0:
op_add_r(low3, false); break;
case 1:
op_add_r(low3, true); break;
case 2:
op_sub_r(low3, false); break;
case 3:
op_sub_r(low3, true); break;
case 4:
op_and_r(low3); break;
case 5:
op_xor_r(low3); break;
case 6:
op_or_r(low3); break;
case 7:
op_cp_r(low3); break;
}
break;
case 3:
switch (low3) {
case 1:
if ((mid3 & 1) == 0) op_pop_qq(mid2);
break;
case 5:
if ((mid3 & 1) == 0) op_push_qq(mid2);
break;
case 6:
switch (mid3) {
case 0:
op_add_n(false); break;
case 1:
op_add_n(true); break;
case 2:
op_sub_n(false); break;
case 3:
op_sub_n(true); break;
case 4:
op_and_n(); break;
case 5:
op_xor_n(); break;
case 6:
op_or_n(); break;
case 7:
op_cp_n(); break;
}
break;
}
if (opcode == 0xF9) op_ld_sp_hl(); // 11 11 1001
break;
}
return;
}
void z80::op_nop() {
addticks(1, 4);
}
void z80::op_ld_r_r(int arg1, int arg2) {
if (arg1 == 6) {
// (HL) <- r
mmu.writebyte(hl.getfull(), getbyteregisterval(arg2));
addticks(2, 7);
} else if (arg2 == 6) {
// r <- (HL)
setbyteregisterval(arg1, mmu.readbyte(hl.getfull()));
addticks(2, 7);
} else {
// r <- r'
setbyteregisterval(arg1, getbyteregisterval(arg2));
addticks(1, 4);
}
}
void z80::op_ld_r_n(int arg) {
quint8 n = getbytearg();
if (arg == 6) {
// (HL) <- n;
mmu.writebyte(hl.getfull(), n);
addticks(3, 10);
} else {
// r <- n
setbyteregisterval(arg, n);
addticks(2, 7);
}
}
void z80::op_ld_ahl_nn(int arg) {
quint16 addr;
if (arg == 4 || arg == 5) {
addr = getwordarg();
if (arg == 5) {
hl.setfull(mmu.readword(addr));
// TODO: make sure readword works like this:
//r.l = mmu.readbyte(addr);
//r.h = mmu.readbyte(addr + 1);
} else {
mmu.writeword(addr, hl.getfull());
// TODO: make sure writeword works like this:
//mmu.writebyte(addr + 1, r.h);
//mmu.writebyte(addr, r.l);
}
addticks(5, 16);
} else {
switch (arg >> 1) {
case 0:
addr = bc.getfull();
addticks(2, 7);
break;
case 1:
addr = de.getfull();
addticks(2, 7);
break;
case 3:
addr = getwordarg();
addticks(4, 13);
break;
}
if (arg && 1) {
af.sethi(mmu.readbyte(addr));
} else {
mmu.writebyte(addr, af.gethi());
}
}
}
void z80::op_ld_dd_nn(int arg) {
quint16 nn = getwordarg();
setwordregisterval(arg, true, nn);
addticks(3, 10);
}
void z80::op_ld_sp_hl() {
sp.setfull(hl.getfull());
addticks(1, 6);
}
void z80::op_push_qq(int arg) {
sp -= 2;
mmu.writebyte(sp.getfull(), getwordregisterval(arg, false));
addticks(3, 11);
}
void z80::op_pop_qq(int arg) {
setwordregisterval(arg, false, mmu.readbyte(sp.getfull()));
sp += 2;
addticks(3, 10);
}
void z80::op_add_r(int arg, bool withcarry) {
if (arg == 6) {
alu.add(mmu.readbyte(hl.getfull()), withcarry);
addticks(2, 7);
} else {
alu.add(getbyteregisterval(arg), withcarry);
addticks(1, 4);
}
}
void z80::op_add_n(bool withcarry) {
alu.add(getbytearg(), withcarry);
addticks(2, 7);
}
void z80::op_sub_r(int arg, bool withcarry) {
if (arg == 6) {
alu.sub(mmu.readbyte(hl.getfull()), withcarry);
addticks(2, 7);
} else {
alu.sub(getbyteregisterval(arg), withcarry);
addticks(1, 4);
}
}
void z80::op_sub_n(bool withcarry) {
alu.sub(getbytearg(), withcarry);
addticks(2, 7);
}
void z80::op_and_r(int arg) {
if (arg == 6) {
alu.land(mmu.readbyte(hl.getfull()));
addticks(2, 7);
} else {
alu.land(getbyteregisterval(arg));
addticks(1, 4);
}
}
void z80::op_and_n() {
alu.land(getbytearg());
addticks(2, 7);
}
void z80::op_or_r(int arg) {
if (arg == 6) {
alu.lor(mmu.readbyte(hl.getfull()));
addticks(2, 7);
} else {
alu.lor(getbyteregisterval(arg));
addticks(1, 4);
}
}
void z80::op_or_n() {
alu.lor(getbytearg());
addticks(2, 7);
}
void z80::op_xor_r(int arg) {
if (arg == 6) {
alu.lxor(mmu.readbyte(hl.getfull()));
addticks(2, 7);
} else {
alu.lxor(getbyteregisterval(arg));
addticks(1, 4);
}
}
void z80::op_xor_n() {
alu.lxor(getbytearg());
addticks(2, 7);
}
void z80::op_cp_r(int arg) {
if (arg == 6) {
alu.cp(mmu.readbyte(hl.getfull()));
addticks(2, 7);
} else {
alu.cp(getbyteregisterval(arg));
addticks(1, 4);
}
}
void z80::op_cp_n() {
alu.cp(getbytearg());
addticks(2, 7);
}
void z80::op_inc_r(int arg) {
if (arg == 6) {
mmu.writebyte(hl.getfull(), alu.inc(mmu.readbyte(hl.getfull())));
addticks(3, 11);
} else {
setbyteregisterval(arg, alu.inc(getbyteregisterval(arg)));
addticks(1, 4);
}
}
void z80::op_dec_r(int arg) {
if (arg == 6) {
mmu.writebyte(hl.getfull(), alu.dec(mmu.readbyte(hl.getfull())));
addticks(3, 11);
} else {
setbyteregisterval(arg, alu.dec(getbyteregisterval(arg)));
addticks(1, 4);
}
}
void z80::op_cpl() {
alu.cpl();
addticks(1, 4);
}
void z80::op_ccf() {
alu.ccf();
addticks(1, 4);
}
void z80::op_scf() {
alu.scf();
addticks(1, 4);
}
void z80::op_halt() {
// if???
assert(false && "Halt called, not implemented");
}
void z80::op_di() {
iff = false;
}
void z80::op_ei() {
iff = true;
}
<commit_msg>Kleine correctie <commit_after>#include "z80.h"
#include <cassert>
z80::z80() {
reset();
}
void z80::cycle() {
pc += 1;
int op = mmu.readbyte(pc.getfull());
call(op);
if (!setticks) assert(false && "No ticks added! (incorrect or no instruction)");
setticks = false;
}
void z80::reset() {
clock_m = 0;
clock_t = 0;
setticks = false;
iff = false;
af.reset();
bc.reset();
de.reset();
hl.reset();
pc.reset();
sp.reset();
alu.setflagregister(&af);
}
quint8 z80::getbyteregisterval(int code) {
switch (code) {
case 7: return af.gethi();
case 0: return bc.gethi();
case 1: return bc.getlo();
case 2: return de.gethi();
case 3: return de.getlo();
case 4: return hl.gethi();
case 5: return hl.getlo();
}
return 0;
}
void z80::setbyteregisterval(int code, quint8 val) {
switch (code) {
case 7: af.sethi(val); break;
case 0: bc.sethi(val); break;
case 1: bc.setlo(val); break;
case 2: de.sethi(val); break;
case 3: de.setlo(val); break;
case 4: hl.sethi(val); break;
case 5: hl.setlo(val); break;
}
}
quint16 z80::getwordregisterval(int code, bool lastsp) {
switch (code) {
case 0: return bc.getfull();
case 1: return de.getfull();
case 2: return hl.getfull();
case 3: return (lastsp) ? sp.getfull() : af.getfull();
}
return 0;
}
void z80::setwordregisterval(int code, bool lastsp, quint16 val) {
switch (code) {
case 0: bc.setfull(val); break;
case 1: de.setfull(val); break;
case 2: hl.setfull(val); break;
case 3: if (lastsp) sp.setfull(val); else af.setfull(val); break;
}
}
quint8 z80::getbytearg() {
quint8 retval = mmu.readbyte(pc.getfull());
pc += 1;
return retval;
}
quint16 z80::getwordarg() {
quint16 retval;
retval = mmu.readbyte(pc.getfull()) << 8;
pc += 1;
retval |= mmu.readbyte(pc.getfull());
pc += 1;
return retval;
}
void z80::addticks(int m, int t) {
clock_m += m;
clock_t += t;
setticks = true;
}
void z80::call(quint8 opcode) {
int hi2 = opcode >> 6;
int mid3 = (opcode >> 3) & 7;
int low3 = opcode & 7;
int mid2 = (opcode >> 4) & 3;
int low4 = opcode & 15;
switch (hi2) {
case 0:
switch (low3) {
case 0:
if (mid3 == 0) op_nop();
break;
case 1:
if ((mid3 & 1) == 0) op_ld_dd_nn(mid2); break;
case 2:
op_ld_ahl_nn(mid3); break;
case 4:
op_inc_r(mid3); break;
case 5:
op_dec_r(mid3); break;
case 6:
op_ld_r_n(mid3); break;
case 7:
switch (mid3) {
case 5:
op_cpl(); break;
case 6:
op_scf(); break;
case 7:
op_ccf(); break;
}
break;
}
break;
case 1:
if (mid3 == 6 && low3 == 6) op_halt();
else op_ld_r_r(mid3, low3);
break;
case 2:
switch (mid3) {
case 0:
op_add_r(low3, false); break;
case 1:
op_add_r(low3, true); break;
case 2:
op_sub_r(low3, false); break;
case 3:
op_sub_r(low3, true); break;
case 4:
op_and_r(low3); break;
case 5:
op_xor_r(low3); break;
case 6:
op_or_r(low3); break;
case 7:
op_cp_r(low3); break;
}
break;
case 3:
switch (low3) {
case 1:
if ((mid3 & 1) == 0) op_pop_qq(mid2);
break;
case 3:
switch (mid3) {
case 6:
op_di();
break;
case 7:
op_ei();
break;
}
break;
case 5:
if ((mid3 & 1) == 0) op_push_qq(mid2);
break;
case 6:
switch (mid3) {
case 0:
op_add_n(false); break;
case 1:
op_add_n(true); break;
case 2:
op_sub_n(false); break;
case 3:
op_sub_n(true); break;
case 4:
op_and_n(); break;
case 5:
op_xor_n(); break;
case 6:
op_or_n(); break;
case 7:
op_cp_n(); break;
}
break;
}
if (opcode == 0xF9) op_ld_sp_hl(); // 11 11 1001
break;
}
return;
}
void z80::op_nop() {
addticks(1, 4);
}
void z80::op_ld_r_r(int arg1, int arg2) {
if (arg1 == 6) {
// (HL) <- r
mmu.writebyte(hl.getfull(), getbyteregisterval(arg2));
addticks(2, 7);
} else if (arg2 == 6) {
// r <- (HL)
setbyteregisterval(arg1, mmu.readbyte(hl.getfull()));
addticks(2, 7);
} else {
// r <- r'
setbyteregisterval(arg1, getbyteregisterval(arg2));
addticks(1, 4);
}
}
void z80::op_ld_r_n(int arg) {
quint8 n = getbytearg();
if (arg == 6) {
// (HL) <- n;
mmu.writebyte(hl.getfull(), n);
addticks(3, 10);
} else {
// r <- n
setbyteregisterval(arg, n);
addticks(2, 7);
}
}
void z80::op_ld_ahl_nn(int arg) {
quint16 addr;
if (arg == 4 || arg == 5) {
addr = getwordarg();
if (arg == 5) {
hl.setfull(mmu.readword(addr));
// TODO: make sure readword works like this:
//r.l = mmu.readbyte(addr);
//r.h = mmu.readbyte(addr + 1);
} else {
mmu.writeword(addr, hl.getfull());
// TODO: make sure writeword works like this:
//mmu.writebyte(addr + 1, r.h);
//mmu.writebyte(addr, r.l);
}
addticks(5, 16);
} else {
switch (arg >> 1) {
case 0:
addr = bc.getfull();
addticks(2, 7);
break;
case 1:
addr = de.getfull();
addticks(2, 7);
break;
case 3:
addr = getwordarg();
addticks(4, 13);
break;
}
if (arg && 1) {
af.sethi(mmu.readbyte(addr));
} else {
mmu.writebyte(addr, af.gethi());
}
}
}
void z80::op_ld_dd_nn(int arg) {
quint16 nn = getwordarg();
setwordregisterval(arg, true, nn);
addticks(3, 10);
}
void z80::op_ld_sp_hl() {
sp.setfull(hl.getfull());
addticks(1, 6);
}
void z80::op_push_qq(int arg) {
sp -= 2;
mmu.writebyte(sp.getfull(), getwordregisterval(arg, false));
addticks(3, 11);
}
void z80::op_pop_qq(int arg) {
setwordregisterval(arg, false, mmu.readbyte(sp.getfull()));
sp += 2;
addticks(3, 10);
}
void z80::op_add_r(int arg, bool withcarry) {
if (arg == 6) {
alu.add(mmu.readbyte(hl.getfull()), withcarry);
addticks(2, 7);
} else {
alu.add(getbyteregisterval(arg), withcarry);
addticks(1, 4);
}
}
void z80::op_add_n(bool withcarry) {
alu.add(getbytearg(), withcarry);
addticks(2, 7);
}
void z80::op_sub_r(int arg, bool withcarry) {
if (arg == 6) {
alu.sub(mmu.readbyte(hl.getfull()), withcarry);
addticks(2, 7);
} else {
alu.sub(getbyteregisterval(arg), withcarry);
addticks(1, 4);
}
}
void z80::op_sub_n(bool withcarry) {
alu.sub(getbytearg(), withcarry);
addticks(2, 7);
}
void z80::op_and_r(int arg) {
if (arg == 6) {
alu.land(mmu.readbyte(hl.getfull()));
addticks(2, 7);
} else {
alu.land(getbyteregisterval(arg));
addticks(1, 4);
}
}
void z80::op_and_n() {
alu.land(getbytearg());
addticks(2, 7);
}
void z80::op_or_r(int arg) {
if (arg == 6) {
alu.lor(mmu.readbyte(hl.getfull()));
addticks(2, 7);
} else {
alu.lor(getbyteregisterval(arg));
addticks(1, 4);
}
}
void z80::op_or_n() {
alu.lor(getbytearg());
addticks(2, 7);
}
void z80::op_xor_r(int arg) {
if (arg == 6) {
alu.lxor(mmu.readbyte(hl.getfull()));
addticks(2, 7);
} else {
alu.lxor(getbyteregisterval(arg));
addticks(1, 4);
}
}
void z80::op_xor_n() {
alu.lxor(getbytearg());
addticks(2, 7);
}
void z80::op_cp_r(int arg) {
if (arg == 6) {
alu.cp(mmu.readbyte(hl.getfull()));
addticks(2, 7);
} else {
alu.cp(getbyteregisterval(arg));
addticks(1, 4);
}
}
void z80::op_cp_n() {
alu.cp(getbytearg());
addticks(2, 7);
}
void z80::op_inc_r(int arg) {
if (arg == 6) {
mmu.writebyte(hl.getfull(), alu.inc(mmu.readbyte(hl.getfull())));
addticks(3, 11);
} else {
setbyteregisterval(arg, alu.inc(getbyteregisterval(arg)));
addticks(1, 4);
}
}
void z80::op_dec_r(int arg) {
if (arg == 6) {
mmu.writebyte(hl.getfull(), alu.dec(mmu.readbyte(hl.getfull())));
addticks(3, 11);
} else {
setbyteregisterval(arg, alu.dec(getbyteregisterval(arg)));
addticks(1, 4);
}
}
void z80::op_cpl() {
alu.cpl();
addticks(1, 4);
}
void z80::op_ccf() {
alu.ccf();
addticks(1, 4);
}
void z80::op_scf() {
alu.scf();
addticks(1, 4);
}
void z80::op_halt() {
// if???
assert(false && "Halt called, not implemented");
}
void z80::op_di() {
iff = false;
addticks(1, 4);
}
void z80::op_ei() {
iff = true;
addticks(1, 4);
}
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright NumFOCUS
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
/*=========================================================================
*
* Portions of this file are subject to the VTK Toolkit Version 3 copyright.
*
* Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
*
* For complete copyright, license and disclaimer of warranty information
* please refer to the NOTICE file at the top of the ITK source tree.
*
*=========================================================================*/
#include "itkPlatformMultiThreader.h"
#include "itkBitCast.h"
#include "itkObjectFactory.h"
#include "itksys/SystemTools.hxx"
#include <cstdlib>
#include "itkWindows.h"
#include <process.h>
namespace itk
{
#if !defined(ITK_LEGACY_REMOVE)
void
PlatformMultiThreader::MultipleMethodExecute()
{
ThreadIdType threadCount;
DWORD threadId;
HANDLE processId[ITK_MAX_THREADS];
// obey the global maximum number of threads limit
if (m_NumberOfWorkUnits > MultiThreaderBase::GetGlobalMaximumNumberOfThreads())
{
m_NumberOfWorkUnits = MultiThreaderBase::GetGlobalMaximumNumberOfThreads();
}
for (threadCount = 0; threadCount < m_NumberOfWorkUnits; ++threadCount)
{
if (m_MultipleMethod[threadCount] == nullptr)
{
itkExceptionMacro(<< "No multiple method set for: " << threadCount);
}
}
// Using _beginthreadex on a PC
//
// We want to use _beginthreadex to start m_NumberOfWorkUnits - 1
// additional threads which will be used to call the NumberOfWorkUnits-1
// methods defined in this->MultipleMethods[](). The parent thread
// will call m_MultipleMethods[NumberOfWorkUnits-1](). When it is done,
// it will wait for all the children to finish.
//
// First, start up the m_NumberOfWorkUnits-1 processes. Keep track
// of their process ids for use later in the waitid call
for (threadCount = 1; threadCount < m_NumberOfWorkUnits; ++threadCount)
{
m_ThreadInfoArray[threadCount].UserData = m_MultipleData[threadCount];
m_ThreadInfoArray[threadCount].NumberOfWorkUnits = m_NumberOfWorkUnits;
processId[threadCount] = bit_cast<HANDLE>(_beginthreadex(
nullptr, 0, m_MultipleMethod[threadCount], &m_ThreadInfoArray[threadCount], 0, (unsigned int *)&threadId));
if (processId[threadCount] == nullptr)
{
itkExceptionMacro("Error in thread creation!");
}
}
// Now, the parent thread calls the last method itself
m_ThreadInfoArray[0].UserData = m_MultipleData[0];
m_ThreadInfoArray[0].NumberOfWorkUnits = m_NumberOfWorkUnits;
(m_MultipleMethod[0])((void *)(&m_ThreadInfoArray[0]));
// The parent thread has finished its method - so now it
// waits for each of the other processes to
// exit
for (threadCount = 1; threadCount < m_NumberOfWorkUnits; ++threadCount)
{
WaitForSingleObject(processId[threadCount], INFINITE);
}
// close the threads
for (threadCount = 1; threadCount < m_NumberOfWorkUnits; ++threadCount)
{
CloseHandle(processId[threadCount]);
}
}
ThreadIdType
PlatformMultiThreader::SpawnThread(ThreadFunctionType f, void * UserData)
{
ThreadIdType id = 0;
DWORD threadId;
while (id < ITK_MAX_THREADS)
{
if (!m_SpawnedThreadActiveFlagLock[id])
{
m_SpawnedThreadActiveFlagLock[id] = std::make_shared<std::mutex>();
}
m_SpawnedThreadActiveFlagLock[id]->lock();
if (m_SpawnedThreadActiveFlag[id] == 0)
{
// We've got a useable thread id, so grab it
m_SpawnedThreadActiveFlag[id] = 1;
m_SpawnedThreadActiveFlagLock[id]->unlock();
break;
}
m_SpawnedThreadActiveFlagLock[id]->unlock();
id++;
}
if (id >= ITK_MAX_THREADS)
{
itkExceptionMacro(<< "You have too many active threads!");
}
m_SpawnedThreadInfoArray[id].UserData = UserData;
m_SpawnedThreadInfoArray[id].NumberOfWorkUnits = 1;
m_SpawnedThreadInfoArray[id].ActiveFlag = &m_SpawnedThreadActiveFlag[id];
m_SpawnedThreadInfoArray[id].ActiveFlagLock = m_SpawnedThreadActiveFlagLock[id];
// Using _beginthreadex on a PC
//
m_SpawnedThreadProcessID[id] =
bit_cast<HANDLE>(_beginthreadex(nullptr, 0, f, &m_SpawnedThreadInfoArray[id], 0, (unsigned int *)&threadId));
if (m_SpawnedThreadProcessID[id] == nullptr)
{
itkExceptionMacro("Error in thread creation !!!");
}
return id;
}
void
PlatformMultiThreader::TerminateThread(ThreadIdType WorkUnitID)
{
if (!m_SpawnedThreadActiveFlag[WorkUnitID])
{
return;
}
m_SpawnedThreadActiveFlagLock[WorkUnitID]->lock();
m_SpawnedThreadActiveFlag[WorkUnitID] = 0;
m_SpawnedThreadActiveFlagLock[WorkUnitID]->unlock();
WaitForSingleObject(m_SpawnedThreadProcessID[WorkUnitID], INFINITE);
CloseHandle(m_SpawnedThreadProcessID[WorkUnitID]);
m_SpawnedThreadActiveFlagLock[WorkUnitID] = nullptr;
}
#endif
void
PlatformMultiThreader::SpawnWaitForSingleMethodThread(ThreadProcessIdType threadHandle)
{
// Using _beginthreadex on a PC
WaitForSingleObject(threadHandle, INFINITE);
CloseHandle(threadHandle);
}
ThreadProcessIdType
PlatformMultiThreader::SpawnDispatchSingleMethodThread(PlatformMultiThreader::WorkUnitInfo * threadInfo)
{
// Using _beginthreadex on a PC
DWORD threadId;
auto threadHandle =
bit_cast<HANDLE>(_beginthreadex(nullptr, 0, this->SingleMethodProxy, threadInfo, 0, (unsigned int *)&threadId));
if (threadHandle == nullptr)
{
itkExceptionMacro("Error in thread creation !!!");
}
return threadHandle;
}
} // end namespace itk
<commit_msg>BUG: Replace `bit_cast<HANDLE>` calls with `reinterpret_cast<HANDLE>`<commit_after>/*=========================================================================
*
* Copyright NumFOCUS
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
/*=========================================================================
*
* Portions of this file are subject to the VTK Toolkit Version 3 copyright.
*
* Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
*
* For complete copyright, license and disclaimer of warranty information
* please refer to the NOTICE file at the top of the ITK source tree.
*
*=========================================================================*/
#include "itkPlatformMultiThreader.h"
#include "itkObjectFactory.h"
#include "itksys/SystemTools.hxx"
#include <cstdlib>
#include "itkWindows.h"
#include <process.h>
namespace itk
{
#if !defined(ITK_LEGACY_REMOVE)
void
PlatformMultiThreader::MultipleMethodExecute()
{
ThreadIdType threadCount;
DWORD threadId;
HANDLE processId[ITK_MAX_THREADS];
// obey the global maximum number of threads limit
if (m_NumberOfWorkUnits > MultiThreaderBase::GetGlobalMaximumNumberOfThreads())
{
m_NumberOfWorkUnits = MultiThreaderBase::GetGlobalMaximumNumberOfThreads();
}
for (threadCount = 0; threadCount < m_NumberOfWorkUnits; ++threadCount)
{
if (m_MultipleMethod[threadCount] == nullptr)
{
itkExceptionMacro(<< "No multiple method set for: " << threadCount);
}
}
// Using _beginthreadex on a PC
//
// We want to use _beginthreadex to start m_NumberOfWorkUnits - 1
// additional threads which will be used to call the NumberOfWorkUnits-1
// methods defined in this->MultipleMethods[](). The parent thread
// will call m_MultipleMethods[NumberOfWorkUnits-1](). When it is done,
// it will wait for all the children to finish.
//
// First, start up the m_NumberOfWorkUnits-1 processes. Keep track
// of their process ids for use later in the waitid call
for (threadCount = 1; threadCount < m_NumberOfWorkUnits; ++threadCount)
{
m_ThreadInfoArray[threadCount].UserData = m_MultipleData[threadCount];
m_ThreadInfoArray[threadCount].NumberOfWorkUnits = m_NumberOfWorkUnits;
processId[threadCount] = reinterpret_cast<HANDLE>(_beginthreadex(
nullptr, 0, m_MultipleMethod[threadCount], &m_ThreadInfoArray[threadCount], 0, (unsigned int *)&threadId));
if (processId[threadCount] == nullptr)
{
itkExceptionMacro("Error in thread creation!");
}
}
// Now, the parent thread calls the last method itself
m_ThreadInfoArray[0].UserData = m_MultipleData[0];
m_ThreadInfoArray[0].NumberOfWorkUnits = m_NumberOfWorkUnits;
(m_MultipleMethod[0])((void *)(&m_ThreadInfoArray[0]));
// The parent thread has finished its method - so now it
// waits for each of the other processes to
// exit
for (threadCount = 1; threadCount < m_NumberOfWorkUnits; ++threadCount)
{
WaitForSingleObject(processId[threadCount], INFINITE);
}
// close the threads
for (threadCount = 1; threadCount < m_NumberOfWorkUnits; ++threadCount)
{
CloseHandle(processId[threadCount]);
}
}
ThreadIdType
PlatformMultiThreader::SpawnThread(ThreadFunctionType f, void * UserData)
{
ThreadIdType id = 0;
DWORD threadId;
while (id < ITK_MAX_THREADS)
{
if (!m_SpawnedThreadActiveFlagLock[id])
{
m_SpawnedThreadActiveFlagLock[id] = std::make_shared<std::mutex>();
}
m_SpawnedThreadActiveFlagLock[id]->lock();
if (m_SpawnedThreadActiveFlag[id] == 0)
{
// We've got a useable thread id, so grab it
m_SpawnedThreadActiveFlag[id] = 1;
m_SpawnedThreadActiveFlagLock[id]->unlock();
break;
}
m_SpawnedThreadActiveFlagLock[id]->unlock();
id++;
}
if (id >= ITK_MAX_THREADS)
{
itkExceptionMacro(<< "You have too many active threads!");
}
m_SpawnedThreadInfoArray[id].UserData = UserData;
m_SpawnedThreadInfoArray[id].NumberOfWorkUnits = 1;
m_SpawnedThreadInfoArray[id].ActiveFlag = &m_SpawnedThreadActiveFlag[id];
m_SpawnedThreadInfoArray[id].ActiveFlagLock = m_SpawnedThreadActiveFlagLock[id];
// Using _beginthreadex on a PC
//
m_SpawnedThreadProcessID[id] = reinterpret_cast<HANDLE>(
_beginthreadex(nullptr, 0, f, &m_SpawnedThreadInfoArray[id], 0, (unsigned int *)&threadId));
if (m_SpawnedThreadProcessID[id] == nullptr)
{
itkExceptionMacro("Error in thread creation !!!");
}
return id;
}
void
PlatformMultiThreader::TerminateThread(ThreadIdType WorkUnitID)
{
if (!m_SpawnedThreadActiveFlag[WorkUnitID])
{
return;
}
m_SpawnedThreadActiveFlagLock[WorkUnitID]->lock();
m_SpawnedThreadActiveFlag[WorkUnitID] = 0;
m_SpawnedThreadActiveFlagLock[WorkUnitID]->unlock();
WaitForSingleObject(m_SpawnedThreadProcessID[WorkUnitID], INFINITE);
CloseHandle(m_SpawnedThreadProcessID[WorkUnitID]);
m_SpawnedThreadActiveFlagLock[WorkUnitID] = nullptr;
}
#endif
void
PlatformMultiThreader::SpawnWaitForSingleMethodThread(ThreadProcessIdType threadHandle)
{
// Using _beginthreadex on a PC
WaitForSingleObject(threadHandle, INFINITE);
CloseHandle(threadHandle);
}
ThreadProcessIdType
PlatformMultiThreader::SpawnDispatchSingleMethodThread(PlatformMultiThreader::WorkUnitInfo * threadInfo)
{
// Using _beginthreadex on a PC
DWORD threadId;
auto threadHandle = reinterpret_cast<HANDLE>(
_beginthreadex(nullptr, 0, this->SingleMethodProxy, threadInfo, 0, (unsigned int *)&threadId));
if (threadHandle == nullptr)
{
itkExceptionMacro("Error in thread creation !!!");
}
return threadHandle;
}
} // end namespace itk
<|endoftext|> |
<commit_before>#include "FEMesh.h"
namespace voom {
// Constructor from input file
FEMesh::FEMesh(const string Nodes, const string ConnTable): Mesh(Nodes, ConnTable) {
ifstream inp(ConnTable.c_str());
uint NumEl = 0, temp = 0;
string ElType;
// First line
// First number is NumNodes, Second is type of element
inp >> NumEl >> ElType;
_elements.resize(NumEl);
uint NumNodesEl = this->createElementShapeAndQuadrature(ElType);
// Compute the geometric elements
for (uint e = 0; e < NumEl; e++) {
vector<int > ConnEl(NumNodesEl, 0);
vector<VectorXd > Xel;
for (uint n = 0; n < NumNodesEl; n++) {
inp >> ConnEl[n];
Xel.push_back(_X[ConnEl[n]]);
}
_elements[e] = new FEgeomElement(e, ConnEl, Xel, _shapes, _quadrature);
} // End of FEgeom
} // End constructor from input files
// Constructor from nodes and connectivities
FEMesh::FEMesh(const vector<VectorXd > & Positions,
const vector<vector<int > > & Connectivity,
string ElementType,
uint QuadOrder):
Mesh(Positions)
{
this->createElementShapeAndQuadrature(ElementType);
// Resize element container
uint NumEl = Connectivity.size();
_elements.resize(NumEl);
// Create list of elements
for(uint i = 0; i < NumEl; i++) {
// Temporary list of nodal positions
vector<VectorXd > positionList(Connectivity[i].size() );
for(uint m = 0; m < Connectivity[i].size(); m++)
positionList[m] = _positions[Connectivity[i][m]];
FEgeomElement *myElement = new FEgeomElement(i, Connectivity[i],
positionList,
_shapes[0],
_quadrature[0]);
_elements[i] = myElement;
} // Loop over element list
} // Constructor from nodes and connectivities
int FEMesh::createElementShapeAndQuadrature(const string ElType) {
uint NumNodesEl = 0;
if (ElType == "C3D8") {
// Full integration hexahedral element
_quadrature = new HexQuadrature(2);
vector<VectorXd > QuadPoints = _quadrature->getQuadPoints();
// Fill quadrature and shapes
for ( uint q = 0; q < QuadPoints.size(); q++ ) {
_shapes.push_back( new HexShape(QuadPoints[q]) );
}
NumNodesEl = 8;
} // end of C3D8
else if (ElType == "C3D8R") {
// Reduced integration hexahedral element
_quadrature = new HexQuadrature(1);
vector<VectorXd > QuadPoints = _quadrature->getQuadPoints();
// Fill quadrature and shapes
for ( uint q = 0; q < QuadPoints.size(); q++ ) {
_shapes.push_back( new HexShape(QuadPoints[q]) );
}
NumNodesEl = 8;
}
else if (ElType == "C3D4") {
// Full integration linear tetrahedral element
_quadrature = new TetQuadrature(1);
vector<VectorXd > QuadPoints = _quadrature->getQuadPoints();
// Fill quadrature and shapes
for ( uint q = 0; q < QuadPoints.size(); q++ ) {
_shapes.push_back( new LinTetShape(QuadPoints[q]) );
}
NumNodesEl = 4;
}
else if (ElType == "C3D10") {
// Full integration quadratic tetrahedral element
_quadrature = new TetQuadrature(2);
vector<VectorXd > QuadPoints = _quadrature->getQuadPoints();
// Fill quadrature and shapes
for ( uint q = 0; q < QuadPoints.size(); q++ ) {
_shapes.push_back( new QuadTetShape(QuadPoints[q]) );
}
NumNodesEl = 10;
}
else if (ElType == "TD3") {
// Full integration linear triangular element
_quadrature = new TriQuadrature(1);
vector<VectorXd > QuadPoints = _quadrature->getQuadPoints();
// Fill quadrature and shapes
for ( uint q = 0; q < QuadPoints.size(); q++ ) {
_shapes.push_back( new LinTriShape(QuadPoints[q]) );
}
NumNodesEl = 3;
}
else if (ElType == "TD6") {
// Full integration quadratic triangular element
_quadrature = new TriQuadrature(2);
vector<VectorXd > QuadPoints = _quadrature->getQuadPoints();
// Fill quadrature and shapes
for ( uint q = 0; q < QuadPoints.size(); q++ ) {
_shapes.push_back( new QuadTriShape(QuadPoints[q]) );
}
NumNodesEl = 6;
}
else {
cerr << "** ERROR: Unknown finite element type: " << ElType << endl;
cerr << "Exiting...\n";
exit(EXIT_FAILURE);
}
return NumNodesEl;
} // End createElementShapeAndQuadrature
} // namespace voom
<commit_msg>Fixing FEMesh Constructor bugs<commit_after>#include "FEMesh.h"
namespace voom {
// Constructor from input file
FEMesh::FEMesh(const string Nodes, const string ConnTable): Mesh(Nodes, ConnTable) {
ifstream inp(ConnTable.c_str());
uint NumEl = 0, temp = 0;
string ElType;
// First line
// First number is NumNodes, Second is type of element
inp >> NumEl >> ElType;
_elements.resize(NumEl);
uint NumNodesEl = this->createElementShapeAndQuadrature(ElType);
// Compute the geometric elements
for (uint e = 0; e < NumEl; e++) {
vector<int > ConnEl(NumNodesEl, 0);
vector<VectorXd > Xel;
for (uint n = 0; n < NumNodesEl; n++) {
inp >> ConnEl[n];
Xel.push_back(_X[ConnEl[n]]);
}
_elements[e] = new FEgeomElement(e, ConnEl, Xel, _shapes, _quadrature);
} // End of FEgeom
} // End constructor from input files
// Constructor from nodes and connectivities
FEMesh::FEMesh(const vector<VectorXd > & Positions,
const vector<vector<int > > & Connectivity,
string ElementType,
uint QuadOrder):
Mesh(Positions)
{
this->createElementShapeAndQuadrature(ElementType);
// Resize element container
uint NumEl = Connectivity.size();
_elements.resize(NumEl);
// Create list of elements
for(uint i = 0; i < NumEl; i++) {
// Temporary list of nodal positions
vector<VectorXd > Xel(Connectivity[i].size() );
for(uint m = 0; m < Connectivity[i].size(); m++)
Xel[m] = _X[Connectivity[i][m]];
FEgeomElement *myElement = new FEgeomElement(i, Connectivity[i],
Xel, _shapes, _quadrature);
_elements[i] = myElement;
} // Loop over element list
} // Constructor from nodes and connectivities
int FEMesh::createElementShapeAndQuadrature(const string ElType) {
uint NumNodesEl = 0;
if (ElType == "C3D8") {
// Full integration hexahedral element
_quadrature = new HexQuadrature(2);
vector<VectorXd > QuadPoints = _quadrature->getQuadPoints();
// Fill quadrature and shapes
for ( uint q = 0; q < QuadPoints.size(); q++ ) {
_shapes.push_back( new HexShape(QuadPoints[q]) );
}
NumNodesEl = 8;
} // end of C3D8
else if (ElType == "C3D8R") {
// Reduced integration hexahedral element
_quadrature = new HexQuadrature(1);
vector<VectorXd > QuadPoints = _quadrature->getQuadPoints();
// Fill quadrature and shapes
for ( uint q = 0; q < QuadPoints.size(); q++ ) {
_shapes.push_back( new HexShape(QuadPoints[q]) );
}
NumNodesEl = 8;
}
else if (ElType == "C3D4") {
// Full integration linear tetrahedral element
_quadrature = new TetQuadrature(1);
vector<VectorXd > QuadPoints = _quadrature->getQuadPoints();
// Fill quadrature and shapes
for ( uint q = 0; q < QuadPoints.size(); q++ ) {
_shapes.push_back( new LinTetShape(QuadPoints[q]) );
}
NumNodesEl = 4;
}
else if (ElType == "C3D10") {
// Full integration quadratic tetrahedral element
_quadrature = new TetQuadrature(2);
vector<VectorXd > QuadPoints = _quadrature->getQuadPoints();
// Fill quadrature and shapes
for ( uint q = 0; q < QuadPoints.size(); q++ ) {
_shapes.push_back( new QuadTetShape(QuadPoints[q]) );
}
NumNodesEl = 10;
}
else if (ElType == "TD3") {
// Full integration linear triangular element
_quadrature = new TriQuadrature(1);
vector<VectorXd > QuadPoints = _quadrature->getQuadPoints();
// Fill quadrature and shapes
for ( uint q = 0; q < QuadPoints.size(); q++ ) {
_shapes.push_back( new LinTriShape(QuadPoints[q]) );
}
NumNodesEl = 3;
}
else if (ElType == "TD6") {
// Full integration quadratic triangular element
_quadrature = new TriQuadrature(2);
vector<VectorXd > QuadPoints = _quadrature->getQuadPoints();
// Fill quadrature and shapes
for ( uint q = 0; q < QuadPoints.size(); q++ ) {
_shapes.push_back( new QuadTriShape(QuadPoints[q]) );
}
NumNodesEl = 6;
}
else {
cerr << "** ERROR: Unknown finite element type: " << ElType << endl;
cerr << "Exiting...\n";
exit(EXIT_FAILURE);
}
return NumNodesEl;
} // End createElementShapeAndQuadrature
} // namespace voom
<|endoftext|> |
<commit_before>#include <iostream>
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/TargetOptions.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/Options.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Lex/HeaderSearchOptions.h"
#include "clang/Lex/MacroArgs.h"
#include "clang/Lex/PPCallbacks.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Lex/PreprocessorOptions.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Option/OptTable.h"
using namespace clang;
struct log_expands : public PPCallbacks {
Preprocessor &pp;
SourceManager &sm;
log_expands(Preprocessor &, SourceManager &);
virtual void MacroExpands(const Token &, const MacroDefinition &, SourceRange,
const MacroArgs *);
};
void configureTarget(CompilerInstance &ci);
llvm::opt::InputArgList parseArgs(int argc, char **argv);
FileID getFileID(CompilerInstance &ci, llvm::opt::InputArgList &args);
void createPreprocessor(CompilerInstance &ci, llvm::opt::InputArgList &args);
void processFile(CompilerInstance &ci, const FileID &fileID);
int main(int argc, char *argv[]) {
CompilerInstance ci;
configureTarget(ci);
auto arguments = parseArgs(argc, argv);
createPreprocessor(ci, arguments);
auto fileID = getFileID(ci, arguments);
processFile(ci, fileID);
return EXIT_SUCCESS;
}
log_expands::log_expands(Preprocessor &p, SourceManager& s) : pp(p), sm(s) {}
void log_expands::MacroExpands(const Token &MacroNameTok,
const MacroDefinition &MD, SourceRange,
const MacroArgs *Args) {
if (!sm.isInMainFile(MacroNameTok.getLocation())) {
// llvm::outs() << "Skipping macro " << pp.getSpelling(MacroNameTok) << " because it is not expanded from the specified file\n";
return;
}
llvm::outs() << "expanding macro " << pp.getSpelling(MacroNameTok) << " into "<< '\n';
const auto macro = MD.getMacroInfo();
for (const auto &tok : macro->tokens())
llvm::outs() << pp.getSpelling(tok) << ' ';
if (!macro->isFunctionLike() || Args == nullptr)
return;
llvm::outs() << '\n' << '\t' << "where:" << '\n';
auto tokenAt = [Args](unsigned int index) {
return Args->getUnexpArgument(0) + index;
};
unsigned int i = 0;
for (const auto args : macro->args()) {
llvm::outs() << '\t' << '\t' << args->getNameStart() << " is ";
while (tokenAt(i)->isNot(tok::eof)) {
llvm::outs() << pp.getSpelling(*tokenAt(i));
i++;
}
i++;
llvm::outs() << '\n';
}
}
void configureTarget(CompilerInstance &ci) {
ci.getDiagnosticOpts().ShowColors = 1;
auto diags = new TextDiagnosticPrinter(llvm::errs(), &ci.getDiagnosticOpts());
ci.createDiagnostics(diags);
std::shared_ptr<TargetOptions> topts(new clang::TargetOptions);
topts->Triple = LLVM_DEFAULT_TARGET_TRIPLE;
ci.setTarget(TargetInfo::CreateTargetInfo(ci.getDiagnostics(), topts));
}
llvm::opt::InputArgList parseArgs(int argc, char **argv) {
std::vector<const char *> ref;
for (int i = 1; i < argc; ++i)
ref.emplace_back(argv[i]);
unsigned missingIndex{0}, missingCount{0};
auto table = driver::createDriverOptTable();
return table->ParseArgs(ref, missingIndex, missingCount);
}
FileID getFileID(CompilerInstance &ci, llvm::opt::InputArgList &args) {
auto inputs = args.getAllArgValues(driver::options::OPT_INPUT);
if (inputs.size() == 1 && inputs[0] != "-") {
const FileEntry *pFile = ci.getFileManager().getFile(inputs[0]);
return ci.getSourceManager().getOrCreateFileID(
pFile, SrcMgr::CharacteristicKind::C_User);
}
llvm::errs()
<< "None or More than one source file was specified -- aborting\n";
exit(EXIT_FAILURE);
return ci.getSourceManager().createFileID(nullptr);
}
void createPreprocessor(CompilerInstance &ci, llvm::opt::InputArgList &args) {
ci.createFileManager();
ci.createSourceManager(ci.getFileManager());
#ifndef SYSTEM_HEADERS
#define SYSTEM_HEADERS
#endif
for (const auto dir : {SYSTEM_HEADERS})
ci.getHeaderSearchOpts().AddPath(dir, frontend::Angled, false, true);
using namespace driver::options;
using namespace llvm::opt;
for (const auto A : args.filtered(OPT_I))
ci.getHeaderSearchOpts().AddPath(A->getValue(), frontend::Quoted, false, true);
for (const auto A : args.filtered(OPT_isystem))
ci.getHeaderSearchOpts().AddPath(A->getValue(), frontend::Angled, false, true);
for (const auto A : args.filtered(OPT_D, OPT_U)) {
if (A->getOption().matches(OPT_D))
ci.getPreprocessorOpts().addMacroDef(A->getValue());
else
ci.getPreprocessorOpts().addMacroUndef(A->getValue());
}
ci.createPreprocessor(TranslationUnitKind::TU_Complete);
}
void processFile(CompilerInstance &ci, const FileID &fileID) {
ci.getSourceManager().setMainFileID(fileID);
ci.getPreprocessor().EnterMainSourceFile();
ci.getDiagnosticClient().BeginSourceFile(ci.getLangOpts(),
&ci.getPreprocessor());
std::unique_ptr<PPCallbacks> logger(new log_expands(ci.getPreprocessor(), ci.getSourceManager()));
ci.getPreprocessor().addPPCallbacks(std::move(logger));
Token tok;
do {
ci.getPreprocessor().Lex(tok);
if (ci.getDiagnostics().hasErrorOccurred())
break;
} while (tok.isNot(tok::eof));
ci.getDiagnosticClient().EndSourceFile();
}
<commit_msg>Improved spacing<commit_after>#include <iostream>
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/TargetOptions.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/Options.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Lex/HeaderSearchOptions.h"
#include "clang/Lex/MacroArgs.h"
#include "clang/Lex/PPCallbacks.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Lex/PreprocessorOptions.h"
#include "clang/Lex/TokenConcatenation.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Option/OptTable.h"
using namespace clang;
struct log_expands : public PPCallbacks {
Preprocessor &pp;
SourceManager &sm;
TokenConcatenation tokCat;
log_expands(Preprocessor &, SourceManager &);
virtual void MacroExpands(const Token &, const MacroDefinition &, SourceRange,
const MacroArgs *);
private:
Token prevprev, prev;
void printToken(const Token& tok);
void flushPrinter();
};
void configureTarget(CompilerInstance &ci);
llvm::opt::InputArgList parseArgs(int argc, char **argv);
FileID getFileID(CompilerInstance &ci, llvm::opt::InputArgList &args);
void createPreprocessor(CompilerInstance &ci, llvm::opt::InputArgList &args);
void processFile(CompilerInstance &ci, const FileID &fileID);
int main(int argc, char *argv[]) {
CompilerInstance ci;
configureTarget(ci);
auto arguments = parseArgs(argc, argv);
createPreprocessor(ci, arguments);
auto fileID = getFileID(ci, arguments);
processFile(ci, fileID);
return EXIT_SUCCESS;
}
log_expands::log_expands(Preprocessor &p, SourceManager& s) : pp(p), sm(s), tokCat(p) {}
void log_expands::printToken(const Token& tok) {
if (tokCat.AvoidConcat(prevprev, prev, tok))
llvm::outs() << ' ';
llvm::outs() << pp.getSpelling(tok);
prevprev = prev;
prev = tok;
}
void log_expands::flushPrinter() {
prevprev = {};
prev = {};
}
void log_expands::MacroExpands(const Token &MacroNameTok,
const MacroDefinition &MD, SourceRange,
const MacroArgs *Args) {
if (!sm.isInMainFile(MacroNameTok.getLocation())) {
// llvm::outs() << "Skipping macro " << pp.getSpelling(MacroNameTok) << " because it is not expanded from the specified file\n";
return;
}
llvm::outs() << "expanding macro " << pp.getSpelling(MacroNameTok) << " into "<< '\n';
const auto macro = MD.getMacroInfo();
for (const auto &tok : macro->tokens())
printToken(tok);
flushPrinter();
llvm::outs() << '\n';
if (!macro->isFunctionLike() || Args == nullptr)
return;
llvm::outs() << '\t' << "where:" << '\n';
auto tokenAt = [Args](unsigned int index) {
return Args->getUnexpArgument(0) + index;
};
unsigned int i = 0;
for (const auto args : macro->args()) {
llvm::outs() << '\t' << '\t' << args->getNameStart() << " is ";
while (tokenAt(i)->isNot(tok::eof)) {
printToken(*tokenAt(i));
i++;
}
flushPrinter();
i++;
llvm::outs() << '\n';
}
}
void configureTarget(CompilerInstance &ci) {
ci.getDiagnosticOpts().ShowColors = 1;
auto diags = new TextDiagnosticPrinter(llvm::errs(), &ci.getDiagnosticOpts());
ci.createDiagnostics(diags);
std::shared_ptr<TargetOptions> topts(new clang::TargetOptions);
topts->Triple = LLVM_DEFAULT_TARGET_TRIPLE;
ci.setTarget(TargetInfo::CreateTargetInfo(ci.getDiagnostics(), topts));
}
llvm::opt::InputArgList parseArgs(int argc, char **argv) {
std::vector<const char *> ref;
for (int i = 1; i < argc; ++i)
ref.emplace_back(argv[i]);
unsigned missingIndex{0}, missingCount{0};
auto table = driver::createDriverOptTable();
return table->ParseArgs(ref, missingIndex, missingCount);
}
FileID getFileID(CompilerInstance &ci, llvm::opt::InputArgList &args) {
auto inputs = args.getAllArgValues(driver::options::OPT_INPUT);
if (inputs.size() == 1 && inputs[0] != "-") {
const FileEntry *pFile = ci.getFileManager().getFile(inputs[0]);
return ci.getSourceManager().getOrCreateFileID(
pFile, SrcMgr::CharacteristicKind::C_User);
}
llvm::errs()
<< "None or More than one source file was specified -- aborting\n";
exit(EXIT_FAILURE);
return ci.getSourceManager().createFileID(nullptr);
}
void createPreprocessor(CompilerInstance &ci, llvm::opt::InputArgList &args) {
ci.createFileManager();
ci.createSourceManager(ci.getFileManager());
#ifndef SYSTEM_HEADERS
#define SYSTEM_HEADERS
#endif
for (const auto dir : {SYSTEM_HEADERS})
ci.getHeaderSearchOpts().AddPath(dir, frontend::Angled, false, true);
using namespace driver::options;
using namespace llvm::opt;
for (const auto A : args.filtered(OPT_I))
ci.getHeaderSearchOpts().AddPath(A->getValue(), frontend::Quoted, false, true);
for (const auto A : args.filtered(OPT_isystem))
ci.getHeaderSearchOpts().AddPath(A->getValue(), frontend::Angled, false, true);
for (const auto A : args.filtered(OPT_D, OPT_U)) {
if (A->getOption().matches(OPT_D))
ci.getPreprocessorOpts().addMacroDef(A->getValue());
else
ci.getPreprocessorOpts().addMacroUndef(A->getValue());
}
ci.createPreprocessor(TranslationUnitKind::TU_Complete);
}
void processFile(CompilerInstance &ci, const FileID &fileID) {
ci.getSourceManager().setMainFileID(fileID);
ci.getPreprocessor().EnterMainSourceFile();
ci.getDiagnosticClient().BeginSourceFile(ci.getLangOpts(),
&ci.getPreprocessor());
std::unique_ptr<PPCallbacks> logger(new log_expands(ci.getPreprocessor(), ci.getSourceManager()));
ci.getPreprocessor().addPPCallbacks(std::move(logger));
Token tok;
do {
ci.getPreprocessor().Lex(tok);
if (ci.getDiagnostics().hasErrorOccurred())
break;
} while (tok.isNot(tok::eof));
ci.getDiagnosticClient().EndSourceFile();
}
<|endoftext|> |
<commit_before>#include "diagram.h"
#include "type.h"
#include "enumType.h"
#include "numericType.h"
#include "stringType.h"
#include "portType.h"
#include "nodeType.h"
#include "edgeType.h"
#include "editor.h"
#include <QtCore/QDebug>
Diagram::Diagram(QString const &name, QString const &nodeName, QString const &displayedName, Editor *editor)
: mDiagramName(name), mDiagramNodeName(nodeName), mDiagramDisplayedName(displayedName), mEditor(editor)
{}
Diagram::~Diagram()
{
foreach(Type *type, mTypes.values()) {
if (type) {
delete type;
}
}
}
bool Diagram::init(QDomElement const &diagramElement)
{
for (QDomElement element = diagramElement.firstChildElement();
!element.isNull();
element = element.nextSiblingElement())
{
if (element.nodeName() == "graphicTypes") {
if (!initGraphicTypes(element)) {
return false;
}
} else if (element.nodeName() == "nonGraphicTypes") {
if (!initNonGraphicTypes(element)) {
return false;
}
} else if (element.nodeName() == "palette") {
initPaletteGroups(element);
} else {
qDebug() << "ERROR: unknown tag" << element.nodeName();
}
}
return true;
}
bool Diagram::initGraphicTypes(QDomElement const &graphicTypesElement)
{
for (QDomElement element = graphicTypesElement.firstChildElement();
!element.isNull();
element = element.nextSiblingElement())
{
if (element.nodeName() == "node") {
Type *nodeType = new NodeType(this);
if (!nodeType->init(element, mDiagramName)) {
delete nodeType;
qDebug() << "Can't parse node";
return false;
}
mTypes[nodeType->qualifiedName()] = nodeType;
} else if (element.nodeName() == "edge") {
Type *edgeType = new EdgeType(this);
if (!edgeType->init(element, mDiagramName)) {
delete edgeType;
qDebug() << "Can't parse edge";
return false;
}
mTypes[edgeType->qualifiedName()] = edgeType;
} else if (element.nodeName() == "import") {
ImportSpecification import = {
element.attribute("name", "")
, element.attribute("as", "")
, element.attribute("displayedName", "")
};
mImports.append(import);
}
else
{
qDebug() << "ERROR: unknown graphic type" << element.nodeName();
return false;
}
}
return true;
}
bool Diagram::initNonGraphicTypes(QDomElement const &nonGraphicTypesElement)
{
for (QDomElement element = nonGraphicTypesElement.firstChildElement();
!element.isNull();
element = element.nextSiblingElement())
{
mGroupsXML = "";
if (element.nodeName() == "groups") {
QString xml;
QTextStream stream(&xml);
element.save(stream, 1);
xml.replace("\"", "\\\"");
xml.replace("\n", "\\n");
mGroupsXML = xml;
} else if (element.nodeName() == "enum") {
Type *enumType = new EnumType();
if (!enumType->init(element, mDiagramName)) {
delete enumType;
qDebug() << "Can't parse enum";
return false;
}
mTypes[enumType->qualifiedName()] = enumType;
} else if (element.nodeName() == "numeric") {
Type *numericType = new NumericType();
if (!numericType->init(element, mDiagramName)) {
delete numericType;
qDebug() << "Can't parse numeric type";
return false;
}
mTypes[numericType->qualifiedName()] = numericType;
} else if (element.nodeName() == "string") {
Type *stringType = new StringType();
if (!stringType->init(element, mDiagramName)) {
delete stringType;
qDebug() << "Can't parse string type";
return false;
}
mTypes[stringType->qualifiedName()] = stringType;
} else if (element.nodeName() == "port") {
Type *portType = new PortType();
if (!portType->init(element, mDiagramName)) {
delete portType;
qDebug() << "Can't parse port type";
return false;
}
mTypes[portType->qualifiedName()] = portType;
}
else {
qDebug() << "ERROR: unknown non graphic type" << element.nodeName();
return false;
}
}
return true;
}
void Diagram::initPaletteGroups(const QDomElement &paletteGroupsElement)
{
for (QDomElement element = paletteGroupsElement.firstChildElement("group");
!element.isNull();
element = element.nextSiblingElement("group"))
{
QString name = element.attribute("name");
QString description = element.attribute("description", "");
mPaletteGroupsDescriptions[name] = description;
for (QDomElement groupElement = element.firstChildElement("element");
!groupElement.isNull();
groupElement = groupElement.nextSiblingElement("element"))
{
mPaletteGroups[name].append(groupElement.attribute("name"));
}
}
}
bool Diagram::resolve()
{
foreach (ImportSpecification import, mImports) {
Type *importedType = mEditor->findType(import.name);
if (importedType == NULL) {
qDebug() << "ERROR: imported type" << import.name << "not found, skipping";
continue;
}
Type *copiedType = importedType->clone();
copiedType->setName(import.as);
copiedType->setDisplayedName(import.displayedName);
copiedType->setDiagram(this);
copiedType->setContext(mDiagramName);
mTypes.insert(copiedType->qualifiedName(), copiedType);
}
foreach(Type *type, mTypes.values())
if (!type->resolve()) {
qDebug() << "ERROR: can't resolve type" << type->name();
return false;
}
return true;
}
Editor* Diagram::editor() const
{
return mEditor;
}
Type* Diagram::findType(QString name)
{
if (mTypes.contains(name)) {
return mTypes[name];
} else {
return mEditor->findType(name);
}
}
QMap<QString, Type*> Diagram::types() const
{
return mTypes;
}
QString Diagram::name() const
{
return mDiagramName;
}
QString Diagram::nodeName() const
{
return mDiagramNodeName;
}
QString Diagram::displayedName() const
{
return mDiagramDisplayedName;
}
QMap<QString, QStringList> Diagram::paletteGroups() const
{
return mPaletteGroups;
}
QMap<QString, QString> Diagram::paletteGroupsDescriptions() const
{
return mPaletteGroupsDescriptions;
}
QString Diagram::getGroupsXML() const
{
return mGroupsXML;
}
<commit_msg>Fixed time-to-time groups nullifying in metamodel<commit_after>#include "diagram.h"
#include "type.h"
#include "enumType.h"
#include "numericType.h"
#include "stringType.h"
#include "portType.h"
#include "nodeType.h"
#include "edgeType.h"
#include "editor.h"
#include <QtCore/QDebug>
Diagram::Diagram(QString const &name, QString const &nodeName, QString const &displayedName, Editor *editor)
: mDiagramName(name), mDiagramNodeName(nodeName), mDiagramDisplayedName(displayedName), mEditor(editor)
{}
Diagram::~Diagram()
{
foreach(Type *type, mTypes.values()) {
if (type) {
delete type;
}
}
}
bool Diagram::init(QDomElement const &diagramElement)
{
for (QDomElement element = diagramElement.firstChildElement();
!element.isNull();
element = element.nextSiblingElement())
{
if (element.nodeName() == "graphicTypes") {
if (!initGraphicTypes(element)) {
return false;
}
} else if (element.nodeName() == "nonGraphicTypes") {
if (!initNonGraphicTypes(element)) {
return false;
}
} else if (element.nodeName() == "palette") {
initPaletteGroups(element);
} else {
qDebug() << "ERROR: unknown tag" << element.nodeName();
}
}
return true;
}
bool Diagram::initGraphicTypes(QDomElement const &graphicTypesElement)
{
for (QDomElement element = graphicTypesElement.firstChildElement();
!element.isNull();
element = element.nextSiblingElement())
{
if (element.nodeName() == "node") {
Type *nodeType = new NodeType(this);
if (!nodeType->init(element, mDiagramName)) {
delete nodeType;
qDebug() << "Can't parse node";
return false;
}
mTypes[nodeType->qualifiedName()] = nodeType;
} else if (element.nodeName() == "edge") {
Type *edgeType = new EdgeType(this);
if (!edgeType->init(element, mDiagramName)) {
delete edgeType;
qDebug() << "Can't parse edge";
return false;
}
mTypes[edgeType->qualifiedName()] = edgeType;
} else if (element.nodeName() == "import") {
ImportSpecification import = {
element.attribute("name", "")
, element.attribute("as", "")
, element.attribute("displayedName", "")
};
mImports.append(import);
}
else
{
qDebug() << "ERROR: unknown graphic type" << element.nodeName();
return false;
}
}
return true;
}
bool Diagram::initNonGraphicTypes(QDomElement const &nonGraphicTypesElement)
{
for (QDomElement element = nonGraphicTypesElement.firstChildElement();
!element.isNull();
element = element.nextSiblingElement())
{
if (element.nodeName() == "groups") {
mGroupsXML = "";
QString xml;
QTextStream stream(&xml);
element.save(stream, 1);
xml.replace("\"", "\\\"");
xml.replace("\n", "\\n");
mGroupsXML = xml;
} else if (element.nodeName() == "enum") {
Type *enumType = new EnumType();
if (!enumType->init(element, mDiagramName)) {
delete enumType;
qDebug() << "Can't parse enum";
return false;
}
mTypes[enumType->qualifiedName()] = enumType;
} else if (element.nodeName() == "numeric") {
Type *numericType = new NumericType();
if (!numericType->init(element, mDiagramName)) {
delete numericType;
qDebug() << "Can't parse numeric type";
return false;
}
mTypes[numericType->qualifiedName()] = numericType;
} else if (element.nodeName() == "string") {
Type *stringType = new StringType();
if (!stringType->init(element, mDiagramName)) {
delete stringType;
qDebug() << "Can't parse string type";
return false;
}
mTypes[stringType->qualifiedName()] = stringType;
} else if (element.nodeName() == "port") {
Type *portType = new PortType();
if (!portType->init(element, mDiagramName)) {
delete portType;
qDebug() << "Can't parse port type";
return false;
}
mTypes[portType->qualifiedName()] = portType;
}
else {
qDebug() << "ERROR: unknown non graphic type" << element.nodeName();
return false;
}
}
return true;
}
void Diagram::initPaletteGroups(const QDomElement &paletteGroupsElement)
{
for (QDomElement element = paletteGroupsElement.firstChildElement("group");
!element.isNull();
element = element.nextSiblingElement("group"))
{
QString name = element.attribute("name");
QString description = element.attribute("description", "");
mPaletteGroupsDescriptions[name] = description;
for (QDomElement groupElement = element.firstChildElement("element");
!groupElement.isNull();
groupElement = groupElement.nextSiblingElement("element"))
{
mPaletteGroups[name].append(groupElement.attribute("name"));
}
}
}
bool Diagram::resolve()
{
foreach (ImportSpecification import, mImports) {
Type *importedType = mEditor->findType(import.name);
if (importedType == NULL) {
qDebug() << "ERROR: imported type" << import.name << "not found, skipping";
continue;
}
Type *copiedType = importedType->clone();
copiedType->setName(import.as);
copiedType->setDisplayedName(import.displayedName);
copiedType->setDiagram(this);
copiedType->setContext(mDiagramName);
mTypes.insert(copiedType->qualifiedName(), copiedType);
}
foreach(Type *type, mTypes.values())
if (!type->resolve()) {
qDebug() << "ERROR: can't resolve type" << type->name();
return false;
}
return true;
}
Editor* Diagram::editor() const
{
return mEditor;
}
Type* Diagram::findType(QString name)
{
if (mTypes.contains(name)) {
return mTypes[name];
} else {
return mEditor->findType(name);
}
}
QMap<QString, Type*> Diagram::types() const
{
return mTypes;
}
QString Diagram::name() const
{
return mDiagramName;
}
QString Diagram::nodeName() const
{
return mDiagramNodeName;
}
QString Diagram::displayedName() const
{
return mDiagramDisplayedName;
}
QMap<QString, QStringList> Diagram::paletteGroups() const
{
return mPaletteGroups;
}
QMap<QString, QString> Diagram::paletteGroupsDescriptions() const
{
return mPaletteGroupsDescriptions;
}
QString Diagram::getGroupsXML() const
{
return mGroupsXML;
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Andreas Streichardt
////////////////////////////////////////////////////////////////////////////////
#include "Basics/MutexLocker.h"
#include "Basics/ConditionLocker.h"
#include <chrono>
#include <thread>
#include <velocypack/Exception.h>
#include <velocypack/Parser.h>
#include <velocypack/velocypack-aliases.h>
#include "AgencyCallback.h"
using namespace arangodb;
AgencyCallback::AgencyCallback(AgencyComm& agency,
std::string const& key,
std::function<bool(VPackSlice const&)> const& cb,
bool needsValue,
bool needsInitialValue)
: key(key),
_useCv(false),
_agency(agency),
_cb(cb),
_needsValue(needsValue) {
if (_needsValue && needsInitialValue) {
refetchAndUpdate();
}
}
void AgencyCallback::refetchAndUpdate() {
if (!_needsValue) {
// no need to pass any value to the callback
executeEmpty();
return;
}
AgencyCommResult result = _agency.getValues(key, true);
if (!result.successful()) {
return;
}
if (!result.parse("", false)) {
LOG(ERR) << "Cannot parse body " << result.body();
return;
}
// mop: we need to find out if it is a directory :S
// because we lost this information while parsing
std::shared_ptr<VPackBuilder> bodyBuilder =
VPackParser::fromJson(result.body().c_str());
VPackSlice slice = bodyBuilder->slice();
if (!slice.isObject() || !slice.hasKey("node")) {
LOG(ERR) << "Invalid structure " << result.body();
return;
}
VPackSlice node = slice.get("node");
if (!slice.isObject()) {
LOG(ERR) << "Node is not an object";
return;
}
bool isDir = node.hasKey("dir");
std::shared_ptr<VPackBuilder> newData = std::make_shared<VPackBuilder>();
if (isDir) {
VPackObjectBuilder builder(newData.get());
for (auto& it: result._values) {
newData->add(it.first, it.second._vpack->slice());
}
} else if (result._values.size() == 0) {
newData->add(VPackSlice::noneSlice());
} else {
newData->add(result._values.begin()->second._vpack->slice());
}
checkValue(newData);
}
void AgencyCallback::checkValue(std::shared_ptr<VPackBuilder> newData) {
if (!_lastData || !_lastData->slice().equals(newData->slice())) {
LOG(DEBUG) << "Got new value " << newData->slice().typeName() << " " << newData->toJson();
if (execute(newData)) {
_lastData = newData;
} else {
LOG(DEBUG) << "Callback was not successful for " << newData->toJson();
}
}
}
bool AgencyCallback::executeEmpty() {
LOG(DEBUG) << "Executing (empty)";
bool result;
{
MUTEX_LOCKER(locker, _lock);
result = _cb(VPackSlice::noneSlice());
}
if (_useCv) {
CONDITION_LOCKER(locker, _cv);
_cv.signal();
}
return result;
}
bool AgencyCallback::execute(std::shared_ptr<VPackBuilder> newData) {
LOG(DEBUG) << "Executing";
bool result;
{
MUTEX_LOCKER(locker, _lock);
result = _cb(newData->slice());
}
if (_useCv) {
CONDITION_LOCKER(locker, _cv);
_cv.signal();
}
return result;
}
void AgencyCallback::waitWithFailover(double timeout) {
VPackSlice compareSlice;
if (_lastData) {
compareSlice = _lastData->slice();
} else {
compareSlice = VPackSlice::noneSlice();
}
std::this_thread::sleep_for(std::chrono::milliseconds(static_cast<int>(timeout * 1000)));
if (!_lastData || _lastData->slice().equals(compareSlice)) {
LOG(DEBUG) << "Waiting done and nothing happended. Refetching to be sure";
// mop: watches have not triggered during our sleep...recheck to be sure
refetchAndUpdate();
}
}
void AgencyCallback::waitForExecution(double maxTimeout) {
VPackSlice compareSlice;
if (_lastData) {
compareSlice = _lastData->slice();
} else {
compareSlice = VPackSlice::noneSlice();
}
_useCv = true;
CONDITION_LOCKER(locker, _cv);
locker.wait(maxTimeout * 1000000.0);
_useCv = false;
if (!_lastData || _lastData->slice().equals(compareSlice)) {
LOG(DEBUG) << "Waiting done and nothing happended. Refetching to be sure";
// mop: watches have not triggered during our sleep...recheck to be sure
refetchAndUpdate();
}
}
<commit_msg>fixed last compile warning<commit_after>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Andreas Streichardt
////////////////////////////////////////////////////////////////////////////////
#include "Basics/MutexLocker.h"
#include "Basics/ConditionLocker.h"
#include <chrono>
#include <thread>
#include <velocypack/Exception.h>
#include <velocypack/Parser.h>
#include <velocypack/velocypack-aliases.h>
#include "AgencyCallback.h"
using namespace arangodb;
AgencyCallback::AgencyCallback(AgencyComm& agency,
std::string const& key,
std::function<bool(VPackSlice const&)> const& cb,
bool needsValue,
bool needsInitialValue)
: key(key),
_useCv(false),
_agency(agency),
_cb(cb),
_needsValue(needsValue) {
if (_needsValue && needsInitialValue) {
refetchAndUpdate();
}
}
void AgencyCallback::refetchAndUpdate() {
if (!_needsValue) {
// no need to pass any value to the callback
executeEmpty();
return;
}
AgencyCommResult result = _agency.getValues(key, true);
if (!result.successful()) {
return;
}
if (!result.parse("", false)) {
LOG(ERR) << "Cannot parse body " << result.body();
return;
}
// mop: we need to find out if it is a directory :S
// because we lost this information while parsing
std::shared_ptr<VPackBuilder> bodyBuilder =
VPackParser::fromJson(result.body().c_str());
VPackSlice slice = bodyBuilder->slice();
if (!slice.isObject() || !slice.hasKey("node")) {
LOG(ERR) << "Invalid structure " << result.body();
return;
}
VPackSlice node = slice.get("node");
if (!slice.isObject()) {
LOG(ERR) << "Node is not an object";
return;
}
bool isDir = node.hasKey("dir");
std::shared_ptr<VPackBuilder> newData = std::make_shared<VPackBuilder>();
if (isDir) {
VPackObjectBuilder builder(newData.get());
for (auto& it: result._values) {
newData->add(it.first, it.second._vpack->slice());
}
} else if (result._values.size() == 0) {
newData->add(VPackSlice::noneSlice());
} else {
newData->add(result._values.begin()->second._vpack->slice());
}
checkValue(newData);
}
void AgencyCallback::checkValue(std::shared_ptr<VPackBuilder> newData) {
if (!_lastData || !_lastData->slice().equals(newData->slice())) {
LOG(DEBUG) << "Got new value " << newData->slice().typeName() << " " << newData->toJson();
if (execute(newData)) {
_lastData = newData;
} else {
LOG(DEBUG) << "Callback was not successful for " << newData->toJson();
}
}
}
bool AgencyCallback::executeEmpty() {
LOG(DEBUG) << "Executing (empty)";
bool result;
{
MUTEX_LOCKER(locker, _lock);
result = _cb(VPackSlice::noneSlice());
}
if (_useCv) {
CONDITION_LOCKER(locker, _cv);
_cv.signal();
}
return result;
}
bool AgencyCallback::execute(std::shared_ptr<VPackBuilder> newData) {
LOG(DEBUG) << "Executing";
bool result;
{
MUTEX_LOCKER(locker, _lock);
result = _cb(newData->slice());
}
if (_useCv) {
CONDITION_LOCKER(locker, _cv);
_cv.signal();
}
return result;
}
void AgencyCallback::waitWithFailover(double timeout) {
VPackSlice compareSlice;
if (_lastData) {
compareSlice = _lastData->slice();
} else {
compareSlice = VPackSlice::noneSlice();
}
std::this_thread::sleep_for(std::chrono::milliseconds(static_cast<int>(timeout * 1000)));
if (!_lastData || _lastData->slice().equals(compareSlice)) {
LOG(DEBUG) << "Waiting done and nothing happended. Refetching to be sure";
// mop: watches have not triggered during our sleep...recheck to be sure
refetchAndUpdate();
}
}
void AgencyCallback::waitForExecution(double maxTimeout) {
VPackSlice compareSlice;
if (_lastData) {
compareSlice = _lastData->slice();
} else {
compareSlice = VPackSlice::noneSlice();
}
_useCv = true;
CONDITION_LOCKER(locker, _cv);
locker.wait(static_cast<uint64_t>(maxTimeout * 1000000.0));
_useCv = false;
if (!_lastData || _lastData->slice().equals(compareSlice)) {
LOG(DEBUG) << "Waiting done and nothing happended. Refetching to be sure";
// mop: watches have not triggered during our sleep...recheck to be sure
refetchAndUpdate();
}
}
<|endoftext|> |
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org
Copyright (c) 2000-2014 Torus Knot Software Ltd
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 "OgreGLES2HardwareOcclusionQuery.h"
#include "OgreLogManager.h"
#include "OgreException.h"
#include "OgreRoot.h"
#include "OgreGLES2RenderSystem.h"
#include "OgreGLES2Util.h"
namespace Ogre {
//------------------------------------------------------------------
/**
* Default object constructor
*
*/
GLES2HardwareOcclusionQuery::GLES2HardwareOcclusionQuery()
{
createQuery();
}
//------------------------------------------------------------------
/**
* Object destructor
*/
GLES2HardwareOcclusionQuery::~GLES2HardwareOcclusionQuery()
{
destroyQuery();
}
//------------------------------------------------------------------
void GLES2HardwareOcclusionQuery::createQuery()
{
// Check for hardware occlusion support
if(getGLES2SupportRef()->checkExtension("GL_EXT_occlusion_query_boolean") || gleswIsSupported(3, 0))
{
OGRE_CHECK_GL_ERROR(glGenQueriesEXT(1, &mQueryID));
}
else
{
OGRE_EXCEPT( Exception::ERR_INTERNAL_ERROR,
"Cannot allocate a Hardware query. This video card doesn't support it, sorry.",
"GLES2HardwareOcclusionQuery::GLES2HardwareOcclusionQuery" );
}
}
//------------------------------------------------------------------
void GLES2HardwareOcclusionQuery::destroyQuery()
{
if(getGLES2SupportRef()->checkExtension("GL_EXT_occlusion_query_boolean") || gleswIsSupported(3, 0))
{
OGRE_CHECK_GL_ERROR(glDeleteQueriesEXT(1, &mQueryID));
}
}
//------------------------------------------------------------------
#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN
void GLES2HardwareOcclusionQuery::notifyOnContextLost()
{
destroyQuery();
}
//------------------------------------------------------------------
void GLES2HardwareOcclusionQuery::notifyOnContextReset()
{
createQuery();
}
#endif
//------------------------------------------------------------------
void GLES2HardwareOcclusionQuery::beginOcclusionQuery()
{
if(getGLES2SupportRef()->checkExtension("GL_EXT_occlusion_query_boolean") || gleswIsSupported(3, 0))
{
OGRE_CHECK_GL_ERROR(glBeginQueryEXT(GL_ANY_SAMPLES_PASSED_EXT, mQueryID));
}
}
//------------------------------------------------------------------
void GLES2HardwareOcclusionQuery::endOcclusionQuery()
{
if(getGLES2SupportRef()->checkExtension("GL_EXT_occlusion_query_boolean") || gleswIsSupported(3, 0))
{
OGRE_CHECK_GL_ERROR(glEndQueryEXT(GL_ANY_SAMPLES_PASSED_EXT));
}
}
//------------------------------------------------------------------
bool GLES2HardwareOcclusionQuery::pullOcclusionQuery( unsigned int* NumOfFragments )
{
if(getGLES2SupportRef()->checkExtension("GL_EXT_occlusion_query_boolean") || gleswIsSupported(3, 0))
{
OGRE_CHECK_GL_ERROR(glGetQueryObjectuivEXT(mQueryID, GL_QUERY_RESULT_EXT, (GLuint*)NumOfFragments));
mPixelCount = *NumOfFragments;
return true;
}
else
return false;
}
//------------------------------------------------------------------
bool GLES2HardwareOcclusionQuery::isStillOutstanding(void)
{
GLuint available = GL_FALSE;
if(getGLES2SupportRef()->checkExtension("GL_EXT_occlusion_query_boolean") || gleswIsSupported(3, 0))
{
OGRE_CHECK_GL_ERROR(glGetQueryObjectuivEXT(mQueryID, GL_QUERY_RESULT_AVAILABLE_EXT, &available));
}
// GL_TRUE means a wait would occur
return !(available == GL_TRUE);
}
}
<commit_msg>GLES2: do not check for hardware support at each function call<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org
Copyright (c) 2000-2014 Torus Knot Software Ltd
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 "OgreGLES2HardwareOcclusionQuery.h"
#include "OgreLogManager.h"
#include "OgreException.h"
#include "OgreRoot.h"
#include "OgreGLES2RenderSystem.h"
#include "OgreGLES2Util.h"
namespace Ogre {
//------------------------------------------------------------------
/**
* Default object constructor
*
*/
GLES2HardwareOcclusionQuery::GLES2HardwareOcclusionQuery()
{
createQuery();
}
//------------------------------------------------------------------
/**
* Object destructor
*/
GLES2HardwareOcclusionQuery::~GLES2HardwareOcclusionQuery()
{
destroyQuery();
}
//------------------------------------------------------------------
void GLES2HardwareOcclusionQuery::createQuery()
{
OGRE_CHECK_GL_ERROR(glGenQueriesEXT(1, &mQueryID));
}
//------------------------------------------------------------------
void GLES2HardwareOcclusionQuery::destroyQuery()
{
OGRE_CHECK_GL_ERROR(glDeleteQueriesEXT(1, &mQueryID));
}
//------------------------------------------------------------------
#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN
void GLES2HardwareOcclusionQuery::notifyOnContextLost()
{
destroyQuery();
}
//------------------------------------------------------------------
void GLES2HardwareOcclusionQuery::notifyOnContextReset()
{
createQuery();
}
#endif
//------------------------------------------------------------------
void GLES2HardwareOcclusionQuery::beginOcclusionQuery()
{
OGRE_CHECK_GL_ERROR(glBeginQueryEXT(GL_ANY_SAMPLES_PASSED_EXT, mQueryID));
}
//------------------------------------------------------------------
void GLES2HardwareOcclusionQuery::endOcclusionQuery()
{
OGRE_CHECK_GL_ERROR(glEndQueryEXT(GL_ANY_SAMPLES_PASSED_EXT));
}
//------------------------------------------------------------------
bool GLES2HardwareOcclusionQuery::pullOcclusionQuery( unsigned int* NumOfFragments )
{
OGRE_CHECK_GL_ERROR(glGetQueryObjectuivEXT(mQueryID, GL_QUERY_RESULT_EXT, (GLuint*)NumOfFragments));
mPixelCount = *NumOfFragments;
return true;
}
//------------------------------------------------------------------
bool GLES2HardwareOcclusionQuery::isStillOutstanding(void)
{
GLuint available = GL_FALSE;
OGRE_CHECK_GL_ERROR(glGetQueryObjectuivEXT(mQueryID, GL_QUERY_RESULT_AVAILABLE_EXT, &available));
// GL_TRUE means a wait would occur
return !(available == GL_TRUE);
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 1997 by Stephan Kulow <[email protected]>
* 2007 the ktimetracker developers
*
* 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 <signal.h>
#include <QFile>
#include <KAboutData>
#include <KCmdLineArgs>
#include <KDebug>
#include <KLocale>
#include <KStandardDirs>
#include <KUniqueApplication>
#include "version.h"
#include "mainwindow.h"
#include <QDebug>
namespace
{
const char* description = I18N_NOOP("KDE Time tracker tool");
void cleanup( int )
{
kDebug(5970) << i18n("Just caught a software interrupt.");
kapp->exit();
}
}
int main( int argc, char *argv[] )
{
KAboutData aboutData( "ktimetracker", 0, ki18n("KTimeTracker"),
KTIMETRACKER_VERSION, ki18n(description), KAboutData::License_GPL,
ki18n("(c) 1997-2007, KDE PIM Developers") );
aboutData.addAuthor( ki18n("Thorsten Stärk"), ki18n( "Current Maintainer" ),
"[email protected]" );
aboutData.addAuthor( ki18n("Sirtaj Singh Kang"), ki18n( "Original Author" ),
"[email protected]" );
aboutData.addAuthor( ki18n("Allen Winter"), KLocalizedString(), "[email protected]" );
aboutData.addAuthor( ki18n("David Faure"), KLocalizedString(), "[email protected]" );
aboutData.addAuthor( ki18n("Mathias Soeken"), KLocalizedString(), "[email protected]" );
aboutData.addAuthor( ki18n("Jesper Pedersen"), KLocalizedString(), "[email protected]" );
aboutData.addAuthor( ki18n("Kalle Dalheimer"), KLocalizedString(), "[email protected]" );
aboutData.addAuthor( ki18n("Mark Bucciarelli"), KLocalizedString(), "[email protected]" );
KCmdLineArgs::init( argc, argv, &aboutData );
KCmdLineOptions options;
options.add("+file", ki18n( "The iCalendar file to open" ));
KCmdLineArgs::addCmdLineOptions( options );
KUniqueApplication myApp;
KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
MainWindow *mainWindow;
if ( args->count() > 0 )
{
QString icsfile = args->arg( 0 );
KUrl* icsfileurl=new KUrl(args->arg( 0 ));
if (( icsfileurl->protocol() == "http" ) || ( icsfileurl->protocol() == "ftp" ) || ( icsfileurl->isLocalFile() ))
{
// leave as is
;
}
else
{
icsfile = KCmdLineArgs::cwd() + '/' + icsfile;
}
mainWindow = new MainWindow( icsfile );
}
else
{
QString newKarmFile(KStandardDirs::locate( "data", "ktimetracker/karm.ics" ));
if ( !QFile::exists( newKarmFile ) )
{
QFile oldFile( KStandardDirs::locate( "data", "karm/karm.ics" ) );
newKarmFile = KStandardDirs::locateLocal( "appdata", QString::fromLatin1( "karm.ics" ) );
if ( oldFile.exists() )
oldFile.copy( newKarmFile );
}
mainWindow = new MainWindow( newKarmFile );
}
if (kapp->isSessionRestored() && KMainWindow::canBeRestored( 1 ))
mainWindow->restore( 1, false );
else
mainWindow->show();
signal( SIGQUIT, cleanup );
signal( SIGINT, cleanup );
int ret = myApp.exec();
delete mainWindow;
return ret;
}
<commit_msg>Copyright year change<commit_after>/*
* Copyright (C) 1997 by Stephan Kulow <[email protected]>
* 2007 the ktimetracker developers
*
* 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 <signal.h>
#include <QFile>
#include <KAboutData>
#include <KCmdLineArgs>
#include <KDebug>
#include <KLocale>
#include <KStandardDirs>
#include <KUniqueApplication>
#include "version.h"
#include "mainwindow.h"
#include <QDebug>
namespace
{
const char* description = I18N_NOOP("KDE Time tracker tool");
void cleanup( int )
{
kDebug(5970) << i18n("Just caught a software interrupt.");
kapp->exit();
}
}
int main( int argc, char *argv[] )
{
KAboutData aboutData( "ktimetracker", 0, ki18n("KTimeTracker"),
KTIMETRACKER_VERSION, ki18n(description), KAboutData::License_GPL,
ki18n("(c) 1997-2008, KDE PIM Developers") );
aboutData.addAuthor( ki18n("Thorsten Stärk"), ki18n( "Current Maintainer" ),
"[email protected]" );
aboutData.addAuthor( ki18n("Sirtaj Singh Kang"), ki18n( "Original Author" ),
"[email protected]" );
aboutData.addAuthor( ki18n("Allen Winter"), KLocalizedString(), "[email protected]" );
aboutData.addAuthor( ki18n("David Faure"), KLocalizedString(), "[email protected]" );
aboutData.addAuthor( ki18n("Mathias Soeken"), KLocalizedString(), "[email protected]" );
aboutData.addAuthor( ki18n("Jesper Pedersen"), KLocalizedString(), "[email protected]" );
aboutData.addAuthor( ki18n("Kalle Dalheimer"), KLocalizedString(), "[email protected]" );
aboutData.addAuthor( ki18n("Mark Bucciarelli"), KLocalizedString(), "[email protected]" );
KCmdLineArgs::init( argc, argv, &aboutData );
KCmdLineOptions options;
options.add("+file", ki18n( "The iCalendar file to open" ));
KCmdLineArgs::addCmdLineOptions( options );
KUniqueApplication myApp;
KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
MainWindow *mainWindow;
if ( args->count() > 0 )
{
QString icsfile = args->arg( 0 );
KUrl* icsfileurl=new KUrl(args->arg( 0 ));
if (( icsfileurl->protocol() == "http" ) || ( icsfileurl->protocol() == "ftp" ) || ( icsfileurl->isLocalFile() ))
{
// leave as is
;
}
else
{
icsfile = KCmdLineArgs::cwd() + '/' + icsfile;
}
mainWindow = new MainWindow( icsfile );
}
else
{
QString newKarmFile(KStandardDirs::locate( "data", "ktimetracker/karm.ics" ));
if ( !QFile::exists( newKarmFile ) )
{
QFile oldFile( KStandardDirs::locate( "data", "karm/karm.ics" ) );
newKarmFile = KStandardDirs::locateLocal( "appdata", QString::fromLatin1( "karm.ics" ) );
if ( oldFile.exists() )
oldFile.copy( newKarmFile );
}
mainWindow = new MainWindow( newKarmFile );
}
if (kapp->isSessionRestored() && KMainWindow::canBeRestored( 1 ))
mainWindow->restore( 1, false );
else
mainWindow->show();
signal( SIGQUIT, cleanup );
signal( SIGINT, cleanup );
int ret = myApp.exec();
delete mainWindow;
return ret;
}
<|endoftext|> |
<commit_before>#include "ExampleGame/Components/GameScripts/Units/Thief.h"
#include "ExampleGame/Components/Grid/GameGrid.h"
#include "ExampleGame/Components/Grid/GridCell.h"
#include "ExampleGame/Components/Grid/GridConstants.h"
#include "ExampleGame/Components/Grid/GridManager.h"
#include "ExampleGame/Components/Grid/GridNavigator.h"
#include "ExampleGame/GameConstants/GameConstants.h"
#include "ExampleGame/GameSingletons/GameSingletons.h"
#include "Vajra/Engine/Components/DerivedComponents/Renderer/SpriteRenderer.h"
#include "Vajra/Engine/Components/DerivedComponents/Transform/Transform.h"
#include "Vajra/Engine/Core/Engine.h"
#include "Vajra/Engine/Input/Input.h"
#include "Vajra/Engine/SceneGraph/SceneGraph3D.h"
#include "Vajra/Engine/Tween/Tween.h"
#include "Vajra/Framework/DeviceUtils/FileSystemUtils/FileSystemUtils.h"
// Tween callbacks
void thiefTweenCallback(ObjectIdType gameObjectId , std::string /* tweenClipName */) {
GameObject* go = ENGINE->GetSceneGraph3D()->GetGameObjectById(gameObjectId);
ASSERT(go != nullptr, "Game object id passed into playerUnitNuumberTweenCallback is not valid");
if(go != nullptr) {
Thief* pUnit = go->GetComponent<Thief>();
ASSERT(pUnit != nullptr, "Game object passed into playerUnitNuumberTweenCallback doesn't have a player unit");
if(pUnit != nullptr) {
pUnit->onSpecialEnd();
}
}
}
void thiefNumberTweenCallback(float /* fromNumber */, float /* toNumber */, float currentNumber, std::string tweenClipName, MessageData1S1I1F* userParams) {
/*GameObject* go = ENGINE->GetSceneGraph3D()->GetGameObjectById(userParams->i);
ASSERT(go != nullptr, "Game object id passed into playerUnitNuumberTweenCallback is not valid");
if(go != nullptr) {
Thief* thief = go->GetComponent<Thief>();
ASSERT(thief != nullptr, "Game object passed into playerUnitNuumberTweenCallback doesn't have a player unit");
if(thief != nullptr) {
if(tweenClipName == "targetsIn") {
for(GameObject* go : thief->targetIndicators ) {
}
}
}
}*/
}
Thief::Thief() : PlayerUnit() {
this->init();
}
Thief::Thief(Object* object_) : PlayerUnit(object_) {
this->init();
}
Thief::~Thief() {
this->destroy();
}
void Thief::init() {
this->unitType = UnitType::UNIT_TYPE_THIEF;
}
void Thief::destroy() {
}
bool Thief::isSpecialTouch(int touchId) {
if(this->getTouchNearUnit()) {
Touch touch = ENGINE->GetInput()->GetTouch(touchId);
if(touch.timeDown >= GetFloatGameConstant(GAME_CONSTANT_long_press_length_in_seconds) && glm::distance(touch.pos, this->touchStartPos) <= GetFloatGameConstant(GAME_CONSTANT_allowed_finger_movement_in_press)) {
this->targetedCell = nullptr;
this->SetTouchIndicatorVisible(false);
this->updateLegalTagets();
return true;
}
}
return false;
}
void Thief::onSpecialTouch(int touchId) {
Touch touch = ENGINE->GetInput()->GetTouch(touchId);
if(touch.phase == TouchPhase::Ended) {
this->targetedCell = SINGLETONS->GetGridManager()->TouchPositionToCell(touch.pos);
// TODO [HACK] Remove when the thief can gather legal targets
if(std::find(this->legalTargets.begin(), this->legalTargets.end(), this->GetCurrentTouchedCell()) != this->legalTargets.end()) {
this->startSpecial();
} else {
this->targetedCell = this->gridNavRef->GetCurrentCell();
this->onSpecialEnd();
}
this->tweenOutTargets();
}
}
void Thief::startSpecial() {
PlayerUnit::startSpecial();
// Remove the indicator at the selected position
GameObject* selectedTargetIndicator = this->targetIndicators[this->targetedCell];
this->targetIndicators.erase(this->targetedCell);
delete selectedTargetIndicator;
this->SetTouchIndicatorCell(this->targetedCell);
this->startTouchIndicatorPulse();
this->SetTouchIndicatorSprite(THIEF_SPECIAL);
this->SetTouchIndicatorVisible(true);
ENGINE->GetTween()->TweenPosition(this->gameObjectRef->GetId(),
this->gameObjectRef->GetTransform()->GetPosition(),
this->targetedCell->center,
1.0f,
false,
TWEEN_TRANSLATION_CURVE_TYPE_PARABOLA,
false,
thiefTweenCallback);
}
void Thief::onSpecialEnd() {
PlayerUnit::onSpecialEnd();
this->gridNavRef->SetGridPosition(this->targetedCell);
}
void Thief::touchedCellChanged(GridCell* prevTouchedCell) {
if(this->inputState == InputState::INPUT_STATE_NAV) {
PlayerUnit::touchedCellChanged(prevTouchedCell);
} else {
if(this->targetIndicators[prevTouchedCell]) {
ENGINE->GetTween()->TweenScale(this->targetIndicators[prevTouchedCell]->GetId(), glm::vec3(GetFloatGameConstant(GAME_CONSTANT_target_indicator_scale_hover)),
glm::vec3(GetFloatGameConstant(GAME_CONSTANT_target_indicator_scale)),
GetFloatGameConstant(GAME_CONSTANT_target_tween_time));
}
if(this->targetIndicators[this->GetCurrentTouchedCell()]) {
ENGINE->GetTween()->TweenScale(this->targetIndicators[this->GetCurrentTouchedCell()]->GetId(), glm::vec3(GetFloatGameConstant(GAME_CONSTANT_target_indicator_scale)),
glm::vec3(GetFloatGameConstant(GAME_CONSTANT_target_indicator_scale_hover)),
GetFloatGameConstant(GAME_CONSTANT_target_tween_time));
}
if(std::find(this->legalTargets.begin(), this->legalTargets.end(), this->GetCurrentTouchedCell()) != this->legalTargets.end()) {
this->SetTouchIndicatorSprite(GOOD_TOUCH);
} else {
this->SetTouchIndicatorSprite(BAD_TOUCH);
}
}
}
void Thief::updateLegalTagets() {
this->legalTargets.clear();
this->deleteTargets();
GridCell* currentCell = this->gridNavRef->GetCurrentCell();
int elevation = SINGLETONS->GetGridManager()->GetGrid()->GetElevationFromWorldY(currentCell->center.y);
std::list<GridCell*> cellsInRange;
SINGLETONS->GetGridManager()->GetGrid()->GetNeighborCells(cellsInRange, this->gridNavRef->GetCurrentCell(),
GetFloatGameConstant(GAME_CONSTANT_jump_distance_in_units)
+ elevation * GetFloatGameConstant(GAME_CONSTANT_jump_elevation_multiplier));
for ( GridCell* c : cellsInRange) {
if(c->y == elevation) { // is the cell on the same height
if(this->gridNavRef->CanReachDestination(c, GetFloatGameConstant(GAME_CONSTANT_jump_distance_in_units)) && SINGLETONS->GetGridManager()->GetGrid()->HasLineOfSight(currentCell, c, elevation) ) {
this->legalTargets.push_back(c);
}
}
else if(c->y <= elevation + 1) { // is the cell below it
if(SINGLETONS->GetGridManager()->GetGrid()->IsCellPassableAtElevation(c->x, c->z, c->y)) {
float dist = glm::distance(c->origin, currentCell->origin);
if(dist <= GetFloatGameConstant(GAME_CONSTANT_jump_distance_in_units) + c->y * GetFloatGameConstant(GAME_CONSTANT_jump_elevation_multiplier)) {
this->legalTargets.push_back(c);
}
}
}
}
this->createTargets();
this->tweenInTargets();
}
void Thief::tweenInTargets() {
glm::vec3 pos;
for(auto contents : this->targetIndicators ) {
if(contents.second != nullptr) {
pos = contents.second->GetTransform()->GetPosition();
ENGINE->GetTween()->TweenPosition(contents.second->GetId(), pos, pos + glm::vec3(0.0f, GetFloatGameConstant(GAME_CONSTANT_target_indicator_offset), 0.0f), GetFloatGameConstant(GAME_CONSTANT_target_tween_time));
}
}
}
void Thief::tweenOutTargets() {
glm::vec3 pos;
for(auto contents : this->targetIndicators ) {
if(contents.second != nullptr) {
pos = contents.second->GetTransform()->GetPosition();
ENGINE->GetTween()->TweenScale(contents.second->GetId(), glm::vec3(GetFloatGameConstant(GAME_CONSTANT_target_indicator_scale)), glm::vec3(0), GetFloatGameConstant(GAME_CONSTANT_target_tween_time));
}
}
}
void Thief::createTargets() {
for( GridCell* c : this->legalTargets ) {
GameObject* indicator = new GameObject(ENGINE->GetSceneGraph3D());
SpriteRenderer* spriteRenderer = indicator->AddComponent<SpriteRenderer>();
std::vector<std::string> pathsToTextures;
pathsToTextures.push_back(FRAMEWORK->GetFileSystemUtils()->GetDevicePictureResourcesFolderName() + "SD_UIEffect_Thief_Jump_01.png");
spriteRenderer->initPlane(1.0f, 1.0f, "sptshdr", pathsToTextures, PlaneOrigin::Center);
indicator->GetTransform()->SetPosition(c->center);
indicator->GetTransform()->SetScale( glm::vec3(GetFloatGameConstant(GAME_CONSTANT_target_indicator_scale)));
indicator->GetTransform()->Translate(0.0f, YAXIS);
indicator->GetTransform()->Rotate(90.0f inRadians, XAXIS);
this->targetIndicators[c] = indicator;
}
}
void Thief::deleteTargets() {
for(auto contents : this->targetIndicators ) {
delete contents.second;
}
this->targetIndicators.clear();
}
<commit_msg>removed old 'TODO' comment<commit_after>#include "ExampleGame/Components/GameScripts/Units/Thief.h"
#include "ExampleGame/Components/Grid/GameGrid.h"
#include "ExampleGame/Components/Grid/GridCell.h"
#include "ExampleGame/Components/Grid/GridConstants.h"
#include "ExampleGame/Components/Grid/GridManager.h"
#include "ExampleGame/Components/Grid/GridNavigator.h"
#include "ExampleGame/GameConstants/GameConstants.h"
#include "ExampleGame/GameSingletons/GameSingletons.h"
#include "Vajra/Engine/Components/DerivedComponents/Renderer/SpriteRenderer.h"
#include "Vajra/Engine/Components/DerivedComponents/Transform/Transform.h"
#include "Vajra/Engine/Core/Engine.h"
#include "Vajra/Engine/Input/Input.h"
#include "Vajra/Engine/SceneGraph/SceneGraph3D.h"
#include "Vajra/Engine/Tween/Tween.h"
#include "Vajra/Framework/DeviceUtils/FileSystemUtils/FileSystemUtils.h"
// Tween callbacks
void thiefTweenCallback(ObjectIdType gameObjectId , std::string /* tweenClipName */) {
GameObject* go = ENGINE->GetSceneGraph3D()->GetGameObjectById(gameObjectId);
ASSERT(go != nullptr, "Game object id passed into playerUnitNuumberTweenCallback is not valid");
if(go != nullptr) {
Thief* pUnit = go->GetComponent<Thief>();
ASSERT(pUnit != nullptr, "Game object passed into playerUnitNuumberTweenCallback doesn't have a player unit");
if(pUnit != nullptr) {
pUnit->onSpecialEnd();
}
}
}
void thiefNumberTweenCallback(float /* fromNumber */, float /* toNumber */, float currentNumber, std::string tweenClipName, MessageData1S1I1F* userParams) {
/*GameObject* go = ENGINE->GetSceneGraph3D()->GetGameObjectById(userParams->i);
ASSERT(go != nullptr, "Game object id passed into playerUnitNuumberTweenCallback is not valid");
if(go != nullptr) {
Thief* thief = go->GetComponent<Thief>();
ASSERT(thief != nullptr, "Game object passed into playerUnitNuumberTweenCallback doesn't have a player unit");
if(thief != nullptr) {
if(tweenClipName == "targetsIn") {
for(GameObject* go : thief->targetIndicators ) {
}
}
}
}*/
}
Thief::Thief() : PlayerUnit() {
this->init();
}
Thief::Thief(Object* object_) : PlayerUnit(object_) {
this->init();
}
Thief::~Thief() {
this->destroy();
}
void Thief::init() {
this->unitType = UnitType::UNIT_TYPE_THIEF;
}
void Thief::destroy() {
}
bool Thief::isSpecialTouch(int touchId) {
if(this->getTouchNearUnit()) {
Touch touch = ENGINE->GetInput()->GetTouch(touchId);
if(touch.timeDown >= GetFloatGameConstant(GAME_CONSTANT_long_press_length_in_seconds) && glm::distance(touch.pos, this->touchStartPos) <= GetFloatGameConstant(GAME_CONSTANT_allowed_finger_movement_in_press)) {
this->targetedCell = nullptr;
this->SetTouchIndicatorVisible(false);
this->updateLegalTagets();
return true;
}
}
return false;
}
void Thief::onSpecialTouch(int touchId) {
Touch touch = ENGINE->GetInput()->GetTouch(touchId);
if(touch.phase == TouchPhase::Ended) {
this->targetedCell = SINGLETONS->GetGridManager()->TouchPositionToCell(touch.pos);
if(std::find(this->legalTargets.begin(), this->legalTargets.end(), this->GetCurrentTouchedCell()) != this->legalTargets.end()) {
this->startSpecial();
} else {
this->targetedCell = this->gridNavRef->GetCurrentCell();
this->onSpecialEnd();
}
this->tweenOutTargets();
}
}
void Thief::startSpecial() {
PlayerUnit::startSpecial();
// Remove the indicator at the selected position
GameObject* selectedTargetIndicator = this->targetIndicators[this->targetedCell];
this->targetIndicators.erase(this->targetedCell);
delete selectedTargetIndicator;
this->SetTouchIndicatorCell(this->targetedCell);
this->startTouchIndicatorPulse();
this->SetTouchIndicatorSprite(THIEF_SPECIAL);
this->SetTouchIndicatorVisible(true);
ENGINE->GetTween()->TweenPosition(this->gameObjectRef->GetId(),
this->gameObjectRef->GetTransform()->GetPosition(),
this->targetedCell->center,
1.0f,
false,
TWEEN_TRANSLATION_CURVE_TYPE_PARABOLA,
false,
thiefTweenCallback);
}
void Thief::onSpecialEnd() {
PlayerUnit::onSpecialEnd();
this->gridNavRef->SetGridPosition(this->targetedCell);
}
void Thief::touchedCellChanged(GridCell* prevTouchedCell) {
if(this->inputState == InputState::INPUT_STATE_NAV) {
PlayerUnit::touchedCellChanged(prevTouchedCell);
} else {
if(this->targetIndicators[prevTouchedCell]) {
ENGINE->GetTween()->TweenScale(this->targetIndicators[prevTouchedCell]->GetId(), glm::vec3(GetFloatGameConstant(GAME_CONSTANT_target_indicator_scale_hover)),
glm::vec3(GetFloatGameConstant(GAME_CONSTANT_target_indicator_scale)),
GetFloatGameConstant(GAME_CONSTANT_target_tween_time));
}
if(this->targetIndicators[this->GetCurrentTouchedCell()]) {
ENGINE->GetTween()->TweenScale(this->targetIndicators[this->GetCurrentTouchedCell()]->GetId(), glm::vec3(GetFloatGameConstant(GAME_CONSTANT_target_indicator_scale)),
glm::vec3(GetFloatGameConstant(GAME_CONSTANT_target_indicator_scale_hover)),
GetFloatGameConstant(GAME_CONSTANT_target_tween_time));
}
if(std::find(this->legalTargets.begin(), this->legalTargets.end(), this->GetCurrentTouchedCell()) != this->legalTargets.end()) {
this->SetTouchIndicatorSprite(GOOD_TOUCH);
} else {
this->SetTouchIndicatorSprite(BAD_TOUCH);
}
}
}
void Thief::updateLegalTagets() {
this->legalTargets.clear();
this->deleteTargets();
GridCell* currentCell = this->gridNavRef->GetCurrentCell();
int elevation = SINGLETONS->GetGridManager()->GetGrid()->GetElevationFromWorldY(currentCell->center.y);
std::list<GridCell*> cellsInRange;
SINGLETONS->GetGridManager()->GetGrid()->GetNeighborCells(cellsInRange, this->gridNavRef->GetCurrentCell(),
GetFloatGameConstant(GAME_CONSTANT_jump_distance_in_units)
+ elevation * GetFloatGameConstant(GAME_CONSTANT_jump_elevation_multiplier));
for ( GridCell* c : cellsInRange) {
if(c->y == elevation) { // is the cell on the same height
if(this->gridNavRef->CanReachDestination(c, GetFloatGameConstant(GAME_CONSTANT_jump_distance_in_units)) && SINGLETONS->GetGridManager()->GetGrid()->HasLineOfSight(currentCell, c, elevation) ) {
this->legalTargets.push_back(c);
}
}
else if(c->y <= elevation + 1) { // is the cell below it
if(SINGLETONS->GetGridManager()->GetGrid()->IsCellPassableAtElevation(c->x, c->z, c->y)) {
float dist = glm::distance(c->origin, currentCell->origin);
if(dist <= GetFloatGameConstant(GAME_CONSTANT_jump_distance_in_units) + c->y * GetFloatGameConstant(GAME_CONSTANT_jump_elevation_multiplier)) {
this->legalTargets.push_back(c);
}
}
}
}
this->createTargets();
this->tweenInTargets();
}
void Thief::tweenInTargets() {
glm::vec3 pos;
for(auto contents : this->targetIndicators ) {
if(contents.second != nullptr) {
pos = contents.second->GetTransform()->GetPosition();
ENGINE->GetTween()->TweenPosition(contents.second->GetId(), pos, pos + glm::vec3(0.0f, GetFloatGameConstant(GAME_CONSTANT_target_indicator_offset), 0.0f), GetFloatGameConstant(GAME_CONSTANT_target_tween_time));
}
}
}
void Thief::tweenOutTargets() {
glm::vec3 pos;
for(auto contents : this->targetIndicators ) {
if(contents.second != nullptr) {
pos = contents.second->GetTransform()->GetPosition();
ENGINE->GetTween()->TweenScale(contents.second->GetId(), glm::vec3(GetFloatGameConstant(GAME_CONSTANT_target_indicator_scale)), glm::vec3(0), GetFloatGameConstant(GAME_CONSTANT_target_tween_time));
}
}
}
void Thief::createTargets() {
for( GridCell* c : this->legalTargets ) {
GameObject* indicator = new GameObject(ENGINE->GetSceneGraph3D());
SpriteRenderer* spriteRenderer = indicator->AddComponent<SpriteRenderer>();
std::vector<std::string> pathsToTextures;
pathsToTextures.push_back(FRAMEWORK->GetFileSystemUtils()->GetDevicePictureResourcesFolderName() + "SD_UIEffect_Thief_Jump_01.png");
spriteRenderer->initPlane(1.0f, 1.0f, "sptshdr", pathsToTextures, PlaneOrigin::Center);
indicator->GetTransform()->SetPosition(c->center);
indicator->GetTransform()->SetScale( glm::vec3(GetFloatGameConstant(GAME_CONSTANT_target_indicator_scale)));
indicator->GetTransform()->Translate(0.0f, YAXIS);
indicator->GetTransform()->Rotate(90.0f inRadians, XAXIS);
this->targetIndicators[c] = indicator;
}
}
void Thief::deleteTargets() {
for(auto contents : this->targetIndicators ) {
delete contents.second;
}
this->targetIndicators.clear();
}
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**************************************************************************/
#include "projectloadwizard.h"
#include "wizards/targetsetuppage.h"
#include "qt4project.h"
#include <QtGui/QCheckBox>
#include <QtGui/QHeaderView>
#include <QtGui/QLabel>
#include <QtGui/QVBoxLayout>
#include <QtGui/QWizardPage>
#include <QtGui/QApplication>
using namespace Qt4ProjectManager;
using namespace Qt4ProjectManager::Internal;
ProjectLoadWizard::ProjectLoadWizard(Qt4Project *project, QWidget *parent, Qt::WindowFlags flags)
: QWizard(parent, flags), m_project(project), m_targetSetupPage(0)
{
Q_ASSERT(project);
setWindowTitle(tr("Project Setup"));
setupTargetPage();
setOptions(options() | QWizard::NoBackButtonOnLastPage);
}
// We don't want to actually show the dialog if we don't show the import page
// We used to simply call ::exec() on the dialog
void ProjectLoadWizard::execDialog()
{
if (!pageIds().isEmpty()) {
QApplication::setOverrideCursor(QCursor(Qt::ArrowCursor));
exec();
QApplication::restoreOverrideCursor();
} else {
done(QDialog::Accepted);
}
}
ProjectLoadWizard::~ProjectLoadWizard()
{
}
void ProjectLoadWizard::done(int result)
{
QWizard::done(result);
// This normally happens on showing the final page, but since we
// don't show it anymore, do it here
if (result == Accepted)
applySettings();
}
void ProjectLoadWizard::setupTargetPage()
{
if (m_targetSetupPage)
return;
m_targetSetupPage = new TargetSetupPage(this);
m_targetSetupPage->setProFilePath(m_project->file()->fileName());
m_targetSetupPage->setImportSearch(true);
resize(900, 450);
addPage(m_targetSetupPage);
}
void ProjectLoadWizard::applySettings()
{
Q_ASSERT(m_targetSetupPage);
m_targetSetupPage->setupProject(m_project);
}
<commit_msg>Show wizard's cancel button even on Mac.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**************************************************************************/
#include "projectloadwizard.h"
#include "wizards/targetsetuppage.h"
#include "qt4project.h"
#include <QtGui/QCheckBox>
#include <QtGui/QHeaderView>
#include <QtGui/QLabel>
#include <QtGui/QVBoxLayout>
#include <QtGui/QWizardPage>
#include <QtGui/QApplication>
using namespace Qt4ProjectManager;
using namespace Qt4ProjectManager::Internal;
ProjectLoadWizard::ProjectLoadWizard(Qt4Project *project, QWidget *parent, Qt::WindowFlags flags)
: QWizard(parent, flags), m_project(project), m_targetSetupPage(0)
{
Q_ASSERT(project);
setWindowTitle(tr("Project Setup"));
setupTargetPage();
setOption(QWizard::NoBackButtonOnLastPage, true);
setOption(QWizard::NoCancelButton, false);
}
// We don't want to actually show the dialog if we don't show the import page
// We used to simply call ::exec() on the dialog
void ProjectLoadWizard::execDialog()
{
if (!pageIds().isEmpty()) {
QApplication::setOverrideCursor(QCursor(Qt::ArrowCursor));
exec();
QApplication::restoreOverrideCursor();
} else {
done(QDialog::Accepted);
}
}
ProjectLoadWizard::~ProjectLoadWizard()
{
}
void ProjectLoadWizard::done(int result)
{
QWizard::done(result);
// This normally happens on showing the final page, but since we
// don't show it anymore, do it here
if (result == Accepted)
applySettings();
}
void ProjectLoadWizard::setupTargetPage()
{
if (m_targetSetupPage)
return;
m_targetSetupPage = new TargetSetupPage(this);
m_targetSetupPage->setProFilePath(m_project->file()->fileName());
m_targetSetupPage->setImportSearch(true);
resize(900, 450);
addPage(m_targetSetupPage);
}
void ProjectLoadWizard::applySettings()
{
Q_ASSERT(m_targetSetupPage);
m_targetSetupPage->setupProject(m_project);
}
<|endoftext|> |
<commit_before>/*
* StringUtil.cpp
*
* Copyright 2002, Log4cpp Project. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#include "StringUtil.hh"
#include <iterator>
#include <stdio.h>
#if defined(_MSC_VER)
#define VSNPRINTF _vsnprintf
#else
#ifdef LOG4CPP_HAVE_SNPRINTF
#define VSNPRINTF vsnprintf
#else
/* use alternative snprintf() from http://www.ijs.si/software/snprintf/ */
#define HAVE_SNPRINTF
#define PREFER_PORTABLE_SNPRINTF
#include <stdlib.h>
#include <stdarg.h>
extern "C" {
#include "snprintf.c"
}
#define VSNPRINTF portable_vsnprintf
#endif // LOG4CPP_HAVE_SNPRINTF
#endif // _MSC_VER
namespace log4cpp {
std::string StringUtil::vform(const char* format, va_list args) {
size_t size = 1024;
char* buffer = new char[size];
while (1) {
int n = VSNPRINTF(buffer, size, format, args);
// If that worked, return a string.
if ((n > -1) && (static_cast<size_t>(n) < size)) {
std::string s(buffer);
delete [] buffer;
return s;
}
// Else try again with more space.
size = (n > -1) ?
n + 1 : // ISO/IEC 9899:1999
size * 2; // twice the old size
delete [] buffer;
buffer = new char[size];
}
}
std::string StringUtil::trim(const std::string& s) {
// test for null string
if(s.empty())
return s;
// find first non-space character
std::string::size_type b = s.find_first_not_of(" \t");
if(b == std::string::npos) // No non-spaces
return "";
// find last non-space character
std::string::size_type e = s.find_last_not_of(" \t");
// return the remaining characters
return std::string(s, b, e - b + 1);
}
unsigned int StringUtil::split(std::vector<std::string>& v,
const std::string& s,
char delimiter, unsigned int maxSegments) {
v.clear();
std::back_insert_iterator<std::vector<std::string> > it(v);
return split(it, s, delimiter, maxSegments);
}
}
<commit_msg>added \r and \n to whitespace characters.<commit_after>/*
* StringUtil.cpp
*
* Copyright 2002, Log4cpp Project. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#include "StringUtil.hh"
#include <iterator>
#include <stdio.h>
#if defined(_MSC_VER)
#define VSNPRINTF _vsnprintf
#else
#ifdef LOG4CPP_HAVE_SNPRINTF
#define VSNPRINTF vsnprintf
#else
/* use alternative snprintf() from http://www.ijs.si/software/snprintf/ */
#define HAVE_SNPRINTF
#define PREFER_PORTABLE_SNPRINTF
#include <stdlib.h>
#include <stdarg.h>
extern "C" {
#include "snprintf.c"
}
#define VSNPRINTF portable_vsnprintf
#endif // LOG4CPP_HAVE_SNPRINTF
#endif // _MSC_VER
namespace log4cpp {
std::string StringUtil::vform(const char* format, va_list args) {
size_t size = 1024;
char* buffer = new char[size];
while (1) {
int n = VSNPRINTF(buffer, size, format, args);
// If that worked, return a string.
if ((n > -1) && (static_cast<size_t>(n) < size)) {
std::string s(buffer);
delete [] buffer;
return s;
}
// Else try again with more space.
size = (n > -1) ?
n + 1 : // ISO/IEC 9899:1999
size * 2; // twice the old size
delete [] buffer;
buffer = new char[size];
}
}
std::string StringUtil::trim(const std::string& s) {
static const char* whiteSpace = " \t\r\n";
// test for null string
if(s.empty())
return s;
// find first non-space character
std::string::size_type b = s.find_first_not_of(whiteSpace);
if(b == std::string::npos) // No non-spaces
return "";
// find last non-space character
std::string::size_type e = s.find_last_not_of(whiteSpace);
// return the remaining characters
return std::string(s, b, e - b + 1);
}
unsigned int StringUtil::split(std::vector<std::string>& v,
const std::string& s,
char delimiter, unsigned int maxSegments) {
v.clear();
std::back_insert_iterator<std::vector<std::string> > it(v);
return split(it, s, delimiter, maxSegments);
}
}
<|endoftext|> |
<commit_before>// Copyright 2010-2018 Google LLC
// 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.
// Linear programming example that shows how to use the API.
#include "ortools/base/commandlineflags.h"
#include "ortools/base/logging.h"
#include "ortools/linear_solver/linear_solver.h"
#include "ortools/linear_solver/linear_solver.pb.h"
namespace operations_research {
void RunLinearProgrammingExample(const std::string& optimization_problem_type) {
LOG(INFO) << "---- Linear programming example with "
<< optimization_problem_type << " ----";
if (!MPSolver::ParseAndCheckSupportForProblemType(
optimization_problem_type)) {
LOG(INFO) << " support for solver not linked in.";
return;
}
MPSolver solver("IntegerProgrammingExample",
MPSolver::ParseSolverTypeOrDie(optimization_problem_type));
const double infinity = solver.infinity();
// x1, x2 and x3 are continuous non-negative variables.
MPVariable* const x1 = solver.MakeNumVar(0.0, infinity, "x1");
MPVariable* const x2 = solver.MakeNumVar(0.0, infinity, "x2");
MPVariable* const x3 = solver.MakeNumVar(0.0, infinity, "x3");
// Maximize 10 * x1 + 6 * x2 + 4 * x3.
MPObjective* const objective = solver.MutableObjective();
objective->SetCoefficient(x1, 10);
objective->SetCoefficient(x2, 6);
objective->SetCoefficient(x3, 4);
objective->SetMaximization();
// x1 + x2 + x3 <= 100.
MPConstraint* const c0 = solver.MakeRowConstraint(-infinity, 100.0);
c0->SetCoefficient(x1, 1);
c0->SetCoefficient(x2, 1);
c0->SetCoefficient(x3, 1);
// 10 * x1 + 4 * x2 + 5 * x3 <= 600.
MPConstraint* const c1 = solver.MakeRowConstraint(-infinity, 600.0);
c1->SetCoefficient(x1, 10);
c1->SetCoefficient(x2, 4);
c1->SetCoefficient(x3, 5);
// 2 * x1 + 2 * x2 + 6 * x3 <= 300.
MPConstraint* const c2 = solver.MakeRowConstraint(-infinity, 300.0);
c2->SetCoefficient(x1, 2);
c2->SetCoefficient(x2, 2);
c2->SetCoefficient(x3, 6);
// TODO(user): Change example to show = and >= constraints.
LOG(INFO) << "Number of variables = " << solver.NumVariables();
LOG(INFO) << "Number of constraints = " << solver.NumConstraints();
const MPSolver::ResultStatus result_status = solver.Solve();
// Check that the problem has an optimal solution.
if (result_status != MPSolver::OPTIMAL) {
LOG(FATAL) << "The problem does not have an optimal solution!";
}
LOG(INFO) << "Problem solved in " << solver.wall_time() << " milliseconds";
// The objective value of the solution.
LOG(INFO) << "Optimal objective value = " << objective->Value();
// The value of each variable in the solution.
LOG(INFO) << "x1 = " << x1->solution_value();
LOG(INFO) << "x2 = " << x2->solution_value();
LOG(INFO) << "x3 = " << x3->solution_value();
LOG(INFO) << "Advanced usage:";
LOG(INFO) << "Problem solved in " << solver.iterations() << " iterations";
LOG(INFO) << "x1: reduced cost = " << x1->reduced_cost();
LOG(INFO) << "x2: reduced cost = " << x2->reduced_cost();
LOG(INFO) << "x3: reduced cost = " << x3->reduced_cost();
const std::vector<double> activities = solver.ComputeConstraintActivities();
LOG(INFO) << "c0: dual value = " << c0->dual_value()
<< " activity = " << activities[c0->index()];
LOG(INFO) << "c1: dual value = " << c1->dual_value()
<< " activity = " << activities[c1->index()];
LOG(INFO) << "c2: dual value = " << c2->dual_value()
<< " activity = " << activities[c2->index()];
}
void RunAllExamples() {
RunLinearProgrammingExample("GLOP");
RunLinearProgrammingExample("CLP");
RunLinearProgrammingExample("SAT");
RunLinearProgrammingExample("SCIP");
RunLinearProgrammingExample("GUROBI_LP");
RunLinearProgrammingExample("CPLEX_LP");
RunLinearProgrammingExample("GLPK_LP");
RunLinearProgrammingExample("XPRESS_LP");
}
} // namespace operations_research
int main(int argc, char** argv) {
google::InitGoogleLogging(argv[0]);
absl::SetFlag(&FLAGS_logtostderr, true);
absl::SetFlag(&FLAGS_log_prefix, false);
gflags::ParseCommandLineFlags(&argc, &argv, true);
operations_research::RunAllExamples();
return EXIT_SUCCESS;
}
<commit_msg>example: Remove uneeded test<commit_after>// Copyright 2010-2018 Google LLC
// 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.
// Linear programming example that shows how to use the API.
#include "ortools/base/commandlineflags.h"
#include "ortools/base/logging.h"
#include "ortools/linear_solver/linear_solver.h"
#include "ortools/linear_solver/linear_solver.pb.h"
namespace operations_research {
void RunLinearProgrammingExample(const std::string& optimization_problem_type) {
LOG(INFO) << "---- Linear programming example with "
<< optimization_problem_type << " ----";
if (!MPSolver::ParseAndCheckSupportForProblemType(
optimization_problem_type)) {
LOG(INFO) << " support for solver not linked in.";
return;
}
MPSolver solver("IntegerProgrammingExample",
MPSolver::ParseSolverTypeOrDie(optimization_problem_type));
const double infinity = solver.infinity();
// x1, x2 and x3 are continuous non-negative variables.
MPVariable* const x1 = solver.MakeNumVar(0.0, infinity, "x1");
MPVariable* const x2 = solver.MakeNumVar(0.0, infinity, "x2");
MPVariable* const x3 = solver.MakeNumVar(0.0, infinity, "x3");
// Maximize 10 * x1 + 6 * x2 + 4 * x3.
MPObjective* const objective = solver.MutableObjective();
objective->SetCoefficient(x1, 10);
objective->SetCoefficient(x2, 6);
objective->SetCoefficient(x3, 4);
objective->SetMaximization();
// x1 + x2 + x3 <= 100.
MPConstraint* const c0 = solver.MakeRowConstraint(-infinity, 100.0);
c0->SetCoefficient(x1, 1);
c0->SetCoefficient(x2, 1);
c0->SetCoefficient(x3, 1);
// 10 * x1 + 4 * x2 + 5 * x3 <= 600.
MPConstraint* const c1 = solver.MakeRowConstraint(-infinity, 600.0);
c1->SetCoefficient(x1, 10);
c1->SetCoefficient(x2, 4);
c1->SetCoefficient(x3, 5);
// 2 * x1 + 2 * x2 + 6 * x3 <= 300.
MPConstraint* const c2 = solver.MakeRowConstraint(-infinity, 300.0);
c2->SetCoefficient(x1, 2);
c2->SetCoefficient(x2, 2);
c2->SetCoefficient(x3, 6);
// TODO(user): Change example to show = and >= constraints.
LOG(INFO) << "Number of variables = " << solver.NumVariables();
LOG(INFO) << "Number of constraints = " << solver.NumConstraints();
const MPSolver::ResultStatus result_status = solver.Solve();
// Check that the problem has an optimal solution.
if (result_status != MPSolver::OPTIMAL) {
LOG(FATAL) << "The problem does not have an optimal solution!";
}
LOG(INFO) << "Problem solved in " << solver.wall_time() << " milliseconds";
// The objective value of the solution.
LOG(INFO) << "Optimal objective value = " << objective->Value();
// The value of each variable in the solution.
LOG(INFO) << "x1 = " << x1->solution_value();
LOG(INFO) << "x2 = " << x2->solution_value();
LOG(INFO) << "x3 = " << x3->solution_value();
LOG(INFO) << "Advanced usage:";
LOG(INFO) << "Problem solved in " << solver.iterations() << " iterations";
LOG(INFO) << "x1: reduced cost = " << x1->reduced_cost();
LOG(INFO) << "x2: reduced cost = " << x2->reduced_cost();
LOG(INFO) << "x3: reduced cost = " << x3->reduced_cost();
const std::vector<double> activities = solver.ComputeConstraintActivities();
LOG(INFO) << "c0: dual value = " << c0->dual_value()
<< " activity = " << activities[c0->index()];
LOG(INFO) << "c1: dual value = " << c1->dual_value()
<< " activity = " << activities[c1->index()];
LOG(INFO) << "c2: dual value = " << c2->dual_value()
<< " activity = " << activities[c2->index()];
}
void RunAllExamples() {
RunLinearProgrammingExample("GLOP");
RunLinearProgrammingExample("CLP");
RunLinearProgrammingExample("GUROBI_LP");
RunLinearProgrammingExample("CPLEX_LP");
RunLinearProgrammingExample("GLPK_LP");
RunLinearProgrammingExample("XPRESS_LP");
}
} // namespace operations_research
int main(int argc, char** argv) {
google::InitGoogleLogging(argv[0]);
absl::SetFlag(&FLAGS_logtostderr, true);
absl::SetFlag(&FLAGS_log_prefix, false);
gflags::ParseCommandLineFlags(&argc, &argv, true);
operations_research::RunAllExamples();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#pragma once
// C++ standard library
#include <string>
#include <memory>
#include <unordered_map>
// Armadillo
#include <armadillo>
// Mantella
#include "mantella_bits/optimisationProblem/surrogateModel.hpp"
#include "mantella_bits/regressionFunction.hpp"
#include "mantella_bits/correlationFunction.hpp"
#include "mantella_bits/helper/unorderedContainer.hpp"
// IWYU pragma: no_forward_declare mant::Hash
// IWYU pragma: no_forward_declare mant::IsEqual
}
namespace mant {
class KrigingModel : public SurrogateModel {
public:
const std::shared_ptr<RegressionFunction> regressionFunction_;
const std::shared_ptr<CorrelationFunction> correlationFunction_;
KrigingModel(
const std::unordered_map<arma::Col<double>, double, Hash, IsEqual>& samples,
const std::shared_ptr<RegressionFunction> regressionFunction,
const std::shared_ptr<CorrelationFunction> correlationFunction);
std::string toString() const override;
protected:
arma::Col<double> meanParameter_;
arma::Col<double> standardDeviationParameter_;
double meanObjectiveValue_;
double standardDeviationObjectiveValue_;
arma::Col<double> beta_;
arma::Col<double> gamma_;
void modelImplementation() override;
double getObjectiveValueImplementation(
const arma::Col<double>& parameter) const final;
};
}
<commit_msg>Fixed extraneous closing brace<commit_after>#pragma once
// C++ standard library
#include <string>
#include <memory>
#include <unordered_map>
// Armadillo
#include <armadillo>
// Mantella
#include "mantella_bits/optimisationProblem/surrogateModel.hpp"
#include "mantella_bits/regressionFunction.hpp"
#include "mantella_bits/correlationFunction.hpp"
#include "mantella_bits/helper/unorderedContainer.hpp"
// IWYU pragma: no_forward_declare mant::Hash
// IWYU pragma: no_forward_declare mant::IsEqual
namespace mant {
class KrigingModel : public SurrogateModel {
public:
const std::shared_ptr<RegressionFunction> regressionFunction_;
const std::shared_ptr<CorrelationFunction> correlationFunction_;
KrigingModel(
const std::unordered_map<arma::Col<double>, double, Hash, IsEqual>& samples,
const std::shared_ptr<RegressionFunction> regressionFunction,
const std::shared_ptr<CorrelationFunction> correlationFunction);
std::string toString() const override;
protected:
arma::Col<double> meanParameter_;
arma::Col<double> standardDeviationParameter_;
double meanObjectiveValue_;
double standardDeviationObjectiveValue_;
arma::Col<double> beta_;
arma::Col<double> gamma_;
void modelImplementation() override;
double getObjectiveValueImplementation(
const arma::Col<double>& parameter) const final;
};
}
<|endoftext|> |
<commit_before>
#include "Translator.hpp"
/* TRANSLATOR GROUP */
TranslatorGroup::~TranslatorGroup(){
clear();
}
void TranslatorGroup::clear(){
std::map<std::string, TranslatorGroup*>::iterator it = els.begin();
while(it != els.end()){
delete it->second;
it++;
}
}
void TranslatorGroup::set(const std::string& key, TranslatorGroup* el){
std::map<std::string, TranslatorGroup*>::iterator it = els.find(key);
if(it != els.end()){
delete it->second;
els.erase(it);
}
els.insert(std::pair<std::string, TranslatorGroup*>(key, el));
}
TranslatorGroup* TranslatorGroup::get(const std::string& key){
std::map<std::string, TranslatorGroup*>::iterator it = els.find(key);
if(it != els.end())
return it->second;
else
return NULL;
}
/* TRANSLATOR */
void Translator::buildPath(const std::string& path, std::vector<std::string>& cpath){
//parse path
std::string tmp;
for(int i = 0; i < path.size(); i++){
const char& c = path[i];
bool end = (i == path.size()-1);
if(c == '.'){
cpath.push_back(tmp);
tmp ="";
}
else if(end){
tmp += c;
cpath.push_back(tmp);
}
else
tmp += c;
}
}
bool Translator::has(const std::string& path){
//build path
std::vector<std::string> cpath;
buildPath(path, cpath);
//explode groups
TranslatorGroup* current = &root;
int i = 0;
while(current != NULL && i < cpath.size()){
current = current->get(cpath[i]);
i++;
}
return (cpath.size() && current != NULL && current->els.size() > 0
&& current->els.begin()->second == NULL);
}
const std::string& Translator::get(const std::string& path){
//build path
std::vector<std::string> cpath;
buildPath(path, cpath);
//explode groups
TranslatorGroup* current = &root;
int i = 0;
while(current != NULL && i < cpath.size()){
current = current->get(cpath[i]);
i++;
}
//search the value
if(cpath.size() && current != NULL && current->els.size() > 0
&& current->els.begin()->second == NULL)
return current->els.begin()->first;
else
return path;
}
bool Translator::hasTrans(const std::string& path){
//build path
std::vector<std::string> cpath;
buildPath(path, cpath);
//check all first domain of translation
std::map<std::string, TranslatorGroup*>::iterator it = root.els.begin();
while(it != root.els.end()){
//explode groups
TranslatorGroup* current = it->second;
int i = 0;
while(current != NULL && i < cpath.size()){
current = current->get(cpath[i]);
i++;
}
return (cpath.size() && current != NULL && current->els.size() > 0
&& current->els.begin()->second == NULL);
}
return false;
}
std::string Translator::trans(const std::string& path){
if(has(locale+"."+path))
return get(locale+"."+path);
else if(has("all."+path))
return get("all."+path);
else
return path;
}
void Translator::set(const std::string& path, const std::string& value){
//build path
std::vector<std::string> cpath;
buildPath(path, cpath);
//explode groups
TranslatorGroup* current = &root;
for(int i = 0; i < cpath.size(); i++){
TranslatorGroup* next = current->get(cpath[i]);
//create a new group or delete if last
if(next == NULL || (i == cpath.size()-1)){
next = new TranslatorGroup;
current->set(cpath[i], next);
}
current = next;
}
//set the value
current->set(value, NULL);
}
void Translator::parse(const std::string& data){
std::string path;
std::string tmp;
std::string id;
const int ID = 0;
const int VAL = 1;
std::string prev_id;
int mode = ID;
int prev_rank = 0;
int rank = 0;
bool ranked = false;
std::vector<std::string> lifo;
for(int i = 0; i < data.size(); i++){
const char& c = data[i];
bool end = (i == data.size()-1);
if(mode == ID){
//new line, end id
if(c == '\n' || c == '='){
//id not null
if(tmp.size() > 0){
//a value
if(c == '='){
id = tmp;
mode = VAL;
}
//rank explode
//go highter
if(rank > prev_rank){
path += prev_id;
path += ".";
lifo.push_back(prev_id);
}
//go lower
else if(rank < prev_rank){
if(lifo.size() > 0)
prev_id = lifo[lifo.size()-1];
path = path.substr(0, path.size()-prev_id.size()-1);
lifo.pop_back();
}
if(mode == ID)
prev_id = tmp;
prev_rank = rank;
ranked = false;
rank = 0;
tmp = "";
}
}
else if(c == ' ' || c == '\t'){
//update rank
if(!ranked)
rank++;
}
else{
if(!ranked)
ranked = true;
tmp += c;
}
}
else if(mode == VAL){
//new value, go back to id mode
if(c == '\n'){
set(path+id, tmp);
tmp ="";
mode = ID;
}
else
tmp += c;
}
}
}
void Translator::load(const std::string& data){
parse(data);
}
bool Translator::loadFromFile(const std::string& path){
std::ifstream file(path.c_str(), std::ios::binary);
std::string data;
if(file){
//get content
data.assign(std::istreambuf_iterator<char>(file),std::istreambuf_iterator<char>());
parse(data);
return true;
}
else
return false;
}
<commit_msg>fixe translator all bug<commit_after>
#include "Translator.hpp"
/* TRANSLATOR GROUP */
TranslatorGroup::~TranslatorGroup(){
clear();
}
void TranslatorGroup::clear(){
std::map<std::string, TranslatorGroup*>::iterator it = els.begin();
while(it != els.end()){
delete it->second;
it++;
}
}
void TranslatorGroup::set(const std::string& key, TranslatorGroup* el){
std::map<std::string, TranslatorGroup*>::iterator it = els.find(key);
if(it != els.end()){
delete it->second;
els.erase(it);
}
els.insert(std::pair<std::string, TranslatorGroup*>(key, el));
}
TranslatorGroup* TranslatorGroup::get(const std::string& key){
std::map<std::string, TranslatorGroup*>::iterator it = els.find(key);
if(it != els.end())
return it->second;
else
return NULL;
}
/* TRANSLATOR */
void Translator::buildPath(const std::string& path, std::vector<std::string>& cpath){
//parse path
std::string tmp;
for(int i = 0; i < path.size(); i++){
const char& c = path[i];
bool end = (i == path.size()-1);
if(c == '.'){
cpath.push_back(tmp);
tmp ="";
}
else if(end){
tmp += c;
cpath.push_back(tmp);
}
else
tmp += c;
}
}
bool Translator::has(const std::string& path){
//build path
std::vector<std::string> cpath;
buildPath(path, cpath);
//explode groups
TranslatorGroup* current = &root;
int i = 0;
while(current != NULL && i < cpath.size()){
current = current->get(cpath[i]);
i++;
}
return (i == cpath.size() && current != NULL && current->els.size() > 0
&& current->els.begin()->second == NULL);
}
const std::string& Translator::get(const std::string& path){
//build path
std::vector<std::string> cpath;
buildPath(path, cpath);
//explode groups
TranslatorGroup* current = &root;
int i = 0;
while(current != NULL && i < cpath.size()){
current = current->get(cpath[i]);
i++;
}
//search the value
if(i == cpath.size() && current != NULL && current->els.size() > 0
&& current->els.begin()->second == NULL)
return current->els.begin()->first;
else
return path;
}
bool Translator::hasTrans(const std::string& path){
//build path
std::vector<std::string> cpath;
buildPath(path, cpath);
//check all first domain of translation
std::map<std::string, TranslatorGroup*>::iterator it = root.els.begin();
while(it != root.els.end()){
//explode groups
TranslatorGroup* current = it->second;
int i = 0;
while(current != NULL && i < cpath.size()){
current = current->get(cpath[i]);
i++;
}
return (i == cpath.size() && current != NULL && current->els.size() > 0
&& current->els.begin()->second == NULL);
}
return false;
}
std::string Translator::trans(const std::string& path){
if(has(locale+"."+path))
return get(locale+"."+path);
else if(has("all."+path))
return get("all."+path);
else
return path;
}
void Translator::set(const std::string& path, const std::string& value){
//build path
std::vector<std::string> cpath;
buildPath(path, cpath);
//explode groups
TranslatorGroup* current = &root;
for(int i = 0; i < cpath.size(); i++){
TranslatorGroup* next = current->get(cpath[i]);
//create a new group or delete if last
if(next == NULL || (i == cpath.size()-1)){
next = new TranslatorGroup;
current->set(cpath[i], next);
}
current = next;
}
//set the value
current->set(value, NULL);
}
void Translator::parse(const std::string& data){
std::string path;
std::string tmp;
std::string id;
const int ID = 0;
const int VAL = 1;
std::string prev_id;
int mode = ID;
int prev_rank = 0;
int rank = 0;
bool ranked = false;
std::vector<std::string> lifo;
for(int i = 0; i < data.size(); i++){
const char& c = data[i];
bool end = (i == data.size()-1);
if(mode == ID){
//new line, end id
if(c == '\n' || c == '='){
//id not null
if(tmp.size() > 0){
//a value
if(c == '='){
id = tmp;
mode = VAL;
}
//rank explode
//go highter
if(rank > prev_rank){
path += prev_id;
path += ".";
lifo.push_back(prev_id);
}
//go lower
else if(rank < prev_rank){
if(lifo.size() > 0)
prev_id = lifo[lifo.size()-1];
path = path.substr(0, path.size()-prev_id.size()-1);
lifo.pop_back();
}
if(mode == ID)
prev_id = tmp;
prev_rank = rank;
ranked = false;
rank = 0;
tmp = "";
}
}
else if(c == ' ' || c == '\t'){
//update rank
if(!ranked)
rank++;
}
else{
if(!ranked)
ranked = true;
tmp += c;
}
}
else if(mode == VAL){
//new value, go back to id mode
if(c == '\n'){
set(path+id, tmp);
tmp ="";
mode = ID;
}
else
tmp += c;
}
}
}
void Translator::load(const std::string& data){
parse(data);
}
bool Translator::loadFromFile(const std::string& path){
std::ifstream file(path.c_str(), std::ios::binary);
std::string data;
if(file){
//get content
data.assign(std::istreambuf_iterator<char>(file),std::istreambuf_iterator<char>());
parse(data);
return true;
}
else
return false;
}
<|endoftext|> |
<commit_before>/* Created and copyrighted by Kevin D. Sidwar. Offered as open source under the MIT License (MIT). */
#include "UartSerial.h"
#include <sys/ioctl.h>
#include <unistd.h>
#include <fcntl.h>
#include <climits>
#include <cstdlib>
#include <cstring>
using namespace remote_wiring::transport;
using namespace std;
UartSerial::UartSerial (
const char * device_
) :
_bytesAvailableCallback(nullptr),
_bytes_available_context(nullptr),
_poll_thread(),
_polling(false),
_polling_file_descriptor{0},
_serial_device_path(nullptr),
_serial_file_descriptor(-1),
_tio_config{0},
_tio_config_original{0}
{
int len = ::strnlen(device_, PATH_MAX);
if ( 0 == len ) {
::perror("UartSerial::UartSerial - Invalid file serial device path");
} else if ( NULL == (_serial_device_path = (char *)::malloc(len + 1))) {
::perror("UartSerial::UartSerial - Unable to allocate memory to store serial device path");
} else {
::strncpy(_serial_device_path, device_, len);
_serial_device_path[len] = '\0';
}
}
UartSerial::~UartSerial (
void
) {
//TODO: Allow `end()` to be called more than once.
::free(_serial_device_path);
}
size_t
UartSerial::available (
void
) {
size_t num_bytes_available = 0;
if ( -1 == _serial_file_descriptor ) {
::perror("UartSerial::available - Invalid file descriptor");
} else if ( -1 == ::ioctl(_serial_file_descriptor, FIONREAD, &num_bytes_available) ) {
::perror("UartSerial::available - `ioctl()` request failed");
num_bytes_available = 0;
}
return num_bytes_available;
}
void
UartSerial::begin (
const uint32_t speed_,
const size_t config_
) {
// Scrubbed parameters
speed_t baud_rate = B0;
size_t c_cflags = (size_t)-1;
// Interpret common baud rates
switch (speed_) {
case 300: baud_rate = B300; break;
case 600: baud_rate = B600; break;
case 1200: baud_rate = B1200; break;
case 2400: baud_rate = B2400; break;
case 4800: baud_rate = B4800; break;
case 9600: baud_rate = B9600; break;
case 14400: break;
case 19200: baud_rate = B19200; break;
case 28800: break;
case 38400: baud_rate = B38400; break;
case 57600: baud_rate = B57600; break;
case 115200: baud_rate = B115200; break;
default: break;
}
switch (config_) {
case SERIAL_5E1:
case SERIAL_5E2:
case SERIAL_5N1:
case SERIAL_5N2:
case SERIAL_5O1:
case SERIAL_5O2:
case SERIAL_6E1:
case SERIAL_6E2:
case SERIAL_6N1:
case SERIAL_6N2:
case SERIAL_6O1:
case SERIAL_6O2:
case SERIAL_7E1:
case SERIAL_7E2:
case SERIAL_7N1:
case SERIAL_7N2:
case SERIAL_7O1:
case SERIAL_7O2:
case SERIAL_8E1:
case SERIAL_8E2:
case SERIAL_8N1:
case SERIAL_8N2:
case SERIAL_8O1:
case SERIAL_8O2:
c_cflags = config_;
default: break;
}
// Validate baud rate
if ( B0 == baud_rate ) {
::perror("UartSerial::begin - Unsupported baud rate");
// Validate configuration flags
} else if ( (size_t)-1 == c_cflags ) {
::perror("UartSerial::begin - Unsupported configuration");
// Attempt to open the device
} else if ( 0 > (_serial_file_descriptor = ::open(_serial_device_path, (O_RDWR | O_NOCTTY | O_NONBLOCK))) ) {
::perror(_serial_device_path);
// Confirm file descriptor is a TTY device
} else if ( 0 == ::isatty(_serial_file_descriptor) ) {
::perror("UartSerial::begin - File descriptor is not a TTY device");
if ( 0 != cleanupSerialFileDescriptor() ) {
::perror("UartSerial::begin - Unable to close serial file descriptor");
}
// Save current device settings
} else if ( 0 != ::tcgetattr(_serial_file_descriptor, &_tio_config_original) ) {
::perror("UartSerial::begin - Unable to save current term attributes");
if ( 0 != cleanupSerialFileDescriptor() ) {
::perror("UartSerial::begin - Unable to close serial file descriptor");
}
// Flush all current i/o data before enabling the new configuration
} else if ( 0 != ::tcflush(_serial_file_descriptor, TCIOFLUSH) ) {
::perror("UartSerial::begin - Unable to flush file descriptor");
if ( 0 != cleanupSerialFileDescriptor() ) {
::perror("UartSerial::begin - Unable to close serial file descriptor");
}
} else {
// Configure the termios structure. See termios man page for further info
// http://man7.org/linux/man-pages/man3/termios.3.html
_tio_config = _tio_config_original;
// c_iflag - input modes
// Leave all input flags unset
// c_oflag - output modes
// Leave all output flags unset
// c_cflag - control modes
_tio_config.c_cflag |= CS8; //TODO: Configuration passed by caller
_tio_config.c_cflag |= CREAD; // Enable receiver
_tio_config.c_cflag |= CLOCAL; // Ignore modem control lines
_tio_config.c_cflag |= HUPCL; // Enable hang-up on close
// c_lflag - local modes
// Leave all local mode flags unset. This enables noncanonical mode input.
// c_cc - special characters
// The following combination of VTIME and VMIN will result in a polling
// read. If data is available a call to read() returns immediately. If
// no data is available a call to read() returns 0.
_tio_config.c_cc[VTIME] = 0;
_tio_config.c_cc[VMIN] = 0;
// Update configuration
if ( 0 != ::cfsetspeed(&_tio_config, baud_rate) ) {
::perror("UartSerial::begin - Unable to set baud rate");
if ( 0 != cleanupSerialFileDescriptor() ) {
::perror("UartSerial::begin - Unable to close serial file descriptor");
}
// Enable new term configuration
} else if ( 0 != ::tcsetattr(_serial_file_descriptor, TCSANOW, &_tio_config) ) {
::perror("UartSerial::begin - Unable to set term attributes");
if ( 0 != cleanupSerialFileDescriptor() ) {
::perror("UartSerial::begin - Unable to close serial file descriptor");
}
}
}
}
int
UartSerial::cleanupSerialFileDescriptor (
void
) {
int error;
if ( 0 != ::close(_serial_file_descriptor) ) {
error = 0x1;
} else {
_serial_file_descriptor = -1;
error = 0x0;
}
return error;
}
void
UartSerial::end (
void
) {
if ( -1 == _serial_file_descriptor ) {
// `end()` has already been called, no action required
} else {
flush();
// Shut down the poll() thread
_polling = false;
_poll_thread.join();
// Restore the original settings and close the descriptor
if ( 0 != ::tcsetattr(_serial_file_descriptor, TCSANOW, &_tio_config_original) ) {
::perror("UartSerial::end - Unable to restore term attributes");
if ( 0 != cleanupSerialFileDescriptor() ) {
::perror("UartSerial::end - Unable to close serial file descriptor");
}
}
}
}
void
UartSerial::flush (
void
) {
if ( -1 == _serial_file_descriptor ) {
::perror("UartSerial::flush - Invalid file descriptor");
} else if ( 0 != ::tcdrain(_serial_file_descriptor) ) {
::perror("UartSerial::flush - Unable to flush the serial buffer");
}
}
void
UartSerial::pollForSerialData (
void
) {
const int timeout_ms = 0;
while ( _polling ) {
switch ( ::poll(&_polling_file_descriptor, 1, timeout_ms) ) {
case -1: // error
::perror("UartSerial::pollForSerialData - Polling error occurred");
break;
case 0: // timeout
// Release control back to the CPU
this_thread::sleep_for(std::chrono::seconds(0));
break;
default:
if ( _polling_file_descriptor.revents & POLLIN ) {
_bytesAvailableCallback(_bytes_available_context);
} else {
// Release control back to the CPU
this_thread::sleep_for(std::chrono::seconds(0));
}
}
}
}
int
UartSerial::read (
void
) {
int buffer;
if ( -1 == _serial_file_descriptor ) {
::perror("UartSerial::read - Invalid file descriptor");
buffer = -1;
} else if ( 0 == ::read(_serial_file_descriptor, &buffer, 1) ) {
buffer = -1;
} else {
buffer &= 0xFF;
}
return buffer;
}
void
UartSerial::registerSerialEventCallback (
serialEvent bytes_available_,
void * context_
) {
if ( bytes_available_ == nullptr ) {
::perror("UartSerial::registerSerialEventCallback - Invalid function pointer");
} else if ( -1 == _serial_file_descriptor ) {
::perror("UartSerial::registerSerialEventCallback - Invalid file descriptor");
} else if ( nullptr != _bytesAvailableCallback ) {
::perror("UartSerial::registerSerialEventCallback - A callback has already been registered");
} else {
_bytesAvailableCallback = bytes_available_;
_bytes_available_context = context_;
// Setup poll struct
_polling_file_descriptor.fd = _serial_file_descriptor;
_polling_file_descriptor.events = POLLIN;
_polling = true;
_poll_thread = std::thread(&UartSerial::pollForSerialData, this);
}
}
void
UartSerial::write (
uint8_t byte_
) {
if ( -1 == _serial_file_descriptor ) {
::perror("UartSerial::write - Invalid file descriptor");
} else if ( 0 > ::write(_serial_file_descriptor, &byte_, 1) ) {
::perror("UartSerial::write - Unable to write data");
}
}
/* Created and copyrighted by Kevin D. Sidwar. Offered as open source under the MIT License (MIT). */
<commit_msg>Fix #4 - multiple calls to end()<commit_after>/* Created and copyrighted by Kevin D. Sidwar. Offered as open source under the MIT License (MIT). */
#include "UartSerial.h"
#include <sys/ioctl.h>
#include <unistd.h>
#include <fcntl.h>
#include <climits>
#include <cstdlib>
#include <cstring>
using namespace remote_wiring::transport;
using namespace std;
UartSerial::UartSerial (
const char * device_
) :
_bytesAvailableCallback(nullptr),
_bytes_available_context(nullptr),
_poll_thread(),
_polling(false),
_polling_file_descriptor{0},
_serial_device_path(nullptr),
_serial_file_descriptor(-1),
_tio_config{0},
_tio_config_original{0}
{
int len = ::strnlen(device_, PATH_MAX);
if ( 0 == len ) {
::perror("UartSerial::UartSerial - Invalid file serial device path");
} else if ( NULL == (_serial_device_path = (char *)::malloc(len + 1))) {
::perror("UartSerial::UartSerial - Unable to allocate memory to store serial device path");
} else {
::strncpy(_serial_device_path, device_, len);
_serial_device_path[len] = '\0';
}
}
UartSerial::~UartSerial (
void
) {
//TODO: Allow `end()` to be called more than once.
::free(_serial_device_path);
}
size_t
UartSerial::available (
void
) {
size_t num_bytes_available = 0;
if ( -1 == _serial_file_descriptor ) {
::perror("UartSerial::available - Invalid file descriptor");
} else if ( -1 == ::ioctl(_serial_file_descriptor, FIONREAD, &num_bytes_available) ) {
::perror("UartSerial::available - `ioctl()` request failed");
num_bytes_available = 0;
}
return num_bytes_available;
}
void
UartSerial::begin (
const uint32_t speed_,
const size_t config_
) {
// Scrubbed parameters
speed_t baud_rate = B0;
size_t c_cflags = (size_t)-1;
// Interpret common baud rates
switch (speed_) {
case 300: baud_rate = B300; break;
case 600: baud_rate = B600; break;
case 1200: baud_rate = B1200; break;
case 2400: baud_rate = B2400; break;
case 4800: baud_rate = B4800; break;
case 9600: baud_rate = B9600; break;
case 14400: break;
case 19200: baud_rate = B19200; break;
case 28800: break;
case 38400: baud_rate = B38400; break;
case 57600: baud_rate = B57600; break;
case 115200: baud_rate = B115200; break;
default: break;
}
switch (config_) {
case SERIAL_5E1:
case SERIAL_5E2:
case SERIAL_5N1:
case SERIAL_5N2:
case SERIAL_5O1:
case SERIAL_5O2:
case SERIAL_6E1:
case SERIAL_6E2:
case SERIAL_6N1:
case SERIAL_6N2:
case SERIAL_6O1:
case SERIAL_6O2:
case SERIAL_7E1:
case SERIAL_7E2:
case SERIAL_7N1:
case SERIAL_7N2:
case SERIAL_7O1:
case SERIAL_7O2:
case SERIAL_8E1:
case SERIAL_8E2:
case SERIAL_8N1:
case SERIAL_8N2:
case SERIAL_8O1:
case SERIAL_8O2:
c_cflags = config_;
default: break;
}
// Validate baud rate
if ( B0 == baud_rate ) {
::perror("UartSerial::begin - Unsupported baud rate");
// Validate configuration flags
} else if ( (size_t)-1 == c_cflags ) {
::perror("UartSerial::begin - Unsupported configuration");
// Attempt to open the device
} else if ( 0 > (_serial_file_descriptor = ::open(_serial_device_path, (O_RDWR | O_NOCTTY | O_NONBLOCK))) ) {
::perror(_serial_device_path);
// Confirm file descriptor is a TTY device
} else if ( 0 == ::isatty(_serial_file_descriptor) ) {
::perror("UartSerial::begin - File descriptor is not a TTY device");
if ( 0 != cleanupSerialFileDescriptor() ) {
::perror("UartSerial::begin - Unable to close serial file descriptor");
}
// Save current device settings
} else if ( 0 != ::tcgetattr(_serial_file_descriptor, &_tio_config_original) ) {
::perror("UartSerial::begin - Unable to save current term attributes");
if ( 0 != cleanupSerialFileDescriptor() ) {
::perror("UartSerial::begin - Unable to close serial file descriptor");
}
// Flush all current i/o data before enabling the new configuration
} else if ( 0 != ::tcflush(_serial_file_descriptor, TCIOFLUSH) ) {
::perror("UartSerial::begin - Unable to flush file descriptor");
if ( 0 != cleanupSerialFileDescriptor() ) {
::perror("UartSerial::begin - Unable to close serial file descriptor");
}
} else {
// Configure the termios structure. See termios man page for further info
// http://man7.org/linux/man-pages/man3/termios.3.html
_tio_config = _tio_config_original;
// c_iflag - input modes
// Leave all input flags unset
// c_oflag - output modes
// Leave all output flags unset
// c_cflag - control modes
_tio_config.c_cflag |= CS8; //TODO: Configuration passed by caller
_tio_config.c_cflag |= CREAD; // Enable receiver
_tio_config.c_cflag |= CLOCAL; // Ignore modem control lines
_tio_config.c_cflag |= HUPCL; // Enable hang-up on close
// c_lflag - local modes
// Leave all local mode flags unset. This enables noncanonical mode input.
// c_cc - special characters
// The following combination of VTIME and VMIN will result in a polling
// read. If data is available a call to read() returns immediately. If
// no data is available a call to read() returns 0.
_tio_config.c_cc[VTIME] = 0;
_tio_config.c_cc[VMIN] = 0;
// Update configuration
if ( 0 != ::cfsetspeed(&_tio_config, baud_rate) ) {
::perror("UartSerial::begin - Unable to set baud rate");
if ( 0 != cleanupSerialFileDescriptor() ) {
::perror("UartSerial::begin - Unable to close serial file descriptor");
}
// Enable new term configuration
} else if ( 0 != ::tcsetattr(_serial_file_descriptor, TCSANOW, &_tio_config) ) {
::perror("UartSerial::begin - Unable to set term attributes");
if ( 0 != cleanupSerialFileDescriptor() ) {
::perror("UartSerial::begin - Unable to close serial file descriptor");
}
}
}
}
int
UartSerial::cleanupSerialFileDescriptor (
void
) {
int error;
if ( 0 != ::close(_serial_file_descriptor) ) {
error = 0x1;
} else {
_serial_file_descriptor = -1;
error = 0x0;
}
return error;
}
void
UartSerial::end (
void
) {
if ( -1 == _serial_file_descriptor ) {
// `end()` has already been called, no action required
} else {
flush();
// Shut down the poll() thread
_polling = false;
_poll_thread.join();
// Restore the original settings and close the descriptor
if ( 0 != ::tcsetattr(_serial_file_descriptor, TCSANOW, &_tio_config_original) ) {
::perror("UartSerial::end - Unable to restore term attributes");
}
if ( 0 != cleanupSerialFileDescriptor() ) {
::perror("UartSerial::end - Unable to close serial file descriptor");
}
}
}
void
UartSerial::flush (
void
) {
if ( -1 == _serial_file_descriptor ) {
::perror("UartSerial::flush - Invalid file descriptor");
} else if ( 0 != ::tcdrain(_serial_file_descriptor) ) {
::perror("UartSerial::flush - Unable to flush the serial buffer");
}
}
void
UartSerial::pollForSerialData (
void
) {
const int timeout_ms = 0;
while ( _polling ) {
switch ( ::poll(&_polling_file_descriptor, 1, timeout_ms) ) {
case -1: // error
::perror("UartSerial::pollForSerialData - Polling error occurred");
break;
case 0: // timeout
// Release control back to the CPU
this_thread::sleep_for(std::chrono::seconds(0));
break;
default:
if ( _polling_file_descriptor.revents & POLLIN ) {
_bytesAvailableCallback(_bytes_available_context);
} else {
// Release control back to the CPU
this_thread::sleep_for(std::chrono::seconds(0));
}
}
}
}
int
UartSerial::read (
void
) {
int buffer;
if ( -1 == _serial_file_descriptor ) {
::perror("UartSerial::read - Invalid file descriptor");
buffer = -1;
} else if ( 0 == ::read(_serial_file_descriptor, &buffer, 1) ) {
buffer = -1;
} else {
buffer &= 0xFF;
}
return buffer;
}
void
UartSerial::registerSerialEventCallback (
serialEvent bytes_available_,
void * context_
) {
if ( bytes_available_ == nullptr ) {
::perror("UartSerial::registerSerialEventCallback - Invalid function pointer");
} else if ( -1 == _serial_file_descriptor ) {
::perror("UartSerial::registerSerialEventCallback - Invalid file descriptor");
} else if ( nullptr != _bytesAvailableCallback ) {
::perror("UartSerial::registerSerialEventCallback - A callback has already been registered");
} else {
_bytesAvailableCallback = bytes_available_;
_bytes_available_context = context_;
// Setup poll struct
_polling_file_descriptor.fd = _serial_file_descriptor;
_polling_file_descriptor.events = POLLIN;
_polling = true;
_poll_thread = std::thread(&UartSerial::pollForSerialData, this);
}
}
void
UartSerial::write (
uint8_t byte_
) {
if ( -1 == _serial_file_descriptor ) {
::perror("UartSerial::write - Invalid file descriptor");
} else if ( 0 > ::write(_serial_file_descriptor, &byte_, 1) ) {
::perror("UartSerial::write - Unable to write data");
}
}
/* Created and copyrighted by Kevin D. Sidwar. Offered as open source under the MIT License (MIT). */
<|endoftext|> |
<commit_before>/*
User Server code for CMPT 276 Group Assignment, Spring 2016.
This server manages a user’s social networking session.
This server supports sign on/off, add friend, unfriend, update status,
get user's friend list.
This server handles disallowed method malformed request.
As defined in ServerUrls.h, the URI for this server is
http://localhost:34572.
*/
#include <exception>
#include <iostream>
#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include <string>
#include <cpprest/base_uri.h>
#include <cpprest/http_listener.h>
#include <cpprest/json.h>
#include <pplx/pplxtasks.h>
#include <was/common.h>
#include <was/storage_account.h>
#include <was/table.h>
#include "../include/ClientUtils.h"
#include "../include/ServerUrls.h"
#include "../include/ServerUtils.h"
#include "../include/TableCache.h"
#include "../include/azure_keys.h"
using azure::storage::cloud_storage_account;
using azure::storage::storage_credentials;
using azure::storage::storage_exception;
using azure::storage::cloud_table;
using azure::storage::cloud_table_client;
using azure::storage::edm_type;
using azure::storage::entity_property;
using azure::storage::table_entity;
using azure::storage::table_operation;
using azure::storage::table_query;
using azure::storage::table_query_iterator;
using azure::storage::table_result;
using pplx::extensibility::critical_section_t;
using pplx::extensibility::scoped_critical_section_t;
using std::cin;
using std::cout;
using std::endl;
using std::getline;
using std::make_pair;
using std::pair;
using std::string;
using std::unordered_map;
using std::vector;
using web::http::client::http_client;
using web::http::http_headers;
using web::http::http_request;
using web::http::http_response;
using web::http::method;
using web::http::methods;
using web::http::status_code;
using web::http::status_codes;
using web::http::uri;
using web::json::value;
using web::http::experimental::listener::http_listener;
using prop_vals_t = vector<pair<string,value>>;
const string get_update_data_op {"GetUpdateData"};
const string update_entity_auth_op {"UpdateEntityAuth"};
const string sign_on {"SignOn"}; //POST
const string sign_off {"SignOff"}; //POST
const string add_friend {"AddFriend"}; // PUT
const string unfriend {"UnFriend"}; //PUT
const string update_status {"UpdateStatus"}; //PUT
const string get_friend_list {"ReadFriendList"}; //GET
// Cache of active sessions
std::unordered_map< string, std::tuple<string, string, string> > sessions;
/*
Return true if an HTTP request has a JSON body
This routine can be called multiple times on the same message.
*/
bool has_json_body (http_request message) {
return message.headers()["Content-type"] == "application/json";
}
/*
Given an HTTP message with a JSON body, return the JSON
body as an unordered map of strings to strings.
get_json_body and get_json_bourne are valid and identical function calls.
If the message has no JSON body, return an empty map.
THIS ROUTINE CAN ONLY BE CALLED ONCE FOR A GIVEN MESSAGE
(see http://microsoft.github.io/cpprestsdk/classweb_1_1http_1_1http__request.html#ae6c3d7532fe943de75dcc0445456cbc7
for source of this limit).
Note that all types of JSON values are returned as strings.
Use C++ conversion utilities to convert to numbers or dates
as necessary.
*/
unordered_map<string,string> get_json_body(http_request message) {
unordered_map<string,string> results {};
const http_headers& headers {message.headers()};
auto content_type (headers.find("Content-Type"));
if (content_type == headers.end() ||
content_type->second != "application/json")
return results;
value json{};
message.extract_json(true)
.then([&json](value v) -> bool
{
json = v;
return true;
})
.wait();
if (json.is_object()) {
for (const auto& v : json.as_object()) {
if (v.second.is_string()) {
results[v.first] = v.second.as_string();
}
else {
results[v.first] = v.second.serialize();
}
}
}
return results;
}
unordered_map<string,string> get_json_bourne(http_request message) {
return get_json_body(message);
}
void handle_post (http_request message){
string path {uri::decode(message.relative_uri().path())};
cout << endl << "**** POST " << path << endl;
auto paths = uri::split_path(path);
// Operation name and user ID
if(paths.size() < 2) {
message.reply(status_codes::BadRequest);
return;
}
else if(paths[0] != sign_on && paths[0] != sign_off) {
message.reply(status_codes::BadRequest);
}
const string operation = paths[0];
const string userid = paths[1];
if(operation == sign_on) {
if(!has_json_body(message)) {
message.reply(status_codes::BadRequest);
return;
}
unordered_map<string, string> json_body {get_json_bourne(message)};
if(json_body.size() != 1) {
message.reply(status_codes::BadRequest);
return;
}
unordered_map<string, string>::const_iterator json_body_password_iterator {json_body.find("Password")};
// No 'Password' property
if(json_body_password_iterator == json_body.end()) {
message.reply(status_codes::BadRequest);
return;
}
vector<pair<string, value>> json_pw;
json_pw.push_back(make_pair(
json_body_password_iterator->first,
value::string(json_body_password_iterator->second)
));
pair<status_code, value> result;
result = do_request(
methods::GET,
string(server_urls::auth_server) + "/" +
get_update_data_op + "/" +
userid,
value::object(json_pw)
);
if(result.first != status_codes::OK) {
message.reply(result.first);
return;
}
else if(result.second.size() != 3) {
message.reply(status_codes::InternalError);
return;
}
const string token = get_json_object_prop(
result.second,
"token"
);
const string data_partition = get_json_object_prop(
result.second,
"DataPartition"
);
const string data_row = get_json_object_prop(
result.second,
"DataRow"
);
if(token.empty() ||
data_partition.empty() ||
data_row.empty() ) {
message.reply(status_codes::InternalError);
return;
}
std::tuple<string, string, string> tuple_insert(
token,
data_partition,
data_row);
std::pair<string, std::tuple<string, string, string>> pair_insert(
userid,
tuple_insert
);
sessions.insert(pair_insert);
message.reply(status_codes::OK);
return;
}
else if(operation == sign_off) {
auto session = sessions.find(userid);
if(session == sessions.end()) {
message.reply(status_codes::NotFound);
return;
}
sessions.erase(session);
message.reply(status_codes::OK);
return;
}
else {
message.reply(status_codes::InternalError);
return;
}
}
void handle_put (http_request message) {
string path {uri::decode(message.relative_uri().path())};
cout << endl << "**** POST " << path << endl;
auto paths = uri::split_path(path);
if(true/*basic criteria*/){}
else if (paths[0] == add_friend) {}
else if (paths[0] == unfriend) {}
else if (paths[0] == update_status) {}
else {
// malformed request
vector<value> vec;
message.reply(status_codes::BadRequest, value::array(vec));
return;
}
}
void handle_get (http_request message) {
string path {uri::decode(message.relative_uri().path())};
cout << endl << "**** POST " << path << endl;
auto paths = uri::split_path(path);
if(true/*basic criteria*/){}
else if (paths[0] == get_friend_list) {}
else {
// malformed request
vector<value> vec;
message.reply(status_codes::BadRequest, value::array(vec));
return;
}
}
int main (int argc, char const * argv[]) {
cout << "Opening listener" << endl;
http_listener listener {server_urls::user_server};
listener.support(methods::GET, &handle_get); // Get user's friend list
listener.support(methods::POST, &handle_post); // SignOn, SignOff
listener.support(methods::PUT, &handle_put); // Add friend, Unfriend, Update Status
/*TO DO: Disallowed method*/
listener.open().wait(); // Wait for listener to complete starting
cout << "Enter carriage return to stop server." << endl;
string line;
getline(std::cin, line);
// Shut it down
listener.close().wait();
cout << "Closed" << endl;
}
<commit_msg>add constants for use in handle_put<commit_after>/*
User Server code for CMPT 276 Group Assignment, Spring 2016.
This server manages a user’s social networking session.
This server supports sign on/off, add friend, unfriend, update status,
get user's friend list.
This server handles disallowed method malformed request.
As defined in ServerUrls.h, the URI for this server is
http://localhost:34572.
*/
#include <exception>
#include <iostream>
#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include <string>
#include <cpprest/base_uri.h>
#include <cpprest/http_listener.h>
#include <cpprest/json.h>
#include <pplx/pplxtasks.h>
#include <was/common.h>
#include <was/storage_account.h>
#include <was/table.h>
#include "../include/ClientUtils.h"
#include "../include/ServerUrls.h"
#include "../include/ServerUtils.h"
#include "../include/TableCache.h"
#include "../include/azure_keys.h"
using azure::storage::cloud_storage_account;
using azure::storage::storage_credentials;
using azure::storage::storage_exception;
using azure::storage::cloud_table;
using azure::storage::cloud_table_client;
using azure::storage::edm_type;
using azure::storage::entity_property;
using azure::storage::table_entity;
using azure::storage::table_operation;
using azure::storage::table_query;
using azure::storage::table_query_iterator;
using azure::storage::table_result;
using pplx::extensibility::critical_section_t;
using pplx::extensibility::scoped_critical_section_t;
using std::cin;
using std::cout;
using std::endl;
using std::getline;
using std::make_pair;
using std::pair;
using std::string;
using std::unordered_map;
using std::vector;
using web::http::client::http_client;
using web::http::http_headers;
using web::http::http_request;
using web::http::http_response;
using web::http::method;
using web::http::methods;
using web::http::status_code;
using web::http::status_codes;
using web::http::uri;
using web::json::value;
using web::http::experimental::listener::http_listener;
using prop_vals_t = vector<pair<string,value>>;
const string get_update_data_op {"GetUpdateData"};
const string read_entity_auth_op {"ReadEntityAuth"};
const string update_entity_auth_op {"UpdateEntityAuth"};
const string auth_table_partition {"Userid"};
const string data_table {"DataTable"};
const string sign_on {"SignOn"}; //POST
const string sign_off {"SignOff"}; //POST
const string add_friend {"AddFriend"}; // PUT
const string unfriend {"UnFriend"}; //PUT
const string update_status {"UpdateStatus"}; //PUT
const string get_friend_list {"ReadFriendList"}; //GET
// Cache of active sessions
std::unordered_map< string, std::tuple<string, string, string> > sessions;
/*
Return true if an HTTP request has a JSON body
This routine can be called multiple times on the same message.
*/
bool has_json_body (http_request message) {
return message.headers()["Content-type"] == "application/json";
}
/*
Given an HTTP message with a JSON body, return the JSON
body as an unordered map of strings to strings.
get_json_body and get_json_bourne are valid and identical function calls.
If the message has no JSON body, return an empty map.
THIS ROUTINE CAN ONLY BE CALLED ONCE FOR A GIVEN MESSAGE
(see http://microsoft.github.io/cpprestsdk/classweb_1_1http_1_1http__request.html#ae6c3d7532fe943de75dcc0445456cbc7
for source of this limit).
Note that all types of JSON values are returned as strings.
Use C++ conversion utilities to convert to numbers or dates
as necessary.
*/
unordered_map<string,string> get_json_body(http_request message) {
unordered_map<string,string> results {};
const http_headers& headers {message.headers()};
auto content_type (headers.find("Content-Type"));
if (content_type == headers.end() ||
content_type->second != "application/json")
return results;
value json{};
message.extract_json(true)
.then([&json](value v) -> bool
{
json = v;
return true;
})
.wait();
if (json.is_object()) {
for (const auto& v : json.as_object()) {
if (v.second.is_string()) {
results[v.first] = v.second.as_string();
}
else {
results[v.first] = v.second.serialize();
}
}
}
return results;
}
unordered_map<string,string> get_json_bourne(http_request message) {
return get_json_body(message);
}
void handle_post (http_request message){
string path {uri::decode(message.relative_uri().path())};
cout << endl << "**** POST " << path << endl;
auto paths = uri::split_path(path);
// Operation name and user ID
if(paths.size() < 2) {
message.reply(status_codes::BadRequest);
return;
}
else if(paths[0] != sign_on && paths[0] != sign_off) {
message.reply(status_codes::BadRequest);
}
const string operation = paths[0];
const string userid = paths[1];
if(operation == sign_on) {
if(!has_json_body(message)) {
message.reply(status_codes::BadRequest);
return;
}
unordered_map<string, string> json_body {get_json_bourne(message)};
if(json_body.size() != 1) {
message.reply(status_codes::BadRequest);
return;
}
unordered_map<string, string>::const_iterator json_body_password_iterator {json_body.find("Password")};
// No 'Password' property
if(json_body_password_iterator == json_body.end()) {
message.reply(status_codes::BadRequest);
return;
}
vector<pair<string, value>> json_pw;
json_pw.push_back(make_pair(
json_body_password_iterator->first,
value::string(json_body_password_iterator->second)
));
pair<status_code, value> result;
result = do_request(
methods::GET,
string(server_urls::auth_server) + "/" +
get_update_data_op + "/" +
userid,
value::object(json_pw)
);
if(result.first != status_codes::OK) {
message.reply(result.first);
return;
}
else if(result.second.size() != 3) {
message.reply(status_codes::InternalError);
return;
}
const string token = get_json_object_prop(
result.second,
"token"
);
const string data_partition = get_json_object_prop(
result.second,
"DataPartition"
);
const string data_row = get_json_object_prop(
result.second,
"DataRow"
);
if(token.empty() ||
data_partition.empty() ||
data_row.empty() ) {
message.reply(status_codes::InternalError);
return;
}
std::tuple<string, string, string> tuple_insert(
token,
data_partition,
data_row);
std::pair<string, std::tuple<string, string, string>> pair_insert(
userid,
tuple_insert
);
sessions.insert(pair_insert);
message.reply(status_codes::OK);
return;
}
else if(operation == sign_off) {
auto session = sessions.find(userid);
if(session == sessions.end()) {
message.reply(status_codes::NotFound);
return;
}
sessions.erase(session);
message.reply(status_codes::OK);
return;
}
else {
message.reply(status_codes::InternalError);
return;
}
}
void handle_put (http_request message) {
string path {uri::decode(message.relative_uri().path())};
cout << endl << "**** POST " << path << endl;
auto paths = uri::split_path(path);
if(true/*basic criteria*/){}
else if (paths[0] == add_friend) {}
else if (paths[0] == unfriend) {}
else if (paths[0] == update_status) {}
else {
// malformed request
vector<value> vec;
message.reply(status_codes::BadRequest, value::array(vec));
return;
}
}
void handle_get (http_request message) {
string path {uri::decode(message.relative_uri().path())};
cout << endl << "**** POST " << path << endl;
auto paths = uri::split_path(path);
if(true/*basic criteria*/){}
else if (paths[0] == get_friend_list) {}
else {
// malformed request
vector<value> vec;
message.reply(status_codes::BadRequest, value::array(vec));
return;
}
}
int main (int argc, char const * argv[]) {
cout << "Opening listener" << endl;
http_listener listener {server_urls::user_server};
listener.support(methods::GET, &handle_get); // Get user's friend list
listener.support(methods::POST, &handle_post); // SignOn, SignOff
listener.support(methods::PUT, &handle_put); // Add friend, Unfriend, Update Status
/*TO DO: Disallowed method*/
listener.open().wait(); // Wait for listener to complete starting
cout << "Enter carriage return to stop server." << endl;
string line;
getline(std::cin, line);
// Shut it down
listener.close().wait();
cout << "Closed" << endl;
}
<|endoftext|> |
<commit_before>#pragma once
#include <oscpack/ip/UdpSocket.h>
#include <oscpack/osc/OscPacketListener.h>
#include <memory>
#include <thread>
#include <functional>
#include <map>
#include <iostream>
class OscReceiver
{
public:
using message_handler = std::function<void(const osc::ReceivedMessage&)>;
//using connection_handler = std::function<void(osc::ReceivedMessageArgumentStream, std::string)>;
OscReceiver(unsigned int port, message_handler&& msg):
m_impl{std::move(msg)}
{
setPort(port);
}
~OscReceiver()
{
m_socket->AsynchronousBreak();
std::this_thread::sleep_for(std::chrono::milliseconds(50));
if(m_runThread.joinable())
m_runThread.detach();
m_socket.reset();
}
void run()
{
m_runThread = std::thread(&UdpListeningReceiveSocket::Run, m_socket.get());
}
/*
template<typename T, class C>
void addHandler(const std::string &s, T&& theMember, C&& theObject)
{
m_impl.addHandler(s, std::bind(theMember, theObject, std::placeholders::_1));
}
void addHandler(const std::string &s, const message_handler h)
{
m_impl.addHandler(s, h);
}
*/
unsigned int port() const
{
return m_port;
}
unsigned int setPort(unsigned int port)
{
m_port = port;
bool ok = false;
while(!ok)
{
try
{
m_socket = std::make_shared<UdpListeningReceiveSocket>
(IpEndpointName(IpEndpointName::ANY_ADDRESS, m_port),
&m_impl);
ok = true;
}
catch(std::runtime_error& e)
{
m_port++;
}
}
// std::cerr << "Receiver port set : " << _port << std::endl;
return m_port;
}
private:
unsigned int m_port = 0;
std::shared_ptr<UdpListeningReceiveSocket> m_socket;
class Impl: public osc::OscPacketListener
{
public:
Impl(message_handler&& msg):
m_messageHandler{std::move(msg)}
{
}
/*
void setConnectionHandler(const std::string& s, const connection_handler& h)
{
_connectionAdress = s;
_connectionHandler = h;
}
void setMessageHandler(const std::string& s, const message_handler& h)
{
_connectionAdress = s;
_connectionHandler = h;
}
*/
protected:
virtual void ProcessMessage(const osc::ReceivedMessage& m,
const IpEndpointName& ip) override
{
try
{
m_messageHandler(m);
/*
auto addr = std::string(m.AddressPattern());
std::cerr << "Message received on " << addr << std::endl;
if(addr == _connectionAdress)
{
char s[16];
ip.AddressAsString(s);
_connectionHandler(m.ArgumentStream(), std::string(s));
}
else if(_map.find(addr) != _map.end())
{
_map[addr](m.ArgumentStream());
}
*/
}
catch( osc::Exception& e )
{
std::cerr << "OSC Parse Error on " << m.AddressPattern() << ": "
<< e.what() << std::endl;
}
}
private:
//std::string _connectionAdress;
//connection_handler _connectionHandler;
message_handler m_messageHandler;
} m_impl;
std::thread m_runThread;
};
<commit_msg>Cleanup<commit_after>#pragma once
#include <oscpack/ip/UdpSocket.h>
#include <oscpack/osc/OscPacketListener.h>
#include <memory>
#include <thread>
#include <functional>
#include <iostream>
class OscReceiver
{
public:
using message_handler = std::function<void(const osc::ReceivedMessage&)>;
OscReceiver(unsigned int port, message_handler&& msg):
m_impl{std::move(msg)}
{
setPort(port);
}
~OscReceiver()
{
m_socket->AsynchronousBreak();
std::this_thread::sleep_for(std::chrono::milliseconds(50));
if(m_runThread.joinable())
m_runThread.detach();
m_socket.reset();
}
void run()
{
m_runThread = std::thread(&UdpListeningReceiveSocket::Run, m_socket.get());
}
unsigned int port() const
{
return m_port;
}
unsigned int setPort(unsigned int port)
{
m_port = port;
bool ok = false;
while(!ok)
{
try
{
m_socket = std::make_shared<UdpListeningReceiveSocket>
(IpEndpointName(IpEndpointName::ANY_ADDRESS, m_port),
&m_impl);
ok = true;
}
catch(std::runtime_error& e)
{
m_port++;
}
}
return m_port;
}
private:
unsigned int m_port = 0;
std::shared_ptr<UdpListeningReceiveSocket> m_socket;
class Impl: public osc::OscPacketListener
{
public:
Impl(message_handler&& msg):
m_messageHandler{std::move(msg)}
{
}
protected:
virtual void ProcessMessage(const osc::ReceivedMessage& m,
const IpEndpointName& ip) override
{
try
{
m_messageHandler(m);
}
catch( std::exception& e )
{
std::cerr << "OSC Parse Error on " << m.AddressPattern() << ": "
<< e.what() << std::endl;
}
}
private:
message_handler m_messageHandler;
} m_impl;
std::thread m_runThread;
};
<|endoftext|> |
<commit_before>/* Copyright 2012 10gen 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 "mongo/base/init.h"
#include "mongo/client/connpool.h"
#include "mongo/platform/cstdint.h"
//#include "mongo/util/net/message_port.h"
//#include "mongo/util/net/message_server.h"
#include "mongo/util/net/listen.h"
#include "mongo/util/fail_point_service.h"
#include "mongo/util/time_support.h"
#include "mongo/util/timer.h"
#include "mongo/unittest/unittest.h"
#include <vector>
#include <boost/scoped_ptr.hpp>
#include <boost/thread/thread.hpp>
/**
* Tests for ScopedDbConnection, particularly in connection pool management.
* The tests also indirectly tests DBClientConnection's failure detection
* logic (hence the use of the dummy server as opposed to mocking the
* connection).
*/
using boost::scoped_ptr;
using mongo::DBClientBase;
using mongo::FailPoint;
using mongo::ScopedDbConnection;
using std::string;
using std::vector;
namespace {
const string TARGET_HOST = "localhost:27017";
const int TARGET_PORT = 27017;
//mongo::mutex shutDownMutex("shutDownMutex");
//bool shuttingDown = false;
}
namespace mongo {
// Symbols defined to build the binary correctly.
/*bool inShutdown() {
scoped_lock sl(shutDownMutex);
return shuttingDown;
}
DBClientBase *createDirectClient() { return NULL; }
void dbexit(ExitCode rc, const char *why){
{
scoped_lock sl(shutDownMutex);
shuttingDown = true;
}
::_exit(rc);
}
bool haveLocalShardingInfo(const string& ns) {
return false;
}
class DummyMessageHandler: public MessageHandler {
public:
virtual void connected(AbstractMessagingPort* p) {
}
virtual void process(Message& m,
AbstractMessagingPort* port,
LastError * le) {
boost::this_thread::interruption_point();
}
virtual void disconnected(AbstractMessagingPort* p) {
}
};
}
namespace mongo_test {
mongo::DummyMessageHandler dummyHandler;
// TODO: Take this out and make it as a reusable class in a header file. The only
// thing that is preventing this from happening is the dependency on the inShutdown
// method to terminate the socket listener thread.
*
Very basic server that accepts connections. Note: can only create one instance
at a time. Should not create as a static global instance because of dependency
with ListeningSockets::_instance.
Warning: Not thread-safe
Note: external symbols used:
shutDownMutex, shuttingDown
class DummyServer {
public:
*
Creates a new server that listens to the given port.
@param port the port number to listen to.
DummyServer(int port): _port(port), _server(NULL) {
}
~DummyServer() {
stop();
}
*
Starts the server if it is not yet running.
@param messageHandler the message handler to use for this server. Ownership
of this object is passed to this server.
void run(mongo::MessageHandler* messsageHandler) {
if (_server != NULL) {
return;
}
mongo::MessageServer::Options options;
options.port = _port;
{
mongo::mutex::scoped_lock sl(shutDownMutex);
shuttingDown = false;
}
_server = mongo::createServer(options, messsageHandler);
_serverThread = boost::thread(runServer, _server);
}
*
Stops the server if it is running.
void stop() {
if (_server == NULL) {
return;
}
{
mongo::mutex::scoped_lock sl(shutDownMutex);
shuttingDown = true;
}
mongo::ListeningSockets::get()->closeAll();
_serverThread.join();
int connCount = mongo::Listener::globalTicketHolder.used();
size_t iterCount = 0;
while (connCount > 0) {
if ((++iterCount % 20) == 0) {
mongo::log() << "DummyServer: Waiting for " << connCount
<< " connections to close." << std::endl;
}
mongo::sleepmillis(500);
connCount = mongo::Listener::globalTicketHolder.used();
}
delete _server;
_server = NULL;
}
*
Helper method for running the server on a separate thread.
static void runServer(mongo::MessageServer* server) {
server->setupSockets();
server->run();
}
private:
const int _port;
boost::thread _serverThread;
mongo::MessageServer* _server;
};
*
Warning: cannot run in parallel
class DummyServerFixture: public mongo::unittest::Test {
public:
void setUp() {
_maxPoolSizePerHost = mongo::PoolForHost::getMaxPerHost();
_dummyServer = new DummyServer(TARGET_PORT);
_dummyServer->run(&dummyHandler);
mongo::DBClientConnection conn;
mongo::Timer timer;
// Make sure the dummy server is up and running before proceeding
while (true) {
try {
conn.connect(TARGET_HOST);
break;
} catch (const mongo::ConnectException&) {
if (timer.seconds() > 20) {
FAIL("Timed out connecting to dummy server");
}
}
}
}
void tearDown() {
ScopedDbConnection::clearPool();
delete _dummyServer;
mongo::PoolForHost::setMaxPerHost(_maxPoolSizePerHost);
}
protected:
static void assertGreaterThan(uint64_t a, uint64_t b) {
ASSERT_GREATER_THAN(a, b);
}
static void assertNotEqual(uint64_t a, uint64_t b) {
ASSERT_NOT_EQUALS(a, b);
}
*
Tries to grab a series of connections from the pool, perform checks on
them, then put them back into the pool. After that, it checks these
connections can be retrieved again from the pool.
@param checkFunc method for comparing new connections and arg2.
@param arg2 the value to pass as the 2nd parameter of checkFunc.
@param newConnsToCreate the number of new connections to make.
void checkNewConns(void (*checkFunc)(uint64_t, uint64_t), uint64_t arg2,
size_t newConnsToCreate) {
vector<ScopedDbConnection*> newConnList;
for (size_t x = 0; x < newConnsToCreate; x++) {
ScopedDbConnection* newConn = new ScopedDbConnection(TARGET_HOST);
checkFunc(newConn->get()->getSockCreationMicroSec(), arg2);
newConnList.push_back(newConn);
}
const uint64_t oldCreationTime = mongo::curTimeMicros64();
for (vector<ScopedDbConnection*>::iterator iter = newConnList.begin();
iter != newConnList.end(); ++iter) {
(*iter)->done();
delete *iter;
}
newConnList.clear();
// Check that connections created after the purge was put back to the pool.
for (size_t x = 0; x < newConnsToCreate; x++) {
ScopedDbConnection* newConn = new ScopedDbConnection(TARGET_HOST);
ASSERT_LESS_THAN(newConn->get()->getSockCreationMicroSec(), oldCreationTime);
newConnList.push_back(newConn);
}
for (vector<ScopedDbConnection*>::iterator iter = newConnList.begin();
iter != newConnList.end(); ++iter) {
(*iter)->done();
delete *iter;
}
}
private:
static void runServer(mongo::MessageServer* server) {
server->setupSockets();
server->run();
}
DummyServer* _dummyServer;
uint32_t _maxPoolSizePerHost;
};*/
class TestListener : public Listener {
public:
TestListener() : Listener("test", "", TARGET_PORT) {}
void accepted(boost::shared_ptr<Socket> psocket, long long connectionId) {}
void operator()() {
Listener::setupSockets();
Listener::initAndListen();
}
};
class DummyServerFixture : public ::testing::Test {
public:
DummyServerFixture() {
_listener = new TestListener();
_thread = new boost::thread(boost::ref(*_listener));
_maxPoolSizePerHost = mongo::PoolForHost::getMaxPerHost();
}
~DummyServerFixture() {
mongo::ListeningSockets::get()->closeAll();
mongo::PoolForHost::setMaxPerHost(_maxPoolSizePerHost);
mongo::ScopedDbConnection::clearPool();
delete _thread;
delete _listener;
}
protected:
static void assertGreaterThan(uint64_t a, uint64_t b) {
ASSERT_GREATER_THAN(a, b);
}
static void assertNotEqual(uint64_t a, uint64_t b) {
ASSERT_NOT_EQUALS(a, b);
}
/**
* Tries to grab a series of connections from the pool, perform checks on
* them, then put them back into the pool. After that, it checks these
* connections can be retrieved again from the pool.
*
* @param checkFunc method for comparing new connections and arg2.
* @param arg2 the value to pass as the 2nd parameter of checkFunc.
* @param newConnsToCreate the number of new connections to make.
*/
void checkNewConns(void (*checkFunc)(uint64_t, uint64_t), uint64_t arg2,
size_t newConnsToCreate) {
vector<ScopedDbConnection*> newConnList;
for (size_t x = 0; x < newConnsToCreate; x++) {
ScopedDbConnection* newConn = new ScopedDbConnection(TARGET_HOST);
checkFunc(newConn->get()->getSockCreationMicroSec(), arg2);
newConnList.push_back(newConn);
}
const uint64_t oldCreationTime = mongo::curTimeMicros64();
for (vector<ScopedDbConnection*>::iterator iter = newConnList.begin();
iter != newConnList.end(); ++iter) {
(*iter)->done();
delete *iter;
}
newConnList.clear();
// Check that connections created after the purge was put back to the pool.
for (size_t x = 0; x < newConnsToCreate; x++) {
ScopedDbConnection* newConn = new ScopedDbConnection(TARGET_HOST);
ASSERT_LESS_THAN(newConn->get()->getSockCreationMicroSec(), oldCreationTime);
newConnList.push_back(newConn);
}
for (vector<ScopedDbConnection*>::iterator iter = newConnList.begin();
iter != newConnList.end(); ++iter) {
(*iter)->done();
delete *iter;
}
}
private:
TestListener* _listener;
boost::thread* _thread;
uint32_t _maxPoolSizePerHost;
};
TEST_F(DummyServerFixture, BasicScopedDbConnection) {
ScopedDbConnection conn1(TARGET_HOST);
ScopedDbConnection conn2(TARGET_HOST);
DBClientBase* conn1Ptr = conn1.get();
conn1.done();
ScopedDbConnection conn3(TARGET_HOST);
ASSERT_EQUALS(conn1Ptr, conn3.get());
conn2.done();
conn3.done();
}
TEST_F(DummyServerFixture, InvalidateBadConnInPool) {
ScopedDbConnection conn1(TARGET_HOST);
ScopedDbConnection conn2(TARGET_HOST);
ScopedDbConnection conn3(TARGET_HOST);
conn1.done();
conn3.done();
const uint64_t badCreationTime = mongo::curTimeMicros64();
mongo::getGlobalFailPointRegistry()->getFailPoint("throwSockExcep")->
setMode(FailPoint::alwaysOn);
try {
conn2->query("test.user", mongo::Query());
}
catch (const mongo::SocketException&) {
}
mongo::getGlobalFailPointRegistry()->getFailPoint("throwSockExcep")->
setMode(FailPoint::off);
conn2.done();
checkNewConns(assertGreaterThan, badCreationTime, 10);
}
TEST_F(DummyServerFixture, DontReturnKnownBadConnToPool) {
ScopedDbConnection conn1(TARGET_HOST);
ScopedDbConnection conn2(TARGET_HOST);
ScopedDbConnection conn3(TARGET_HOST);
conn1.done();
mongo::getGlobalFailPointRegistry()->getFailPoint("throwSockExcep")->
setMode(FailPoint::alwaysOn);
try {
conn3->query("test.user", mongo::Query());
}
catch (const mongo::SocketException&) {
}
mongo::getGlobalFailPointRegistry()->getFailPoint("throwSockExcep")->
setMode(FailPoint::off);
const uint64_t badCreationTime = conn3->getSockCreationMicroSec();
conn3.done();
// attempting to put a 'bad' connection back to the pool
conn2.done();
checkNewConns(assertGreaterThan, badCreationTime, 10);
}
TEST_F(DummyServerFixture, InvalidateBadConnEvenWhenPoolIsFull) {
mongo::PoolForHost::setMaxPerHost(2);
ScopedDbConnection conn1(TARGET_HOST);
ScopedDbConnection conn2(TARGET_HOST);
ScopedDbConnection conn3(TARGET_HOST);
conn1.done();
conn3.done();
const uint64_t badCreationTime = mongo::curTimeMicros64();
mongo::getGlobalFailPointRegistry()->getFailPoint("throwSockExcep")->
setMode(FailPoint::alwaysOn);
try {
conn2->query("test.user", mongo::Query());
}
catch (const mongo::SocketException&) {
}
mongo::getGlobalFailPointRegistry()->getFailPoint("throwSockExcep")->
setMode(FailPoint::off);
conn2.done();
checkNewConns(assertGreaterThan, badCreationTime, 2);
}
TEST_F(DummyServerFixture, DontReturnConnGoneBadToPool) {
ScopedDbConnection conn1(TARGET_HOST);
const uint64_t conn1CreationTime = conn1->getSockCreationMicroSec();
uint64_t conn2CreationTime = 0;
{
ScopedDbConnection conn2(TARGET_HOST);
conn2CreationTime = conn2->getSockCreationMicroSec();
conn1.done();
// conn2 gets out of scope without calling done()
}
// conn2 should not have been put back into the pool but it should
// also not invalidate older connections since it didn't encounter
// a socket exception.
ScopedDbConnection conn1Again(TARGET_HOST);
ASSERT_EQUALS(conn1CreationTime, conn1Again->getSockCreationMicroSec());
checkNewConns(assertNotEqual, conn2CreationTime, 10);
conn1Again.done();
}
}
<commit_msg>CXX-11 adjustments after feedback<commit_after>/* Copyright 2012 10gen 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 "mongo/base/init.h"
#include "mongo/client/connpool.h"
#include "mongo/platform/cstdint.h"
// #include "mongo/util/net/message_port.h"
// #include "mongo/util/net/message_server.h"
#include "mongo/util/net/listen.h"
#include "mongo/util/fail_point_service.h"
#include "mongo/util/time_support.h"
#include "mongo/util/timer.h"
#include "mongo/unittest/unittest.h"
#include <vector>
#include <boost/scoped_ptr.hpp>
#include <boost/thread/thread.hpp>
/**
* Tests for ScopedDbConnection, particularly in connection pool management.
* The tests also indirectly tests DBClientConnection's failure detection
* logic (hence the use of the dummy server as opposed to mocking the
* connection).
*/
using boost::scoped_ptr;
using mongo::DBClientBase;
using mongo::FailPoint;
using mongo::ScopedDbConnection;
using std::string;
using std::vector;
namespace {
const string TARGET_HOST = "localhost:27017";
const int TARGET_PORT = 27017;
mongo::mutex shutDownMutex("shutDownMutex");
bool shuttingDown = false;
}
namespace mongo {
class TestListener : public Listener {
public:
TestListener() : Listener("test", "", TARGET_PORT) {}
void accepted(boost::shared_ptr<Socket> psocket, long long connectionId) {}
void operator()() {
Listener::setupSockets();
Listener::initAndListen();
}
};
class DummyServerFixture : public ::testing::Test {
public:
DummyServerFixture() {
_listener = new TestListener();
_thread = new boost::thread(boost::ref(*_listener));
_maxPoolSizePerHost = mongo::PoolForHost::getMaxPerHost();
}
~DummyServerFixture() {
mongo::ListeningSockets::get()->closeAll();
mongo::PoolForHost::setMaxPerHost(_maxPoolSizePerHost);
mongo::ScopedDbConnection::clearPool();
// exit the listen loop by shutting down
{
scoped_lock sl(shutDownMutex);
shuttingDown = true;
}
// ensure listener thread is finished before delete
_thread->join();
delete _thread;
delete _listener;
}
protected:
static void assertGreaterThan(uint64_t a, uint64_t b) {
ASSERT_GREATER_THAN(a, b);
}
static void assertNotEqual(uint64_t a, uint64_t b) {
ASSERT_NOT_EQUALS(a, b);
}
/**
* Tries to grab a series of connections from the pool, perform checks on
* them, then put them back into the pool. After that, it checks these
* connections can be retrieved again from the pool.
*
* @param checkFunc method for comparing new connections and arg2.
* @param arg2 the value to pass as the 2nd parameter of checkFunc.
* @param newConnsToCreate the number of new connections to make.
*/
void checkNewConns(void (*checkFunc)(uint64_t, uint64_t), uint64_t arg2,
size_t newConnsToCreate) {
vector<ScopedDbConnection*> newConnList;
for (size_t x = 0; x < newConnsToCreate; x++) {
ScopedDbConnection* newConn = new ScopedDbConnection(TARGET_HOST);
checkFunc(newConn->get()->getSockCreationMicroSec(), arg2);
newConnList.push_back(newConn);
}
const uint64_t oldCreationTime = mongo::curTimeMicros64();
for (vector<ScopedDbConnection*>::iterator iter = newConnList.begin();
iter != newConnList.end(); ++iter) {
(*iter)->done();
delete *iter;
}
newConnList.clear();
// Check that connections created after the purge was put back to the pool.
for (size_t x = 0; x < newConnsToCreate; x++) {
ScopedDbConnection* newConn = new ScopedDbConnection(TARGET_HOST);
ASSERT_LESS_THAN(newConn->get()->getSockCreationMicroSec(), oldCreationTime);
newConnList.push_back(newConn);
}
for (vector<ScopedDbConnection*>::iterator iter = newConnList.begin();
iter != newConnList.end(); ++iter) {
(*iter)->done();
delete *iter;
}
}
private:
TestListener* _listener;
boost::thread* _thread;
uint32_t _maxPoolSizePerHost;
};
TEST_F(DummyServerFixture, BasicScopedDbConnection) {
ScopedDbConnection conn1(TARGET_HOST);
ScopedDbConnection conn2(TARGET_HOST);
DBClientBase* conn1Ptr = conn1.get();
conn1.done();
ScopedDbConnection conn3(TARGET_HOST);
ASSERT_EQUALS(conn1Ptr, conn3.get());
conn2.done();
conn3.done();
}
TEST_F(DummyServerFixture, InvalidateBadConnInPool) {
ScopedDbConnection conn1(TARGET_HOST);
ScopedDbConnection conn2(TARGET_HOST);
ScopedDbConnection conn3(TARGET_HOST);
conn1.done();
conn3.done();
const uint64_t badCreationTime = mongo::curTimeMicros64();
mongo::getGlobalFailPointRegistry()->getFailPoint("throwSockExcep")->
setMode(FailPoint::alwaysOn);
try {
conn2->query("test.user", mongo::Query());
}
catch (const mongo::SocketException&) {
}
mongo::getGlobalFailPointRegistry()->getFailPoint("throwSockExcep")->
setMode(FailPoint::off);
conn2.done();
checkNewConns(assertGreaterThan, badCreationTime, 10);
}
TEST_F(DummyServerFixture, DontReturnKnownBadConnToPool) {
ScopedDbConnection conn1(TARGET_HOST);
ScopedDbConnection conn2(TARGET_HOST);
ScopedDbConnection conn3(TARGET_HOST);
conn1.done();
mongo::getGlobalFailPointRegistry()->getFailPoint("throwSockExcep")->
setMode(FailPoint::alwaysOn);
try {
conn3->query("test.user", mongo::Query());
}
catch (const mongo::SocketException&) {
}
mongo::getGlobalFailPointRegistry()->getFailPoint("throwSockExcep")->
setMode(FailPoint::off);
const uint64_t badCreationTime = conn3->getSockCreationMicroSec();
conn3.done();
// attempting to put a 'bad' connection back to the pool
conn2.done();
checkNewConns(assertGreaterThan, badCreationTime, 10);
}
TEST_F(DummyServerFixture, InvalidateBadConnEvenWhenPoolIsFull) {
mongo::PoolForHost::setMaxPerHost(2);
ScopedDbConnection conn1(TARGET_HOST);
ScopedDbConnection conn2(TARGET_HOST);
ScopedDbConnection conn3(TARGET_HOST);
conn1.done();
conn3.done();
const uint64_t badCreationTime = mongo::curTimeMicros64();
mongo::getGlobalFailPointRegistry()->getFailPoint("throwSockExcep")->
setMode(FailPoint::alwaysOn);
try {
conn2->query("test.user", mongo::Query());
}
catch (const mongo::SocketException&) {
}
mongo::getGlobalFailPointRegistry()->getFailPoint("throwSockExcep")->
setMode(FailPoint::off);
conn2.done();
checkNewConns(assertGreaterThan, badCreationTime, 2);
}
TEST_F(DummyServerFixture, DontReturnConnGoneBadToPool) {
ScopedDbConnection conn1(TARGET_HOST);
const uint64_t conn1CreationTime = conn1->getSockCreationMicroSec();
uint64_t conn2CreationTime = 0;
{
ScopedDbConnection conn2(TARGET_HOST);
conn2CreationTime = conn2->getSockCreationMicroSec();
conn1.done();
// conn2 gets out of scope without calling done()
}
// conn2 should not have been put back into the pool but it should
// also not invalidate older connections since it didn't encounter
// a socket exception.
ScopedDbConnection conn1Again(TARGET_HOST);
ASSERT_EQUALS(conn1CreationTime, conn1Again->getSockCreationMicroSec());
checkNewConns(assertNotEqual, conn2CreationTime, 10);
conn1Again.done();
}
}
<|endoftext|> |
<commit_before><commit_msg>ensure the getCycleTime function returns a value<commit_after><|endoftext|> |
<commit_before>#include "Module/Adaptor/Adaptor.hpp"
using namespace aff3ct;
using namespace aff3ct::module;
Adaptor
::~Adaptor()
{
(*this->buffer)[this->id].clear();
(*this->first)[this->id] = 0;
(*this->last )[this->id] = 0;
}
void Adaptor
::deep_copy(const Adaptor &m)
{
Module::deep_copy(m);
int id = -1;
for (size_t i = 0; i < this->buffer->size(); i++)
if ((*this->buffer)[i].size() == 0)
id = (int)i;
if (id == -1)
{
this->id = this->buffer->size();
this->buffer->push_back(std::vector<std::vector<std::vector<int8_t>>>(this->n_sockets,
std::vector<std::vector<int8_t>>(this->buffer_size)));
}
else
{
this->id = (size_t)id;
(*this->buffer)[this->id].resize(this->n_sockets, std::vector<std::vector<int8_t>>(this->buffer_size));
}
for (auto s = 0; s < this->n_sockets; s++)
for (auto b = 0; b < this->buffer_size; b++)
(*this->buffer)[this->id][s][b].resize(this->n_frames * this->n_bytes[s]);
if (this->id >= this->first->size())
{
std::stringstream message;
message << "'id' can't be higher than 'first->size()' ('id' = " << this->id
<< ", 'first->size()' = " << this->first->size() << ").";
throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());
}
this->waiting_canceled.reset(new std::atomic<bool>(m.waiting_canceled->load()));
}
size_t Adaptor
::compute_bytes(const size_t n_elmts, const std::type_index type)
{
if (type == typeid(int8_t )) return n_elmts * sizeof(int8_t );
else if (type == typeid(int16_t)) return n_elmts * sizeof(int16_t);
else if (type == typeid(int32_t)) return n_elmts * sizeof(int32_t);
else if (type == typeid(int64_t)) return n_elmts * sizeof(int64_t);
else if (type == typeid(float )) return n_elmts * sizeof(float );
else if (type == typeid(double )) return n_elmts * sizeof(double );
else
{
std::stringstream message;
message << "This should never happen.";
throw tools::runtime_error(__FILE__, __LINE__, __func__, message.str());
}
}
std::vector<size_t> Adaptor
::compute_bytes(const std::vector<size_t> &n_elmts, const std::vector<std::type_index> &type)
{
if (n_elmts.size() != type.size())
{
std::stringstream message;
message << "'n_elmts.size()' has to be equal to 'type.size()' ('n_elmts.size()' = " << n_elmts.size()
<< ", 'type.size()' = " << type.size() << ").";
throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());
}
std::vector<size_t> bytes(n_elmts.size());
for (size_t i = 0; i < n_elmts.size(); i++)
bytes[i] = Adaptor::compute_bytes(n_elmts[i], type[i]);
return bytes;
}
void Adaptor::send_cancel_signal()
{
*this->waiting_canceled = true;
}
void Adaptor::reset()
{
*this->waiting_canceled = false;
}
<commit_msg>Fix compilation warning.<commit_after>#include "Module/Adaptor/Adaptor.hpp"
using namespace aff3ct;
using namespace aff3ct::module;
Adaptor
::~Adaptor()
{
(*this->buffer)[this->id].clear();
(*this->first)[this->id] = 0;
(*this->last )[this->id] = 0;
}
void Adaptor
::deep_copy(const Adaptor &m)
{
Module::deep_copy(m);
int id = -1;
for (size_t i = 0; i < this->buffer->size(); i++)
if ((*this->buffer)[i].size() == 0)
id = (int)i;
if (id == -1)
{
this->id = this->buffer->size();
this->buffer->push_back(std::vector<std::vector<std::vector<int8_t>>>(this->n_sockets,
std::vector<std::vector<int8_t>>(this->buffer_size)));
}
else
{
this->id = (size_t)id;
(*this->buffer)[this->id].resize(this->n_sockets, std::vector<std::vector<int8_t>>(this->buffer_size));
}
for (size_t s = 0; s < this->n_sockets; s++)
for (size_t b = 0; b < this->buffer_size; b++)
(*this->buffer)[this->id][s][b].resize(this->n_frames * this->n_bytes[s]);
if (this->id >= this->first->size())
{
std::stringstream message;
message << "'id' can't be higher than 'first->size()' ('id' = " << this->id
<< ", 'first->size()' = " << this->first->size() << ").";
throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());
}
this->waiting_canceled.reset(new std::atomic<bool>(m.waiting_canceled->load()));
}
size_t Adaptor
::compute_bytes(const size_t n_elmts, const std::type_index type)
{
if (type == typeid(int8_t )) return n_elmts * sizeof(int8_t );
else if (type == typeid(int16_t)) return n_elmts * sizeof(int16_t);
else if (type == typeid(int32_t)) return n_elmts * sizeof(int32_t);
else if (type == typeid(int64_t)) return n_elmts * sizeof(int64_t);
else if (type == typeid(float )) return n_elmts * sizeof(float );
else if (type == typeid(double )) return n_elmts * sizeof(double );
else
{
std::stringstream message;
message << "This should never happen.";
throw tools::runtime_error(__FILE__, __LINE__, __func__, message.str());
}
}
std::vector<size_t> Adaptor
::compute_bytes(const std::vector<size_t> &n_elmts, const std::vector<std::type_index> &type)
{
if (n_elmts.size() != type.size())
{
std::stringstream message;
message << "'n_elmts.size()' has to be equal to 'type.size()' ('n_elmts.size()' = " << n_elmts.size()
<< ", 'type.size()' = " << type.size() << ").";
throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());
}
std::vector<size_t> bytes(n_elmts.size());
for (size_t i = 0; i < n_elmts.size(); i++)
bytes[i] = Adaptor::compute_bytes(n_elmts[i], type[i]);
return bytes;
}
void Adaptor::send_cancel_signal()
{
*this->waiting_canceled = true;
}
void Adaptor::reset()
{
*this->waiting_canceled = false;
}
<|endoftext|> |
<commit_before>/*********************************************************************
* AnitomyJs - Node.js wrapper for Anitomy
*
* Copyright (c) 2016 Thiago Oliveira
*
* MIT License <https://github.com/nevermnd/anitomy-js/blob/master/LICENSE>
********************************************************************/
#include "anitomy_js.h"
namespace anitomyJs {
void AnitomyJs::SetInput(v8::Local<v8::Value> value) {
is_batch_parse_ = value->IsArray();
if (is_batch_parse_) {
v8::Local<v8::Array> input = v8::Local<v8::Array>::Cast(value);
for (unsigned int i = 0; i < input->Length(); i++) input_.push_back(ToWideString(input->Get(i)));
} else {
input_.push_back(ToWideString(value));
}
}
void AnitomyJs::Parse() {
for (std::wstring str : input_) {
anitomy_.Parse(str);
parsed_.push_back(anitomy_.elements());
}
}
std::vector<anitomy::Elements> AnitomyJs::Parsed() {
return parsed_;
}
// TODO For ~desu's sake, stop doing this flag shit
v8::Local<v8::Value> AnitomyJs::ParsedResult(v8::Isolate* isolate) {
v8::Local<v8::Array> output = v8::Array::New(isolate, parsed_.size());
unsigned int index = 0;
for (anitomy::Elements element : parsed_) {
output->Set(index, BuildObject(element, isolate));
index++;
}
if (is_batch_parse_) return output;
return output->Get(0);
}
std::wstring AnitomyJs::ToWideString(v8::Local<v8::Value> str) {
v8::String::Utf8Value utf_value(str->ToString());
std::string str_value(*utf_value);
return std::wstring(str_value.begin(), str_value.end());
}
std::string AnitomyJs::ToStr(anitomy::string_t str) {
std::wstring ws_value(str.c_str());
return std::string(ws_value.begin(), ws_value.end());
}
void AnitomyJs::SetEntry(v8::Local<v8::Object>& object, v8::Isolate* isolate, const char* entry,
anitomy::Elements& elements, anitomy::ElementCategory pos) {
v8::Local<v8::String> entry_name = v8::String::NewFromUtf8(isolate, entry);
switch(elements.count(pos)) {
case 0:
break;
case 1:
object->Set(entry_name, v8::String::NewFromUtf8(isolate, ToStr(elements.get(pos)).c_str()));
break;
default:
object->Set(entry_name, CategoryArray(elements, pos, isolate));
}
}
v8::Local<v8::Array> AnitomyJs::CategoryArray(anitomy::Elements& elements,
anitomy::ElementCategory pos, v8::Isolate* isolate) {
std::vector<anitomy::string_t> category_elements = elements.get_all(pos);
v8::Local<v8::Array> output = v8::Array::New(isolate, category_elements.size());
unsigned int index = 0;
for (anitomy::string_t value : category_elements) {
output->Set(index, v8::String::NewFromUtf8(isolate, ToStr(value).c_str()));
index++;
}
return output;
}
v8::Local<v8::Object> AnitomyJs::BuildObject(anitomy::Elements& elements, v8::Isolate* isolate) {
v8::Local<v8::Object> object = v8::Object::New(isolate);
SetEntry(object, isolate, "anime_season", elements, anitomy::kElementAnimeSeason);
SetEntry(object, isolate, "season_prefix", elements, anitomy::kElementAnimeSeasonPrefix);
SetEntry(object, isolate, "anime_title", elements, anitomy::kElementAnimeTitle);
SetEntry(object, isolate, "anime_type", elements, anitomy::kElementAnimeType);
SetEntry(object, isolate, "anime_year", elements, anitomy::kElementAnimeYear);
SetEntry(object, isolate, "audio_term", elements, anitomy::kElementAudioTerm);
SetEntry(object, isolate, "device_compatibility", elements, anitomy::kElementDeviceCompatibility);
SetEntry(object, isolate, "episode_number", elements, anitomy::kElementEpisodeNumber);
SetEntry(object, isolate, "episode_number_alt", elements, anitomy::kElementEpisodeNumberAlt);
SetEntry(object, isolate, "episode_prefix", elements, anitomy::kElementEpisodePrefix);
SetEntry(object, isolate, "episode_title", elements, anitomy::kElementEpisodeTitle);
SetEntry(object, isolate, "file_checksum", elements, anitomy::kElementFileChecksum);
SetEntry(object, isolate, "file_extension", elements, anitomy::kElementFileExtension);
SetEntry(object, isolate, "file_name", elements, anitomy::kElementFileName);
SetEntry(object, isolate, "language", elements, anitomy::kElementLanguage);
SetEntry(object, isolate, "other", elements, anitomy::kElementOther);
SetEntry(object, isolate, "release_group", elements, anitomy::kElementReleaseGroup);
SetEntry(object, isolate, "release_information", elements, anitomy::kElementReleaseInformation);
SetEntry(object, isolate, "release_version", elements, anitomy::kElementReleaseVersion);
SetEntry(object, isolate, "source", elements, anitomy::kElementSource);
SetEntry(object, isolate, "subtitles", elements, anitomy::kElementSubtitles);
SetEntry(object, isolate, "video_resolution", elements, anitomy::kElementVideoResolution);
SetEntry(object, isolate, "video_term", elements, anitomy::kElementVideoTerm);
SetEntry(object, isolate, "volume_number", elements, anitomy::kElementVolumeNumber);
SetEntry(object, isolate, "volume_prefix", elements, anitomy::kElementVolumePrefix);
SetEntry(object, isolate, "unknow", elements, anitomy::kElementUnknown);
return object;
}
}<commit_msg>Fix typo in anitomy_js.cpp<commit_after>/*********************************************************************
* AnitomyJs - Node.js wrapper for Anitomy
*
* Copyright (c) 2016 Thiago Oliveira
*
* MIT License <https://github.com/nevermnd/anitomy-js/blob/master/LICENSE>
********************************************************************/
#include "anitomy_js.h"
namespace anitomyJs {
void AnitomyJs::SetInput(v8::Local<v8::Value> value) {
is_batch_parse_ = value->IsArray();
if (is_batch_parse_) {
v8::Local<v8::Array> input = v8::Local<v8::Array>::Cast(value);
for (unsigned int i = 0; i < input->Length(); i++) input_.push_back(ToWideString(input->Get(i)));
} else {
input_.push_back(ToWideString(value));
}
}
void AnitomyJs::Parse() {
for (std::wstring str : input_) {
anitomy_.Parse(str);
parsed_.push_back(anitomy_.elements());
}
}
std::vector<anitomy::Elements> AnitomyJs::Parsed() {
return parsed_;
}
// TODO For ~desu's sake, stop doing this flag shit
v8::Local<v8::Value> AnitomyJs::ParsedResult(v8::Isolate* isolate) {
v8::Local<v8::Array> output = v8::Array::New(isolate, parsed_.size());
unsigned int index = 0;
for (anitomy::Elements element : parsed_) {
output->Set(index, BuildObject(element, isolate));
index++;
}
if (is_batch_parse_) return output;
return output->Get(0);
}
std::wstring AnitomyJs::ToWideString(v8::Local<v8::Value> str) {
v8::String::Utf8Value utf_value(str->ToString());
std::string str_value(*utf_value);
return std::wstring(str_value.begin(), str_value.end());
}
std::string AnitomyJs::ToStr(anitomy::string_t str) {
std::wstring ws_value(str.c_str());
return std::string(ws_value.begin(), ws_value.end());
}
void AnitomyJs::SetEntry(v8::Local<v8::Object>& object, v8::Isolate* isolate, const char* entry,
anitomy::Elements& elements, anitomy::ElementCategory pos) {
v8::Local<v8::String> entry_name = v8::String::NewFromUtf8(isolate, entry);
switch(elements.count(pos)) {
case 0:
break;
case 1:
object->Set(entry_name, v8::String::NewFromUtf8(isolate, ToStr(elements.get(pos)).c_str()));
break;
default:
object->Set(entry_name, CategoryArray(elements, pos, isolate));
}
}
v8::Local<v8::Array> AnitomyJs::CategoryArray(anitomy::Elements& elements,
anitomy::ElementCategory pos, v8::Isolate* isolate) {
std::vector<anitomy::string_t> category_elements = elements.get_all(pos);
v8::Local<v8::Array> output = v8::Array::New(isolate, category_elements.size());
unsigned int index = 0;
for (anitomy::string_t value : category_elements) {
output->Set(index, v8::String::NewFromUtf8(isolate, ToStr(value).c_str()));
index++;
}
return output;
}
v8::Local<v8::Object> AnitomyJs::BuildObject(anitomy::Elements& elements, v8::Isolate* isolate) {
v8::Local<v8::Object> object = v8::Object::New(isolate);
SetEntry(object, isolate, "anime_season", elements, anitomy::kElementAnimeSeason);
SetEntry(object, isolate, "season_prefix", elements, anitomy::kElementAnimeSeasonPrefix);
SetEntry(object, isolate, "anime_title", elements, anitomy::kElementAnimeTitle);
SetEntry(object, isolate, "anime_type", elements, anitomy::kElementAnimeType);
SetEntry(object, isolate, "anime_year", elements, anitomy::kElementAnimeYear);
SetEntry(object, isolate, "audio_term", elements, anitomy::kElementAudioTerm);
SetEntry(object, isolate, "device_compatibility", elements, anitomy::kElementDeviceCompatibility);
SetEntry(object, isolate, "episode_number", elements, anitomy::kElementEpisodeNumber);
SetEntry(object, isolate, "episode_number_alt", elements, anitomy::kElementEpisodeNumberAlt);
SetEntry(object, isolate, "episode_prefix", elements, anitomy::kElementEpisodePrefix);
SetEntry(object, isolate, "episode_title", elements, anitomy::kElementEpisodeTitle);
SetEntry(object, isolate, "file_checksum", elements, anitomy::kElementFileChecksum);
SetEntry(object, isolate, "file_extension", elements, anitomy::kElementFileExtension);
SetEntry(object, isolate, "file_name", elements, anitomy::kElementFileName);
SetEntry(object, isolate, "language", elements, anitomy::kElementLanguage);
SetEntry(object, isolate, "other", elements, anitomy::kElementOther);
SetEntry(object, isolate, "release_group", elements, anitomy::kElementReleaseGroup);
SetEntry(object, isolate, "release_information", elements, anitomy::kElementReleaseInformation);
SetEntry(object, isolate, "release_version", elements, anitomy::kElementReleaseVersion);
SetEntry(object, isolate, "source", elements, anitomy::kElementSource);
SetEntry(object, isolate, "subtitles", elements, anitomy::kElementSubtitles);
SetEntry(object, isolate, "video_resolution", elements, anitomy::kElementVideoResolution);
SetEntry(object, isolate, "video_term", elements, anitomy::kElementVideoTerm);
SetEntry(object, isolate, "volume_number", elements, anitomy::kElementVolumeNumber);
SetEntry(object, isolate, "volume_prefix", elements, anitomy::kElementVolumePrefix);
SetEntry(object, isolate, "unknown", elements, anitomy::kElementUnknown);
return object;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008, 2009 Nokia Corporation.
*
* Contact: Marius Vollmer <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* 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 <QtTest/QtTest>
#include <QtCore>
#include "fileutils.h"
#include "infocdbbackend.h"
#include "cdbwriter.h"
class InfoCdbBackendUnitTest : public QObject
{
Q_OBJECT
InfoCdbBackend *backend;
private slots:
void initTestCase();
void databaseExists();
void listKeys();
void listPlugins();
void listKeysForPlugin();
void typeForKey();
void docForKey();
void pluginForKey();
void keyExists();
void constructionStringForKey();
void keyProvided();
void dynamics();
void cleanupTestCase();
};
void InfoCdbBackendUnitTest::initTestCase()
{
// Create the cdb
CDBWriter writer(LOCAL_FILE("cache.cdb"));
writer.add("KEYS", "Battery.Charging");
writer.add("KEYS", "Internet.BytesOut");
writer.add("PLUGINS", "contextkit-dbus");
writer.add("contextkit-dbus:KEYS", "Battery.Charging");
writer.add("contextkit-dbus:KEYS", "Internet.BytesOut");
writer.add("Battery.Charging:KEYTYPE", "TRUTH");
writer.add("Internet.BytesOut:KEYTYPE", "INTEGER");
writer.add("Battery.Charging:KEYDOC", "doc1");
writer.add("Internet.BytesOut:KEYPLUGIN", "contextkit-dbus");
writer.add("Battery.Charging:KEYPLUGIN", "contextkit-dbus");
writer.add("Battery.Charging:KEYCONSTRUCTIONSTRING", "system:org.freedesktop.ContextKit.contextd1");
writer.add("Internet.BytesOut:KEYCONSTRUCTIONSTRING", "session:org.freedesktop.ContextKit.contextd2");
writer.close();
utilSetEnv("CONTEXT_PROVIDERS", LOCAL_DIR);
utilSetEnv("CONTEXT_CORE_DECLARATIONS", "/dev/null");
backend = new InfoCdbBackend();
}
void InfoCdbBackendUnitTest::databaseExists()
{
QCOMPARE(backend->databaseExists(), true);
}
void InfoCdbBackendUnitTest::listKeys()
{
QStringList keys = backend->listKeys();
QCOMPARE(keys.count(), 2);
QVERIFY(keys.contains("Battery.Charging"));
QVERIFY(keys.contains("Internet.BytesOut"));
}
void InfoCdbBackendUnitTest::listPlugins()
{
QStringList plugins = backend->listPlugins();
QCOMPARE(plugins.count(), 1);
QVERIFY(plugins.contains("contextkit-dbus"));
}
void InfoCdbBackendUnitTest::listKeysForPlugin()
{
QStringList keys1 = backend->listKeysForPlugin("contextkit-dbus");
QCOMPARE(keys1.count(), 2);
QVERIFY(keys1.contains("Battery.Charging"));
QVERIFY(keys1.contains("Internet.BytesOut"));
QStringList keys2 = backend->listKeysForPlugin("non-existant");
QCOMPARE(keys2.count(), 0);
}
void InfoCdbBackendUnitTest::typeForKey()
{
QCOMPARE(backend->typeForKey("Internet.BytesOut"), QString("INTEGER"));
QCOMPARE(backend->typeForKey("Battery.Charging"), QString("TRUTH"));
QCOMPARE(backend->typeForKey("Does.Not.Exist"), QString());
}
void InfoCdbBackendUnitTest::docForKey()
{
QCOMPARE(backend->docForKey("Internet.BytesOut"), QString());
QCOMPARE(backend->docForKey("Battery.Charging"), QString("doc1"));
QCOMPARE(backend->docForKey("Does.Not.Exist"), QString());
}
void InfoCdbBackendUnitTest::pluginForKey()
{
foreach (QString key, backend->listKeys())
QCOMPARE(backend->pluginForKey(key), QString("contextkit-dbus"));
QCOMPARE(backend->pluginForKey("Does.Not.Exist"), QString());
}
void InfoCdbBackendUnitTest::keyExists()
{
foreach (QString key, backend->listKeys())
QCOMPARE(backend->keyExists(key), true);
QCOMPARE(backend->keyExists("Does.Not.Exist"), false);
QCOMPARE(backend->keyExists("Battery.Charging"), true);
}
void InfoCdbBackendUnitTest::constructionStringForKey()
{
foreach (QString key, backend->listKeys())
QVERIFY(backend->constructionStringForKey(key) != QString());
QCOMPARE(backend->constructionStringForKey("Battery.Charging"), QString("system:org.freedesktop.ContextKit.contextd1"));
QCOMPARE(backend->constructionStringForKey("Does.Not.Exist"), QString());
}
void InfoCdbBackendUnitTest::keyProvided()
{
foreach (QString key, backend->listKeys())
QVERIFY(backend->keyProvided(key) == true);
QCOMPARE(backend->keyProvided("Does.Not.Exist"), false);
}
void InfoCdbBackendUnitTest::dynamics()
{
// Write new database
CDBWriter writer(LOCAL_FILE("cache-next.cdb"));
writer.add("KEYS", "Battery.Charging");
writer.add("KEYS", "Battery.Capacity");
writer.add("PLUGINS", "contextkit-dbus");
writer.add("contextkit-dbus:KEYS", "Battery.Charging");
writer.add("contextkit-dbus:KEYS", "Battery.Capacity");
writer.add("Battery.Charging:KEYTYPE", "INTEGER");
writer.add("Battery.Charging:KEYDOC", "doc1");
writer.add("Battery.Charging:KEYPLUGIN", "contextkit-dbus");
writer.add("Battery.Charging:KEYCONSTRUCTIONSTRING", "system:org.freedesktop.ContextKit.contextd1");
writer.add("Battery.Capacity:KEYTYPE", "INTEGER");
writer.add("Battery.Capacity:KEYDOC", "doc3");
writer.add("Battery.Capacity:KEYPLUGIN", "contextkit-dbus");
writer.add("Battery.Capacity:KEYCONSTRUCTIONSTRING", "system:org.freedesktop.ContextKit.contextd1");
writer.close();
backend->connectNotify("-"); // Fake it. Spy does something fishy here.
// Setup the spy observers
QSignalSpy spy1(backend, SIGNAL(keysRemoved(QStringList)));
QSignalSpy spy2(backend, SIGNAL(keysChanged(QStringList)));
QSignalSpy spy3(backend, SIGNAL(keyDataChanged(QString)));
QSignalSpy spy4(backend, SIGNAL(keysAdded(QStringList)));
utilCopyLocalWithRemove("cache-next.cdb", "cache.cdb");
// Test the new values
QCOMPARE(backend->databaseExists(), true);
QCOMPARE(backend->listKeys().count(), 2);
QVERIFY(backend->listKeys().contains("Battery.Charging"));
QVERIFY(backend->listKeys().contains("Battery.Capacity"));
QCOMPARE(backend->typeForKey("Battery.Charging"), QString("INTEGER"));
QCOMPARE(backend->docForKey("Battery.Charging"), QString("doc1"));
QVERIFY(backend->keyProvided("Battery.Charging") == true);
QVERIFY(backend->keyProvided("Internet.BytesOut") == false);
// Test emissions
QCOMPARE(spy1.count(), 1);
QList<QVariant> args1 = spy1.takeFirst();
QCOMPARE(args1.at(0).toList().size(), 1);
QCOMPARE(args1.at(0).toStringList().at(0), QString("Internet.BytesOut"));
QCOMPARE(spy2.count(), 1);
QList<QVariant> args2 = spy2.takeFirst();
QCOMPARE(args2.at(0).toList().size(), 2);
QCOMPARE(args2.at(0).toStringList().at(0), QString("Battery.Charging"));
QCOMPARE(args2.at(0).toStringList().at(1), QString("Battery.Capacity"));
QCOMPARE(spy3.count(), 3);
QCOMPARE(spy4.count(), 1);
QList<QVariant> args4 = spy4.takeFirst();
QCOMPARE(args4.at(0).toList().size(), 1);
QCOMPARE(args4.at(0).toStringList().at(0), QString("Battery.Capacity"));
backend->disconnectNotify("-"); // Fake it. Spy does something fishy here.
}
void InfoCdbBackendUnitTest::cleanupTestCase()
{
QFile::remove("cache.cdb");
QFile::remove(LOCAL_FILE("cache.cdb"));
QFile::remove("cache-next.cdb");
QFile::remove(LOCAL_FILE("cache-next.cdb"));
}
#include "infocdbbackendunittest.moc"
QTEST_MAIN(InfoCdbBackendUnitTest);
<commit_msg>Refactoring the CDB creation.<commit_after>/*
* Copyright (C) 2008, 2009 Nokia Corporation.
*
* Contact: Marius Vollmer <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* 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 <QtTest/QtTest>
#include <QtCore>
#include "fileutils.h"
#include "infocdbbackend.h"
#include "cdbwriter.h"
class InfoCdbBackendUnitTest : public QObject
{
Q_OBJECT
InfoCdbBackend *backend;
private:
void createBaseDatabase(QString path);
void createAlternateDatabase(QString path);
private slots:
void initTestCase();
void databaseExists();
void listKeys();
void listPlugins();
void listKeysForPlugin();
void typeForKey();
void docForKey();
void pluginForKey();
void keyExists();
void constructionStringForKey();
void keyProvided();
void dynamics();
void cleanupTestCase();
};
void InfoCdbBackendUnitTest::createBaseDatabase(QString path)
{
CDBWriter writer(path);
writer.add("KEYS", "Battery.Charging");
writer.add("KEYS", "Internet.BytesOut");
writer.add("PLUGINS", "contextkit-dbus");
writer.add("contextkit-dbus:KEYS", "Battery.Charging");
writer.add("contextkit-dbus:KEYS", "Internet.BytesOut");
writer.add("Battery.Charging:KEYTYPE", "TRUTH");
writer.add("Internet.BytesOut:KEYTYPE", "INTEGER");
writer.add("Battery.Charging:KEYDOC", "doc1");
writer.add("Internet.BytesOut:KEYPLUGIN", "contextkit-dbus");
writer.add("Battery.Charging:KEYPLUGIN", "contextkit-dbus");
writer.add("Battery.Charging:KEYCONSTRUCTIONSTRING", "system:org.freedesktop.ContextKit.contextd1");
writer.add("Internet.BytesOut:KEYCONSTRUCTIONSTRING", "session:org.freedesktop.ContextKit.contextd2");
writer.close();
}
void InfoCdbBackendUnitTest::createAlternateDatabase(QString path)
{
CDBWriter writer(path);
writer.add("KEYS", "Battery.Charging");
writer.add("KEYS", "Battery.Capacity");
writer.add("PLUGINS", "contextkit-dbus");
writer.add("contextkit-dbus:KEYS", "Battery.Charging");
writer.add("contextkit-dbus:KEYS", "Battery.Capacity");
writer.add("Battery.Charging:KEYTYPE", "INTEGER");
writer.add("Battery.Charging:KEYDOC", "doc1");
writer.add("Battery.Charging:KEYPLUGIN", "contextkit-dbus");
writer.add("Battery.Charging:KEYCONSTRUCTIONSTRING", "system:org.freedesktop.ContextKit.contextd1");
writer.add("Battery.Capacity:KEYTYPE", "INTEGER");
writer.add("Battery.Capacity:KEYDOC", "doc3");
writer.add("Battery.Capacity:KEYPLUGIN", "contextkit-dbus");
writer.add("Battery.Capacity:KEYCONSTRUCTIONSTRING", "system:org.freedesktop.ContextKit.contextd1");
writer.close();
}
void InfoCdbBackendUnitTest::initTestCase()
{
createBaseDatabase(LOCAL_FILE("cache.cdb"));
utilSetEnv("CONTEXT_PROVIDERS", LOCAL_DIR);
utilSetEnv("CONTEXT_CORE_DECLARATIONS", "/dev/null");
backend = new InfoCdbBackend();
}
void InfoCdbBackendUnitTest::databaseExists()
{
QCOMPARE(backend->databaseExists(), true);
}
void InfoCdbBackendUnitTest::listKeys()
{
QStringList keys = backend->listKeys();
QCOMPARE(keys.count(), 2);
QVERIFY(keys.contains("Battery.Charging"));
QVERIFY(keys.contains("Internet.BytesOut"));
}
void InfoCdbBackendUnitTest::listPlugins()
{
QStringList plugins = backend->listPlugins();
QCOMPARE(plugins.count(), 1);
QVERIFY(plugins.contains("contextkit-dbus"));
}
void InfoCdbBackendUnitTest::listKeysForPlugin()
{
QStringList keys1 = backend->listKeysForPlugin("contextkit-dbus");
QCOMPARE(keys1.count(), 2);
QVERIFY(keys1.contains("Battery.Charging"));
QVERIFY(keys1.contains("Internet.BytesOut"));
QStringList keys2 = backend->listKeysForPlugin("non-existant");
QCOMPARE(keys2.count(), 0);
}
void InfoCdbBackendUnitTest::typeForKey()
{
QCOMPARE(backend->typeForKey("Internet.BytesOut"), QString("INTEGER"));
QCOMPARE(backend->typeForKey("Battery.Charging"), QString("TRUTH"));
QCOMPARE(backend->typeForKey("Does.Not.Exist"), QString());
}
void InfoCdbBackendUnitTest::docForKey()
{
QCOMPARE(backend->docForKey("Internet.BytesOut"), QString());
QCOMPARE(backend->docForKey("Battery.Charging"), QString("doc1"));
QCOMPARE(backend->docForKey("Does.Not.Exist"), QString());
}
void InfoCdbBackendUnitTest::pluginForKey()
{
foreach (QString key, backend->listKeys())
QCOMPARE(backend->pluginForKey(key), QString("contextkit-dbus"));
QCOMPARE(backend->pluginForKey("Does.Not.Exist"), QString());
}
void InfoCdbBackendUnitTest::keyExists()
{
foreach (QString key, backend->listKeys())
QCOMPARE(backend->keyExists(key), true);
QCOMPARE(backend->keyExists("Does.Not.Exist"), false);
QCOMPARE(backend->keyExists("Battery.Charging"), true);
}
void InfoCdbBackendUnitTest::constructionStringForKey()
{
foreach (QString key, backend->listKeys())
QVERIFY(backend->constructionStringForKey(key) != QString());
QCOMPARE(backend->constructionStringForKey("Battery.Charging"), QString("system:org.freedesktop.ContextKit.contextd1"));
QCOMPARE(backend->constructionStringForKey("Does.Not.Exist"), QString());
}
void InfoCdbBackendUnitTest::keyProvided()
{
foreach (QString key, backend->listKeys())
QVERIFY(backend->keyProvided(key) == true);
QCOMPARE(backend->keyProvided("Does.Not.Exist"), false);
}
void InfoCdbBackendUnitTest::dynamics()
{
backend->connectNotify("-"); // Fake it. Spy does something fishy here.
// Setup the spy observers
QSignalSpy spy1(backend, SIGNAL(keysRemoved(QStringList)));
QSignalSpy spy2(backend, SIGNAL(keysChanged(QStringList)));
QSignalSpy spy3(backend, SIGNAL(keyDataChanged(QString)));
QSignalSpy spy4(backend, SIGNAL(keysAdded(QStringList)));
createAlternateDatabase(LOCAL_FILE("cache-next.cdb"));
utilCopyLocalWithRemove("cache-next.cdb", "cache.cdb");
// Test the new values
QCOMPARE(backend->databaseExists(), true);
QCOMPARE(backend->listKeys().count(), 2);
QVERIFY(backend->listKeys().contains("Battery.Charging"));
QVERIFY(backend->listKeys().contains("Battery.Capacity"));
QCOMPARE(backend->typeForKey("Battery.Charging"), QString("INTEGER"));
QCOMPARE(backend->docForKey("Battery.Charging"), QString("doc1"));
QVERIFY(backend->keyProvided("Battery.Charging") == true);
QVERIFY(backend->keyProvided("Internet.BytesOut") == false);
// Test emissions
QCOMPARE(spy1.count(), 1);
QList<QVariant> args1 = spy1.takeFirst();
QCOMPARE(args1.at(0).toList().size(), 1);
QCOMPARE(args1.at(0).toStringList().at(0), QString("Internet.BytesOut"));
QCOMPARE(spy2.count(), 1);
QList<QVariant> args2 = spy2.takeFirst();
QCOMPARE(args2.at(0).toList().size(), 2);
QCOMPARE(args2.at(0).toStringList().at(0), QString("Battery.Charging"));
QCOMPARE(args2.at(0).toStringList().at(1), QString("Battery.Capacity"));
QCOMPARE(spy3.count(), 3);
QCOMPARE(spy4.count(), 1);
QList<QVariant> args4 = spy4.takeFirst();
QCOMPARE(args4.at(0).toList().size(), 1);
QCOMPARE(args4.at(0).toStringList().at(0), QString("Battery.Capacity"));
backend->disconnectNotify("-"); // Fake it. Spy does something fishy here.
}
void InfoCdbBackendUnitTest::cleanupTestCase()
{
QFile::remove("cache.cdb");
QFile::remove(LOCAL_FILE("cache.cdb"));
QFile::remove("cache-next.cdb");
QFile::remove(LOCAL_FILE("cache-next.cdb"));
}
#include "infocdbbackendunittest.moc"
QTEST_MAIN(InfoCdbBackendUnitTest);
<|endoftext|> |
<commit_before><commit_msg>Create main_BACKUP.cpp<commit_after><|endoftext|> |
<commit_before>/***************************************************************************//**
* FILE : rendition.hpp
*/
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is libZinc.
*
* The Initial Developer of the Original Code is
* Auckland Uniservices Ltd, Auckland, New Zealand.
* Portions created by the Initial Developer are Copyright (C) 2012
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef __ZN_CMISS_RENDITION_HPP__
#define __ZN_CMISS_RENDITION_HPP__
#include "zinc/rendition.h"
#include "zinc/graphic.hpp"
#include "zinc/fieldtypesgroup.hpp"
#include "zinc/selection.hpp"
namespace zinc
{
class Rendition
{
protected:
Cmiss_rendition_id id;
public:
Rendition() : id(0)
{ }
// takes ownership of C handle, responsibility for destroying it
explicit Rendition(Cmiss_rendition_id rendition_id) : id(rendition_id)
{ }
Rendition(const Rendition& rendition) : id(Cmiss_rendition_access(rendition.id))
{ }
Rendition& operator=(const Rendition& rendition)
{
Cmiss_rendition_id temp_id = Cmiss_rendition_access(rendition.id);
if (0 != id)
{
Cmiss_rendition_destroy(&id);
}
id = temp_id;
return *this;
}
~Rendition()
{
if (0 != id)
{
Cmiss_rendition_destroy(&id);
}
}
bool isValid()
{
return (0 != id);
}
// needed for casting constructors: see RenditionImage(Rendition&)
Cmiss_rendition_id getId()
{
return id;
}
int beginChange()
{
return Cmiss_rendition_begin_change(id);
}
int endChange()
{
return Cmiss_rendition_end_change(id);
}
Graphic createGraphic(Graphic::GraphicType graphicType)
{
return Graphic(Cmiss_rendition_create_graphic(id,
static_cast<Cmiss_graphic_type>(graphicType)));
}
GraphicIsoSurface createGraphicIsoSurface()
{
Cmiss_graphic_id graphic = Cmiss_rendition_create_graphic(id,
static_cast<Cmiss_graphic_type>(Graphic::GRAPHIC_ISO_SURFACES));
return GraphicIsoSurface(Cmiss_graphic_cast_iso_surface(graphic));
}
SelectionHandler createSelectionHandler()
{
return SelectionHandler(Cmiss_rendition_create_selection_handler(id));
}
/***************************************************************************//**
* Returns the graphic of the specified name from the rendition. Beware that
* graphics in the same rendition may have the same name and this function will
* only return the first graphic found with the specified name;
*
* @param rendition Rendition in which to find the graphic.
* @param graphic_name The name of the graphic to find.
* @return New reference to graphic of specified name, or 0 if not found.
*/
Graphic findGraphicByName(const char *graphicName)
{
return Graphic(Cmiss_rendition_find_graphic_by_name(id, graphicName));
}
Graphic getFirstGraphic()
{
return Graphic(Cmiss_rendition_get_first_graphic(id));
}
Graphic getNextGraphic(Graphic& refGraphic)
{
return Graphic(Cmiss_rendition_get_next_graphic(id, refGraphic.getId()));
}
Graphic getPreviousGraphic(Graphic& refGraphic)
{
return Graphic(Cmiss_rendition_get_previous_graphic(id, refGraphic.getId()));
}
int getNumberOfGraphics()
{
return Cmiss_rendition_get_number_of_graphics(id);
}
FieldGroup getSelectionGroup()
{
return FieldGroup(Cmiss_rendition_get_selection_group(id));
}
int setSelectionGroup(FieldGroup& fieldGroup)
{
return Cmiss_rendition_set_selection_group(id,
(Cmiss_field_group_id)(fieldGroup.getId()));
}
bool getVisibilityFlag()
{
return Cmiss_rendition_get_visibility_flag(id);
}
int setVisibilityFlag(bool visibilityFlag)
{
return Cmiss_rendition_set_visibility_flag(id, (int)visibilityFlag);
}
int moveGraphicBefore(Graphic& graphic, Graphic& refGraphic)
{
return Cmiss_rendition_move_graphic_before(id, graphic.getId(), refGraphic.getId());
}
int removeAllGraphics()
{
return Cmiss_rendition_remove_all_graphics(id);
}
int removeGraphic(Graphic& graphic)
{
return Cmiss_rendition_remove_graphic(id, graphic.getId());
}
};
} // namespace Cmiss
#endif /* __ZN_CMISS_RENDITION_HPP__ */
<commit_msg>Doxygen documetation comment tidy up for zinc/rendition.hpp. https://tracker.physiomeproject.org/show_bug.cgi?id=3535<commit_after>/***************************************************************************//**
* FILE : rendition.hpp
*/
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is libZinc.
*
* The Initial Developer of the Original Code is
* Auckland Uniservices Ltd, Auckland, New Zealand.
* Portions created by the Initial Developer are Copyright (C) 2012
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef __ZN_CMISS_RENDITION_HPP__
#define __ZN_CMISS_RENDITION_HPP__
#include "zinc/rendition.h"
#include "zinc/graphic.hpp"
#include "zinc/fieldtypesgroup.hpp"
#include "zinc/selection.hpp"
namespace zinc
{
class Rendition
{
protected:
Cmiss_rendition_id id;
public:
Rendition() : id(0)
{ }
// takes ownership of C handle, responsibility for destroying it
explicit Rendition(Cmiss_rendition_id rendition_id) : id(rendition_id)
{ }
Rendition(const Rendition& rendition) : id(Cmiss_rendition_access(rendition.id))
{ }
Rendition& operator=(const Rendition& rendition)
{
Cmiss_rendition_id temp_id = Cmiss_rendition_access(rendition.id);
if (0 != id)
{
Cmiss_rendition_destroy(&id);
}
id = temp_id;
return *this;
}
~Rendition()
{
if (0 != id)
{
Cmiss_rendition_destroy(&id);
}
}
bool isValid()
{
return (0 != id);
}
// needed for casting constructors: see RenditionImage(Rendition&)
Cmiss_rendition_id getId()
{
return id;
}
int beginChange()
{
return Cmiss_rendition_begin_change(id);
}
int endChange()
{
return Cmiss_rendition_end_change(id);
}
Graphic createGraphic(Graphic::GraphicType graphicType)
{
return Graphic(Cmiss_rendition_create_graphic(id,
static_cast<Cmiss_graphic_type>(graphicType)));
}
GraphicIsoSurface createGraphicIsoSurface()
{
Cmiss_graphic_id graphic = Cmiss_rendition_create_graphic(id,
static_cast<Cmiss_graphic_type>(Graphic::GRAPHIC_ISO_SURFACES));
return GraphicIsoSurface(Cmiss_graphic_cast_iso_surface(graphic));
}
SelectionHandler createSelectionHandler()
{
return SelectionHandler(Cmiss_rendition_create_selection_handler(id));
}
/**
* Returns the graphic of the specified name from the rendition. Beware that
* graphics in the same rendition may have the same name and this function will
* only return the first graphic found with the specified name;
*
* @param rendition Rendition in which to find the graphic.
* @param graphic_name The name of the graphic to find.
* @return New reference to graphic of specified name, or 0 if not found.
*/
Graphic findGraphicByName(const char *graphicName)
{
return Graphic(Cmiss_rendition_find_graphic_by_name(id, graphicName));
}
Graphic getFirstGraphic()
{
return Graphic(Cmiss_rendition_get_first_graphic(id));
}
Graphic getNextGraphic(Graphic& refGraphic)
{
return Graphic(Cmiss_rendition_get_next_graphic(id, refGraphic.getId()));
}
Graphic getPreviousGraphic(Graphic& refGraphic)
{
return Graphic(Cmiss_rendition_get_previous_graphic(id, refGraphic.getId()));
}
int getNumberOfGraphics()
{
return Cmiss_rendition_get_number_of_graphics(id);
}
FieldGroup getSelectionGroup()
{
return FieldGroup(Cmiss_rendition_get_selection_group(id));
}
int setSelectionGroup(FieldGroup& fieldGroup)
{
return Cmiss_rendition_set_selection_group(id,
(Cmiss_field_group_id)(fieldGroup.getId()));
}
bool getVisibilityFlag()
{
return Cmiss_rendition_get_visibility_flag(id);
}
int setVisibilityFlag(bool visibilityFlag)
{
return Cmiss_rendition_set_visibility_flag(id, (int)visibilityFlag);
}
int moveGraphicBefore(Graphic& graphic, Graphic& refGraphic)
{
return Cmiss_rendition_move_graphic_before(id, graphic.getId(), refGraphic.getId());
}
int removeAllGraphics()
{
return Cmiss_rendition_remove_all_graphics(id);
}
int removeGraphic(Graphic& graphic)
{
return Cmiss_rendition_remove_graphic(id, graphic.getId());
}
};
} // namespace Cmiss
#endif /* __ZN_CMISS_RENDITION_HPP__ */
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2002-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders 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.
*
* Authors: Nathan Binkert
*/
#ifndef __REFCNT_HH__
#define __REFCNT_HH__
#include <stddef.h> //For the NULL macro definition
class RefCounted
{
private:
int count;
private:
RefCounted(const RefCounted &);
public:
RefCounted() : count(0) {}
virtual ~RefCounted() {}
void incref() { ++count; }
void decref() { if (--count <= 0) delete this; }
};
template <class T>
class RefCountingPtr
{
protected:
T *data;
void copy(T *d)
{
data = d;
if (data)
data->incref();
}
void del()
{
if (data)
data->decref();
}
void set(T *d)
{
if (data == d)
return;
del();
copy(d);
}
public:
RefCountingPtr() : data(NULL) {}
RefCountingPtr(T *data) { copy(data); }
RefCountingPtr(const RefCountingPtr &r) { copy(r.data); }
~RefCountingPtr() { del(); }
T *operator->() { return data; }
T &operator*() { return *data; }
T *get() { return data; }
const T *operator->() const { return data; }
const T &operator*() const { return *data; }
const T *get() const { return data; }
RefCountingPtr &operator=(T *p) { set(p); return *this; }
RefCountingPtr &operator=(const RefCountingPtr &r)
{ return operator=(r.data); }
bool operator!() const { return data == 0; }
operator bool() const { return data != 0; }
};
template<class T>
bool operator==(const RefCountingPtr<T> &l, const RefCountingPtr<T> &r)
{ return l.get() == r.get(); }
template<class T>
bool operator==(const RefCountingPtr<T> &l, const T *r)
{ return l.get() == r; }
template<class T>
bool operator==(const T &l, const RefCountingPtr<T> &r)
{ return l == r.get(); }
template<class T>
bool operator!=(const RefCountingPtr<T> &l, const RefCountingPtr<T> &r)
{ return l.get() != r.get(); }
template<class T>
bool operator!=(const RefCountingPtr<T> &l, const T *r)
{ return l.get() != r; }
template<class T>
bool operator!=(const T &l, const RefCountingPtr<T> &r)
{ return l != r.get(); }
#endif // __REFCNT_HH__
<commit_msg>No need to use NULL, just use 0 The result of operator= cannot be an l-value<commit_after>/*
* Copyright (c) 2002-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders 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.
*
* Authors: Nathan Binkert
*/
#ifndef __BASE_REFCNT_HH__
#define __BASE_REFCNT_HH__
class RefCounted
{
private:
int count;
private:
RefCounted(const RefCounted &);
public:
RefCounted() : count(0) {}
virtual ~RefCounted() {}
void incref() { ++count; }
void decref() { if (--count <= 0) delete this; }
};
template <class T>
class RefCountingPtr
{
protected:
T *data;
void copy(T *d)
{
data = d;
if (data)
data->incref();
}
void del()
{
if (data)
data->decref();
}
void set(T *d)
{
if (data == d)
return;
del();
copy(d);
}
public:
RefCountingPtr() : data(0) {}
RefCountingPtr(T *data) { copy(data); }
RefCountingPtr(const RefCountingPtr &r) { copy(r.data); }
~RefCountingPtr() { del(); }
T *operator->() { return data; }
T &operator*() { return *data; }
T *get() { return data; }
const T *operator->() const { return data; }
const T &operator*() const { return *data; }
const T *get() const { return data; }
const RefCountingPtr &operator=(T *p) { set(p); return *this; }
const RefCountingPtr &operator=(const RefCountingPtr &r)
{ return operator=(r.data); }
bool operator!() const { return data == 0; }
operator bool() const { return data != 0; }
};
template<class T>
bool operator==(const RefCountingPtr<T> &l, const RefCountingPtr<T> &r)
{ return l.get() == r.get(); }
template<class T>
bool operator==(const RefCountingPtr<T> &l, const T *r)
{ return l.get() == r; }
template<class T>
bool operator==(const T &l, const RefCountingPtr<T> &r)
{ return l == r.get(); }
template<class T>
bool operator!=(const RefCountingPtr<T> &l, const RefCountingPtr<T> &r)
{ return l.get() != r.get(); }
template<class T>
bool operator!=(const RefCountingPtr<T> &l, const T *r)
{ return l.get() != r; }
template<class T>
bool operator!=(const T &l, const RefCountingPtr<T> &r)
{ return l != r.get(); }
#endif // __BASE_REFCNT_HH__
<|endoftext|> |
<commit_before>// @(#)root/utils:$Id$
// Author: Axel Naumann, 2014-04-07
/*************************************************************************
* Copyright (C) 1995-2014, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
// Provides bindings to TCling (compiled with rtti) from rootcling (compiled
// without rtti).
#include "rootclingTCling.h"
#include "TClass.h"
#include "TCling.h"
#include "TEnum.h"
#include "TFile.h"
#include "TProtoClass.h"
#include "TROOT.h"
#include "TStreamerInfo.h"
#include "TClassEdit.h"
#include "TMetaUtils.h"
#include <memory>
#include <iostream>
#include <unordered_set>
std::string gPCMFilename;
std::vector<std::string> gClassesToStore;
std::vector<std::string> gTypedefsToStore;
std::vector<std::string> gEnumsToStore;
std::vector<std::string> gAncestorPCMNames;
extern "C"
const char ** *TROOT__GetExtraInterpreterArgs()
{
return &TROOT::GetExtraInterpreterArgs();
}
extern "C"
cling::Interpreter *TCling__GetInterpreter()
{
static bool sInitialized = false;
gROOT; // trigger initialization
if (!sInitialized) {
gCling->SetClassAutoloading(false);
sInitialized = true;
}
return ((TCling *)gCling)->GetInterpreter();
}
extern "C"
void InitializeStreamerInfoROOTFile(const char *filename)
{
gPCMFilename = filename;
}
extern "C"
void AddStreamerInfoToROOTFile(const char *normName)
{
// Filter unnamed and (anonymous) classes.
if (normName && normName[0] && normName[0] != '(')
gClassesToStore.emplace_back(normName);
}
extern "C"
void AddTypedefToROOTFile(const char *tdname)
{
gTypedefsToStore.emplace_back(tdname);
}
extern "C"
void AddEnumToROOTFile(const char *enumname)
{
gEnumsToStore.emplace_back(enumname);
}
extern "C"
void AddAncestorPCMROOTFile(const char *pcmName)
{
gAncestorPCMNames.emplace_back(pcmName);
}
static bool IsUniquePtrOffsetZero()
{
auto regularPtr = (long *)0x42;
std::unique_ptr<long> uniquePtr(regularPtr);
auto regularPtr_2 = reinterpret_cast<long **>(&uniquePtr);
static bool isZero = uniquePtr.get() == *regularPtr_2;
uniquePtr.release();
if (!isZero) {
ROOT::TMetaUtils::Error("CloseStreamerInfoROOTFile",
"UniquePtr points to %p, reinterpreting it gives %p and should have %p\n", uniquePtr.get(), *(regularPtr_2), regularPtr);
}
return isZero;
}
static bool IsUnsupportedUniquePointer(const char *normName, TDataMember *dm)
{
using namespace ROOT::TMetaUtils;
auto dmTypeName = dm->GetTypeName();
if (TClassEdit::IsUniquePtr(dmTypeName)) {
if (!IsUniquePtrOffsetZero()) return true;
auto clm = TClass::GetClass(dmTypeName);
if (!clm) {
Error("CloseStreamerInfoROOTFile", "Class %s is not available.\n", dmTypeName);
return true;
}
auto upDms = clm->GetListOfDataMembers();
if (!upDms) {
Error("CloseStreamerInfoROOTFile", "Cannot determine unique pointer %s data members.\n", dmTypeName);
return true;
}
if (0 == upDms->GetSize()) {
Error("CloseStreamerInfoROOTFile", "Unique pointer %s has zero data members.\n", dmTypeName);
return true;
}
// We check if the unique_ptr has a default deleter
std::vector<std::string> out;
int i;
TClassEdit::GetSplit(dmTypeName, out, i);
std::string_view deleterTypeName(out[2].c_str());
if (0 != deleterTypeName.find("default_delete<")) {
Error("CloseStreamerInfoROOTFile", "I/O is supported only for unique_ptrs with a default deleter. %s::%s appears to have a custom one, %s.\n", normName, dm->GetName(), deleterTypeName);
return true;
}
}
return false;
}
static bool IsSupportedClass(TClass *cl)
{
// Check if the Class is of an unsupported type
using namespace ROOT::TMetaUtils;
// Check if this is a collection of unique_ptrs
if (ROOT::ESTLType::kNotSTL != cl->GetCollectionType()) {
std::vector<std::string> out;
int i;
TClassEdit::GetSplit(cl->GetName(), out, i);
std::string_view containedObjectTypeName(out[1].c_str());
if (TClassEdit::IsUniquePtr(containedObjectTypeName)) {
Error("CloseStreamerInfoROOTFile", "Collections of unique pointers such as the selected %s are not yet supported.\n", cl->GetName());
return false;
}
}
return true;
}
extern "C"
bool CloseStreamerInfoROOTFile(bool writeEmptyRootPCM)
{
// Write all persistent TClasses.
// Avoid plugins.
TVirtualStreamerInfo::SetFactory(new TStreamerInfo());
// Don't use TFile::Open(); we don't need plugins.
TFile dictFile((gPCMFilename + "?filetype=pcm").c_str(), "RECREATE");
// Reset the content of the pcm
if (writeEmptyRootPCM) {
TObject obj;
obj.Write("EMPTY");
return true;
};
using namespace ROOT::TMetaUtils;
TObjArray protoClasses(gClassesToStore.size());
for (const auto & normName : gClassesToStore) {
TClass *cl = TClass::GetClass(normName.c_str(), kTRUE /*load*/);
if (!cl) {
Error("CloseStreamerInfoROOTFile", "Cannot find class %s.\n", normName.c_str());
return false;
}
if (!IsSupportedClass(cl)) return false;
// Check if a datamember is a unique_ptr and if yes that it has a default
// deleter.
auto dms = cl->GetListOfDataMembers();
if (!dms) {
Error("CloseStreamerInfoROOTFile", "Cannot find data members for %s.\n", normName.c_str());
return false;
}
for (auto dmObj : *dms) {
auto dm = (TDataMember *) dmObj;
if (!dm->IsPersistent()) continue;
if (IsUnsupportedUniquePointer(normName.c_str(), dm)) return false;
// We need this for the collections of T automatically selected by rootcling
if (!dm->GetDataType() && dm->IsSTLContainer()) {
auto dmTypeName = dm->GetTypeName();
auto clm = TClass::GetClass(dmTypeName);
if (!clm) {
Error("CloseStreamerInfoROOTFile", "Cannot find class %s.\n", dmTypeName);
return false;
}
if (!IsSupportedClass(clm)) return false;
}
}
// Never store a proto class for a class which rootcling already has
// an 'official' TClass (i.e. the dictionary is in libCore or libRIO).
if (cl->IsLoaded()) continue;
// We include transient classes as they could be used by a derived
// class which may have rules setting the member of the transient class.
// (And the derived class RealData *do* contain member from the transient
// base classes.
// if (cl->GetClassVersion() == 0)
// continue;
// Let's include also proxied collections in order to delay parsing as long as possible.
// In the first implementations, proxied collections did not result in a protoclass.
// If this is a proxied collection then offsets are not needed.
// if (cl->GetCollectionProxy())
// continue;
cl->Property(); // Force initialization of the bits and property fields.
protoClasses.AddLast(new TProtoClass(cl));
}
TObjArray typedefs(gTypedefsToStore.size());
for (const auto & dtname : gTypedefsToStore) {
TDataType *dt = (TDataType *)gROOT->GetListOfTypes()->FindObject(dtname.c_str());
if (!dt) {
Error("CloseStreamerInfoROOTFile", "Cannot find typedef %s.\n", dtname.c_str());
return false;
}
if (dt->GetType() == -1) {
dt->Property(); // Force initialization of the bits and property fields.
dt->GetTypeName(); // Force caching of type name.
typedefs.AddLast(dt);
}
}
TObjArray enums(gEnumsToStore.size());
for (const auto & enumname : gEnumsToStore) {
TEnum *en = nullptr;
const size_t lastSepPos = enumname.find_last_of("::");
if (lastSepPos != std::string::npos) {
const std::string nsName = enumname.substr(0, lastSepPos - 1);
TClass *tclassInstance = TClass::GetClass(nsName.c_str());
if (!tclassInstance) {
Error("CloseStreamerInfoROOTFile", "Cannot find TClass instance for namespace %s.\n", nsName.c_str());
return false;
}
auto enumListPtr = tclassInstance->GetListOfEnums();
if (!enumListPtr) {
Error("CloseStreamerInfoROOTFile", "TClass instance for namespace %s does not have any enum associated. This is an inconsistency.\n", nsName.c_str());
return false;
}
const std::string unqualifiedEnumName = enumname.substr(lastSepPos + 1);
en = (TEnum *)enumListPtr->FindObject(unqualifiedEnumName.c_str());
if (en) en->SetTitle(nsName.c_str());
} else {
en = (TEnum *)gROOT->GetListOfEnums()->FindObject(enumname.c_str());
if (en) en->SetTitle("");
}
if (!en) {
Error("CloseStreamerInfoROOTFile", "Cannot find enum %s.\n", enumname.c_str());
return false;
}
en->Property(); // Force initialization of the bits and property fields.
enums.AddLast(en);
}
if (dictFile.IsZombie())
return false;
// Instead of plugins:
protoClasses.Write("__ProtoClasses", TObject::kSingleKey);
protoClasses.Delete();
typedefs.Write("__Typedefs", TObject::kSingleKey);
enums.Write("__Enums", TObject::kSingleKey);
dictFile.WriteObjectAny(&gAncestorPCMNames, "std::vector<std::string>", "__AncestorPCMNames");
return true;
}
<commit_msg>Check unique_ptr offset exactly once if at least a unique_ptr is present in the selected classes<commit_after>// @(#)root/utils:$Id$
// Author: Axel Naumann, 2014-04-07
/*************************************************************************
* Copyright (C) 1995-2014, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
// Provides bindings to TCling (compiled with rtti) from rootcling (compiled
// without rtti).
#include "rootclingTCling.h"
#include "TClass.h"
#include "TCling.h"
#include "TEnum.h"
#include "TFile.h"
#include "TProtoClass.h"
#include "TROOT.h"
#include "TStreamerInfo.h"
#include "TClassEdit.h"
#include "TMetaUtils.h"
#include <memory>
#include <iostream>
#include <unordered_set>
std::string gPCMFilename;
std::vector<std::string> gClassesToStore;
std::vector<std::string> gTypedefsToStore;
std::vector<std::string> gEnumsToStore;
std::vector<std::string> gAncestorPCMNames;
extern "C"
const char ** *TROOT__GetExtraInterpreterArgs()
{
return &TROOT::GetExtraInterpreterArgs();
}
extern "C"
cling::Interpreter *TCling__GetInterpreter()
{
static bool sInitialized = false;
gROOT; // trigger initialization
if (!sInitialized) {
gCling->SetClassAutoloading(false);
sInitialized = true;
}
return ((TCling *)gCling)->GetInterpreter();
}
extern "C"
void InitializeStreamerInfoROOTFile(const char *filename)
{
gPCMFilename = filename;
}
extern "C"
void AddStreamerInfoToROOTFile(const char *normName)
{
// Filter unnamed and (anonymous) classes.
if (normName && normName[0] && normName[0] != '(')
gClassesToStore.emplace_back(normName);
}
extern "C"
void AddTypedefToROOTFile(const char *tdname)
{
gTypedefsToStore.emplace_back(tdname);
}
extern "C"
void AddEnumToROOTFile(const char *enumname)
{
gEnumsToStore.emplace_back(enumname);
}
extern "C"
void AddAncestorPCMROOTFile(const char *pcmName)
{
gAncestorPCMNames.emplace_back(pcmName);
}
static bool IsUniquePtrOffsetZero()
{
auto regularPtr = (long *)0x42;
std::unique_ptr<long> uniquePtr(regularPtr);
auto regularPtr_2 = reinterpret_cast<long **>(&uniquePtr);
bool isZero = uniquePtr.get() == *regularPtr_2;
uniquePtr.release();
if (!isZero) {
ROOT::TMetaUtils::Error("CloseStreamerInfoROOTFile",
"UniquePtr points to %p, reinterpreting it gives %p and should have %p\n", uniquePtr.get(), *(regularPtr_2), regularPtr);
}
return isZero;
}
static bool IsUnsupportedUniquePointer(const char *normName, TDataMember *dm)
{
using namespace ROOT::TMetaUtils;
auto dmTypeName = dm->GetTypeName();
static bool isUniquePtrOffsetZero = IsUniquePtrOffsetZero(); // call this only once
if (TClassEdit::IsUniquePtr(dmTypeName)) {
if (!isUniquePtrOffsetZero) return true;
auto clm = TClass::GetClass(dmTypeName);
if (!clm) {
Error("CloseStreamerInfoROOTFile", "Class %s is not available.\n", dmTypeName);
return true;
}
auto upDms = clm->GetListOfDataMembers();
if (!upDms) {
Error("CloseStreamerInfoROOTFile", "Cannot determine unique pointer %s data members.\n", dmTypeName);
return true;
}
if (0 == upDms->GetSize()) {
Error("CloseStreamerInfoROOTFile", "Unique pointer %s has zero data members.\n", dmTypeName);
return true;
}
// We check if the unique_ptr has a default deleter
std::vector<std::string> out;
int i;
TClassEdit::GetSplit(dmTypeName, out, i);
std::string_view deleterTypeName(out[2].c_str());
if (0 != deleterTypeName.find("default_delete<")) {
Error("CloseStreamerInfoROOTFile", "I/O is supported only for unique_ptrs with a default deleter. %s::%s appears to have a custom one, %s.\n", normName, dm->GetName(), deleterTypeName);
return true;
}
}
return false;
}
static bool IsSupportedClass(TClass *cl)
{
// Check if the Class is of an unsupported type
using namespace ROOT::TMetaUtils;
// Check if this is a collection of unique_ptrs
if (ROOT::ESTLType::kNotSTL != cl->GetCollectionType()) {
std::vector<std::string> out;
int i;
TClassEdit::GetSplit(cl->GetName(), out, i);
std::string_view containedObjectTypeName(out[1].c_str());
if (TClassEdit::IsUniquePtr(containedObjectTypeName)) {
Error("CloseStreamerInfoROOTFile", "Collections of unique pointers such as the selected %s are not yet supported.\n", cl->GetName());
return false;
}
}
return true;
}
extern "C"
bool CloseStreamerInfoROOTFile(bool writeEmptyRootPCM)
{
// Write all persistent TClasses.
// Avoid plugins.
TVirtualStreamerInfo::SetFactory(new TStreamerInfo());
// Don't use TFile::Open(); we don't need plugins.
TFile dictFile((gPCMFilename + "?filetype=pcm").c_str(), "RECREATE");
// Reset the content of the pcm
if (writeEmptyRootPCM) {
TObject obj;
obj.Write("EMPTY");
return true;
};
using namespace ROOT::TMetaUtils;
TObjArray protoClasses(gClassesToStore.size());
for (const auto & normName : gClassesToStore) {
TClass *cl = TClass::GetClass(normName.c_str(), kTRUE /*load*/);
if (!cl) {
Error("CloseStreamerInfoROOTFile", "Cannot find class %s.\n", normName.c_str());
return false;
}
if (!IsSupportedClass(cl)) return false;
// Check if a datamember is a unique_ptr and if yes that it has a default
// deleter.
auto dms = cl->GetListOfDataMembers();
if (!dms) {
Error("CloseStreamerInfoROOTFile", "Cannot find data members for %s.\n", normName.c_str());
return false;
}
for (auto dmObj : *dms) {
auto dm = (TDataMember *) dmObj;
if (!dm->IsPersistent()) continue;
if (IsUnsupportedUniquePointer(normName.c_str(), dm)) return false;
// We need this for the collections of T automatically selected by rootcling
if (!dm->GetDataType() && dm->IsSTLContainer()) {
auto dmTypeName = dm->GetTypeName();
auto clm = TClass::GetClass(dmTypeName);
if (!clm) {
Error("CloseStreamerInfoROOTFile", "Cannot find class %s.\n", dmTypeName);
return false;
}
if (!IsSupportedClass(clm)) return false;
}
}
// Never store a proto class for a class which rootcling already has
// an 'official' TClass (i.e. the dictionary is in libCore or libRIO).
if (cl->IsLoaded()) continue;
// We include transient classes as they could be used by a derived
// class which may have rules setting the member of the transient class.
// (And the derived class RealData *do* contain member from the transient
// base classes.
// if (cl->GetClassVersion() == 0)
// continue;
// Let's include also proxied collections in order to delay parsing as long as possible.
// In the first implementations, proxied collections did not result in a protoclass.
// If this is a proxied collection then offsets are not needed.
// if (cl->GetCollectionProxy())
// continue;
cl->Property(); // Force initialization of the bits and property fields.
protoClasses.AddLast(new TProtoClass(cl));
}
TObjArray typedefs(gTypedefsToStore.size());
for (const auto & dtname : gTypedefsToStore) {
TDataType *dt = (TDataType *)gROOT->GetListOfTypes()->FindObject(dtname.c_str());
if (!dt) {
Error("CloseStreamerInfoROOTFile", "Cannot find typedef %s.\n", dtname.c_str());
return false;
}
if (dt->GetType() == -1) {
dt->Property(); // Force initialization of the bits and property fields.
dt->GetTypeName(); // Force caching of type name.
typedefs.AddLast(dt);
}
}
TObjArray enums(gEnumsToStore.size());
for (const auto & enumname : gEnumsToStore) {
TEnum *en = nullptr;
const size_t lastSepPos = enumname.find_last_of("::");
if (lastSepPos != std::string::npos) {
const std::string nsName = enumname.substr(0, lastSepPos - 1);
TClass *tclassInstance = TClass::GetClass(nsName.c_str());
if (!tclassInstance) {
Error("CloseStreamerInfoROOTFile", "Cannot find TClass instance for namespace %s.\n", nsName.c_str());
return false;
}
auto enumListPtr = tclassInstance->GetListOfEnums();
if (!enumListPtr) {
Error("CloseStreamerInfoROOTFile", "TClass instance for namespace %s does not have any enum associated. This is an inconsistency.\n", nsName.c_str());
return false;
}
const std::string unqualifiedEnumName = enumname.substr(lastSepPos + 1);
en = (TEnum *)enumListPtr->FindObject(unqualifiedEnumName.c_str());
if (en) en->SetTitle(nsName.c_str());
} else {
en = (TEnum *)gROOT->GetListOfEnums()->FindObject(enumname.c_str());
if (en) en->SetTitle("");
}
if (!en) {
Error("CloseStreamerInfoROOTFile", "Cannot find enum %s.\n", enumname.c_str());
return false;
}
en->Property(); // Force initialization of the bits and property fields.
enums.AddLast(en);
}
if (dictFile.IsZombie())
return false;
// Instead of plugins:
protoClasses.Write("__ProtoClasses", TObject::kSingleKey);
protoClasses.Delete();
typedefs.Write("__Typedefs", TObject::kSingleKey);
enums.Write("__Enums", TObject::kSingleKey);
dictFile.WriteObjectAny(&gAncestorPCMNames, "std::vector<std::string>", "__AncestorPCMNames");
return true;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2021 ASMlover. 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 ofconditions 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 materialsprovided 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.
#include "value.hh"
namespace tadpole {
bool Value::is_truthy() const {
switch (type_) {
case ValueType::NIL: return false;
case ValueType::BOOLEAN: return as_.boolean;
case ValueType::NUMERIC: return as_.numeric != 0;
case ValueType::OBJECT: return as_.object->is_truthy();
}
return false;
}
str_t Value::stringify() const { return ""; }
}
<commit_msg>:construction: chore(value): updated the implementation of value<commit_after>// Copyright (c) 2021 ASMlover. 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 ofconditions 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 materialsprovided 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.
#include "value.hh"
namespace tadpole {
bool Value::is_truthy() const {
switch (type_) {
case ValueType::NIL: return false;
case ValueType::BOOLEAN: return as_.boolean;
case ValueType::NUMERIC: return as_.numeric != 0;
case ValueType::OBJECT: return as_.object->is_truthy();
}
return false;
}
str_t Value::stringify() const {
switch (type_) {
case ValueType::NIL: return "nil";
case ValueType::BOOLEAN: return as_.boolean ? "true" : "false";
case ValueType::NUMERIC: return tadpole::as_string(as_.numeric);
case ValueType::OBJECT: return as_.object->stringify();
}
return "<value>";
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2021 ASMlover. All rights reserved.
//
// ______ __ ___
// /\__ _\ /\ \ /\_ \
// \/_/\ \/ __ \_\ \ _____ ___\//\ \ __
// \ \ \ /'__`\ /'_` \/\ '__`\ / __`\\ \ \ /'__`\
// \ \ \/\ \L\.\_/\ \L\ \ \ \L\ \/\ \L\ \\_\ \_/\ __/
// \ \_\ \__/.\_\ \___,_\ \ ,__/\ \____//\____\ \____\
// \/_/\/__/\/_/\/__,_ /\ \ \/ \/___/ \/____/\/____/
// \ \_\
// \/_/
//
// 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 ofconditions 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 materialsprovided 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.
#include <iostream>
#include <Common/Colorful.hh>
#include <GC/MarkSweep.hh>
namespace Tadpole::GC {
MarkSweep::MarkSweep() noexcept {
}
MarkSweep::~MarkSweep() {
while (!objects_.empty()) {
auto* o = objects_.back();
objects_.pop_back();
reclaim_object(o);
}
}
void MarkSweep::collect() {}
void MarkSweep::append_object(Object::BaseObject* o) {}
void MarkSweep::mark_object(Object::BaseObject* o) {}
sz_t MarkSweep::get_count() const { return 0; }
sz_t MarkSweep::get_threshold() const { return 0; }
void MarkSweep::set_threshold(sz_t threshold) {}
void MarkSweep::mark() {}
void MarkSweep::mark_from_roots() {}
void MarkSweep::sweep() {}
void MarkSweep::reclaim_object(Object::BaseObject* o) {}
}
<commit_msg>:construction: chore(marksweep-collect): add collect implementation of mark-sweep<commit_after>// Copyright (c) 2021 ASMlover. All rights reserved.
//
// ______ __ ___
// /\__ _\ /\ \ /\_ \
// \/_/\ \/ __ \_\ \ _____ ___\//\ \ __
// \ \ \ /'__`\ /'_` \/\ '__`\ / __`\\ \ \ /'__`\
// \ \ \/\ \L\.\_/\ \L\ \ \ \L\ \/\ \L\ \\_\ \_/\ __/
// \ \_\ \__/.\_\ \___,_\ \ ,__/\ \____//\____\ \____\
// \/_/\/__/\/_/\/__,_ /\ \ \/ \/___/ \/____/\/____/
// \ \_\
// \/_/
//
// 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 ofconditions 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 materialsprovided 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.
#include <iostream>
#include <Common/Colorful.hh>
#include <GC/MarkSweep.hh>
namespace Tadpole::GC {
MarkSweep::MarkSweep() noexcept {
}
MarkSweep::~MarkSweep() {
while (!objects_.empty()) {
auto* o = objects_.back();
objects_.pop_back();
reclaim_object(o);
}
}
void MarkSweep::collect() {
mark_from_roots();
sweep();
gc_threshold_ = std::max(std::min(gc_threshold_, kGCThresholdMin), objects_.size() * kGCFactor);
gc_threshold_ = Common::as_align(gc_threshold_, kGCAlign);
}
void MarkSweep::append_object(Object::BaseObject* o) {}
void MarkSweep::mark_object(Object::BaseObject* o) {}
sz_t MarkSweep::get_count() const { return 0; }
sz_t MarkSweep::get_threshold() const { return 0; }
void MarkSweep::set_threshold(sz_t threshold) {}
void MarkSweep::mark() {}
void MarkSweep::mark_from_roots() {}
void MarkSweep::sweep() {}
void MarkSweep::reclaim_object(Object::BaseObject* o) {}
}
<|endoftext|> |
<commit_before>/*
** Copyright (C) 2017 Softbank Robotics Europe
** See COPYING for the license
*/
#ifndef QI_SHA1_HPP
#define QI_SHA1_HPP
#pragma once
#include <array>
#include <cstdint>
#include <type_traits>
#include <openssl/sha.h>
#include <boost/uuid/sha1.hpp>
#include <qi/scoped.hpp>
#include <qi/type/traits.hpp>
/// @file Contains sha1 digest functions.
///
/// The implementation relies on openssl.
///
/// An alternative is `boost::uuids::detail::sha1` but:
/// 1) it is in a `detail` namespace, so not officially supported
/// 2) the produced digests are different from the one of tools such as
/// `openssl sha1` and `sha1sum` (!).
/// This is apparently because of a wrong handling of endianness.
namespace qi {
/// The result of a sha1 computation is an array of 20 bytes.
using Sha1Digest = std::array<uint8_t, 20>;
namespace detail
{
// With pointers, we use the single-call update.
//
// Precondition: boundedRange(b, e) && s has been initialized
//
// I == T*, with T having the size of one byte (e.g. int8_t, uint8_t,
// unsigned char on some platforms, etc.)
template<typename I>
int sha1Update(SHA_CTX& s, I b, I e, std::true_type /* is_pointer */)
{
return SHA1_Update(&s, b, e - b);
}
// With non-pointer iterators, we update byte by byte.
//
// Precondition: boundedRange(b, e) && s has been initialized
//
// InputIterator<T> I, with T having the size of one byte
template<typename I>
int sha1Update(SHA_CTX& s, I b, I e, std::false_type /* is_pointer */)
{
int res;
while (b != e)
{
const auto c = *b;
res = SHA1_Update(&s, &c, 1u);
if (res == 0)
{
return res;
}
++b;
}
return res;
}
} // namespace detail
/// Computes the sha1 digest of the given bytes.
///
/// Note: Passing pointers intead of non-pointer iterators (even random access ones)
/// will typically be faster, due to the underlying C api.
///
/// Precondition: boundedRange(b, e)
///
/// InputIterator<T> I, with T having the size of one byte
template<typename I>
Sha1Digest sha1(I b, I e)
{
static_assert(sizeof(traits::Decay<decltype(*b)>) == 1,
"sha1: element size is different than 1.");
SHA_CTX x;
if (!SHA1_Init(&x))
{
throw std::runtime_error("Can't initialize the sha1 context. "
"data=\"" + std::string(b, e) + "\"");
}
bool release = false;
auto _ = scoped([&]() {
if (!release)
{
// `SHA1_Final` both computes and frees the context.
// Here we just want to free, but there's no other way...
SHA1_Final(Sha1Digest{0}.data(), &x);
}
});
if (!detail::sha1Update(x, b, e, std::is_pointer<I>{}))
{
throw std::runtime_error("Can't update sha1 on \"" + std::string(b, e) + "\"");
}
Sha1Digest d;
release = true;
if (!SHA1_Final(d.data(), &x))
{
throw std::runtime_error("Can't compute sha1 on \"" + std::string(b, e) + "\"");
}
return d;
}
/// Computes the sha1 digest of the given bytes.
///
/// Warning: This function operates on binary data. If you pass a string literal,
/// it will be processed as a normal array. This means that the final '\0' will
/// be processed.
///
/// Thus beware that:
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// assert(sha("youpi") != sha1(std::string{"youpi"}));
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Linearizable<T> L, with T having the size of one byte
template<typename L>
Sha1Digest sha1(const L& l)
{
return sha1(begin(l), end(l));
}
} // namespace qi
#endif // QI_SHA1_HPP
<commit_msg>sha1: Initializes a local variable.<commit_after>/*
** Copyright (C) 2017 Softbank Robotics Europe
** See COPYING for the license
*/
#ifndef QI_SHA1_HPP
#define QI_SHA1_HPP
#pragma once
#include <array>
#include <cstdint>
#include <type_traits>
#include <openssl/sha.h>
#include <boost/uuid/sha1.hpp>
#include <qi/scoped.hpp>
#include <qi/type/traits.hpp>
/// @file Contains sha1 digest functions.
///
/// The implementation relies on openssl.
///
/// An alternative is `boost::uuids::detail::sha1` but:
/// 1) it is in a `detail` namespace, so not officially supported
/// 2) the produced digests are different from the one of tools such as
/// `openssl sha1` and `sha1sum` (!).
/// This is apparently because of a wrong handling of endianness.
namespace qi {
/// The result of a sha1 computation is an array of 20 bytes.
using Sha1Digest = std::array<uint8_t, 20>;
namespace detail
{
// With pointers, we use the single-call update.
//
// Precondition: boundedRange(b, e) && s has been initialized
//
// I == T*, with T having the size of one byte (e.g. int8_t, uint8_t,
// unsigned char on some platforms, etc.)
template<typename I>
int sha1Update(SHA_CTX& s, I b, I e, std::true_type /* is_pointer */)
{
return SHA1_Update(&s, b, e - b);
}
// With non-pointer iterators, we update byte by byte.
//
// Precondition: boundedRange(b, e) && s has been initialized
//
// InputIterator<T> I, with T having the size of one byte
template<typename I>
int sha1Update(SHA_CTX& s, I b, I e, std::false_type /* is_pointer */)
{
int res = 1;
while (b != e)
{
const auto c = *b;
res = SHA1_Update(&s, &c, 1u);
if (res == 0)
{
return res;
}
++b;
}
return res;
}
} // namespace detail
/// Computes the sha1 digest of the given bytes.
///
/// Note: Passing pointers instead of non-pointer iterators (even random access ones)
/// will typically be faster, due to the underlying C api.
///
/// Precondition: boundedRange(b, e)
///
/// InputIterator<T> I, with T having the size of one byte
template<typename I>
Sha1Digest sha1(I b, I e)
{
static_assert(sizeof(traits::Decay<decltype(*b)>) == 1,
"sha1: element size is different than 1.");
SHA_CTX x;
if (!SHA1_Init(&x))
{
throw std::runtime_error("Can't initialize the sha1 context. "
"data=\"" + std::string(b, e) + "\"");
}
bool release = false;
auto _ = scoped([&]() {
if (!release)
{
// `SHA1_Final` both computes and frees the context.
// Here we just want to free, but there's no other way...
SHA1_Final(Sha1Digest{0}.data(), &x);
}
});
if (!detail::sha1Update(x, b, e, std::is_pointer<I>{}))
{
throw std::runtime_error("Can't update sha1 on \"" + std::string(b, e) + "\"");
}
Sha1Digest d;
release = true;
if (!SHA1_Final(d.data(), &x))
{
throw std::runtime_error("Can't compute sha1 on \"" + std::string(b, e) + "\"");
}
return d;
}
/// Computes the sha1 digest of the given bytes.
///
/// Warning: This function operates on binary data. If you pass a string literal,
/// it will be processed as a normal array. This means that the final '\0' will
/// be processed.
///
/// Thus beware that:
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// assert(sha("youpi") != sha1(std::string{"youpi"}));
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Linearizable<T> L, with T having the size of one byte
template<typename L>
Sha1Digest sha1(const L& l)
{
return sha1(begin(l), end(l));
}
} // namespace qi
#endif // QI_SHA1_HPP
<|endoftext|> |
<commit_before>/***************************************************************************
* The Kernel-Machine Library *
* Copyright (C) 2004, 2005 by Rutger W. ter Borg *
* *
* 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307 *
***************************************************************************/
#ifndef KRLS_HPP
#define KRLS_HPP
#include <boost/numeric/bindings/traits/ublas_matrix.hpp>
#include <boost/numeric/bindings/traits/ublas_symmetric.hpp>
#include <boost/numeric/bindings/traits/ublas_vector.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/bindings/atlas/cblas.hpp>
#include <kml/kernel_machine.hpp>
#include <kml/regression.hpp>
#include <kml/symmetric_view.hpp>
namespace atlas = boost::numeric::bindings::atlas;
namespace kml {
/*!
\brief Kernel Recursive Least Squares
A preprocessing step is taken to absorb the bias term into the weight vector w, by
redefining w as (w^T, b)^T and \f$\phi\f$ as (phi^T,1)^T. For details, see Engel et al,
Sparse Online Greedy Support Vector Regression, below on page 3:
\f$k(x,x')=k(x,x') + \lambda^2\f$, where \f$\lambda\f$ is a small, positive constant.
\section bibliography References
-# Engel et al., 2003. Kernel Recursive Least Squares.
*/
template< typename Problem, typename Kernel, typename PropertyMap, class Enable = void>
class krls: public kernel_machine< Problem, Kernel, PropertyMap > {};
template< typename Problem, typename Kernel, typename PropertyMap >
class krls< Problem, Kernel, PropertyMap, typename boost::enable_if< is_regression<Problem> >::type>:
public kernel_machine< Problem, Kernel, PropertyMap > {
typedef kernel_machine< Problem, Kernel, PropertyMap > base_type;
typedef typename base_type::kernel_type kernel_type;
typedef double scalar_type;
typedef symmetric_view< ublas::matrix<double> > symmetric_type;
typedef ublas::matrix<double> matrix_type;
typedef ublas::vector<double> vector_type;
typedef typename Problem::input_type input_type;
typedef typename Problem::output_type output_type;
typedef typename boost::property_traits<PropertyMap>::key_type key_type;
typedef typename boost::property_traits<PropertyMap>::value_type object_type;
public:
krls( scalar_type n, scalar_type l,
typename boost::call_traits<kernel_type>::param_type k,
typename boost::call_traits<PropertyMap>::param_type map ):
base_type(k,map), nu(n), lambda_squared(l*l) {}
template< typename TokenIterator >
krls( TokenIterator const begin, TokenIterator const end,
typename boost::call_traits<kernel_type>::param_type k,
typename boost::call_traits<PropertyMap>::param_type map ):
base_type(k,map) {
nu = 1e-1; // default value
scalar_type lambda=1e-3; // default value
TokenIterator token(begin);
if ( token != end ) {
nu = boost::lexical_cast<double>( *token++ );
if ( token != end ) lambda = boost::lexical_cast<double>( *token );
}
lambda_squared=lambda*lambda;
}
output_type operator()( input_type const &x ) {
vector_type temp_K( base_type::key_lookup.size() );
base_type::fill_kernel( x, base_type::key_lookup.begin(), base_type::key_lookup.end(), temp_K.begin() );
for( int i=0; i < temp_K.size(); ++i )
temp_K[i] += lambda_squared;
return atlas::dot( base_type::weight, temp_K );
}
/*! learn the entire range of keys indicated by this range */
template<typename KeyIterator>
void learn( KeyIterator begin, KeyIterator end ) {
KeyIterator key_iterator(begin);
while( key_iterator != end ) {
increment( *key_iterator );
++key_iterator;
}
}
/*! \param key key of example in data */
void increment( key_type const &key ) {
//std::cout << "running key " << key << " through KRLS... " << std::endl;
// calculate the base_type::kernel function on (x_t,x_t), needed later on
scalar_type k_tt = base_type::kernel( key, key ) + lambda_squared;
// check whether dictionary is still not initialised
if ( base_type::key_lookup.empty() ) {
// there is no dictionary yet, so initialise all variables
// resize the matrix K, its inverse R and matrix P to 1 x 1
K.grow_row_column();
R.grow_row_column();
P.grow_row_column();
// and use values as stated in the paper
K.matrix(0,0) = k_tt;
R.matrix(0,0) = 1.0 / k_tt;
P.matrix(0,0) = 1.0;
// add to weight vector
base_type::weight.push_back( (*base_type::data)[key].get<1>() / k_tt );
// add to support vector set
base_type::key_lookup.push_back( key );
} else {
// KRLS already initialised, continue
vector_type a_t( K.size1() );
vector_type k_t( K.size1() );
// fill vector k_t
base_type::fill_kernel( key, base_type::key_lookup.begin(), base_type::key_lookup.end(), k_t.begin() );
for( int i=0; i<k_t.size(); ++i ) k_t[i] += lambda_squared;
// a_t <- R %*% k_t
ublas::matrix_range< ublas::matrix<double> > R_range( R.view() );
ublas::symmetric_adaptor< ublas::matrix_range< ublas::matrix<double> > > R_view( R_range );
atlas::symv( R_view, k_t, a_t );
scalar_type delta_t = k_tt - atlas::dot( k_t, a_t );
// Perform Approximate Linear Dependency (ALD) test
if (delta_t > nu) {
// add x_t to support vector set, adjust all needed variables
unsigned int old_size = base_type::key_lookup.size();
// update K (equation 14)
// fetch a view into the last row of the matrix of the _old_ size
K.grow_row_column();
ublas::matrix_vector_slice< ublas::matrix<double> > K_row_part( K.shrinked_row(old_size) );
atlas::copy( k_t, K_row_part );
K.matrix( old_size, old_size ) = k_tt;
// update R (equation 14)
scalar_type factor = static_cast<scalar_type>(1) / delta_t;
atlas::syr( factor, a_t, R_view );
R.grow_row_column();
ublas::matrix_vector_slice< ublas::matrix<double> > R_row_part( R.shrinked_row(old_size) );
atlas::scal( -factor, a_t );
R_row_part.assign( a_t );
R.matrix( old_size, old_size ) = factor;
// update P (equation 15)
// assign unit vector with 1 on last element.
P.grow_row_column();
ublas::matrix_vector_slice< ublas::matrix<double> > P_row_part( P.shrinked_row(old_size) );
atlas::set( 0.0, P_row_part );
P.matrix( old_size, old_size ) = 1.0;
// adjust weight vector alpha (equation 16)
factor = (*base_type::data)[key].get<1>() - atlas::dot(k_t,base_type::weight);
atlas::axpy( factor, a_t, base_type::weight );
// add new weight to the weight vector
base_type::weight.push_back( factor / delta_t );
// add support vector to the set
base_type::key_lookup.push_back( key );
} else {
// support vector set unchanged (see algorithmic on page 4 of paper)
// adjust weight vector and permutation matrix P
// P_a <- P_t-1 %*% a_t
vector_type P_a( base_type::key_lookup.size() );
// spmv(A,x,y) y <- A x
ublas::matrix_range< ublas::matrix<double> > P_range( P.view() );
ublas::symmetric_adaptor< ublas::matrix_range< ublas::matrix<double> > > P_view( P_range );
atlas::symv( P_view, a_t, P_a );
// 1 / (1 + a_t %*% P_(t-1) %*% a)
scalar_type factor = 1.0 / (1.0 + atlas::dot( a_t, P_a ));
// update weights (equation 13)
atlas::symv( factor* (*base_type::data)[key].get<1>() - atlas::dot(k_t,base_type::weight),
R_view, P_a, static_cast<scalar_type>(1), base_type::weight );
// update permutation matrix (equation 14)
atlas::syr( -factor, P_a, P_view );
}
}
}
private:
symmetric_type K; // kernel matrix K
symmetric_type R; // inverse of kernel matrix K
symmetric_type P; // permutation matrix P
scalar_type nu; // ALD parameter
scalar_type lambda_squared; // kernel function addition
};
} // namespace kml
#endif
<commit_msg>Minor changes to krls.hpp<commit_after>/***************************************************************************
* The Kernel-Machine Library *
* Copyright (C) 2004, 2005 by Rutger W. ter Borg *
* *
* 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307 *
***************************************************************************/
#ifndef KRLS_HPP
#define KRLS_HPP
#include <boost/numeric/bindings/traits/ublas_matrix.hpp>
#include <boost/numeric/bindings/traits/ublas_symmetric.hpp>
#include <boost/numeric/bindings/traits/ublas_vector.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/bindings/atlas/cblas.hpp>
#include <kml/kernel_machine.hpp>
#include <kml/regression.hpp>
#include <kml/symmetric_view.hpp>
namespace atlas = boost::numeric::bindings::atlas;
namespace kml {
/*!
\brief Kernel Recursive Least Squares
A preprocessing step is taken to absorb the bias term into the weight vector w, by
redefining w as (w^T, b)^T and \f$\phi\f$ as (phi^T,1)^T. For details, see Engel et al,
Sparse Online Greedy Support Vector Regression, below on page 3:
\f$k(x,x')=k(x,x') + \lambda^2\f$, where \f$\lambda\f$ is a small, positive constant.
\section bibliography References
-# Engel et al., 2003. Kernel Recursive Least Squares.
*/
template< typename Problem, typename Kernel, typename PropertyMap, class Enable = void>
class krls: public kernel_machine< Problem, Kernel, PropertyMap > {}
;
template< typename Problem, typename Kernel, typename PropertyMap >
class krls< Problem, Kernel, PropertyMap, typename boost::enable_if< is_regression<Problem> >::type>:
public kernel_machine< Problem, Kernel, PropertyMap > {
typedef kernel_machine< Problem, Kernel, PropertyMap > base_type;
typedef typename base_type::kernel_type kernel_type;
typedef double scalar_type;
typedef symmetric_view< ublas::matrix<double> > symmetric_type;
typedef ublas::matrix<double> matrix_type;
typedef ublas::vector<double> vector_type;
typedef typename Problem::input_type input_type;
typedef typename Problem::output_type output_type;
typedef typename boost::property_traits<PropertyMap>::key_type key_type;
typedef typename boost::property_traits<PropertyMap>::value_type object_type;
public:
krls( scalar_type n, scalar_type l,
typename boost::call_traits<kernel_type>::param_type k,
typename boost::call_traits<PropertyMap>::param_type map ):
base_type(k,map), nu(n), lambda_squared(l*l) {}
template< typename TokenIterator >
krls( TokenIterator const begin, TokenIterator const end,
typename boost::call_traits<kernel_type>::param_type k,
typename boost::call_traits<PropertyMap>::param_type map ):
base_type(k,map) {
nu = 1e-1; // default value
scalar_type lambda=1e-3; // default value
TokenIterator token(begin);
if ( token != end ) {
nu = boost::lexical_cast<double>( *token++ );
if ( token != end )
lambda = boost::lexical_cast<double>( *token );
}
lambda_squared=lambda*lambda;
}
output_type operator()( input_type const &x ) {
vector_type temp_K( base_type::key_lookup.size() );
base_type::fill_kernel( x, base_type::key_lookup.begin(), base_type::key_lookup.end(), temp_K.begin() );
for( int i=0; i < temp_K.size(); ++i )
temp_K[i] += lambda_squared;
return atlas::dot( base_type::weight, temp_K );
}
/*! learn the entire range of keys indicated by this range */
template<typename KeyIterator>
void learn( KeyIterator begin, KeyIterator end ) {
KeyIterator key_iterator(begin);
while( key_iterator != end ) {
increment( *key_iterator );
++key_iterator;
}
}
/*! \param key key of example in data */
void increment( key_type const &key ) {
//std::cout << "running key " << key << " through KRLS... " << std::endl;
// calculate the base_type::kernel function on (x_t,x_t), needed later on
scalar_type k_tt = base_type::kernel( key, key ) + lambda_squared;
// check whether dictionary is still not initialised
if ( base_type::key_lookup.empty() ) {
// there is no dictionary yet, so initialise all variables
// resize the matrix K, its inverse R and matrix P to 1 x 1
K.grow_row_column();
R.grow_row_column();
P.grow_row_column();
// and use values as stated in the paper
K.matrix(0,0) = k_tt;
R.matrix(0,0) = 1.0 / k_tt;
P.matrix(0,0) = 1.0;
// add to weight vector
base_type::weight.push_back( (*base_type::data)[key].get<1>() / k_tt );
// add to support vector set
base_type::key_lookup.push_back( key );
} else {
// KRLS already initialised, continue
vector_type a_t( K.size1() );
vector_type k_t( K.size1() );
// fill vector k_t
base_type::fill_kernel( key, base_type::key_lookup.begin(), base_type::key_lookup.end(), k_t.begin() );
for( typename vector_type::size_type i=0; i<k_t.size(); ++i )
k_t[i] += lambda_squared;
// a_t <- R %*% k_t
ublas::matrix_range< ublas::matrix<double> > R_range( R.view() );
ublas::symmetric_adaptor< ublas::matrix_range< ublas::matrix<double> > > R_view( R_range );
atlas::symv( R_view, k_t, a_t );
scalar_type delta_t = k_tt - atlas::dot( k_t, a_t );
// Perform Approximate Linear Dependency (ALD) test
if (delta_t > nu) {
// add x_t to support vector set, adjust all needed variables
unsigned int old_size = base_type::key_lookup.size();
// update K (equation 14)
// fetch a view into the last row of the matrix of the _old_ size
K.grow_row_column();
ublas::matrix_vector_slice< ublas::matrix<double> > K_row_part( K.shrinked_row(old_size) );
atlas::copy( k_t, K_row_part );
K.matrix( old_size, old_size ) = k_tt;
// update R (equation 14)
scalar_type factor = static_cast<scalar_type>(1) / delta_t;
atlas::syr( factor, a_t, R_view );
R.grow_row_column();
ublas::matrix_vector_slice< ublas::matrix<double> > R_row_part( R.shrinked_row(old_size) );
atlas::scal( -factor, a_t );
R_row_part.assign( a_t );
R.matrix( old_size, old_size ) = factor;
// update P (equation 15)
// assign unit vector with 1 on last element.
P.grow_row_column();
ublas::matrix_vector_slice< ublas::matrix<double> > P_row_part( P.shrinked_row(old_size) );
atlas::set
( 0.0, P_row_part );
P.matrix( old_size, old_size ) = 1.0;
// adjust weight vector alpha (equation 16)
factor = (*base_type::data)[key].get<1>() - atlas::dot(k_t,base_type::weight);
atlas::axpy( factor, a_t, base_type::weight );
// add new weight to the weight vector
base_type::weight.push_back( factor / delta_t );
// add support vector to the set
base_type::key_lookup.push_back( key );
} else {
// support vector set unchanged (see algorithmic on page 4 of paper)
// adjust weight vector and permutation matrix P
// P_a <- P_t-1 %*% a_t
vector_type P_a( base_type::key_lookup.size() );
// spmv(A,x,y) y <- A x
ublas::matrix_range< ublas::matrix<double> > P_range( P.view() );
ublas::symmetric_adaptor< ublas::matrix_range< ublas::matrix<double> > > P_view( P_range );
atlas::symv( P_view, a_t, P_a );
// 1 / (1 + a_t %*% P_(t-1) %*% a)
scalar_type factor = 1.0 / (1.0 + atlas::dot( a_t, P_a ));
// update weights (equation 13)
atlas::symv( factor* (*base_type::data)[key].get<1>() - atlas::dot(k_t,base_type::weight),
R_view, P_a, static_cast<scalar_type>(1), base_type::weight );
// update permutation matrix (equation 14)
atlas::syr( -factor, P_a, P_view );
}
}
}
private:
symmetric_type K; // kernel matrix K
symmetric_type R; // inverse of kernel matrix K
symmetric_type P; // permutation matrix P
scalar_type nu; // ALD parameter
scalar_type lambda_squared; // kernel function addition
};
} // namespace kml
#endif
<|endoftext|> |
<commit_before>// @(#)root/geom:$Id$
// Author: Andrei Gheata 28/04/04
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
////////////////////////////////////////////////////////////////////////////////
// TGeoHelix - class representing a helix curve
//
// A helix is a curve defined by the following equations:
// x = (1/c) * COS(q*phi)
// y = (1/c) * SIN(q*phi)
// z = s * alfa
// where:
// c = 1/Rxy - curvature in XY plane
// phi - phi angle
// S = 2*PI*s - vertical separation between helix loops
// q = +/- 1 - (+)=left-handed, (-)=right-handed
//
// In particular, a helix describes the trajectory of a charged particle in magnetic
// field. In such case, the helix is right-handed for negative particle charge.
// To define a helix, one must define:
// - the curvature - positive defined
// - the Z step made after one full turn of the helix
// - the particle charge sign
// - the initial particle position and direction (force normalization to unit)
// - the magnetic field direction
//
// A helix provides:
// - propagation to a given Z position (in global frame)
// Double_t *point = TGeoHelix::PropagateToZ(Double_t z);
// - propagation to an arbitrary plane, returning also the new point
// - propagation in a geometry until the next crossed surface
// - computation of the total track length along a helix
#include "TMath.h"
#include "TGeoShape.h"
#include "TGeoMatrix.h"
#include "TGeoHelix.h"
ClassImp(TGeoHelix)
//_____________________________________________________________________________
TGeoHelix::TGeoHelix()
{
// Dummy constructor
fC = 0.;
fS = 0.;
fStep = 0.;
fPhi = 0.;
fPointInit[0] = fPointInit[1] = fPointInit[2] = 0.;
fDirInit[0] = fDirInit[1] = fDirInit[2] = 0.;
fPoint[0] = fPoint[1] = fPoint[2] = 0.;
fDir[0] = fDir[1] = fDir[2] = 0.;
fB[0] = fB[1] = fB[2] = 0.;
fQ = 0;
fMatrix = 0;
TObject::SetBit(kHelixNeedUpdate, kTRUE);
TObject::SetBit(kHelixStraigth, kFALSE);
TObject::SetBit(kHelixCircle, kFALSE);
}
//_____________________________________________________________________________
TGeoHelix::TGeoHelix(Double_t curvature, Double_t hstep, Int_t charge)
{
// Normal constructor
SetXYcurvature(curvature);
SetHelixStep(hstep);
SetCharge(charge);
fStep = 0.;
fPhi = 0.;
fPointInit[0] = fPointInit[1] = fPointInit[2] = 0.;
fDirInit[0] = fDirInit[1] = fDirInit[2] = 0.;
fPoint[0] = fPoint[1] = fPoint[2] = 0.;
fDir[0] = fDir[1] = fDir[2] = 0.;
fB[0] = fB[1] = fB[2] = 0.;
fQ = 0;
fMatrix = new TGeoHMatrix();
TObject::SetBit(kHelixNeedUpdate, kTRUE);
TObject::SetBit(kHelixStraigth, kFALSE);
TObject::SetBit(kHelixCircle, kFALSE);
}
//_____________________________________________________________________________
TGeoHelix::~TGeoHelix()
{
// Destructor
if (fMatrix) delete fMatrix;
}
//_____________________________________________________________________________
Double_t TGeoHelix::ComputeSafeStep(Double_t epsil) const
{
// Compute safe linear step that can be made such that the error
// between linear-helix extrapolation is less than EPSIL.
if (TestBit(kHelixStraigth) || TMath::Abs(fC)<TGeoShape::Tolerance()) return 1.E30;
Double_t c = GetTotalCurvature();
Double_t step = TMath::Sqrt(2.*epsil/c);
return step;
}
//_____________________________________________________________________________
void TGeoHelix::InitPoint(Double_t x0, Double_t y0, Double_t z0)
{
// Initialize coordinates of a point on the helix
fPointInit[0] = x0;
fPointInit[1] = y0;
fPointInit[2] = z0;
TObject::SetBit(kHelixNeedUpdate, kTRUE);
}
//_____________________________________________________________________________
void TGeoHelix::InitPoint (Double_t *point)
{
// Set initial point on the helix.
InitPoint(point[0], point[1], point[2]);
}
//_____________________________________________________________________________
void TGeoHelix::InitDirection(Double_t dirx, Double_t diry, Double_t dirz, Bool_t is_normalized)
{
// Initialize particle direction (tangent on the helix in initial point)
fDirInit[0] = dirx;
fDirInit[1] = diry;
fDirInit[2] = dirz;
TObject::SetBit(kHelixNeedUpdate, kTRUE);
if (is_normalized) return;
Double_t norm = 1./TMath::Sqrt(dirx*dirx+diry*diry+dirz*dirz);
for (Int_t i=0; i<3; i++) fDirInit[i] *= norm;
}
//_____________________________________________________________________________
void TGeoHelix::InitDirection(Double_t *dir, Bool_t is_normalized)
{
// Initialize particle direction (tangent on the helix in initial point)
InitDirection(dir[0], dir[1], dir[2], is_normalized);
}
//_____________________________________________________________________________
Double_t TGeoHelix::GetTotalCurvature() const
{
// Compute helix total curvature
Double_t k = fC/(1.+fC*fC*fS*fS);
return k;
}
//_____________________________________________________________________________
void TGeoHelix::SetXYcurvature(Double_t curvature)
{
// Set XY curvature: c = 1/Rxy
fC = curvature;
TObject::SetBit(kHelixNeedUpdate, kTRUE);
if (fC < 0) {
Error("SetXYcurvature", "Curvature %f not valid. Must be positive.", fC);
return;
}
if (TMath::Abs(fC) < TGeoShape::Tolerance()) {
Warning("SetXYcurvature", "Curvature is zero. Helix is a straigth line.");
TObject::SetBit(kHelixStraigth, kTRUE);
}
}
//_____________________________________________________________________________
void TGeoHelix::SetCharge(Int_t charge)
{
// Positive charge means left-handed helix.
if (charge==0) {
Error("ctor", "charge cannot be 0 - define it positive for a left-handed helix, negative otherwise");
return;
}
Int_t q = TMath::Sign(1, charge);
if (q == fQ) return;
fQ = q;
TObject::SetBit(kHelixNeedUpdate, kTRUE);
}
//_____________________________________________________________________________
void TGeoHelix::SetField(Double_t bx, Double_t by, Double_t bz, Bool_t is_normalized)
{
// Initialize particle direction (tangent on the helix in initial point)
fB[0] = bx;
fB[1] = by;
fB[2] = bz;
TObject::SetBit(kHelixNeedUpdate, kTRUE);
if (is_normalized) return;
Double_t norm = 1./TMath::Sqrt(bx*bx+by*by+bz*bz);
for (Int_t i=0; i<3; i++) fB[i] *= norm;
}
//_____________________________________________________________________________
void TGeoHelix::SetHelixStep(Double_t step)
{
// Set Z step of the helix on a complete turn. Positive or null.
if (step < 0) {
Error("ctor", "Z step %f not valid. Must be positive.", step);
return;
}
TObject::SetBit(kHelixNeedUpdate, kTRUE);
fS = 0.5*step/TMath::Pi();
if (fS < TGeoShape::Tolerance()) TObject::SetBit(kHelixCircle, kTRUE);
}
//_____________________________________________________________________________
void TGeoHelix::ResetStep()
{
// Reset current point/direction to initial values
fStep = 0.;
memcpy(fPoint, fPointInit, 3*sizeof(Double_t));
memcpy(fDir, fDirInit, 3*sizeof(Double_t));
}
//_____________________________________________________________________________
void TGeoHelix::Step(Double_t step)
{
// Make a step from current point along the helix and compute new point, direction and angle
// To reach a plane/ shape boundary, one has to:
// 1. Compute the safety to the plane/boundary
// 2. Define / update a helix according local field and particle state (position, direction, charge)
// 3. Compute the magnetic safety (maximum distance for which the field can be considered constant)
// 4. Call TGeoHelix::Step() having as argument the minimum between 1. and 3.
// 5. Repeat from 1. until the step to be made is small enough.
// 6. Add to the total step the distance along a straigth line from the last point
// to the plane/shape boundary
Int_t i;
fStep += step;
if (TObject::TestBit(kHelixStraigth)) {
for (i=0; i<3; i++) {
fPoint[i] = fPointInit[i]+fStep*fDirInit[i];
fDir[i] = fDirInit[i];
}
return;
}
if (TObject::TestBit(kHelixNeedUpdate)) UpdateHelix();
Double_t r = 1./fC;
fPhi = fStep/TMath::Sqrt(r*r+fS*fS);
Double_t vect[3];
vect[0] = r * TMath::Cos(fPhi);
vect[1] = -fQ * r * TMath::Sin(fPhi);
vect[2] = fS * fPhi;
fMatrix->LocalToMaster(vect, fPoint);
Double_t ddb = fDirInit[0]*fB[0]+fDirInit[1]*fB[1]+fDirInit[2]*fB[2];
Double_t f = -TMath::Sqrt(1.-ddb*ddb);
vect[0] = f*TMath::Sin(fPhi);
vect[1] = fQ*f*TMath::Cos(fPhi);
vect[2] = ddb;
fMatrix->LocalToMasterVect(vect, fDir);
}
//_____________________________________________________________________________
Double_t TGeoHelix::StepToPlane(Double_t *point, Double_t *norm)
{
// Propagate initial point up to a given Z position in MARS.
Double_t step = 0.;
Double_t snext = 1.E30;
Double_t dx, dy, dz;
Double_t ddn, pdn;
if (TObject::TestBit(kHelixNeedUpdate)) UpdateHelix();
dx = point[0] - fPoint[0];
dy = point[1] - fPoint[1];
dz = point[2] - fPoint[2];
pdn = dx*norm[0]+dy*norm[1]+dz*norm[2];
ddn = fDir[0]*norm[0]+fDir[1]*norm[1]+fDir[2]*norm[2];
if (TObject::TestBit(kHelixStraigth)) {
// propagate straigth line to plane
if ((pdn*ddn) <= 0) return snext;
snext = pdn/ddn;
Step(snext);
return snext;
}
Double_t r = 1./fC;
Double_t dist;
Double_t safety = TMath::Abs(pdn);
Double_t safestep = ComputeSafeStep();
snext = 1.E30;
Bool_t approaching = (ddn*pdn>0)?kTRUE:kFALSE;
if (approaching) snext = pdn/ddn;
else if (safety > 2.*r) return snext;
while (snext > safestep) {
dist = TMath::Max(safety, safestep);
Step(dist);
step += dist;
dx = point[0] - fPoint[0];
dy = point[1] - fPoint[1];
dz = point[2] - fPoint[2];
pdn = dx*norm[0]+dy*norm[1]+dz*norm[2];
ddn = fDir[0]*norm[0]+fDir[1]*norm[1]+fDir[2]*norm[2];
safety = TMath::Abs(pdn);
approaching = (ddn*pdn>0)?kTRUE:kFALSE;
snext = 1.E30;
if (approaching) snext = pdn/ddn;
else if (safety > 2.*r) {
ResetStep();
return snext;
}
}
step += snext;
Step(snext);
return step;
}
//_____________________________________________________________________________
void TGeoHelix::UpdateHelix()
{
// Update the local helix matrix.
TObject::SetBit(kHelixNeedUpdate, kFALSE);
fStep = 0.;
memcpy(fPoint, fPointInit, 3*sizeof(Double_t));
memcpy(fDir, fDirInit, 3*sizeof(Double_t));
Double_t rot[9];
Double_t tr[3];
Double_t ddb = fDirInit[0]*fB[0]+fDirInit[1]*fB[1]+fDirInit[2]*fB[2];
if ((1.-TMath::Abs(ddb))<TGeoShape::Tolerance() || TMath::Abs(fC)<TGeoShape::Tolerance()) {
// helix is just a straigth line
TObject::SetBit(kHelixStraigth, kTRUE);
fMatrix->Clear();
return;
}
rot[2] = fB[0];
rot[5] = fB[1];
rot[8] = fB[2];
if (ddb < 0) fS = -TMath::Abs(fS);
Double_t fy = - fQ*TMath::Sqrt(1.-ddb*ddb);
fy = 1./fy;
rot[1] = fy*(fDirInit[0]-fB[0]*ddb);
rot[4] = fy*(fDirInit[1]-fB[1]*ddb);
rot[7] = fy*(fDirInit[2]-fB[2]*ddb);
rot[0] = rot[4]*rot[8] - rot[7]*rot[5];
rot[3] = rot[7]*rot[2] - rot[1]*rot[8];
rot[6] = rot[1]*rot[5] - rot[4]*rot[2];
tr[0] = fPointInit[0] - rot[0]/fC;
tr[1] = fPointInit[1] - rot[3]/fC;
tr[2] = fPointInit[2] - rot[6]/fC;
fMatrix->SetTranslation(tr);
fMatrix->SetRotation(rot);
}
<commit_msg>Output direction vector was not normalized<commit_after>// @(#)root/geom:$Id$
// Author: Andrei Gheata 28/04/04
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
////////////////////////////////////////////////////////////////////////////////
// TGeoHelix - class representing a helix curve
//
// A helix is a curve defined by the following equations:
// x = (1/c) * COS(q*phi)
// y = (1/c) * SIN(q*phi)
// z = s * alfa
// where:
// c = 1/Rxy - curvature in XY plane
// phi - phi angle
// S = 2*PI*s - vertical separation between helix loops
// q = +/- 1 - (+)=left-handed, (-)=right-handed
//
// In particular, a helix describes the trajectory of a charged particle in magnetic
// field. In such case, the helix is right-handed for negative particle charge.
// To define a helix, one must define:
// - the curvature - positive defined
// - the Z step made after one full turn of the helix
// - the particle charge sign
// - the initial particle position and direction (force normalization to unit)
// - the magnetic field direction
//
// A helix provides:
// - propagation to a given Z position (in global frame)
// Double_t *point = TGeoHelix::PropagateToZ(Double_t z);
// - propagation to an arbitrary plane, returning also the new point
// - propagation in a geometry until the next crossed surface
// - computation of the total track length along a helix
#include "TMath.h"
#include "TGeoShape.h"
#include "TGeoMatrix.h"
#include "TGeoHelix.h"
ClassImp(TGeoHelix)
//_____________________________________________________________________________
TGeoHelix::TGeoHelix()
{
// Dummy constructor
fC = 0.;
fS = 0.;
fStep = 0.;
fPhi = 0.;
fPointInit[0] = fPointInit[1] = fPointInit[2] = 0.;
fDirInit[0] = fDirInit[1] = fDirInit[2] = 0.;
fPoint[0] = fPoint[1] = fPoint[2] = 0.;
fDir[0] = fDir[1] = fDir[2] = 0.;
fB[0] = fB[1] = fB[2] = 0.;
fQ = 0;
fMatrix = 0;
TObject::SetBit(kHelixNeedUpdate, kTRUE);
TObject::SetBit(kHelixStraigth, kFALSE);
TObject::SetBit(kHelixCircle, kFALSE);
}
//_____________________________________________________________________________
TGeoHelix::TGeoHelix(Double_t curvature, Double_t hstep, Int_t charge)
{
// Normal constructor
SetXYcurvature(curvature);
SetHelixStep(hstep);
SetCharge(charge);
fStep = 0.;
fPhi = 0.;
fPointInit[0] = fPointInit[1] = fPointInit[2] = 0.;
fDirInit[0] = fDirInit[1] = fDirInit[2] = 0.;
fPoint[0] = fPoint[1] = fPoint[2] = 0.;
fDir[0] = fDir[1] = fDir[2] = 0.;
fB[0] = fB[1] = fB[2] = 0.;
fQ = 0;
fMatrix = new TGeoHMatrix();
TObject::SetBit(kHelixNeedUpdate, kTRUE);
TObject::SetBit(kHelixStraigth, kFALSE);
TObject::SetBit(kHelixCircle, kFALSE);
}
//_____________________________________________________________________________
TGeoHelix::~TGeoHelix()
{
// Destructor
if (fMatrix) delete fMatrix;
}
//_____________________________________________________________________________
Double_t TGeoHelix::ComputeSafeStep(Double_t epsil) const
{
// Compute safe linear step that can be made such that the error
// between linear-helix extrapolation is less than EPSIL.
if (TestBit(kHelixStraigth) || TMath::Abs(fC)<TGeoShape::Tolerance()) return 1.E30;
Double_t c = GetTotalCurvature();
Double_t step = TMath::Sqrt(2.*epsil/c);
return step;
}
//_____________________________________________________________________________
void TGeoHelix::InitPoint(Double_t x0, Double_t y0, Double_t z0)
{
// Initialize coordinates of a point on the helix
fPointInit[0] = x0;
fPointInit[1] = y0;
fPointInit[2] = z0;
TObject::SetBit(kHelixNeedUpdate, kTRUE);
}
//_____________________________________________________________________________
void TGeoHelix::InitPoint (Double_t *point)
{
// Set initial point on the helix.
InitPoint(point[0], point[1], point[2]);
}
//_____________________________________________________________________________
void TGeoHelix::InitDirection(Double_t dirx, Double_t diry, Double_t dirz, Bool_t is_normalized)
{
// Initialize particle direction (tangent on the helix in initial point)
fDirInit[0] = dirx;
fDirInit[1] = diry;
fDirInit[2] = dirz;
TObject::SetBit(kHelixNeedUpdate, kTRUE);
if (is_normalized) return;
Double_t norm = 1./TMath::Sqrt(dirx*dirx+diry*diry+dirz*dirz);
for (Int_t i=0; i<3; i++) fDirInit[i] *= norm;
}
//_____________________________________________________________________________
void TGeoHelix::InitDirection(Double_t *dir, Bool_t is_normalized)
{
// Initialize particle direction (tangent on the helix in initial point)
InitDirection(dir[0], dir[1], dir[2], is_normalized);
}
//_____________________________________________________________________________
Double_t TGeoHelix::GetTotalCurvature() const
{
// Compute helix total curvature
Double_t k = fC/(1.+fC*fC*fS*fS);
return k;
}
//_____________________________________________________________________________
void TGeoHelix::SetXYcurvature(Double_t curvature)
{
// Set XY curvature: c = 1/Rxy
fC = curvature;
TObject::SetBit(kHelixNeedUpdate, kTRUE);
if (fC < 0) {
Error("SetXYcurvature", "Curvature %f not valid. Must be positive.", fC);
return;
}
if (TMath::Abs(fC) < TGeoShape::Tolerance()) {
Warning("SetXYcurvature", "Curvature is zero. Helix is a straigth line.");
TObject::SetBit(kHelixStraigth, kTRUE);
}
}
//_____________________________________________________________________________
void TGeoHelix::SetCharge(Int_t charge)
{
// Positive charge means left-handed helix.
if (charge==0) {
Error("ctor", "charge cannot be 0 - define it positive for a left-handed helix, negative otherwise");
return;
}
Int_t q = TMath::Sign(1, charge);
if (q == fQ) return;
fQ = q;
TObject::SetBit(kHelixNeedUpdate, kTRUE);
}
//_____________________________________________________________________________
void TGeoHelix::SetField(Double_t bx, Double_t by, Double_t bz, Bool_t is_normalized)
{
// Initialize particle direction (tangent on the helix in initial point)
fB[0] = bx;
fB[1] = by;
fB[2] = bz;
TObject::SetBit(kHelixNeedUpdate, kTRUE);
if (is_normalized) return;
Double_t norm = 1./TMath::Sqrt(bx*bx+by*by+bz*bz);
for (Int_t i=0; i<3; i++) fB[i] *= norm;
}
//_____________________________________________________________________________
void TGeoHelix::SetHelixStep(Double_t step)
{
// Set Z step of the helix on a complete turn. Positive or null.
if (step < 0) {
Error("ctor", "Z step %f not valid. Must be positive.", step);
return;
}
TObject::SetBit(kHelixNeedUpdate, kTRUE);
fS = 0.5*step/TMath::Pi();
if (fS < TGeoShape::Tolerance()) TObject::SetBit(kHelixCircle, kTRUE);
}
//_____________________________________________________________________________
void TGeoHelix::ResetStep()
{
// Reset current point/direction to initial values
fStep = 0.;
memcpy(fPoint, fPointInit, 3*sizeof(Double_t));
memcpy(fDir, fDirInit, 3*sizeof(Double_t));
}
//_____________________________________________________________________________
void TGeoHelix::Step(Double_t step)
{
// Make a step from current point along the helix and compute new point, direction and angle
// To reach a plane/ shape boundary, one has to:
// 1. Compute the safety to the plane/boundary
// 2. Define / update a helix according local field and particle state (position, direction, charge)
// 3. Compute the magnetic safety (maximum distance for which the field can be considered constant)
// 4. Call TGeoHelix::Step() having as argument the minimum between 1. and 3.
// 5. Repeat from 1. until the step to be made is small enough.
// 6. Add to the total step the distance along a straigth line from the last point
// to the plane/shape boundary
Int_t i;
fStep += step;
if (TObject::TestBit(kHelixStraigth)) {
for (i=0; i<3; i++) {
fPoint[i] = fPointInit[i]+fStep*fDirInit[i];
fDir[i] = fDirInit[i];
}
return;
}
if (TObject::TestBit(kHelixNeedUpdate)) UpdateHelix();
Double_t r = 1./fC;
fPhi = fStep/TMath::Sqrt(r*r+fS*fS);
Double_t vect[3];
vect[0] = r * TMath::Cos(fPhi);
vect[1] = -fQ * r * TMath::Sin(fPhi);
vect[2] = fS * fPhi;
fMatrix->LocalToMaster(vect, fPoint);
Double_t ddb = fDirInit[0]*fB[0]+fDirInit[1]*fB[1]+fDirInit[2]*fB[2];
Double_t f = -TMath::Sqrt(1.-ddb*ddb);
vect[0] = f*TMath::Sin(fPhi);
vect[1] = fQ*f*TMath::Cos(fPhi);
vect[2] = ddb;
TMath::Normalize(vect);
fMatrix->LocalToMasterVect(vect, fDir);
}
//_____________________________________________________________________________
Double_t TGeoHelix::StepToPlane(Double_t *point, Double_t *norm)
{
// Propagate initial point up to a given Z position in MARS.
Double_t step = 0.;
Double_t snext = 1.E30;
Double_t dx, dy, dz;
Double_t ddn, pdn;
if (TObject::TestBit(kHelixNeedUpdate)) UpdateHelix();
dx = point[0] - fPoint[0];
dy = point[1] - fPoint[1];
dz = point[2] - fPoint[2];
pdn = dx*norm[0]+dy*norm[1]+dz*norm[2];
ddn = fDir[0]*norm[0]+fDir[1]*norm[1]+fDir[2]*norm[2];
if (TObject::TestBit(kHelixStraigth)) {
// propagate straigth line to plane
if ((pdn*ddn) <= 0) return snext;
snext = pdn/ddn;
Step(snext);
return snext;
}
Double_t r = 1./fC;
Double_t dist;
Double_t safety = TMath::Abs(pdn);
Double_t safestep = ComputeSafeStep();
snext = 1.E30;
Bool_t approaching = (ddn*pdn>0)?kTRUE:kFALSE;
if (approaching) snext = pdn/ddn;
else if (safety > 2.*r) return snext;
while (snext > safestep) {
dist = TMath::Max(safety, safestep);
Step(dist);
step += dist;
dx = point[0] - fPoint[0];
dy = point[1] - fPoint[1];
dz = point[2] - fPoint[2];
pdn = dx*norm[0]+dy*norm[1]+dz*norm[2];
ddn = fDir[0]*norm[0]+fDir[1]*norm[1]+fDir[2]*norm[2];
safety = TMath::Abs(pdn);
approaching = (ddn*pdn>0)?kTRUE:kFALSE;
snext = 1.E30;
if (approaching) snext = pdn/ddn;
else if (safety > 2.*r) {
ResetStep();
return snext;
}
}
step += snext;
Step(snext);
return step;
}
//_____________________________________________________________________________
void TGeoHelix::UpdateHelix()
{
// Update the local helix matrix.
TObject::SetBit(kHelixNeedUpdate, kFALSE);
fStep = 0.;
memcpy(fPoint, fPointInit, 3*sizeof(Double_t));
memcpy(fDir, fDirInit, 3*sizeof(Double_t));
Double_t rot[9];
Double_t tr[3];
Double_t ddb = fDirInit[0]*fB[0]+fDirInit[1]*fB[1]+fDirInit[2]*fB[2];
if ((1.-TMath::Abs(ddb))<TGeoShape::Tolerance() || TMath::Abs(fC)<TGeoShape::Tolerance()) {
// helix is just a straigth line
TObject::SetBit(kHelixStraigth, kTRUE);
fMatrix->Clear();
return;
}
rot[2] = fB[0];
rot[5] = fB[1];
rot[8] = fB[2];
if (ddb < 0) fS = -TMath::Abs(fS);
Double_t fy = - fQ*TMath::Sqrt(1.-ddb*ddb);
fy = 1./fy;
rot[1] = fy*(fDirInit[0]-fB[0]*ddb);
rot[4] = fy*(fDirInit[1]-fB[1]*ddb);
rot[7] = fy*(fDirInit[2]-fB[2]*ddb);
rot[0] = rot[4]*rot[8] - rot[7]*rot[5];
rot[3] = rot[7]*rot[2] - rot[1]*rot[8];
rot[6] = rot[1]*rot[5] - rot[4]*rot[2];
tr[0] = fPointInit[0] - rot[0]/fC;
tr[1] = fPointInit[1] - rot[3]/fC;
tr[2] = fPointInit[2] - rot[6]/fC;
fMatrix->SetTranslation(tr);
fMatrix->SetRotation(rot);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <X11/keysym.h>
#include <cstring>
#include "base/message_loop.h"
#include "chrome/browser/chromeos/input_method/input_method_manager.h"
#include "chrome/browser/chromeos/input_method/xkeyboard.h"
#include "chrome/browser/chromeos/system_key_event_listener.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "ui/base/x/x11_util.h"
#include <X11/Xlib.h> // should be here since it #defines lots of macros.
namespace chromeos {
class SystemKeyEventListenerTest : public InProcessBrowserTest {
public:
SystemKeyEventListenerTest()
: manager_(input_method::InputMethodManager::GetInstance()),
initial_caps_lock_state_(manager_->GetXKeyboard()->CapsLockIsEnabled()),
num_lock_mask_(manager_->GetXKeyboard()->GetNumLockMask()),
listener_(NULL) {
CHECK(num_lock_mask_);
}
protected:
class CapsLockObserver : public SystemKeyEventListener::CapsLockObserver {
public:
CapsLockObserver() {
}
private:
virtual void OnCapsLockChange(bool enabled) {
MessageLoopForUI::current()->Quit();
}
DISALLOW_COPY_AND_ASSIGN(CapsLockObserver);
};
// Start listening for X events.
virtual void SetUpOnMainThread() OVERRIDE {
SystemKeyEventListener::Initialize();
listener_ = SystemKeyEventListener::GetInstance();
}
// Stop listening for X events.
virtual void CleanUpOnMainThread() OVERRIDE {
SystemKeyEventListener::Shutdown();
listener_ = NULL;
MessageLoopForUI::current()->RunAllPending();
}
// Feed a key event to SystemKeyEventListener. Returnes true if the event is
// consumed by the listener.
bool SendFakeEvent(KeySym keysym, int modifiers, bool is_press) {
scoped_ptr<XEvent> event(SynthesizeKeyEvent(keysym, modifiers, is_press));
// It seems that the Xvfb fake X server in build bots ignores a key event
// synthesized by XTestFakeKeyEvent() or XSendEvent(). We just call
// ProcessedXEvent() instead.
return listener_->ProcessedXEvent(event.get());
}
input_method::InputMethodManager* manager_;
const bool initial_caps_lock_state_;
const unsigned int num_lock_mask_;
SystemKeyEventListener* listener_;
CapsLockObserver observer_;
private:
XEvent* SynthesizeKeyEvent(KeySym keysym, int modifiers, bool is_press) {
XEvent* event = new XEvent;
std::memset(event, 0, sizeof(XEvent));
Display* display = ui::GetXDisplay();
Window focused;
int dummy;
XGetInputFocus(display, &focused, &dummy);
XKeyEvent* key_event = &event->xkey;
key_event->display = display;
key_event->keycode = XKeysymToKeycode(display, keysym);
key_event->root = ui::GetX11RootWindow();
key_event->same_screen = True;
key_event->send_event = False;
key_event->state = modifiers;
key_event->subwindow = None;
key_event->time = CurrentTime;
key_event->type = is_press ? KeyPress : KeyRelease;
key_event->window = focused;
key_event->x = key_event->x_root = key_event->y = key_event->y_root = 1;
return event;
}
DISALLOW_COPY_AND_ASSIGN(SystemKeyEventListenerTest);
};
// Tests if the current Caps Lock status is toggled and OnCapsLockChange method
// is called when both Shift keys are pressed.
IN_PROC_BROWSER_TEST_F(SystemKeyEventListenerTest, TestCapsLock) {
listener_->AddCapsLockObserver(&observer_);
// Press both Shift keys. Note that ProcessedXEvent() returns false even when
// the second Shift key is pressed.
EXPECT_FALSE(SendFakeEvent(XK_Shift_L, 0, true));
EXPECT_FALSE(SendFakeEvent(XK_Shift_R, ShiftMask, true));
EXPECT_FALSE(SendFakeEvent(XK_Shift_R, ShiftMask, false));
EXPECT_FALSE(SendFakeEvent(XK_Shift_L, ShiftMask, false));
// Enter a new message loop and wait for OnCapsLockChange() to be called.
ui_test_utils::RunMessageLoop();
// Make sure the Caps Lock status is actually changed.
EXPECT_EQ(
!initial_caps_lock_state_, manager_->GetXKeyboard()->CapsLockIsEnabled());
// Test all other Shift_L/R combinations.
EXPECT_FALSE(SendFakeEvent(XK_Shift_L, 0, true));
EXPECT_FALSE(SendFakeEvent(XK_Shift_R, ShiftMask, true));
EXPECT_FALSE(SendFakeEvent(XK_Shift_L, ShiftMask, false));
EXPECT_FALSE(SendFakeEvent(XK_Shift_R, ShiftMask, false));
ui_test_utils::RunMessageLoop();
EXPECT_EQ(
initial_caps_lock_state_, manager_->GetXKeyboard()->CapsLockIsEnabled());
EXPECT_FALSE(SendFakeEvent(XK_Shift_R, 0, true));
EXPECT_FALSE(SendFakeEvent(XK_Shift_L, ShiftMask, true));
EXPECT_FALSE(SendFakeEvent(XK_Shift_L, ShiftMask, false));
EXPECT_FALSE(SendFakeEvent(XK_Shift_R, ShiftMask, false));
ui_test_utils::RunMessageLoop();
EXPECT_EQ(
!initial_caps_lock_state_, manager_->GetXKeyboard()->CapsLockIsEnabled());
EXPECT_FALSE(SendFakeEvent(XK_Shift_R, 0, true));
EXPECT_FALSE(SendFakeEvent(XK_Shift_L, ShiftMask, true));
EXPECT_FALSE(SendFakeEvent(XK_Shift_R, ShiftMask, false));
EXPECT_FALSE(SendFakeEvent(XK_Shift_L, ShiftMask, false));
ui_test_utils::RunMessageLoop();
EXPECT_EQ(
initial_caps_lock_state_, manager_->GetXKeyboard()->CapsLockIsEnabled());
// Restore the original state.
listener_->RemoveCapsLockObserver(&observer_);
manager_->GetXKeyboard()->SetCapsLockEnabled(initial_caps_lock_state_);
}
// Tests the same above, but with Num Lock. Pressing both Shift keys should
// toggle Caps Lock even when Num Lock is enabled. See crosbug.com/23067.
IN_PROC_BROWSER_TEST_F(SystemKeyEventListenerTest, TestCapsLockWithNumLock) {
listener_->AddCapsLockObserver(&observer_);
EXPECT_FALSE(SendFakeEvent(XK_Shift_L, num_lock_mask_, true));
EXPECT_FALSE(SendFakeEvent(XK_Shift_R, ShiftMask | num_lock_mask_, true));
EXPECT_FALSE(SendFakeEvent(XK_Shift_R, ShiftMask | num_lock_mask_, false));
EXPECT_FALSE(SendFakeEvent(XK_Shift_L, ShiftMask | num_lock_mask_, false));
ui_test_utils::RunMessageLoop();
EXPECT_EQ(
!initial_caps_lock_state_, manager_->GetXKeyboard()->CapsLockIsEnabled());
EXPECT_FALSE(SendFakeEvent(XK_Shift_L, num_lock_mask_, true));
EXPECT_FALSE(SendFakeEvent(XK_Shift_R, ShiftMask | num_lock_mask_, true));
EXPECT_FALSE(SendFakeEvent(XK_Shift_L, ShiftMask | num_lock_mask_, false));
EXPECT_FALSE(SendFakeEvent(XK_Shift_R, ShiftMask | num_lock_mask_, false));
ui_test_utils::RunMessageLoop();
EXPECT_EQ(
initial_caps_lock_state_, manager_->GetXKeyboard()->CapsLockIsEnabled());
EXPECT_FALSE(SendFakeEvent(XK_Shift_R, num_lock_mask_, true));
EXPECT_FALSE(SendFakeEvent(XK_Shift_L, ShiftMask | num_lock_mask_, true));
EXPECT_FALSE(SendFakeEvent(XK_Shift_L, ShiftMask | num_lock_mask_, false));
EXPECT_FALSE(SendFakeEvent(XK_Shift_R, ShiftMask | num_lock_mask_, false));
ui_test_utils::RunMessageLoop();
EXPECT_EQ(
!initial_caps_lock_state_, manager_->GetXKeyboard()->CapsLockIsEnabled());
EXPECT_FALSE(SendFakeEvent(XK_Shift_R, num_lock_mask_, true));
EXPECT_FALSE(SendFakeEvent(XK_Shift_L, ShiftMask | num_lock_mask_, true));
EXPECT_FALSE(SendFakeEvent(XK_Shift_R, ShiftMask | num_lock_mask_, false));
EXPECT_FALSE(SendFakeEvent(XK_Shift_L, ShiftMask | num_lock_mask_, false));
ui_test_utils::RunMessageLoop();
EXPECT_EQ(
initial_caps_lock_state_, manager_->GetXKeyboard()->CapsLockIsEnabled());
listener_->RemoveCapsLockObserver(&observer_);
manager_->GetXKeyboard()->SetCapsLockEnabled(initial_caps_lock_state_);
}
// Test pressing Shift_L+R with an another modifier like Control. Caps Lock
// status should not be changed this time.
IN_PROC_BROWSER_TEST_F(SystemKeyEventListenerTest, TestCapsLockWithControl) {
listener_->AddCapsLockObserver(&observer_);
EXPECT_FALSE(SendFakeEvent(XK_Shift_L, ControlMask, true));
EXPECT_FALSE(SendFakeEvent(XK_Shift_R, ShiftMask | ControlMask, true));
EXPECT_FALSE(SendFakeEvent(XK_Shift_R, ShiftMask | ControlMask, false));
EXPECT_FALSE(SendFakeEvent(XK_Shift_L, ShiftMask | ControlMask, false));
EXPECT_EQ(
initial_caps_lock_state_, manager_->GetXKeyboard()->CapsLockIsEnabled());
listener_->RemoveCapsLockObserver(&observer_);
manager_->GetXKeyboard()->SetCapsLockEnabled(initial_caps_lock_state_);
}
// TODO(yusukes): Test IME hot keys.
} // namespace chromeos
<commit_msg>Add browser tests that check if the IME hot keys like Shift+Alt are working correctly.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <X11/keysym.h>
#include <cstring>
#include "base/message_loop.h"
#include "chrome/browser/chromeos/input_method/input_method_manager.h"
#include "chrome/browser/chromeos/input_method/xkeyboard.h"
#include "chrome/browser/chromeos/language_preferences.h"
#include "chrome/browser/chromeos/system_key_event_listener.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "ui/base/x/x11_util.h"
#include <X11/Xlib.h> // should be here since it #defines lots of macros.
namespace chromeos {
namespace {
static const char* active_input_methods[] = {
"xkb:us::eng", // The first one should be US Qwerty.
"xkb:us:dvorak:eng",
"xkb:kr:kr104:kor", // for testing XK_space with ShiftMask.
// TODO(yusukes): Add "mozc-jp", "xkb:jp::jpn", and "mozc-hangul" to test
// more IME hot keys once build bots start supporting ibus-daemon.
};
class CapsLockObserver : public SystemKeyEventListener::CapsLockObserver {
public:
CapsLockObserver() {
}
private:
virtual void OnCapsLockChange(bool enabled) OVERRIDE {
MessageLoopForUI::current()->Quit();
}
DISALLOW_COPY_AND_ASSIGN(CapsLockObserver);
};
class InputMethodObserver : public input_method::InputMethodManager::Observer {
public:
InputMethodObserver() {
}
const std::string& current_input_method_id() const {
return current_input_method_id_;
}
private:
virtual void InputMethodChanged(
input_method::InputMethodManager* manager,
const input_method::InputMethodDescriptor& current_input_method,
size_t num_active_input_methods) OVERRIDE {
current_input_method_id_ = current_input_method.id();
}
virtual void ActiveInputMethodsChanged(
input_method::InputMethodManager* manager,
const input_method::InputMethodDescriptor& current_input_method,
size_t num_active_input_methods) OVERRIDE {
}
virtual void PropertyListChanged(
input_method::InputMethodManager* manager,
const input_method::ImePropertyList& current_ime_properties) OVERRIDE {
}
std::string current_input_method_id_;
DISALLOW_COPY_AND_ASSIGN(InputMethodObserver);
};
} // namespace
class SystemKeyEventListenerTest : public InProcessBrowserTest {
public:
SystemKeyEventListenerTest()
: manager_(input_method::InputMethodManager::GetInstance()),
initial_caps_lock_state_(manager_->GetXKeyboard()->CapsLockIsEnabled()),
num_lock_mask_(manager_->GetXKeyboard()->GetNumLockMask()),
listener_(NULL) {
CHECK(num_lock_mask_);
}
protected:
// Start listening for X events.
virtual void SetUpOnMainThread() OVERRIDE {
ActivateInputMethods();
SystemKeyEventListener::Initialize();
listener_ = SystemKeyEventListener::GetInstance();
}
// Stop listening for X events.
virtual void CleanUpOnMainThread() OVERRIDE {
SystemKeyEventListener::Shutdown();
listener_ = NULL;
DeactivateInputMethods();
MessageLoopForUI::current()->RunAllPending();
}
// Feed a key event to SystemKeyEventListener. Returnes true if the event is
// consumed by the listener.
bool SendFakeEvent(KeySym keysym, int modifiers, bool is_press) {
scoped_ptr<XEvent> event(SynthesizeKeyEvent(keysym, modifiers, is_press));
// It seems that the Xvfb fake X server in build bots ignores a key event
// synthesized by XTestFakeKeyEvent() or XSendEvent(). We just call
// ProcessedXEvent() instead.
return listener_->ProcessedXEvent(event.get());
}
// Enables input methods in active_input_methods[].
void ActivateInputMethods() {
input_method::ImeConfigValue value;
value.type = input_method::ImeConfigValue::kValueTypeStringList;
for (size_t i = 0; i < arraysize(active_input_methods); ++i)
value.string_list_value.push_back(active_input_methods[i]);
manager_->SetImeConfig(language_prefs::kGeneralSectionName,
language_prefs::kPreloadEnginesConfigName,
value);
}
// Disables all input methods except US Qwerty.
void DeactivateInputMethods() {
input_method::ImeConfigValue value;
value.type = input_method::ImeConfigValue::kValueTypeStringList;
value.string_list_value.push_back(active_input_methods[0]); // Qwerty
manager_->SetImeConfig(language_prefs::kGeneralSectionName,
language_prefs::kPreloadEnginesConfigName,
value);
}
input_method::InputMethodManager* manager_;
const bool initial_caps_lock_state_;
const unsigned int num_lock_mask_;
SystemKeyEventListener* listener_;
CapsLockObserver caps_lock_observer_;
InputMethodObserver input_method_observer_;
private:
XEvent* SynthesizeKeyEvent(KeySym keysym, int modifiers, bool is_press) {
XEvent* event = new XEvent;
std::memset(event, 0, sizeof(XEvent));
Display* display = ui::GetXDisplay();
Window focused;
int dummy;
XGetInputFocus(display, &focused, &dummy);
XKeyEvent* key_event = &event->xkey;
key_event->display = display;
key_event->keycode = XKeysymToKeycode(display, keysym);
key_event->root = ui::GetX11RootWindow();
key_event->same_screen = True;
key_event->send_event = False;
key_event->state = modifiers;
key_event->subwindow = None;
key_event->time = CurrentTime;
key_event->type = is_press ? KeyPress : KeyRelease;
key_event->window = focused;
key_event->x = key_event->x_root = key_event->y = key_event->y_root = 1;
return event;
}
DISALLOW_COPY_AND_ASSIGN(SystemKeyEventListenerTest);
};
// Tests if the current Caps Lock status is toggled and OnCapsLockChange method
// is called when both Shift keys are pressed.
IN_PROC_BROWSER_TEST_F(SystemKeyEventListenerTest, TestCapsLock) {
listener_->AddCapsLockObserver(&caps_lock_observer_);
// Press both Shift keys. Note that ProcessedXEvent() returns false even when
// the second Shift key is pressed.
EXPECT_FALSE(SendFakeEvent(XK_Shift_L, 0, true));
EXPECT_FALSE(SendFakeEvent(XK_Shift_R, ShiftMask, true));
EXPECT_FALSE(SendFakeEvent(XK_Shift_R, ShiftMask, false));
EXPECT_FALSE(SendFakeEvent(XK_Shift_L, ShiftMask, false));
// Enter a new message loop and wait for OnCapsLockChange() to be called.
ui_test_utils::RunMessageLoop();
// Make sure the Caps Lock status is actually changed.
EXPECT_EQ(
!initial_caps_lock_state_, manager_->GetXKeyboard()->CapsLockIsEnabled());
// Test all other Shift_L/R combinations.
EXPECT_FALSE(SendFakeEvent(XK_Shift_L, 0, true));
EXPECT_FALSE(SendFakeEvent(XK_Shift_R, ShiftMask, true));
EXPECT_FALSE(SendFakeEvent(XK_Shift_L, ShiftMask, false));
EXPECT_FALSE(SendFakeEvent(XK_Shift_R, ShiftMask, false));
ui_test_utils::RunMessageLoop();
EXPECT_EQ(
initial_caps_lock_state_, manager_->GetXKeyboard()->CapsLockIsEnabled());
EXPECT_FALSE(SendFakeEvent(XK_Shift_R, 0, true));
EXPECT_FALSE(SendFakeEvent(XK_Shift_L, ShiftMask, true));
EXPECT_FALSE(SendFakeEvent(XK_Shift_L, ShiftMask, false));
EXPECT_FALSE(SendFakeEvent(XK_Shift_R, ShiftMask, false));
ui_test_utils::RunMessageLoop();
EXPECT_EQ(
!initial_caps_lock_state_, manager_->GetXKeyboard()->CapsLockIsEnabled());
EXPECT_FALSE(SendFakeEvent(XK_Shift_R, 0, true));
EXPECT_FALSE(SendFakeEvent(XK_Shift_L, ShiftMask, true));
EXPECT_FALSE(SendFakeEvent(XK_Shift_R, ShiftMask, false));
EXPECT_FALSE(SendFakeEvent(XK_Shift_L, ShiftMask, false));
ui_test_utils::RunMessageLoop();
EXPECT_EQ(
initial_caps_lock_state_, manager_->GetXKeyboard()->CapsLockIsEnabled());
// Restore the original state.
listener_->RemoveCapsLockObserver(&caps_lock_observer_);
manager_->GetXKeyboard()->SetCapsLockEnabled(initial_caps_lock_state_);
}
// Tests the same above, but with Num Lock. Pressing both Shift keys should
// toggle Caps Lock even when Num Lock is enabled. See crosbug.com/23067.
IN_PROC_BROWSER_TEST_F(SystemKeyEventListenerTest, TestCapsLockWithNumLock) {
listener_->AddCapsLockObserver(&caps_lock_observer_);
EXPECT_FALSE(SendFakeEvent(XK_Shift_L, num_lock_mask_, true));
EXPECT_FALSE(SendFakeEvent(XK_Shift_R, ShiftMask | num_lock_mask_, true));
EXPECT_FALSE(SendFakeEvent(XK_Shift_R, ShiftMask | num_lock_mask_, false));
EXPECT_FALSE(SendFakeEvent(XK_Shift_L, ShiftMask | num_lock_mask_, false));
ui_test_utils::RunMessageLoop();
EXPECT_EQ(
!initial_caps_lock_state_, manager_->GetXKeyboard()->CapsLockIsEnabled());
EXPECT_FALSE(SendFakeEvent(XK_Shift_L, num_lock_mask_, true));
EXPECT_FALSE(SendFakeEvent(XK_Shift_R, ShiftMask | num_lock_mask_, true));
EXPECT_FALSE(SendFakeEvent(XK_Shift_L, ShiftMask | num_lock_mask_, false));
EXPECT_FALSE(SendFakeEvent(XK_Shift_R, ShiftMask | num_lock_mask_, false));
ui_test_utils::RunMessageLoop();
EXPECT_EQ(
initial_caps_lock_state_, manager_->GetXKeyboard()->CapsLockIsEnabled());
EXPECT_FALSE(SendFakeEvent(XK_Shift_R, num_lock_mask_, true));
EXPECT_FALSE(SendFakeEvent(XK_Shift_L, ShiftMask | num_lock_mask_, true));
EXPECT_FALSE(SendFakeEvent(XK_Shift_L, ShiftMask | num_lock_mask_, false));
EXPECT_FALSE(SendFakeEvent(XK_Shift_R, ShiftMask | num_lock_mask_, false));
ui_test_utils::RunMessageLoop();
EXPECT_EQ(
!initial_caps_lock_state_, manager_->GetXKeyboard()->CapsLockIsEnabled());
EXPECT_FALSE(SendFakeEvent(XK_Shift_R, num_lock_mask_, true));
EXPECT_FALSE(SendFakeEvent(XK_Shift_L, ShiftMask | num_lock_mask_, true));
EXPECT_FALSE(SendFakeEvent(XK_Shift_R, ShiftMask | num_lock_mask_, false));
EXPECT_FALSE(SendFakeEvent(XK_Shift_L, ShiftMask | num_lock_mask_, false));
ui_test_utils::RunMessageLoop();
EXPECT_EQ(
initial_caps_lock_state_, manager_->GetXKeyboard()->CapsLockIsEnabled());
listener_->RemoveCapsLockObserver(&caps_lock_observer_);
manager_->GetXKeyboard()->SetCapsLockEnabled(initial_caps_lock_state_);
}
// Tests pressing Shift_L+R with an another modifier like Control. Caps Lock
// status should not be changed this time.
IN_PROC_BROWSER_TEST_F(SystemKeyEventListenerTest, TestCapsLockWithControl) {
listener_->AddCapsLockObserver(&caps_lock_observer_);
EXPECT_FALSE(SendFakeEvent(XK_Shift_L, ControlMask, true));
EXPECT_FALSE(SendFakeEvent(XK_Shift_R, ShiftMask | ControlMask, true));
EXPECT_FALSE(SendFakeEvent(XK_Shift_R, ShiftMask | ControlMask, false));
EXPECT_FALSE(SendFakeEvent(XK_Shift_L, ShiftMask | ControlMask, false));
EXPECT_EQ(
initial_caps_lock_state_, manager_->GetXKeyboard()->CapsLockIsEnabled());
listener_->RemoveCapsLockObserver(&caps_lock_observer_);
manager_->GetXKeyboard()->SetCapsLockEnabled(initial_caps_lock_state_);
}
// Tests IME hot keys.
IN_PROC_BROWSER_TEST_F(SystemKeyEventListenerTest, TestInputMethod) {
manager_->AddObserver(&input_method_observer_);
// Press Shift+Alt to select the second IME.
EXPECT_FALSE(SendFakeEvent(XK_Shift_L, 0, true));
EXPECT_FALSE(SendFakeEvent(XK_Meta_L, ShiftMask, true));
EXPECT_TRUE(SendFakeEvent(XK_Meta_L, ShiftMask | Mod1Mask, false));
EXPECT_TRUE(SendFakeEvent(XK_Shift_L, ShiftMask, false));
// Do not call ui_test_utils::RunMessageLoop() here since the observer gets
// notified before returning from the SendFakeEvent call.
EXPECT_TRUE(input_method_observer_.current_input_method_id() ==
active_input_methods[1]);
// Press Control+space to move back to the previous one.
EXPECT_FALSE(SendFakeEvent(XK_Control_L, 0, true));
EXPECT_TRUE(SendFakeEvent(XK_space, ControlMask, true));
EXPECT_TRUE(SendFakeEvent(XK_space, ControlMask, false));
EXPECT_TRUE(SendFakeEvent(XK_Control_L, ControlMask, false));
EXPECT_TRUE(input_method_observer_.current_input_method_id() ==
active_input_methods[0]);
manager_->RemoveObserver(&input_method_observer_);
}
// Tests IME hot keys with Num Lock. See crosbug.com/23067.
IN_PROC_BROWSER_TEST_F(SystemKeyEventListenerTest, TestInputMethodWithNumLock) {
manager_->AddObserver(&input_method_observer_);
EXPECT_FALSE(SendFakeEvent(XK_Shift_L, num_lock_mask_, true));
EXPECT_FALSE(SendFakeEvent(XK_Meta_L, ShiftMask | num_lock_mask_, true));
EXPECT_TRUE(
SendFakeEvent(XK_Meta_L, ShiftMask | Mod1Mask | num_lock_mask_, false));
EXPECT_TRUE(SendFakeEvent(XK_Shift_L, ShiftMask | num_lock_mask_, false));
EXPECT_TRUE(input_method_observer_.current_input_method_id() ==
active_input_methods[1]);
EXPECT_FALSE(SendFakeEvent(XK_Control_L, num_lock_mask_, true));
EXPECT_TRUE(SendFakeEvent(XK_space, ControlMask | num_lock_mask_, true));
EXPECT_TRUE(SendFakeEvent(XK_space, ControlMask | num_lock_mask_, false));
EXPECT_TRUE(SendFakeEvent(XK_Control_L, ControlMask | num_lock_mask_, false));
EXPECT_TRUE(input_method_observer_.current_input_method_id() ==
active_input_methods[0]);
manager_->RemoveObserver(&input_method_observer_);
}
// Tests if Shift+space selects the Korean layout.
IN_PROC_BROWSER_TEST_F(SystemKeyEventListenerTest, TestKoreanInputMethod) {
manager_->AddObserver(&input_method_observer_);
// Press Shift+space
EXPECT_FALSE(SendFakeEvent(XK_Shift_R, 0, true));
EXPECT_TRUE(SendFakeEvent(XK_space, ShiftMask, true));
EXPECT_TRUE(SendFakeEvent(XK_space, ShiftMask, false));
EXPECT_TRUE(SendFakeEvent(XK_Shift_R, ShiftMask, false));
EXPECT_TRUE(input_method_observer_.current_input_method_id() ==
active_input_methods[2]);
// Press Control+space.
EXPECT_FALSE(SendFakeEvent(XK_Control_L, 0, true));
EXPECT_TRUE(SendFakeEvent(XK_space, ControlMask, true));
EXPECT_TRUE(SendFakeEvent(XK_space, ControlMask, false));
EXPECT_TRUE(SendFakeEvent(XK_Control_L, ControlMask, false));
EXPECT_TRUE(input_method_observer_.current_input_method_id() ==
active_input_methods[0]);
// TODO(yusukes): Add tests for input method specific hot keys like XK_Henkan,
// XK_Muhenkan, XK_ZenkakuHankaku, and XK_Hangul. This is not so easy since 1)
// we have to enable "mozc-jp" and "mozc-hangul" that require ibus-daemon, and
// 2) to let XKeysymToKeycode() handle e.g. XK_Henkan etc, we have to change
// the XKB layout to "jp" first.
manager_->RemoveObserver(&input_method_observer_);
}
} // namespace chromeos
<|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.
//
// This test creates a fake safebrowsing service, where we can inject
// malware and phishing urls. It then uses a real browser to go to
// these urls, and sends "goback" or "proceed" commands and verifies
// they work.
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_thread.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/renderer_host/render_process_host.h"
#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
#include "chrome/browser/safe_browsing/malware_details.h"
#include "chrome/browser/safe_browsing/safe_browsing_service.h"
#include "chrome/browser/safe_browsing/safe_browsing_blocking_page.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/tab_contents_view.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
// A SafeBrowingService class that allows us to inject the malicious URLs.
class FakeSafeBrowsingService : public SafeBrowsingService {
public:
FakeSafeBrowsingService() {}
virtual ~FakeSafeBrowsingService() {}
// Called on the IO thread to check if the given url is safe or not. If we
// can synchronously determine that the url is safe, CheckUrl returns true.
// Otherwise it returns false, and "client" is called asynchronously with the
// result when it is ready.
// Overrides SafeBrowsingService::CheckUrl.
virtual bool CheckBrowseUrl(const GURL& gurl, Client* client) {
const std::string& url = gurl.spec();
if (badurls[url] == URL_SAFE)
return true;
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
NewRunnableMethod(this, &FakeSafeBrowsingService::OnCheckDone,
url, client));
return false;
}
void OnCheckDone(std::string url, Client* client) {
client->OnSafeBrowsingResult(GURL(url), badurls[url]);
}
void AddURLResult(const GURL& url, UrlCheckResult checkresult) {
badurls[url.spec()] = checkresult;
}
virtual void ReportMalwareDetails(scoped_refptr<MalwareDetails> details) {
details_.push_back(details);
// Notify the UI thread, that we got a report.
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
NewRunnableMethod(this,
&FakeSafeBrowsingService::OnMalwareDetailsDone));
}
void OnMalwareDetailsDone() {
EXPECT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::UI));
MessageLoopForUI::current()->Quit();
}
std::list<scoped_refptr<MalwareDetails> >* GetDetails() {
return &details_;
}
std::list<scoped_refptr<MalwareDetails> > details_;
private:
base::hash_map<std::string, UrlCheckResult> badurls;
};
// Factory that creates FakeSafeBrowsingService instances.
class TestSafeBrowsingServiceFactory : public SafeBrowsingServiceFactory {
public:
TestSafeBrowsingServiceFactory() { }
virtual ~TestSafeBrowsingServiceFactory() { }
virtual SafeBrowsingService* CreateSafeBrowsingService() {
return new FakeSafeBrowsingService();
}
};
// Tests the safe browsing blocking page in a browser.
class SafeBrowsingBlockingPageTest : public InProcessBrowserTest,
public SafeBrowsingService::Client {
public:
SafeBrowsingBlockingPageTest() {
}
virtual void SetUp() {
SafeBrowsingService::RegisterFactory(&factory);
InProcessBrowserTest::SetUp();
}
virtual void TearDown() {
InProcessBrowserTest::TearDown();
SafeBrowsingService::RegisterFactory(NULL);
}
virtual void SetUpInProcessBrowserTestFixture() {
ASSERT_TRUE(test_server()->Start());
}
// SafeBrowsingService::Client implementation.
virtual void OnSafeBrowsingResult(
const GURL& url, SafeBrowsingService::UrlCheckResult result) {
}
virtual void OnBlockingPageComplete(bool proceed) {
}
void AddURLResult(const GURL& url,
SafeBrowsingService::UrlCheckResult checkresult) {
FakeSafeBrowsingService* service =
static_cast<FakeSafeBrowsingService*>(
g_browser_process->resource_dispatcher_host()->
safe_browsing_service());
ASSERT_TRUE(service);
service->AddURLResult(url, checkresult);
}
void SendCommand(const std::string& command) {
TabContents* contents = browser()->GetSelectedTabContents();
SafeBrowsingBlockingPage* interstitial_page =
static_cast<SafeBrowsingBlockingPage*>(
contents->interstitial_page());
ASSERT_TRUE(interstitial_page);
interstitial_page->CommandReceived(command);
}
void DontProceedThroughInterstitial() {
TabContents* contents = browser()->GetSelectedTabContents();
InterstitialPage* interstitial_page = contents->interstitial_page();
ASSERT_TRUE(interstitial_page);
interstitial_page->DontProceed();
}
void ProceedThroughInterstitial() {
TabContents* contents = browser()->GetSelectedTabContents();
InterstitialPage* interstitial_page = contents->interstitial_page();
ASSERT_TRUE(interstitial_page);
interstitial_page->Proceed();
}
void AssertNoInterstitial() {
TabContents* contents = browser()->GetSelectedTabContents();
InterstitialPage* interstitial_page = contents->interstitial_page();
ASSERT_FALSE(interstitial_page);
}
void WaitForNavigation() {
NavigationController* controller =
&browser()->GetSelectedTabContents()->controller();
ui_test_utils::WaitForNavigation(controller);
}
void AssertReportSent() {
// When a report is scheduled in the IO thread we should get notified.
ui_test_utils::RunMessageLoop();
FakeSafeBrowsingService* service =
static_cast<FakeSafeBrowsingService*>(
g_browser_process->resource_dispatcher_host()->
safe_browsing_service());
ASSERT_EQ(1u, service->GetDetails()->size());
}
private:
TestSafeBrowsingServiceFactory factory;
DISALLOW_COPY_AND_ASSIGN(SafeBrowsingBlockingPageTest);
};
namespace {
const char kEmptyPage[] = "files/empty.html";
const char kMalwarePage[] = "files/safe_browsing/malware.html";
const char kMalwareIframe[] = "files/safe_browsing/malware_iframe.html";
IN_PROC_BROWSER_TEST_F(SafeBrowsingBlockingPageTest, MalwareDontProceed) {
GURL url = test_server()->GetURL(kEmptyPage);
AddURLResult(url, SafeBrowsingService::URL_MALWARE);
ui_test_utils::NavigateToURL(browser(), url);
SendCommand("\"takeMeBack\""); // Simulate the user clicking "back"
AssertNoInterstitial(); // Assert the interstitial is gone
EXPECT_EQ(GURL(chrome::kAboutBlankURL), // Back to "about:blank"
browser()->GetSelectedTabContents()->GetURL());
}
IN_PROC_BROWSER_TEST_F(SafeBrowsingBlockingPageTest, MalwareProceed) {
GURL url = test_server()->GetURL(kEmptyPage);
AddURLResult(url, SafeBrowsingService::URL_MALWARE);
ui_test_utils::NavigateToURL(browser(), url);
SendCommand("\"proceed\""); // Simulate the user clicking "proceed"
WaitForNavigation(); // Wait until we finish the navigation.
AssertNoInterstitial(); // Assert the interstitial is gone.
EXPECT_EQ(url, browser()->GetSelectedTabContents()->GetURL());
}
IN_PROC_BROWSER_TEST_F(SafeBrowsingBlockingPageTest, PhishingDontProceed) {
GURL url = test_server()->GetURL(kEmptyPage);
AddURLResult(url, SafeBrowsingService::URL_PHISHING);
ui_test_utils::NavigateToURL(browser(), url);
SendCommand("\"takeMeBack\""); // Simulate the user clicking "proceed"
AssertNoInterstitial(); // Assert the interstitial is gone
EXPECT_EQ(GURL(chrome::kAboutBlankURL), // We are back to "about:blank".
browser()->GetSelectedTabContents()->GetURL());
}
IN_PROC_BROWSER_TEST_F(SafeBrowsingBlockingPageTest, PhishingProceed) {
GURL url = test_server()->GetURL(kEmptyPage);
AddURLResult(url, SafeBrowsingService::URL_PHISHING);
ui_test_utils::NavigateToURL(browser(), url);
SendCommand("\"proceed\""); // Simulate the user clicking "proceed".
WaitForNavigation(); // Wait until we finish the navigation.
AssertNoInterstitial(); // Assert the interstitial is gone
EXPECT_EQ(url, browser()->GetSelectedTabContents()->GetURL());
}
IN_PROC_BROWSER_TEST_F(SafeBrowsingBlockingPageTest, PhishingReportError) {
GURL url = test_server()->GetURL(kEmptyPage);
AddURLResult(url, SafeBrowsingService::URL_PHISHING);
ui_test_utils::NavigateToURL(browser(), url);
SendCommand("\"reportError\""); // Simulate the user clicking "report error"
WaitForNavigation(); // Wait until we finish the navigation.
AssertNoInterstitial(); // Assert the interstitial is gone
// We are in the error reporting page.
EXPECT_EQ("/safebrowsing/report_error/",
browser()->GetSelectedTabContents()->GetURL().path());
}
IN_PROC_BROWSER_TEST_F(SafeBrowsingBlockingPageTest, PhishingLearnMore) {
GURL url = test_server()->GetURL(kEmptyPage);
AddURLResult(url, SafeBrowsingService::URL_PHISHING);
ui_test_utils::NavigateToURL(browser(), url);
SendCommand("\"learnMore\""); // Simulate the user clicking "learn more"
WaitForNavigation(); // Wait until we finish the navigation.
AssertNoInterstitial(); // Assert the interstitial is gone
// We are in the help page.
EXPECT_EQ("/support/bin/answer.py",
browser()->GetSelectedTabContents()->GetURL().path());
}
IN_PROC_BROWSER_TEST_F(SafeBrowsingBlockingPageTest, MalwareIframeDontProceed) {
GURL url = test_server()->GetURL(kMalwarePage);
GURL iframe_url = test_server()->GetURL(kMalwareIframe);
AddURLResult(iframe_url, SafeBrowsingService::URL_MALWARE);
ui_test_utils::NavigateToURL(browser(), url);
SendCommand("\"takeMeBack\""); // Simulate the user clicking "back"
AssertNoInterstitial(); // Assert the interstitial is gone
EXPECT_EQ(GURL(chrome::kAboutBlankURL), // Back to "about:blank"
browser()->GetSelectedTabContents()->GetURL());
}
IN_PROC_BROWSER_TEST_F(SafeBrowsingBlockingPageTest, MalwareIframeProceed) {
GURL url = test_server()->GetURL(kMalwarePage);
GURL iframe_url = test_server()->GetURL(kMalwareIframe);
AddURLResult(iframe_url, SafeBrowsingService::URL_MALWARE);
ui_test_utils::NavigateToURL(browser(), url);
SendCommand("\"proceed\""); // Simulate the user clicking "proceed"
AssertNoInterstitial(); // Assert the interstitial is gone
EXPECT_EQ(url, browser()->GetSelectedTabContents()->GetURL());
}
IN_PROC_BROWSER_TEST_F(SafeBrowsingBlockingPageTest,
MalwareIframeReportDetails) {
// Enable reporting of malware details.
browser()->GetProfile()->GetPrefs()->SetBoolean(
prefs::kSafeBrowsingReportingEnabled, true);
EXPECT_TRUE(browser()->GetProfile()->GetPrefs()->GetBoolean(
prefs::kSafeBrowsingReportingEnabled));
GURL url = test_server()->GetURL(kMalwarePage);
GURL iframe_url = test_server()->GetURL(kMalwareIframe);
AddURLResult(iframe_url, SafeBrowsingService::URL_MALWARE);
ui_test_utils::NavigateToURL(browser(), url);
SendCommand("\"proceed\""); // Simulate the user clicking "back"
AssertNoInterstitial(); // Assert the interstitial is gone
EXPECT_EQ(url, browser()->GetSelectedTabContents()->GetURL());
AssertReportSent();
}
} // namespace
<commit_msg>Disable crashy SafeBrowsingBlockingPageTest.MalwareIframeProceed<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.
//
// This test creates a fake safebrowsing service, where we can inject
// malware and phishing urls. It then uses a real browser to go to
// these urls, and sends "goback" or "proceed" commands and verifies
// they work.
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_thread.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/renderer_host/render_process_host.h"
#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
#include "chrome/browser/safe_browsing/malware_details.h"
#include "chrome/browser/safe_browsing/safe_browsing_service.h"
#include "chrome/browser/safe_browsing/safe_browsing_blocking_page.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/tab_contents_view.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
// A SafeBrowingService class that allows us to inject the malicious URLs.
class FakeSafeBrowsingService : public SafeBrowsingService {
public:
FakeSafeBrowsingService() {}
virtual ~FakeSafeBrowsingService() {}
// Called on the IO thread to check if the given url is safe or not. If we
// can synchronously determine that the url is safe, CheckUrl returns true.
// Otherwise it returns false, and "client" is called asynchronously with the
// result when it is ready.
// Overrides SafeBrowsingService::CheckUrl.
virtual bool CheckBrowseUrl(const GURL& gurl, Client* client) {
const std::string& url = gurl.spec();
if (badurls[url] == URL_SAFE)
return true;
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
NewRunnableMethod(this, &FakeSafeBrowsingService::OnCheckDone,
url, client));
return false;
}
void OnCheckDone(std::string url, Client* client) {
client->OnSafeBrowsingResult(GURL(url), badurls[url]);
}
void AddURLResult(const GURL& url, UrlCheckResult checkresult) {
badurls[url.spec()] = checkresult;
}
virtual void ReportMalwareDetails(scoped_refptr<MalwareDetails> details) {
details_.push_back(details);
// Notify the UI thread, that we got a report.
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
NewRunnableMethod(this,
&FakeSafeBrowsingService::OnMalwareDetailsDone));
}
void OnMalwareDetailsDone() {
EXPECT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::UI));
MessageLoopForUI::current()->Quit();
}
std::list<scoped_refptr<MalwareDetails> >* GetDetails() {
return &details_;
}
std::list<scoped_refptr<MalwareDetails> > details_;
private:
base::hash_map<std::string, UrlCheckResult> badurls;
};
// Factory that creates FakeSafeBrowsingService instances.
class TestSafeBrowsingServiceFactory : public SafeBrowsingServiceFactory {
public:
TestSafeBrowsingServiceFactory() { }
virtual ~TestSafeBrowsingServiceFactory() { }
virtual SafeBrowsingService* CreateSafeBrowsingService() {
return new FakeSafeBrowsingService();
}
};
// Tests the safe browsing blocking page in a browser.
class SafeBrowsingBlockingPageTest : public InProcessBrowserTest,
public SafeBrowsingService::Client {
public:
SafeBrowsingBlockingPageTest() {
}
virtual void SetUp() {
SafeBrowsingService::RegisterFactory(&factory);
InProcessBrowserTest::SetUp();
}
virtual void TearDown() {
InProcessBrowserTest::TearDown();
SafeBrowsingService::RegisterFactory(NULL);
}
virtual void SetUpInProcessBrowserTestFixture() {
ASSERT_TRUE(test_server()->Start());
}
// SafeBrowsingService::Client implementation.
virtual void OnSafeBrowsingResult(
const GURL& url, SafeBrowsingService::UrlCheckResult result) {
}
virtual void OnBlockingPageComplete(bool proceed) {
}
void AddURLResult(const GURL& url,
SafeBrowsingService::UrlCheckResult checkresult) {
FakeSafeBrowsingService* service =
static_cast<FakeSafeBrowsingService*>(
g_browser_process->resource_dispatcher_host()->
safe_browsing_service());
ASSERT_TRUE(service);
service->AddURLResult(url, checkresult);
}
void SendCommand(const std::string& command) {
TabContents* contents = browser()->GetSelectedTabContents();
SafeBrowsingBlockingPage* interstitial_page =
static_cast<SafeBrowsingBlockingPage*>(
contents->interstitial_page());
ASSERT_TRUE(interstitial_page);
interstitial_page->CommandReceived(command);
}
void DontProceedThroughInterstitial() {
TabContents* contents = browser()->GetSelectedTabContents();
InterstitialPage* interstitial_page = contents->interstitial_page();
ASSERT_TRUE(interstitial_page);
interstitial_page->DontProceed();
}
void ProceedThroughInterstitial() {
TabContents* contents = browser()->GetSelectedTabContents();
InterstitialPage* interstitial_page = contents->interstitial_page();
ASSERT_TRUE(interstitial_page);
interstitial_page->Proceed();
}
void AssertNoInterstitial() {
TabContents* contents = browser()->GetSelectedTabContents();
InterstitialPage* interstitial_page = contents->interstitial_page();
ASSERT_FALSE(interstitial_page);
}
void WaitForNavigation() {
NavigationController* controller =
&browser()->GetSelectedTabContents()->controller();
ui_test_utils::WaitForNavigation(controller);
}
void AssertReportSent() {
// When a report is scheduled in the IO thread we should get notified.
ui_test_utils::RunMessageLoop();
FakeSafeBrowsingService* service =
static_cast<FakeSafeBrowsingService*>(
g_browser_process->resource_dispatcher_host()->
safe_browsing_service());
ASSERT_EQ(1u, service->GetDetails()->size());
}
private:
TestSafeBrowsingServiceFactory factory;
DISALLOW_COPY_AND_ASSIGN(SafeBrowsingBlockingPageTest);
};
namespace {
const char kEmptyPage[] = "files/empty.html";
const char kMalwarePage[] = "files/safe_browsing/malware.html";
const char kMalwareIframe[] = "files/safe_browsing/malware_iframe.html";
IN_PROC_BROWSER_TEST_F(SafeBrowsingBlockingPageTest, MalwareDontProceed) {
GURL url = test_server()->GetURL(kEmptyPage);
AddURLResult(url, SafeBrowsingService::URL_MALWARE);
ui_test_utils::NavigateToURL(browser(), url);
SendCommand("\"takeMeBack\""); // Simulate the user clicking "back"
AssertNoInterstitial(); // Assert the interstitial is gone
EXPECT_EQ(GURL(chrome::kAboutBlankURL), // Back to "about:blank"
browser()->GetSelectedTabContents()->GetURL());
}
IN_PROC_BROWSER_TEST_F(SafeBrowsingBlockingPageTest, MalwareProceed) {
GURL url = test_server()->GetURL(kEmptyPage);
AddURLResult(url, SafeBrowsingService::URL_MALWARE);
ui_test_utils::NavigateToURL(browser(), url);
SendCommand("\"proceed\""); // Simulate the user clicking "proceed"
WaitForNavigation(); // Wait until we finish the navigation.
AssertNoInterstitial(); // Assert the interstitial is gone.
EXPECT_EQ(url, browser()->GetSelectedTabContents()->GetURL());
}
IN_PROC_BROWSER_TEST_F(SafeBrowsingBlockingPageTest, PhishingDontProceed) {
GURL url = test_server()->GetURL(kEmptyPage);
AddURLResult(url, SafeBrowsingService::URL_PHISHING);
ui_test_utils::NavigateToURL(browser(), url);
SendCommand("\"takeMeBack\""); // Simulate the user clicking "proceed"
AssertNoInterstitial(); // Assert the interstitial is gone
EXPECT_EQ(GURL(chrome::kAboutBlankURL), // We are back to "about:blank".
browser()->GetSelectedTabContents()->GetURL());
}
IN_PROC_BROWSER_TEST_F(SafeBrowsingBlockingPageTest, PhishingProceed) {
GURL url = test_server()->GetURL(kEmptyPage);
AddURLResult(url, SafeBrowsingService::URL_PHISHING);
ui_test_utils::NavigateToURL(browser(), url);
SendCommand("\"proceed\""); // Simulate the user clicking "proceed".
WaitForNavigation(); // Wait until we finish the navigation.
AssertNoInterstitial(); // Assert the interstitial is gone
EXPECT_EQ(url, browser()->GetSelectedTabContents()->GetURL());
}
IN_PROC_BROWSER_TEST_F(SafeBrowsingBlockingPageTest, PhishingReportError) {
GURL url = test_server()->GetURL(kEmptyPage);
AddURLResult(url, SafeBrowsingService::URL_PHISHING);
ui_test_utils::NavigateToURL(browser(), url);
SendCommand("\"reportError\""); // Simulate the user clicking "report error"
WaitForNavigation(); // Wait until we finish the navigation.
AssertNoInterstitial(); // Assert the interstitial is gone
// We are in the error reporting page.
EXPECT_EQ("/safebrowsing/report_error/",
browser()->GetSelectedTabContents()->GetURL().path());
}
IN_PROC_BROWSER_TEST_F(SafeBrowsingBlockingPageTest, PhishingLearnMore) {
GURL url = test_server()->GetURL(kEmptyPage);
AddURLResult(url, SafeBrowsingService::URL_PHISHING);
ui_test_utils::NavigateToURL(browser(), url);
SendCommand("\"learnMore\""); // Simulate the user clicking "learn more"
WaitForNavigation(); // Wait until we finish the navigation.
AssertNoInterstitial(); // Assert the interstitial is gone
// We are in the help page.
EXPECT_EQ("/support/bin/answer.py",
browser()->GetSelectedTabContents()->GetURL().path());
}
IN_PROC_BROWSER_TEST_F(SafeBrowsingBlockingPageTest, MalwareIframeDontProceed) {
GURL url = test_server()->GetURL(kMalwarePage);
GURL iframe_url = test_server()->GetURL(kMalwareIframe);
AddURLResult(iframe_url, SafeBrowsingService::URL_MALWARE);
ui_test_utils::NavigateToURL(browser(), url);
SendCommand("\"takeMeBack\""); // Simulate the user clicking "back"
AssertNoInterstitial(); // Assert the interstitial is gone
EXPECT_EQ(GURL(chrome::kAboutBlankURL), // Back to "about:blank"
browser()->GetSelectedTabContents()->GetURL());
}
// Crashy, http://crbug.com/68834.
IN_PROC_BROWSER_TEST_F(SafeBrowsingBlockingPageTest,
DISABLED_MalwareIframeProceed) {
GURL url = test_server()->GetURL(kMalwarePage);
GURL iframe_url = test_server()->GetURL(kMalwareIframe);
AddURLResult(iframe_url, SafeBrowsingService::URL_MALWARE);
ui_test_utils::NavigateToURL(browser(), url);
SendCommand("\"proceed\""); // Simulate the user clicking "proceed"
AssertNoInterstitial(); // Assert the interstitial is gone
EXPECT_EQ(url, browser()->GetSelectedTabContents()->GetURL());
}
IN_PROC_BROWSER_TEST_F(SafeBrowsingBlockingPageTest,
MalwareIframeReportDetails) {
// Enable reporting of malware details.
browser()->GetProfile()->GetPrefs()->SetBoolean(
prefs::kSafeBrowsingReportingEnabled, true);
EXPECT_TRUE(browser()->GetProfile()->GetPrefs()->GetBoolean(
prefs::kSafeBrowsingReportingEnabled));
GURL url = test_server()->GetURL(kMalwarePage);
GURL iframe_url = test_server()->GetURL(kMalwareIframe);
AddURLResult(iframe_url, SafeBrowsingService::URL_MALWARE);
ui_test_utils::NavigateToURL(browser(), url);
SendCommand("\"proceed\""); // Simulate the user clicking "back"
AssertNoInterstitial(); // Assert the interstitial is gone
EXPECT_EQ(url, browser()->GetSelectedTabContents()->GetURL());
AssertReportSent();
}
} // namespace
<|endoftext|> |
<commit_before>// Copyright (c) 2009 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 entry.
#include "chrome/browser/sync/util/extensions_activity_monitor.h"
#include "base/file_path.h"
#include "base/string_util.h"
#include "base/waitable_event.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/extensions/extension_bookmarks_module.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/extension_constants.h"
#include "chrome/common/notification_service.h"
#include "testing/gtest/include/gtest/gtest.h"
using browser_sync::ExtensionsActivityMonitor;
namespace keys = extension_manifest_keys;
namespace {
static const char* kTestExtensionPath1 = "c:\\testextension1";
static const char* kTestExtensionPath2 = "c:\\testextension2";
static const char* kTestExtensionVersion = "1.0.0.0";
static const char* kTestExtensionName = "foo extension";
template <class FunctionType>
class BookmarkAPIEventTask : public Task {
public:
BookmarkAPIEventTask(FunctionType* t, Extension* e, size_t repeats,
base::WaitableEvent* done) :
function_(t), extension_(e), repeats_(repeats), done_(done) {}
virtual void Run() {
for (size_t i = 0; i < repeats_; i++) {
NotificationService::current()->Notify(
NotificationType::EXTENSION_BOOKMARKS_API_INVOKED,
Source<Extension>(extension_.get()),
Details<const BookmarksFunction>(function_.get()));
}
done_->Signal();
}
private:
scoped_ptr<Extension> extension_;
scoped_refptr<FunctionType> function_;
size_t repeats_;
base::WaitableEvent* done_;
DISALLOW_COPY_AND_ASSIGN(BookmarkAPIEventTask);
};
class BookmarkAPIEventGenerator {
public:
BookmarkAPIEventGenerator(MessageLoop* ui_loop) : ui_loop_(ui_loop) {}
virtual ~BookmarkAPIEventGenerator() {}
template <class T>
void NewEvent(const std::string& extension_path,
T* bookmarks_function, size_t repeats) {
FilePath path(UTF8ToWide(extension_path));
Extension* extension = new Extension(path);
std::string error;
DictionaryValue input;
input.SetString(keys::kVersion, kTestExtensionVersion);
input.SetString(keys::kName, kTestExtensionName);
extension->InitFromValue(input, false, &error);
bookmarks_function->set_name(T::function_name());
base::WaitableEvent done_event(false, false);
ui_loop_->PostTask(FROM_HERE, new BookmarkAPIEventTask<T>(
bookmarks_function, extension, repeats, &done_event));
done_event.Wait();
}
private:
MessageLoop* ui_loop_;
DISALLOW_COPY_AND_ASSIGN(BookmarkAPIEventGenerator);
};
} // namespace
class DoUIThreadSetupTask : public Task {
public:
DoUIThreadSetupTask(NotificationService** service,
base::WaitableEvent* done)
: service_(service), signal_when_done_(done) {}
virtual ~DoUIThreadSetupTask() {}
virtual void Run() {
*service_ = new NotificationService();
signal_when_done_->Signal();
}
private:
NotificationService** service_;
base::WaitableEvent* signal_when_done_;
DISALLOW_COPY_AND_ASSIGN(DoUIThreadSetupTask);
};
class ExtensionsActivityMonitorTest : public testing::Test {
public:
ExtensionsActivityMonitorTest() : service_(NULL),
ui_thread_(ChromeThread::UI) { }
virtual ~ExtensionsActivityMonitorTest() {}
virtual void SetUp() {
ui_thread_.Start();
base::WaitableEvent service_created(false, false);
ui_thread_.message_loop()->PostTask(FROM_HERE,
new DoUIThreadSetupTask(&service_, &service_created));
service_created.Wait();
}
virtual void TearDown() {
ui_thread_.message_loop()->DeleteSoon(FROM_HERE, service_);
ui_thread_.Stop();
}
MessageLoop* ui_loop() { return ui_thread_.message_loop(); }
static std::string GetExtensionIdForPath(const std::string& extension_path) {
std::string error;
FilePath path(UTF8ToWide(extension_path));
Extension e(path);
DictionaryValue input;
input.SetString(keys::kVersion, kTestExtensionVersion);
input.SetString(keys::kName, kTestExtensionName);
e.InitFromValue(input, false, &error);
EXPECT_EQ("", error);
return e.id();
}
private:
NotificationService* service_;
ChromeThread ui_thread_;
};
TEST_F(ExtensionsActivityMonitorTest, Basic) {
ExtensionsActivityMonitor* monitor = new ExtensionsActivityMonitor(ui_loop());
BookmarkAPIEventGenerator generator(ui_loop());
generator.NewEvent<RemoveBookmarkFunction>(kTestExtensionPath1,
new RemoveBookmarkFunction(), 1);
generator.NewEvent<MoveBookmarkFunction>(kTestExtensionPath1,
new MoveBookmarkFunction(), 1);
generator.NewEvent<UpdateBookmarkFunction>(kTestExtensionPath1,
new UpdateBookmarkFunction(), 2);
generator.NewEvent<CreateBookmarkFunction>(kTestExtensionPath1,
new CreateBookmarkFunction(), 3);
generator.NewEvent<SearchBookmarksFunction>(kTestExtensionPath1,
new SearchBookmarksFunction(), 5);
const int writes_by_extension1 = 1 + 1 + 2 + 3;
generator.NewEvent<RemoveTreeBookmarkFunction>(kTestExtensionPath2,
new RemoveTreeBookmarkFunction(), 8);
generator.NewEvent<GetBookmarkTreeFunction>(kTestExtensionPath2,
new GetBookmarkTreeFunction(), 13);
generator.NewEvent<GetBookmarkChildrenFunction>(kTestExtensionPath2,
new GetBookmarkChildrenFunction(), 21);
generator.NewEvent<GetBookmarksFunction>(kTestExtensionPath2,
new GetBookmarksFunction(), 33);
const int writes_by_extension2 = 8;
ExtensionsActivityMonitor::Records results;
monitor->GetAndClearRecords(&results);
std::string id1 = GetExtensionIdForPath(kTestExtensionPath1);
std::string id2 = GetExtensionIdForPath(kTestExtensionPath2);
EXPECT_EQ(2, results.size());
EXPECT_TRUE(results.end() != results.find(id1));
EXPECT_TRUE(results.end() != results.find(id2));
EXPECT_EQ(writes_by_extension1, results[id1].bookmark_write_count);
EXPECT_EQ(writes_by_extension2, results[id2].bookmark_write_count);
ui_loop()->DeleteSoon(FROM_HERE, monitor);
}
TEST_F(ExtensionsActivityMonitorTest, Put) {
ExtensionsActivityMonitor* monitor = new ExtensionsActivityMonitor(ui_loop());
BookmarkAPIEventGenerator generator(ui_loop());
std::string id1 = GetExtensionIdForPath(kTestExtensionPath1);
std::string id2 = GetExtensionIdForPath(kTestExtensionPath2);
generator.NewEvent<CreateBookmarkFunction>(kTestExtensionPath1,
new CreateBookmarkFunction(), 5);
generator.NewEvent<MoveBookmarkFunction>(kTestExtensionPath2,
new MoveBookmarkFunction(), 8);
ExtensionsActivityMonitor::Records results;
monitor->GetAndClearRecords(&results);
EXPECT_EQ(2, results.size());
EXPECT_EQ(5, results[id1].bookmark_write_count);
EXPECT_EQ(8, results[id2].bookmark_write_count);
generator.NewEvent<GetBookmarksFunction>(kTestExtensionPath2,
new GetBookmarksFunction(), 3);
generator.NewEvent<UpdateBookmarkFunction>(kTestExtensionPath2,
new UpdateBookmarkFunction(), 2);
// Simulate a commit failure, which augments the active record set with the
// refugee records.
monitor->PutRecords(results);
ExtensionsActivityMonitor::Records new_records;
monitor->GetAndClearRecords(&new_records);
EXPECT_EQ(2, results.size());
EXPECT_EQ(id1, new_records[id1].extension_id);
EXPECT_EQ(id2, new_records[id2].extension_id);
EXPECT_EQ(5, new_records[id1].bookmark_write_count);
EXPECT_EQ(8 + 2, new_records[id2].bookmark_write_count);
ui_loop()->DeleteSoon(FROM_HERE, monitor);
}
TEST_F(ExtensionsActivityMonitorTest, MultiGet) {
ExtensionsActivityMonitor* monitor = new ExtensionsActivityMonitor(ui_loop());
BookmarkAPIEventGenerator generator(ui_loop());
std::string id1 = GetExtensionIdForPath(kTestExtensionPath1);
generator.NewEvent<CreateBookmarkFunction>(kTestExtensionPath1,
new CreateBookmarkFunction(), 5);
ExtensionsActivityMonitor::Records results;
monitor->GetAndClearRecords(&results);
EXPECT_EQ(1, results.size());
EXPECT_EQ(5, results[id1].bookmark_write_count);
monitor->GetAndClearRecords(&results);
EXPECT_TRUE(results.empty());
generator.NewEvent<CreateBookmarkFunction>(kTestExtensionPath1,
new CreateBookmarkFunction(), 3);
monitor->GetAndClearRecords(&results);
EXPECT_EQ(1, results.size());
EXPECT_EQ(3, results[id1].bookmark_write_count);
ui_loop()->DeleteSoon(FROM_HERE, monitor);
}
<commit_msg>Revert (1 of 4) 30157 - Add newline to end of another file.<commit_after>// Copyright (c) 2009 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 entry.
#include "chrome/browser/sync/util/extensions_activity_monitor.h"
#include "base/file_path.h"
#include "base/string_util.h"
#include "base/waitable_event.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/extensions/extension_bookmarks_module.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/extension_constants.h"
#include "chrome/common/notification_service.h"
#include "testing/gtest/include/gtest/gtest.h"
using browser_sync::ExtensionsActivityMonitor;
namespace keys = extension_manifest_keys;
namespace {
static const char* kTestExtensionPath1 = "c:\\testextension1";
static const char* kTestExtensionPath2 = "c:\\testextension2";
static const char* kTestExtensionVersion = "1.0.0.0";
static const char* kTestExtensionName = "foo extension";
template <class FunctionType>
class BookmarkAPIEventTask : public Task {
public:
BookmarkAPIEventTask(FunctionType* t, Extension* e, size_t repeats,
base::WaitableEvent* done) :
function_(t), extension_(e), repeats_(repeats), done_(done) {}
virtual void Run() {
for (size_t i = 0; i < repeats_; i++) {
NotificationService::current()->Notify(
NotificationType::EXTENSION_BOOKMARKS_API_INVOKED,
Source<Extension>(extension_.get()),
Details<const BookmarksFunction>(function_.get()));
}
done_->Signal();
}
private:
scoped_ptr<Extension> extension_;
scoped_refptr<FunctionType> function_;
size_t repeats_;
base::WaitableEvent* done_;
DISALLOW_COPY_AND_ASSIGN(BookmarkAPIEventTask);
};
class BookmarkAPIEventGenerator {
public:
BookmarkAPIEventGenerator(MessageLoop* ui_loop) : ui_loop_(ui_loop) {}
virtual ~BookmarkAPIEventGenerator() {}
template <class T>
void NewEvent(const std::string& extension_path,
T* bookmarks_function, size_t repeats) {
FilePath path(UTF8ToWide(extension_path));
Extension* extension = new Extension(path);
std::string error;
DictionaryValue input;
input.SetString(keys::kVersion, kTestExtensionVersion);
input.SetString(keys::kName, kTestExtensionName);
extension->InitFromValue(input, false, &error);
bookmarks_function->set_name(T::function_name());
base::WaitableEvent done_event(false, false);
ui_loop_->PostTask(FROM_HERE, new BookmarkAPIEventTask<T>(
bookmarks_function, extension, repeats, &done_event));
done_event.Wait();
}
private:
MessageLoop* ui_loop_;
DISALLOW_COPY_AND_ASSIGN(BookmarkAPIEventGenerator);
};
} // namespace
class DoUIThreadSetupTask : public Task {
public:
DoUIThreadSetupTask(NotificationService** service,
base::WaitableEvent* done)
: service_(service), signal_when_done_(done) {}
virtual ~DoUIThreadSetupTask() {}
virtual void Run() {
*service_ = new NotificationService();
signal_when_done_->Signal();
}
private:
NotificationService** service_;
base::WaitableEvent* signal_when_done_;
DISALLOW_COPY_AND_ASSIGN(DoUIThreadSetupTask);
};
class ExtensionsActivityMonitorTest : public testing::Test {
public:
ExtensionsActivityMonitorTest() : service_(NULL),
ui_thread_(ChromeThread::UI) { }
virtual ~ExtensionsActivityMonitorTest() {}
virtual void SetUp() {
ui_thread_.Start();
base::WaitableEvent service_created(false, false);
ui_thread_.message_loop()->PostTask(FROM_HERE,
new DoUIThreadSetupTask(&service_, &service_created));
service_created.Wait();
}
virtual void TearDown() {
ui_thread_.message_loop()->DeleteSoon(FROM_HERE, service_);
ui_thread_.Stop();
}
MessageLoop* ui_loop() { return ui_thread_.message_loop(); }
static std::string GetExtensionIdForPath(const std::string& extension_path) {
std::string error;
FilePath path(UTF8ToWide(extension_path));
Extension e(path);
DictionaryValue input;
input.SetString(keys::kVersion, kTestExtensionVersion);
input.SetString(keys::kName, kTestExtensionName);
e.InitFromValue(input, false, &error);
EXPECT_EQ("", error);
return e.id();
}
private:
NotificationService* service_;
ChromeThread ui_thread_;
};
TEST_F(ExtensionsActivityMonitorTest, Basic) {
ExtensionsActivityMonitor* monitor = new ExtensionsActivityMonitor(ui_loop());
BookmarkAPIEventGenerator generator(ui_loop());
generator.NewEvent<RemoveBookmarkFunction>(kTestExtensionPath1,
new RemoveBookmarkFunction(), 1);
generator.NewEvent<MoveBookmarkFunction>(kTestExtensionPath1,
new MoveBookmarkFunction(), 1);
generator.NewEvent<UpdateBookmarkFunction>(kTestExtensionPath1,
new UpdateBookmarkFunction(), 2);
generator.NewEvent<CreateBookmarkFunction>(kTestExtensionPath1,
new CreateBookmarkFunction(), 3);
generator.NewEvent<SearchBookmarksFunction>(kTestExtensionPath1,
new SearchBookmarksFunction(), 5);
const int writes_by_extension1 = 1 + 1 + 2 + 3;
generator.NewEvent<RemoveTreeBookmarkFunction>(kTestExtensionPath2,
new RemoveTreeBookmarkFunction(), 8);
generator.NewEvent<GetBookmarkTreeFunction>(kTestExtensionPath2,
new GetBookmarkTreeFunction(), 13);
generator.NewEvent<GetBookmarkChildrenFunction>(kTestExtensionPath2,
new GetBookmarkChildrenFunction(), 21);
generator.NewEvent<GetBookmarksFunction>(kTestExtensionPath2,
new GetBookmarksFunction(), 33);
const int writes_by_extension2 = 8;
ExtensionsActivityMonitor::Records results;
monitor->GetAndClearRecords(&results);
std::string id1 = GetExtensionIdForPath(kTestExtensionPath1);
std::string id2 = GetExtensionIdForPath(kTestExtensionPath2);
EXPECT_EQ(2, results.size());
EXPECT_TRUE(results.end() != results.find(id1));
EXPECT_TRUE(results.end() != results.find(id2));
EXPECT_EQ(writes_by_extension1, results[id1].bookmark_write_count);
EXPECT_EQ(writes_by_extension2, results[id2].bookmark_write_count);
ui_loop()->DeleteSoon(FROM_HERE, monitor);
}
TEST_F(ExtensionsActivityMonitorTest, Put) {
ExtensionsActivityMonitor* monitor = new ExtensionsActivityMonitor(ui_loop());
BookmarkAPIEventGenerator generator(ui_loop());
std::string id1 = GetExtensionIdForPath(kTestExtensionPath1);
std::string id2 = GetExtensionIdForPath(kTestExtensionPath2);
generator.NewEvent<CreateBookmarkFunction>(kTestExtensionPath1,
new CreateBookmarkFunction(), 5);
generator.NewEvent<MoveBookmarkFunction>(kTestExtensionPath2,
new MoveBookmarkFunction(), 8);
ExtensionsActivityMonitor::Records results;
monitor->GetAndClearRecords(&results);
EXPECT_EQ(2, results.size());
EXPECT_EQ(5, results[id1].bookmark_write_count);
EXPECT_EQ(8, results[id2].bookmark_write_count);
generator.NewEvent<GetBookmarksFunction>(kTestExtensionPath2,
new GetBookmarksFunction(), 3);
generator.NewEvent<UpdateBookmarkFunction>(kTestExtensionPath2,
new UpdateBookmarkFunction(), 2);
// Simulate a commit failure, which augments the active record set with the
// refugee records.
monitor->PutRecords(results);
ExtensionsActivityMonitor::Records new_records;
monitor->GetAndClearRecords(&new_records);
EXPECT_EQ(2, results.size());
EXPECT_EQ(id1, new_records[id1].extension_id);
EXPECT_EQ(id2, new_records[id2].extension_id);
EXPECT_EQ(5, new_records[id1].bookmark_write_count);
EXPECT_EQ(8 + 2, new_records[id2].bookmark_write_count);
ui_loop()->DeleteSoon(FROM_HERE, monitor);
}
TEST_F(ExtensionsActivityMonitorTest, MultiGet) {
ExtensionsActivityMonitor* monitor = new ExtensionsActivityMonitor(ui_loop());
BookmarkAPIEventGenerator generator(ui_loop());
std::string id1 = GetExtensionIdForPath(kTestExtensionPath1);
generator.NewEvent<CreateBookmarkFunction>(kTestExtensionPath1,
new CreateBookmarkFunction(), 5);
ExtensionsActivityMonitor::Records results;
monitor->GetAndClearRecords(&results);
EXPECT_EQ(1, results.size());
EXPECT_EQ(5, results[id1].bookmark_write_count);
monitor->GetAndClearRecords(&results);
EXPECT_TRUE(results.empty());
generator.NewEvent<CreateBookmarkFunction>(kTestExtensionPath1,
new CreateBookmarkFunction(), 3);
monitor->GetAndClearRecords(&results);
EXPECT_EQ(1, results.size());
EXPECT_EQ(3, results[id1].bookmark_write_count);
ui_loop()->DeleteSoon(FROM_HERE, monitor);
}<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/base/cert_database.h"
#include <openssl/x509.h>
#include "base/logging.h"
#include "net/base/net_errors.h"
#include "net/base/openssl_private_key_store.h"
#include "net/base/x509_certificate.h"
namespace net {
CertDatabase::CertDatabase() {
}
int CertDatabase::CheckUserCert(X509Certificate* cert) {
if (!cert)
return ERR_CERT_INVALID;
if (cert->HasExpired())
return ERR_CERT_DATE_INVALID;
if (!OpenSSLPrivateKeyStore::GetInstance()->FetchPrivateKey(
X509_PUBKEY_get(X509_get_X509_PUBKEY(cert->os_cert_handle()))))
return ERR_NO_PRIVATE_KEY_FOR_CERT;
return OK;
}
int CertDatabase::AddUserCert(X509Certificate* cert) {
// TODO(bulach): implement me.
NOTIMPLEMENTED();
return ERR_NOT_IMPLEMENTED;
}
void CertDatabase::ListCerts(CertificateList* certs) {
// TODO(bulach): implement me.
NOTIMPLEMENTED();
}
CryptoModule* CertDatabase::GetDefaultModule() const {
// TODO(bulach): implement me.
NOTIMPLEMENTED();
return NULL;
}
void CertDatabase::ListModules(CryptoModuleList* modules, bool need_rw) const {
// TODO(bulach): implement me.
NOTIMPLEMENTED();
modules->clear();
}
int CertDatabase::ImportFromPKCS12(net::CryptoModule* module,
const std::string& data,
const string16& password) {
// TODO(bulach): implement me.
NOTIMPLEMENTED();
return ERR_NOT_IMPLEMENTED;
}
int CertDatabase::ExportToPKCS12(const CertificateList& certs,
const string16& password,
std::string* output) const {
// TODO(bulach): implement me.
NOTIMPLEMENTED();
return 0;
}
bool CertDatabase::DeleteCertAndKey(const X509Certificate* cert) {
// TODO(bulach): implement me.
NOTIMPLEMENTED();
return false;
}
unsigned int CertDatabase::GetCertTrust(const X509Certificate* cert,
CertType type) const {
// TODO(bulach): implement me.
NOTIMPLEMENTED();
return 0;
}
bool CertDatabase::SetCertTrust(const X509Certificate* cert,
CertType type,
unsigned int trust_bits) {
// TODO(bulach): implement me.
NOTIMPLEMENTED();
return false;
}
} // namespace net
<commit_msg>Fixes OpenSSL build: adds missing include following r77024.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/base/cert_database.h"
#include <openssl/x509.h>
#include "base/logging.h"
#include "net/base/crypto_module.h"
#include "net/base/net_errors.h"
#include "net/base/openssl_private_key_store.h"
#include "net/base/x509_certificate.h"
namespace net {
CertDatabase::CertDatabase() {
}
int CertDatabase::CheckUserCert(X509Certificate* cert) {
if (!cert)
return ERR_CERT_INVALID;
if (cert->HasExpired())
return ERR_CERT_DATE_INVALID;
if (!OpenSSLPrivateKeyStore::GetInstance()->FetchPrivateKey(
X509_PUBKEY_get(X509_get_X509_PUBKEY(cert->os_cert_handle()))))
return ERR_NO_PRIVATE_KEY_FOR_CERT;
return OK;
}
int CertDatabase::AddUserCert(X509Certificate* cert) {
// TODO(bulach): implement me.
NOTIMPLEMENTED();
return ERR_NOT_IMPLEMENTED;
}
void CertDatabase::ListCerts(CertificateList* certs) {
// TODO(bulach): implement me.
NOTIMPLEMENTED();
}
CryptoModule* CertDatabase::GetDefaultModule() const {
// TODO(bulach): implement me.
NOTIMPLEMENTED();
return NULL;
}
void CertDatabase::ListModules(CryptoModuleList* modules, bool need_rw) const {
// TODO(bulach): implement me.
NOTIMPLEMENTED();
modules->clear();
}
int CertDatabase::ImportFromPKCS12(net::CryptoModule* module,
const std::string& data,
const string16& password) {
// TODO(bulach): implement me.
NOTIMPLEMENTED();
return ERR_NOT_IMPLEMENTED;
}
int CertDatabase::ExportToPKCS12(const CertificateList& certs,
const string16& password,
std::string* output) const {
// TODO(bulach): implement me.
NOTIMPLEMENTED();
return 0;
}
bool CertDatabase::DeleteCertAndKey(const X509Certificate* cert) {
// TODO(bulach): implement me.
NOTIMPLEMENTED();
return false;
}
unsigned int CertDatabase::GetCertTrust(const X509Certificate* cert,
CertType type) const {
// TODO(bulach): implement me.
NOTIMPLEMENTED();
return 0;
}
bool CertDatabase::SetCertTrust(const X509Certificate* cert,
CertType type,
unsigned int trust_bits) {
// TODO(bulach): implement me.
NOTIMPLEMENTED();
return false;
}
} // namespace net
<|endoftext|> |
<commit_before><commit_msg>Return ERR_SSL_PROTOCOL_ERROR instead of the default ERR_FAILED when we read EOF during the SSL handshake. The ERR_SSL_PROTOCOL_ERROR error code will allow the TLS-intolerant server handling code in http_network_transaction.cc to kick in if necessary.<commit_after><|endoftext|> |
<commit_before><commit_msg>lambda version of ferret<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <math.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>
#include <pthread.h>
#include <cass.h>
extern "C" {
#include <cass_timer.h>
}
extern "C" {
#include <../image/image.h>
}
#include "tpool.h"
#include "queue.h"
#include "tbb/task_scheduler_init.h"
#include "tbb/pipeline.h"
#include <stack>
#include <functional>
#define PIPELINE_WIDTH 1024
struct load_data {
int width, height;
char *name;
unsigned char *HSV, *RGB;
};
struct seg_data {
int width, height, nrgn;
char *name;
unsigned char *mask;
unsigned char *HSV;
};
struct extract_data {
cass_dataset_t ds;
char *name;
};
struct vec_query_data {
char *name;
cass_dataset_t *ds;
cass_result_t result;
};
struct rank_data {
char *name;
cass_dataset_t *ds;
cass_result_t result;
};
int main( int argc, char *argv[] ) {
// Setup
tbb::task_scheduler_init init( tbb::task_scheduler_init::deferred );
stimer_t tmr;
int ret, i;
int cnt_enqueue = 0;
int cnt_dequeue = 0;
#ifdef PARSEC_VERSION
#define __PARSEC_STRING(x) #x
#define __PARSEC_XSTRING(x) __PARSEC_STRING(x)
printf("PARSEC Benchmark Suite Version "__PARSEC_XSTRING(PARSEC_VERSION)"\n");
fflush(NULL);
#else
printf("PARSEC Benchmark Suite\n");
fflush(NULL);
#endif //PARSEC_VERSION
if (argc < 8)
{
printf("%s <database> <table> <query dir> <top K> <depth> <n> <out>\n", argv[0]);
return 0;
}
char *extra_params = "-L 8 - T 20";
cass_env_t *env;
cass_table_t *table;
cass_table_t *query_table;
int vec_dist_id = 0;
int vecset_dist_id = 0;
const char *db_dir = argv[1];
const char *table_name = argv[2];
const char *query_dir = argv[3];
int top_K = atoi( argv[4] );
int num_tokens = atoi( argv[5] );
int nthreads = atoi( argv[6] );
init.initialize( nthreads );
const char *output_path = argv[7];
FILE *fout = fopen( output_path, "w" );
assert( fout != NULL );
cass_init();
if( ( ret = cass_env_open( &env, db_dir, 0 ) ) != 0 ) {
printf( "ERROR: %s\n", cass_strerror( ret ) );
return 0;
}
assert( ( vec_dist_id = cass_reg_lookup( &env->vec_dist, "L2_float" ) ) >= 0 );
assert( ( vecset_dist_id = cass_reg_lookup( &env->vecset_dist, "emd" ) ) >= 0 );
i = cass_reg_lookup( &env->table, table_name );
table = query_table = cass_reg_get( &env->table, i );
if( ( i = table->parent_id ) >= 0 )
query_table = cass_reg_get( &env->table, i );
if( query_table != table )
cass_table_load( query_table );
cass_map_load( query_table->map );
cass_table_load( table );
image_init( argv[0] );
stimer_tick( &tmr );
// Create pipeline stages
char path[ BUFSIZ ];
int first_call = 1;
struct stack_data {
DIR *dir;
char *head;
};
std::stack<stack_data*> stack;
// forward declarations
std::function< void( const char *dir, char *head ) > enter_directory;
std::function< void() > leave_directory;
std::function< void( char *head ) > reset_path_head;
std::function< load_data*( const char *file, char *head ) > load_file;
std::function< load_data*( const char *dir, char *head ) > dispatch;
std::function< load_data*() > read_next_item;
// enter a directory
enter_directory = [&]( const char *dir, char *head ) -> void {
// open the directory
DIR *pd = NULL;
assert( ( pd = opendir( dir ) ) != NULL );
// store the data
struct stack_data *data = new stack_data;
data->dir = pd;
data->head = head;
// push onto the stack
stack.push( data );
return;
};
// leave the directory (now that we've completed it)
leave_directory = [&]() -> void {
// remove the top of the stack
struct stack_data *data = stack.top();
stack.pop();
// close the directory file descriptor
DIR *pd = data->dir;
if( pd != NULL )
closedir( pd );
// remove the appended file name from the path
reset_path_head( data->head );
delete data;
return;
};
// remove the appended part of the path
reset_path_head = [&]( char *head ) -> void {
head[0] = 0;
};
load_file = [&]( const char *file, char *head ) -> load_data* {
// initialize the new token
struct load_data *data = new load_data;
// copy the file name to the token
data->name = strdup( file );
// read in the image - assert checks for errors
assert( image_read_rgb_hsv( file, &data->width, &data->height, &data->RGB, &data->HSV ) == 0 );
// reset the path buffer head
reset_path_head( head );
// increment enqueued counter
cnt_enqueue++;
// return a pointer to the data
return data;
};
// decide what to do with a file
dispatch = [&]( const char *dir, char *head ) -> load_data* {
// if one of the special directories, skip
if( dir[0] == '.' && ( dir[1] == 0 || ( dir[1] == '.' && dir[2] == 0 ) ) )
return read_next_item(); // i.e. recurse to the next item
struct stat st;
// append the file name to the path
strcat( head, dir );
assert( stat( path, &st ) == 0 );
if( S_ISREG( st.st_mode ) )
// just return the loaded file
return load_file( path, head );
else if( S_ISDIR( st.st_mode ) ) {
// append the path separator
strcat( head, "/" );
// enter the directory
enter_directory( path, head + strlen( head ) );
// recurse for the next item
return read_next_item();
}
};
// find the next item
read_next_item = [&]() -> load_data* {
// if the stack is empty, we are done
if( stack.empty() )
return NULL;
// examine the top of the stack (current directory)
struct dirent *ent = NULL;
struct stack_data *data = stack.top();
// get the next file
ent = readdir( data->dir );
if( ent == NULL ) {
// we've finished the directory! close it and recurse back up the tree
data = NULL;
leave_directory();
return read_next_item();
} else {
// figure out what to do with this file
return dispatch( ent->d_name, data->head );
}
};
auto read_f = [&]( tbb::flow_control& fc ) -> load_data* {
struct load_data *next = NULL;
if( first_call ) {
// special handling at the start
first_call = 0;
path[0] = 0; // empty the path buffer
if( ! strcmp( query_dir, "." ) ) {
// if they used the special directory notation,
// make sure to enter the current directory before getting an item
enter_directory( ".", path );
next = read_next_item();
//return read_next_item();
} else {
// otherwise, we can just figure out what to do with the path provided
next = dispatch( query_dir, path );
//return dispatch( query_dir, path );
}
} else {
// otherwise, just get the next item
next = read_next_item();
//return read_next_item();
}
if( next == NULL )
fc.stop();
return next;
};
auto seg_f = [&]( load_data *load ) -> seg_data* {
struct seg_data *seg;
seg = new seg_data;
seg->name = load->name;
seg->width = load->width;
seg->height = load->height;
seg->HSV = load->HSV;
image_segment( &seg->mask, &seg->nrgn, load->RGB, load->width, load->height );
delete load->RGB;
delete load;
return seg;
};
auto extract_f = [&]( seg_data *seg ) -> extract_data* {
struct extract_data *extract;
assert( seg != NULL );
extract = new extract_data;
extract->name = seg->name;
image_extract_helper( seg->HSV, seg->mask, seg->width, seg->height, seg->nrgn, &extract->ds );
delete seg->mask;
delete seg->HSV;
delete seg;
return extract;
};
auto query_f = [&]( extract_data *extract ) -> vec_query_data* {
struct vec_query_data *vec;
cass_query_t query;
assert( extract != NULL );
vec = new vec_query_data;
vec->name = extract->name;
memset( &query, 0, sizeof query );
query.flags = CASS_RESULT_LISTS | CASS_RESULT_USERMEM;
vec->ds = query.dataset = &extract->ds;
query.vecset_id = 0;
query.vec_dist_id = vec_dist_id;
query.vecset_dist_id = vecset_dist_id;
query.topk = 2 * top_K;
query.extra_params = extra_params;
cass_result_alloc_list( &vec->result, vec->ds->vecset[0].num_regions, query.topk );
cass_table_query( table, &query, &vec->result );
return vec;
};
auto rank_f = [&]( vec_query_data *vec ) -> rank_data* {
struct rank_data *rank;
cass_result_t *candidate;
cass_query_t query;
assert( vec != NULL );
rank = new rank_data;
rank->name = vec->name;
query.flags = CASS_RESULT_LIST | CASS_RESULT_USERMEM | CASS_RESULT_SORT;
query.dataset = vec->ds;
query.vecset_id = 0;
query.vec_dist_id = vec_dist_id;
query.vecset_dist_id = vecset_dist_id;
query.topk = top_K;
query.extra_params = NULL;
candidate = cass_result_merge_lists( &vec->result, (cass_dataset_t*) query_table->__private, 0 );
query.candidate = candidate;
cass_result_alloc_list( &rank->result, 0, top_K );
cass_table_query( query_table, &query, &rank->result );
cass_result_free( &vec->result );
cass_result_free( candidate );
free( candidate );
cass_dataset_release( vec->ds );
free( vec->ds );
delete vec;
return rank;
};
auto write_f = [&]( rank_data *rank ) -> void {
assert( rank != NULL );
fprintf( fout, "%s", rank->name );
ARRAY_BEGIN_FOREACH(rank->result.u.list, cass_list_entry_t p)
{
char *obj = NULL;
if (p.dist == HUGE) continue;
cass_map_id_to_dataobj(query_table->map, p.id, &obj);
assert(obj != NULL);
fprintf(fout, "\t%s:%g", obj, p.dist);
} ARRAY_END_FOREACH;
fprintf( fout, "\n" );
cass_result_free( &rank->result );
delete rank->name;
delete rank;
// add the count printer
cnt_dequeue++;
fprintf( stderr, "(%d,%d)\n", cnt_enqueue, cnt_dequeue );
return;
};
// Run pipeline
tbb::parallel_pipeline( PIPELINE_WIDTH,
tbb::make_filter< void, load_data* >( tbb::filter::serial_in_order, read_f ) &
tbb::make_filter< load_data*, seg_data* >( tbb::filter::parallel, seg_f ) &
tbb::make_filter< seg_data*, extract_data* >( tbb::filter::parallel, extract_f ) &
tbb::make_filter< extract_data*, vec_query_data* >( tbb::filter::parallel, query_f ) &
tbb::make_filter< vec_query_data*, rank_data* >( tbb::filter::parallel, rank_f ) &
tbb::make_filter< rank_data*, void >( tbb::filter::serial_out_of_order, write_f ) );
// Clean up
assert( cnt_enqueue == cnt_dequeue );
stimer_tuck( &tmr, "QUERY TIME" );
if( ( ret = cass_env_close( env, 0 ) ) != 0 ) {
printf( "ERROR: %s\n", cass_strerror( ret ) );
return 0;
}
cass_cleanup();
image_cleanup();
fclose( fout );
return 0;
}
<|endoftext|> |
<commit_before>//===- CrashDebugger.cpp - Debug compilation crashes ----------------------===//
//
// This file defines the bugpoint internals that narrow down compilation crashes
//
//===----------------------------------------------------------------------===//
#include "BugDriver.h"
#include "SystemUtils.h"
#include "ListReducer.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Pass.h"
#include "llvm/Constant.h"
#include "llvm/iTerminators.h"
#include "llvm/Type.h"
#include "llvm/SymbolTable.h"
#include "llvm/Support/CFG.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Bytecode/Writer.h"
#include <fstream>
#include <set>
class DebugCrashes : public ListReducer<const PassInfo*> {
BugDriver &BD;
public:
DebugCrashes(BugDriver &bd) : BD(bd) {}
// doTest - Return true iff running the "removed" passes succeeds, and running
// the "Kept" passes fail when run on the output of the "removed" passes. If
// we return true, we update the current module of bugpoint.
//
virtual TestResult doTest(std::vector<const PassInfo*> &Removed,
std::vector<const PassInfo*> &Kept);
};
DebugCrashes::TestResult
DebugCrashes::doTest(std::vector<const PassInfo*> &Prefix,
std::vector<const PassInfo*> &Suffix) {
std::string PrefixOutput;
Module *OrigProgram = 0;
if (!Prefix.empty()) {
std::cout << "Checking to see if these passes crash: "
<< getPassesString(Prefix) << ": ";
if (BD.runPasses(Prefix, PrefixOutput))
return KeepPrefix;
OrigProgram = BD.Program;
BD.Program = BD.ParseInputFile(PrefixOutput);
if (BD.Program == 0) {
std::cerr << BD.getToolName() << ": Error reading bytecode file '"
<< PrefixOutput << "'!\n";
exit(1);
}
removeFile(PrefixOutput);
}
std::cout << "Checking to see if these passes crash: "
<< getPassesString(Suffix) << ": ";
if (BD.runPasses(Suffix)) {
delete OrigProgram; // The suffix crashes alone...
return KeepSuffix;
}
// Nothing failed, restore state...
if (OrigProgram) {
delete BD.Program;
BD.Program = OrigProgram;
}
return NoFailure;
}
class ReduceCrashingFunctions : public ListReducer<Function*> {
BugDriver &BD;
public:
ReduceCrashingFunctions(BugDriver &bd) : BD(bd) {}
virtual TestResult doTest(std::vector<Function*> &Prefix,
std::vector<Function*> &Kept) {
if (TestFuncs(Kept))
return KeepSuffix;
if (!Prefix.empty() && TestFuncs(Prefix))
return KeepPrefix;
return NoFailure;
}
bool TestFuncs(std::vector<Function*> &Prefix);
};
bool ReduceCrashingFunctions::TestFuncs(std::vector<Function*> &Funcs) {
// Clone the program to try hacking it appart...
Module *M = CloneModule(BD.Program);
// Convert list to set for fast lookup...
std::set<Function*> Functions;
for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
Function *CMF = M->getFunction(Funcs[i]->getName(),
Funcs[i]->getFunctionType());
assert(CMF && "Function not in module?!");
Functions.insert(CMF);
}
std::cout << "Checking for crash with only these functions:";
for (unsigned i = 0, e = Funcs.size(); i != e; ++i)
std::cout << " " << Funcs[i]->getName();
std::cout << ": ";
// Loop over and delete any functions which we aren't supposed to be playing
// with...
for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
if (!I->isExternal() && !Functions.count(I))
DeleteFunctionBody(I);
// Try running the hacked up program...
std::swap(BD.Program, M);
if (BD.runPasses(BD.PassesToRun)) {
delete M; // It crashed, keep the trimmed version...
// Make sure to use function pointers that point into the now-current
// module.
Funcs.assign(Functions.begin(), Functions.end());
return true;
}
delete BD.Program; // It didn't crash, revert...
BD.Program = M;
return false;
}
/// ReduceCrashingBlocks reducer - This works by setting the terminators of all
/// terminators except the specified basic blocks to a 'ret' instruction, then
/// running the simplify-cfg pass. This has the effect of chopping up the CFG
/// really fast which can reduce large functions quickly.
///
class ReduceCrashingBlocks : public ListReducer<BasicBlock*> {
BugDriver &BD;
public:
ReduceCrashingBlocks(BugDriver &bd) : BD(bd) {}
virtual TestResult doTest(std::vector<BasicBlock*> &Prefix,
std::vector<BasicBlock*> &Kept) {
if (TestBlocks(Kept))
return KeepSuffix;
if (!Prefix.empty() && TestBlocks(Prefix))
return KeepPrefix;
return NoFailure;
}
bool TestBlocks(std::vector<BasicBlock*> &Prefix);
};
bool ReduceCrashingBlocks::TestBlocks(std::vector<BasicBlock*> &BBs) {
// Clone the program to try hacking it appart...
Module *M = CloneModule(BD.Program);
// Convert list to set for fast lookup...
std::set<BasicBlock*> Blocks;
for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
// Convert the basic block from the original module to the new module...
Function *F = BBs[i]->getParent();
Function *CMF = M->getFunction(F->getName(), F->getFunctionType());
assert(CMF && "Function not in module?!");
// Get the mapped basic block...
Function::iterator CBI = CMF->begin();
std::advance(CBI, std::distance(F->begin(), Function::iterator(BBs[i])));
Blocks.insert(CBI);
}
std::cout << "Checking for crash with only these blocks:";
for (unsigned i = 0, e = Blocks.size(); i != e; ++i)
std::cout << " " << BBs[i]->getName();
std::cout << ": ";
// Loop over and delete any hack up any blocks that are not listed...
for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
for (Function::iterator BB = I->begin(), E = I->end(); BB != E; ++BB)
if (!Blocks.count(BB) && !isa<ReturnInst>(BB->getTerminator())) {
// Loop over all of the successors of this block, deleting any PHI nodes
// that might include it.
for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
(*SI)->removePredecessor(BB);
// Delete the old terminator instruction...
BB->getInstList().pop_back();
// Add a new return instruction of the appropriate type...
const Type *RetTy = BB->getParent()->getReturnType();
ReturnInst *RI = new ReturnInst(RetTy == Type::VoidTy ? 0 :
Constant::getNullValue(RetTy));
BB->getInstList().push_back(RI);
}
// The CFG Simplifier pass may delete one of the basic blocks we are
// interested in. If it does we need to take the block out of the list. Make
// a "persistent mapping" by turning basic blocks into <function, name> pairs.
// This won't work well if blocks are unnamed, but that is just the risk we
// have to take.
std::vector<std::pair<Function*, std::string> > BlockInfo;
for (std::set<BasicBlock*>::iterator I = Blocks.begin(), E = Blocks.end();
I != E; ++I)
BlockInfo.push_back(std::make_pair((*I)->getParent(), (*I)->getName()));
// Now run the CFG simplify pass on the function...
PassManager Passes;
Passes.add(createCFGSimplificationPass());
Passes.add(createVerifierPass());
Passes.run(*M);
// Try running on the hacked up program...
std::swap(BD.Program, M);
if (BD.runPasses(BD.PassesToRun)) {
delete M; // It crashed, keep the trimmed version...
// Make sure to use basic block pointers that point into the now-current
// module, and that they don't include any deleted blocks.
BBs.clear();
for (unsigned i = 0, e = BlockInfo.size(); i != e; ++i) {
SymbolTable &ST = BlockInfo[i].first->getSymbolTable();
SymbolTable::iterator I = ST.find(Type::LabelTy);
if (I != ST.end() && I->second.count(BlockInfo[i].second))
BBs.push_back(cast<BasicBlock>(I->second[BlockInfo[i].second]));
}
return true;
}
delete BD.Program; // It didn't crash, revert...
BD.Program = M;
return false;
}
/// debugCrash - This method is called when some pass crashes on input. It
/// attempts to prune down the testcase to something reasonable, and figure
/// out exactly which pass is crashing.
///
bool BugDriver::debugCrash() {
bool AnyReduction = false;
std::cout << "\n*** Debugging optimizer crash!\n";
// Reduce the list of passes which causes the optimizer to crash...
unsigned OldSize = PassesToRun.size();
DebugCrashes(*this).reduceList(PassesToRun);
std::cout << "\n*** Found crashing pass"
<< (PassesToRun.size() == 1 ? ": " : "es: ")
<< getPassesString(PassesToRun) << "\n";
EmitProgressBytecode("passinput");
// See if we can get away with nuking all of the global variable initializers
// in the program...
if (Program->gbegin() != Program->gend()) {
Module *M = CloneModule(Program);
bool DeletedInit = false;
for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
if (I->hasInitializer()) {
I->setInitializer(0);
I->setLinkage(GlobalValue::ExternalLinkage);
DeletedInit = true;
}
if (!DeletedInit) {
delete M; // No change made...
} else {
// See if the program still causes a crash...
std::cout << "\nChecking to see if we can delete global inits: ";
std::swap(Program, M);
if (runPasses(PassesToRun)) { // Still crashes?
AnyReduction = true;
delete M;
std::cout << "\n*** Able to remove all global initializers!\n";
} else { // No longer crashes?
delete Program; // Restore program.
Program = M;
std::cout << " - Removing all global inits hides problem!\n";
}
}
}
// Now try to reduce the number of functions in the module to something small.
std::vector<Function*> Functions;
for (Module::iterator I = Program->begin(), E = Program->end(); I != E; ++I)
if (!I->isExternal())
Functions.push_back(I);
if (Functions.size() > 1) {
std::cout << "\n*** Attempting to reduce the number of functions "
"in the testcase\n";
OldSize = Functions.size();
ReduceCrashingFunctions(*this).reduceList(Functions);
if (Functions.size() < OldSize) {
EmitProgressBytecode("reduced-function");
AnyReduction = true;
}
}
// Attempt to delete entire basic blocks at a time to speed up
// convergence... this actually works by setting the terminator of the blocks
// to a return instruction then running simplifycfg, which can potentially
// shrinks the code dramatically quickly
//
std::vector<BasicBlock*> Blocks;
for (Module::iterator I = Program->begin(), E = Program->end(); I != E; ++I)
for (Function::iterator FI = I->begin(), E = I->end(); FI != E; ++FI)
Blocks.push_back(FI);
ReduceCrashingBlocks(*this).reduceList(Blocks);
// FIXME: This should use the list reducer to converge faster by deleting
// larger chunks of instructions at a time!
unsigned Simplification = 4;
do {
--Simplification;
std::cout << "\n*** Attempting to reduce testcase by deleting instruc"
<< "tions: Simplification Level #" << Simplification << "\n";
// Now that we have deleted the functions that are unneccesary for the
// program, try to remove instructions that are not neccesary to cause the
// crash. To do this, we loop through all of the instructions in the
// remaining functions, deleting them (replacing any values produced with
// nulls), and then running ADCE and SimplifyCFG. If the transformed input
// still triggers failure, keep deleting until we cannot trigger failure
// anymore.
//
TryAgain:
// Loop over all of the (non-terminator) instructions remaining in the
// function, attempting to delete them.
for (Module::iterator FI = Program->begin(), E = Program->end();
FI != E; ++FI)
if (!FI->isExternal()) {
for (Function::iterator BI = FI->begin(), E = FI->end(); BI != E; ++BI)
for (BasicBlock::iterator I = BI->begin(), E = --BI->end();
I != E; ++I) {
Module *M = deleteInstructionFromProgram(I, Simplification);
// Make the function the current program...
std::swap(Program, M);
// Find out if the pass still crashes on this pass...
std::cout << "Checking instruction '" << I->getName() << "': ";
if (runPasses(PassesToRun)) {
// Yup, it does, we delete the old module, and continue trying to
// reduce the testcase...
delete M;
AnyReduction = true;
goto TryAgain; // I wish I had a multi-level break here!
}
// This pass didn't crash without this instruction, try the next
// one.
delete Program;
Program = M;
}
}
} while (Simplification);
// Try to clean up the testcase by running funcresolve and globaldce...
std::cout << "\n*** Attempting to perform final cleanups: ";
Module *M = performFinalCleanups();
std::swap(Program, M);
// Find out if the pass still crashes on the cleaned up program...
if (runPasses(PassesToRun)) {
// Yup, it does, keep the reduced version...
delete M;
AnyReduction = true;
} else {
delete Program; // Otherwise, restore the original module...
Program = M;
}
if (AnyReduction)
EmitProgressBytecode("reduced-simplified");
return false;
}
<commit_msg>Added code that ensures that we don't try to reduce an empty vector of basic blocks. This fixes the bugpoint regressions.<commit_after>//===- CrashDebugger.cpp - Debug compilation crashes ----------------------===//
//
// This file defines the bugpoint internals that narrow down compilation crashes
//
//===----------------------------------------------------------------------===//
#include "BugDriver.h"
#include "SystemUtils.h"
#include "ListReducer.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Pass.h"
#include "llvm/Constant.h"
#include "llvm/iTerminators.h"
#include "llvm/Type.h"
#include "llvm/SymbolTable.h"
#include "llvm/Support/CFG.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Bytecode/Writer.h"
#include <fstream>
#include <set>
class DebugCrashes : public ListReducer<const PassInfo*> {
BugDriver &BD;
public:
DebugCrashes(BugDriver &bd) : BD(bd) {}
// doTest - Return true iff running the "removed" passes succeeds, and running
// the "Kept" passes fail when run on the output of the "removed" passes. If
// we return true, we update the current module of bugpoint.
//
virtual TestResult doTest(std::vector<const PassInfo*> &Removed,
std::vector<const PassInfo*> &Kept);
};
DebugCrashes::TestResult
DebugCrashes::doTest(std::vector<const PassInfo*> &Prefix,
std::vector<const PassInfo*> &Suffix) {
std::string PrefixOutput;
Module *OrigProgram = 0;
if (!Prefix.empty()) {
std::cout << "Checking to see if these passes crash: "
<< getPassesString(Prefix) << ": ";
if (BD.runPasses(Prefix, PrefixOutput))
return KeepPrefix;
OrigProgram = BD.Program;
BD.Program = BD.ParseInputFile(PrefixOutput);
if (BD.Program == 0) {
std::cerr << BD.getToolName() << ": Error reading bytecode file '"
<< PrefixOutput << "'!\n";
exit(1);
}
removeFile(PrefixOutput);
}
std::cout << "Checking to see if these passes crash: "
<< getPassesString(Suffix) << ": ";
if (BD.runPasses(Suffix)) {
delete OrigProgram; // The suffix crashes alone...
return KeepSuffix;
}
// Nothing failed, restore state...
if (OrigProgram) {
delete BD.Program;
BD.Program = OrigProgram;
}
return NoFailure;
}
class ReduceCrashingFunctions : public ListReducer<Function*> {
BugDriver &BD;
public:
ReduceCrashingFunctions(BugDriver &bd) : BD(bd) {}
virtual TestResult doTest(std::vector<Function*> &Prefix,
std::vector<Function*> &Kept) {
if (TestFuncs(Kept))
return KeepSuffix;
if (!Prefix.empty() && TestFuncs(Prefix))
return KeepPrefix;
return NoFailure;
}
bool TestFuncs(std::vector<Function*> &Prefix);
};
bool ReduceCrashingFunctions::TestFuncs(std::vector<Function*> &Funcs) {
// Clone the program to try hacking it appart...
Module *M = CloneModule(BD.Program);
// Convert list to set for fast lookup...
std::set<Function*> Functions;
for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
Function *CMF = M->getFunction(Funcs[i]->getName(),
Funcs[i]->getFunctionType());
assert(CMF && "Function not in module?!");
Functions.insert(CMF);
}
std::cout << "Checking for crash with only these functions:";
for (unsigned i = 0, e = Funcs.size(); i != e; ++i)
std::cout << " " << Funcs[i]->getName();
std::cout << ": ";
// Loop over and delete any functions which we aren't supposed to be playing
// with...
for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
if (!I->isExternal() && !Functions.count(I))
DeleteFunctionBody(I);
// Try running the hacked up program...
std::swap(BD.Program, M);
if (BD.runPasses(BD.PassesToRun)) {
delete M; // It crashed, keep the trimmed version...
// Make sure to use function pointers that point into the now-current
// module.
Funcs.assign(Functions.begin(), Functions.end());
return true;
}
delete BD.Program; // It didn't crash, revert...
BD.Program = M;
return false;
}
/// ReduceCrashingBlocks reducer - This works by setting the terminators of all
/// terminators except the specified basic blocks to a 'ret' instruction, then
/// running the simplify-cfg pass. This has the effect of chopping up the CFG
/// really fast which can reduce large functions quickly.
///
class ReduceCrashingBlocks : public ListReducer<BasicBlock*> {
BugDriver &BD;
public:
ReduceCrashingBlocks(BugDriver &bd) : BD(bd) {}
virtual TestResult doTest(std::vector<BasicBlock*> &Prefix,
std::vector<BasicBlock*> &Kept) {
if (!Kept.empty() && TestBlocks(Kept))
return KeepSuffix;
if (!Prefix.empty() && TestBlocks(Prefix))
return KeepPrefix;
return NoFailure;
}
bool TestBlocks(std::vector<BasicBlock*> &Prefix);
};
bool ReduceCrashingBlocks::TestBlocks(std::vector<BasicBlock*> &BBs) {
// Clone the program to try hacking it appart...
Module *M = CloneModule(BD.Program);
// Convert list to set for fast lookup...
std::set<BasicBlock*> Blocks;
for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
// Convert the basic block from the original module to the new module...
Function *F = BBs[i]->getParent();
Function *CMF = M->getFunction(F->getName(), F->getFunctionType());
assert(CMF && "Function not in module?!");
// Get the mapped basic block...
Function::iterator CBI = CMF->begin();
std::advance(CBI, std::distance(F->begin(), Function::iterator(BBs[i])));
Blocks.insert(CBI);
}
std::cout << "Checking for crash with only these blocks:";
for (unsigned i = 0, e = Blocks.size(); i != e; ++i)
std::cout << " " << BBs[i]->getName();
std::cout << ": ";
// Loop over and delete any hack up any blocks that are not listed...
for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
for (Function::iterator BB = I->begin(), E = I->end(); BB != E; ++BB)
if (!Blocks.count(BB) && !isa<ReturnInst>(BB->getTerminator())) {
// Loop over all of the successors of this block, deleting any PHI nodes
// that might include it.
for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
(*SI)->removePredecessor(BB);
// Delete the old terminator instruction...
BB->getInstList().pop_back();
// Add a new return instruction of the appropriate type...
const Type *RetTy = BB->getParent()->getReturnType();
ReturnInst *RI = new ReturnInst(RetTy == Type::VoidTy ? 0 :
Constant::getNullValue(RetTy));
BB->getInstList().push_back(RI);
}
// The CFG Simplifier pass may delete one of the basic blocks we are
// interested in. If it does we need to take the block out of the list. Make
// a "persistent mapping" by turning basic blocks into <function, name> pairs.
// This won't work well if blocks are unnamed, but that is just the risk we
// have to take.
std::vector<std::pair<Function*, std::string> > BlockInfo;
for (std::set<BasicBlock*>::iterator I = Blocks.begin(), E = Blocks.end();
I != E; ++I)
BlockInfo.push_back(std::make_pair((*I)->getParent(), (*I)->getName()));
// Now run the CFG simplify pass on the function...
PassManager Passes;
Passes.add(createCFGSimplificationPass());
Passes.add(createVerifierPass());
Passes.run(*M);
// Try running on the hacked up program...
std::swap(BD.Program, M);
if (BD.runPasses(BD.PassesToRun)) {
delete M; // It crashed, keep the trimmed version...
// Make sure to use basic block pointers that point into the now-current
// module, and that they don't include any deleted blocks.
BBs.clear();
for (unsigned i = 0, e = BlockInfo.size(); i != e; ++i) {
SymbolTable &ST = BlockInfo[i].first->getSymbolTable();
SymbolTable::iterator I = ST.find(Type::LabelTy);
if (I != ST.end() && I->second.count(BlockInfo[i].second))
BBs.push_back(cast<BasicBlock>(I->second[BlockInfo[i].second]));
}
return true;
}
delete BD.Program; // It didn't crash, revert...
BD.Program = M;
return false;
}
/// debugCrash - This method is called when some pass crashes on input. It
/// attempts to prune down the testcase to something reasonable, and figure
/// out exactly which pass is crashing.
///
bool BugDriver::debugCrash() {
bool AnyReduction = false;
std::cout << "\n*** Debugging optimizer crash!\n";
// Reduce the list of passes which causes the optimizer to crash...
unsigned OldSize = PassesToRun.size();
DebugCrashes(*this).reduceList(PassesToRun);
std::cout << "\n*** Found crashing pass"
<< (PassesToRun.size() == 1 ? ": " : "es: ")
<< getPassesString(PassesToRun) << "\n";
EmitProgressBytecode("passinput");
// See if we can get away with nuking all of the global variable initializers
// in the program...
if (Program->gbegin() != Program->gend()) {
Module *M = CloneModule(Program);
bool DeletedInit = false;
for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
if (I->hasInitializer()) {
I->setInitializer(0);
I->setLinkage(GlobalValue::ExternalLinkage);
DeletedInit = true;
}
if (!DeletedInit) {
delete M; // No change made...
} else {
// See if the program still causes a crash...
std::cout << "\nChecking to see if we can delete global inits: ";
std::swap(Program, M);
if (runPasses(PassesToRun)) { // Still crashes?
AnyReduction = true;
delete M;
std::cout << "\n*** Able to remove all global initializers!\n";
} else { // No longer crashes?
delete Program; // Restore program.
Program = M;
std::cout << " - Removing all global inits hides problem!\n";
}
}
}
// Now try to reduce the number of functions in the module to something small.
std::vector<Function*> Functions;
for (Module::iterator I = Program->begin(), E = Program->end(); I != E; ++I)
if (!I->isExternal())
Functions.push_back(I);
if (Functions.size() > 1) {
std::cout << "\n*** Attempting to reduce the number of functions "
"in the testcase\n";
OldSize = Functions.size();
ReduceCrashingFunctions(*this).reduceList(Functions);
if (Functions.size() < OldSize) {
EmitProgressBytecode("reduced-function");
AnyReduction = true;
}
}
// Attempt to delete entire basic blocks at a time to speed up
// convergence... this actually works by setting the terminator of the blocks
// to a return instruction then running simplifycfg, which can potentially
// shrinks the code dramatically quickly
//
std::vector<BasicBlock*> Blocks;
for (Module::iterator I = Program->begin(), E = Program->end(); I != E; ++I)
for (Function::iterator FI = I->begin(), E = I->end(); FI != E; ++FI)
Blocks.push_back(FI);
ReduceCrashingBlocks(*this).reduceList(Blocks);
// FIXME: This should use the list reducer to converge faster by deleting
// larger chunks of instructions at a time!
unsigned Simplification = 4;
do {
--Simplification;
std::cout << "\n*** Attempting to reduce testcase by deleting instruc"
<< "tions: Simplification Level #" << Simplification << "\n";
// Now that we have deleted the functions that are unneccesary for the
// program, try to remove instructions that are not neccesary to cause the
// crash. To do this, we loop through all of the instructions in the
// remaining functions, deleting them (replacing any values produced with
// nulls), and then running ADCE and SimplifyCFG. If the transformed input
// still triggers failure, keep deleting until we cannot trigger failure
// anymore.
//
TryAgain:
// Loop over all of the (non-terminator) instructions remaining in the
// function, attempting to delete them.
for (Module::iterator FI = Program->begin(), E = Program->end();
FI != E; ++FI)
if (!FI->isExternal()) {
for (Function::iterator BI = FI->begin(), E = FI->end(); BI != E; ++BI)
for (BasicBlock::iterator I = BI->begin(), E = --BI->end();
I != E; ++I) {
Module *M = deleteInstructionFromProgram(I, Simplification);
// Make the function the current program...
std::swap(Program, M);
// Find out if the pass still crashes on this pass...
std::cout << "Checking instruction '" << I->getName() << "': ";
if (runPasses(PassesToRun)) {
// Yup, it does, we delete the old module, and continue trying to
// reduce the testcase...
delete M;
AnyReduction = true;
goto TryAgain; // I wish I had a multi-level break here!
}
// This pass didn't crash without this instruction, try the next
// one.
delete Program;
Program = M;
}
}
} while (Simplification);
// Try to clean up the testcase by running funcresolve and globaldce...
std::cout << "\n*** Attempting to perform final cleanups: ";
Module *M = performFinalCleanups();
std::swap(Program, M);
// Find out if the pass still crashes on the cleaned up program...
if (runPasses(PassesToRun)) {
// Yup, it does, keep the reduced version...
delete M;
AnyReduction = true;
} else {
delete Program; // Otherwise, restore the original module...
Program = M;
}
if (AnyReduction)
EmitProgressBytecode("reduced-simplified");
return false;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2010-2011 by Patrick Schaefer, Zuse Institute Berlin
* 2011 by Michael Berlin, Zuse Institute Berlin
*
* Licensed under the BSD License, see LICENSE file for details.
*
*/
#include "libxtreemfs/user_mapping_unix.h"
#ifndef WIN32
#include <grp.h>
#include <pwd.h>
#include <stdint.h>
#include <sys/types.h>
#include <boost/lexical_cast.hpp>
#include <fstream>
#include <iostream>
#include "util/logging.h"
using namespace std;
using namespace xtreemfs::util;
namespace xtreemfs {
std::string UserMappingUnix::UIDToUsername(uid_t uid) {
if (uid == static_cast<uid_t>(-1)) {
return string("-1");
}
string username;
// Retrieve username.
size_t bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
if (bufsize == -1) {
// Max size unknown, use safe value.
bufsize = 16384;
}
char* buf = new char[bufsize];
struct passwd pwd;
struct passwd* result = NULL;
int s = getpwuid_r(uid, &pwd, buf, bufsize, &result);
if (result == NULL) {
if (s == 0) {
if (Logging::log->loggingActive(LEVEL_INFO)) {
Logging::log->getLog(LEVEL_INFO)
<< "no mapping for uid " << uid << std::endl;
}
} else {
Logging::log->getLog(LEVEL_ERROR)
<< "failed to retrieve passwd entry for uid: " << uid << endl;
}
// Return uid as name if no mapping found.
try {
username = boost::lexical_cast<string>(uid);
} catch(const boost::bad_lexical_cast&) {
Logging::log->getLog(LEVEL_ERROR)
<< "failed to use uid for usermapping: " << uid << endl;
username = "nobody";
}
} else {
username = string(pwd.pw_name);
}
delete[] buf;
return username;
}
uid_t UserMappingUnix::UsernameToUID(const std::string& username) {
uid_t uid = 65534; // nobody.
// Retrieve uid.
size_t bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
if (bufsize == -1) {
// Max size unknown, use safe value.
bufsize = 16384;
}
char* buf = new char[bufsize];
struct passwd pwd;
struct passwd* result = NULL;
int s = getpwnam_r(username.c_str(), &pwd, buf, bufsize, &result);
if (result == NULL) {
if (s == 0) {
if (Logging::log->loggingActive(LEVEL_INFO)) {
Logging::log->getLog(LEVEL_INFO)
<< "no mapping for username: " << username << endl;
}
} else {
Logging::log->getLog(LEVEL_ERROR)
<< "failed to retrieve passwd entry for username: "
<< username<< endl;
}
// Map reserved value -1 to nobody.
if (username == "-1") {
uid = 65534; // nobody.
} else {
// Try to convert the username into an integer. (Needed if an integer was
// stored in the first place because there was no username found for the
// uid at the creation of the file.)
try {
uid = boost::lexical_cast<uid_t>(username);
} catch(const boost::bad_lexical_cast&) {
uid = 65534; // nobody.
}
// boost::lexical_cast silently converts negative values into unsigned
// integers. Check if username actually contains a negative value.
if (uid != 65534) {
try {
// It's needed to use a 64 bit signed integer to detect a -(2^31)-1
// as a negative value and not as an overflowed unsigned integer of
// value 2^32-1.
int64_t uid_signed = boost::lexical_cast<int64_t>(username);
if (uid_signed < 0) {
uid = 65534; // nobody.
}
} catch(const boost::bad_lexical_cast&) {
// Leave uid as it is if lexical_cast failed.
}
}
}
} else {
uid = pwd.pw_uid;
}
delete[] buf;
return uid;
}
std::string UserMappingUnix::GIDToGroupname(gid_t gid) {
if (gid == static_cast<gid_t>(-1)) {
return string("-1");
}
string groupname;
// Retrieve username.
size_t bufsize = sysconf(_SC_GETGR_R_SIZE_MAX);
if (bufsize == -1) {
// Max size unknown, use safe value.
bufsize = 16384;
}
char* buf = new char[bufsize];
struct group grp;
struct group* result = NULL;
int s = getgrgid_r(gid, &grp, buf, bufsize, &result);
if (result == NULL) {
if (s == 0) {
if (Logging::log->loggingActive(LEVEL_INFO)) {
Logging::log->getLog(LEVEL_INFO)
<< "no mapping for gid " << gid << endl;
}
} else {
Logging::log->getLog(LEVEL_ERROR)
<< "failed to retrieve group entry for gid: " << gid << endl;
}
// Return uid as name if no mapping found.
try {
groupname = boost::lexical_cast<string>(gid);
} catch(const boost::bad_lexical_cast&) {
Logging::log->getLog(LEVEL_ERROR)
<< "failed to use gid for usermapping: " << gid << endl;
groupname = "nobody";
}
} else {
groupname = string(grp.gr_name);
}
delete[] buf;
return groupname;
}
gid_t UserMappingUnix::GroupnameToGID(const std::string& groupname) {
gid_t gid = 65534; // nobody.
// Retrieve gid.
size_t bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
if (bufsize == -1) {
// Max size unknown, use safe value.
bufsize = 16384;
}
char* buf = new char[bufsize];
struct group grp;
struct group* result = NULL;
int s = getgrnam_r(groupname.c_str(), &grp, buf, bufsize, &result);
if (result == NULL) {
if (s == 0) {
if (Logging::log->loggingActive(LEVEL_INFO)) {
Logging::log->getLog(LEVEL_INFO)
<< "no mapping for groupname: " << groupname << endl;
}
} else {
Logging::log->getLog(LEVEL_ERROR)
<< "failed to retrieve passwd entry for groupname: "
<< groupname<< endl;
}
// Map reserved value -1 to nobody.
if (groupname == "-1") {
gid = 65534; // nobody.
} else {
// Try to convert the groupname into an integer. (Needed if an integer was
// stored in the first place because there was no groupname found for the
// gid at the creation of the file.)
try {
gid = boost::lexical_cast<gid_t>(groupname);
} catch(const boost::bad_lexical_cast&) {
gid = 65534; // nobody.
}
// boost::lexical_cast silently converts negative values into unsigned
// integers. Check if groupname actually contains a negative value.
if (gid != 65534) {
try {
// It's needed to use a 64 bit signed integer to detect a -(2^31)-1
// as a negative value and not as an overflowed unsigned integer of
// value 2^32-1.
int64_t gid_signed = boost::lexical_cast<int64_t>(groupname);
if (gid_signed < 0) {
gid = 65534; // nobody.
}
} catch(const boost::bad_lexical_cast&) {
// Leave gid as it is if lexical_cast failed.
}
}
}
} else {
gid = grp.gr_gid;
}
delete[] buf;
return gid;
}
void UserMappingUnix::GetGroupnames(uid_t uid,
gid_t gid,
pid_t pid,
std::list<std::string>* groupnames) {
groupnames->push_back(GIDToGroupname(gid));
#ifdef __linux__
// Parse /proc/<pid>/task/<pid>/status like fuse_req_getgroups.
string filename = "/proc/" + boost::lexical_cast<string>(pid) + "/task/"
+ boost::lexical_cast<string>(pid) + "/status";
ifstream in(filename.c_str());
string line;
// C++ getline() does check for failbit or badbit of the istream. If of these
// bits are set, it does break from the while loop, for instance if the file
// does not exist. In this case no additional groups are added.
while (getline(in, line)) {
if (line.length() >= 8 && line.substr(0, 8) == "Groups:\t") {
// "Groups: " entry found, read all groups
std::stringstream stringstream(line.substr(8, line.length() - 8 - 1));
std::string group_id;
while (getline(stringstream, group_id, ' ')) {
gid_t supplementary_gid = boost::lexical_cast<gid_t>(group_id);
if (supplementary_gid != gid) {
groupnames->push_back(GIDToGroupname(supplementary_gid));
}
}
break;
}
}
#endif
}
} // namespace xtreemfs
#endif // !WIN32
<commit_msg>client: Deleted unused file which is no longer used since the refactoring of the user mapping classes.<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (c) 2006 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders 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.
*
* Authors: Gabe Black
*/
#ifndef __ARCH_SPARC_INTERRUPT_HH__
#define __ARCH_SPARC_INTERRUPT_HH__
#include "arch/sparc/faults.hh"
#include "cpu/thread_context.hh"
namespace SparcISA
{
enum interrupts_t {
trap_level_zero,
hstick_match,
interrupt_vector,
cpu_mondo,
dev_mondo,
resumable_error,
soft_interrupt,
num_interrupt_types
};
class Interrupts
{
private:
bool interrupts[num_interrupt_types];
int numPosted;
public:
Interrupts()
{
for (int i = 0; i < num_interrupt_types; ++i) {
interrupts[i] = false;
}
numPosted = 0;
}
void post(int int_type)
{
if (int_type < 0 || int_type >= num_interrupt_types)
panic("posting unknown interrupt!\n");
interrupts[int_type] = true;
++numPosted;
}
void post(int int_num, int index)
{
}
void clear(int int_num, int index)
{
}
void clear_all()
{
}
bool check_interrupts(ThreadContext * tc) const
{
if (numPosted)
return true;
else
return false;
}
Fault getInterrupt(ThreadContext * tc)
{
int hpstate = tc->readMiscReg(MISCREG_HPSTATE);
int pstate = tc->readMiscReg(MISCREG_PSTATE);
bool ie = pstate & PSTATE::ie;
// THESE ARE IN ORDER OF PRIORITY
// since there are early returns, and the highest
// priority interrupts should get serviced,
// it is v. important that new interrupts are inserted
// in the right order of processing
if (hpstate & HPSTATE::hpriv) {
if (ie) {
if (interrupts[hstick_match]) {
interrupts[hstick_match] = false;
--numPosted;
return new HstickMatch;
}
if (interrupts[interrupt_vector]) {
interrupts[interrupt_vector] = false;
--numPosted;
//HAVEN'T IMPLed THIS YET
return NoFault;
}
}
} else {
if (interrupts[trap_level_zero]) {
//HAVEN'T IMPLed YET
if ((pstate & HPSTATE::tlz) && (tc->readMiscReg(MISCREG_TL) == 0)) {
interrupts[trap_level_zero] = false;
--numPosted;
return NoFault;
}
}
if (interrupts[hstick_match]) {
interrupts[hstick_match] = false;
--numPosted;
return new HstickMatch;
}
if (ie) {
if (interrupts[cpu_mondo]) {
interrupts[cpu_mondo] = false;
--numPosted;
return new CpuMondo;
}
if (interrupts[dev_mondo]) {
interrupts[dev_mondo] = false;
--numPosted;
return new DevMondo;
}
if (interrupts[soft_interrupt]) {
int il = InterruptLevel(tc->readMiscReg(MISCREG_SOFTINT));
// it seems that interrupt vectors are right in
// the middle of interrupt levels with regard to
// priority, so have to check
if ((il < 6) &&
interrupts[interrupt_vector]) {
// may require more details here since there
// may be lots of interrupts embedded in an
// platform interrupt vector
interrupts[interrupt_vector] = false;
--numPosted;
//HAVEN'T IMPLed YET
return NoFault;
} else {
if (il > tc->readMiscReg(MISCREG_PIL)) {
uint64_t si = tc->readMiscReg(MISCREG_SOFTINT);
uint64_t more = si & ~(1 << (il + 1));
if (!InterruptLevel(more)) {
interrupts[soft_interrupt] = false;
--numPosted;
}
return new InterruptLevelN(il);
}
}
}
if (interrupts[resumable_error]) {
interrupts[resumable_error] = false;
--numPosted;
return new ResumableError;
}
}
}
return NoFault;
// conditioning the softint interrups
if (tc->readMiscReg(MISCREG_HPSTATE) & HPSTATE::hpriv) {
// if running in privileged mode, then pend the interrupt
return NoFault;
} else {
int int_level = InterruptLevel(tc->readMiscReg(MISCREG_SOFTINT));
if ((int_level <= tc->readMiscReg(MISCREG_PIL)) ||
!(tc->readMiscReg(MISCREG_PSTATE) & PSTATE::ie)) {
// if PIL or no interrupt enabled, then pend the interrupt
return NoFault;
} else {
return new InterruptLevelN(int_level);
}
}
}
void updateIntrInfo(ThreadContext * tc)
{
}
void serialize(std::ostream &os)
{
}
void unserialize(Checkpoint *cp, const std::string §ion)
{
}
};
}
#endif // __ARCH_SPARC_INTERRUPT_HH__
<commit_msg>Add Trap Level Zero to interrupts, remove some unreachable code that I forgot to remove last time.<commit_after>/*
* Copyright (c) 2006 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders 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 __ARCH_SPARC_INTERRUPT_HH__
#define __ARCH_SPARC_INTERRUPT_HH__
#include "arch/sparc/faults.hh"
#include "cpu/thread_context.hh"
namespace SparcISA
{
enum interrupts_t {
trap_level_zero,
hstick_match,
interrupt_vector,
cpu_mondo,
dev_mondo,
resumable_error,
soft_interrupt,
num_interrupt_types
};
class Interrupts
{
private:
bool interrupts[num_interrupt_types];
int numPosted;
public:
Interrupts()
{
for (int i = 0; i < num_interrupt_types; ++i) {
interrupts[i] = false;
}
numPosted = 0;
}
void post(int int_type)
{
if (int_type < 0 || int_type >= num_interrupt_types)
panic("posting unknown interrupt!\n");
interrupts[int_type] = true;
++numPosted;
}
void post(int int_num, int index)
{
}
void clear(int int_num, int index)
{
}
void clear_all()
{
}
bool check_interrupts(ThreadContext * tc) const
{
if (numPosted)
return true;
else
return false;
}
Fault getInterrupt(ThreadContext * tc)
{
int hpstate = tc->readMiscReg(MISCREG_HPSTATE);
int pstate = tc->readMiscReg(MISCREG_PSTATE);
bool ie = pstate & PSTATE::ie;
// THESE ARE IN ORDER OF PRIORITY
// since there are early returns, and the highest
// priority interrupts should get serviced,
// it is v. important that new interrupts are inserted
// in the right order of processing
if (hpstate & HPSTATE::hpriv) {
if (ie) {
if (interrupts[hstick_match]) {
interrupts[hstick_match] = false;
--numPosted;
return new HstickMatch;
}
if (interrupts[interrupt_vector]) {
interrupts[interrupt_vector] = false;
--numPosted;
//HAVEN'T IMPLed THIS YET
return NoFault;
}
}
} else {
if (interrupts[trap_level_zero]) {
if ((pstate & HPSTATE::tlz) && (tc->readMiscReg(MISCREG_TL) == 0)) {
interrupts[trap_level_zero] = false;
--numPosted;
return new TrapLevelZero;
}
}
if (interrupts[hstick_match]) {
interrupts[hstick_match] = false;
--numPosted;
return new HstickMatch;
}
if (ie) {
if (interrupts[cpu_mondo]) {
interrupts[cpu_mondo] = false;
--numPosted;
return new CpuMondo;
}
if (interrupts[dev_mondo]) {
interrupts[dev_mondo] = false;
--numPosted;
return new DevMondo;
}
if (interrupts[soft_interrupt]) {
int il = InterruptLevel(tc->readMiscReg(MISCREG_SOFTINT));
// it seems that interrupt vectors are right in
// the middle of interrupt levels with regard to
// priority, so have to check
if ((il < 6) &&
interrupts[interrupt_vector]) {
// may require more details here since there
// may be lots of interrupts embedded in an
// platform interrupt vector
interrupts[interrupt_vector] = false;
--numPosted;
//HAVEN'T IMPLed YET
return NoFault;
} else {
if (il > tc->readMiscReg(MISCREG_PIL)) {
uint64_t si = tc->readMiscReg(MISCREG_SOFTINT);
uint64_t more = si & ~(1 << (il + 1));
if (!InterruptLevel(more)) {
interrupts[soft_interrupt] = false;
--numPosted;
}
return new InterruptLevelN(il);
}
}
}
if (interrupts[resumable_error]) {
interrupts[resumable_error] = false;
--numPosted;
return new ResumableError;
}
}
}
return NoFault;
}
void updateIntrInfo(ThreadContext * tc)
{
}
void serialize(std::ostream &os)
{
}
void unserialize(Checkpoint *cp, const std::string §ion)
{
}
};
}
#endif // __ARCH_SPARC_INTERRUPT_HH__
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2007 The Hewlett-Packard Development Company
* All rights reserved.
*
* Redistribution and use of this software in source and binary forms,
* with or without modification, are permitted provided that the
* following conditions are met:
*
* The software must be used only for Non-Commercial Use which means any
* use which is NOT directed to receiving any direct monetary
* compensation for, or commercial advantage from such use. Illustrative
* examples of non-commercial use are academic research, personal study,
* teaching, education and corporate research & development.
* Illustrative examples of commercial use are distributing products for
* commercial advantage and providing services using the software for
* commercial advantage.
*
* If you wish to use this software or functionality therein that may be
* covered by patents for commercial use, please contact:
* Director of Intellectual Property Licensing
* Office of Strategy and Technology
* Hewlett-Packard Company
* 1501 Page Mill Road
* Palo Alto, California 94304
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer. Redistributions
* in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution. Neither the name of
* the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission. No right of
* sublicense is granted herewith. Derivatives of the software and
* output created using the software may be prepared, but only for
* Non-Commercial Uses. Derivatives of the software may be shared with
* others provided: (i) the others agree to abide by the list of
* conditions herein which includes the Non-Commercial Use restrictions;
* and (ii) such Derivatives of the software include the above copyright
* notice to acknowledge the contribution from this software where
* applicable, this list of conditions and the disclaimer below.
*
* 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.
*
* Authors: Gabe Black
*/
#include "arch/x86/linux/system.hh"
#include "arch/vtophys.hh"
#include "base/trace.hh"
#include "mem/physical.hh"
#include "params/LinuxX86System.hh"
using namespace LittleEndianGuest;
using namespace X86ISA;
LinuxX86System::LinuxX86System(Params *p)
: X86System(p), commandLine(p->command_line)
{
}
LinuxX86System::~LinuxX86System()
{
}
void
LinuxX86System::startup()
{
X86System::startup();
//Build the real mode data structure.
}
LinuxX86System *
LinuxX86SystemParams::create()
{
return new LinuxX86System(this);
}
<commit_msg>X86: Start setting up the real mode data structure.<commit_after>/*
* Copyright (c) 2007 The Hewlett-Packard Development Company
* All rights reserved.
*
* Redistribution and use of this software in source and binary forms,
* with or without modification, are permitted provided that the
* following conditions are met:
*
* The software must be used only for Non-Commercial Use which means any
* use which is NOT directed to receiving any direct monetary
* compensation for, or commercial advantage from such use. Illustrative
* examples of non-commercial use are academic research, personal study,
* teaching, education and corporate research & development.
* Illustrative examples of commercial use are distributing products for
* commercial advantage and providing services using the software for
* commercial advantage.
*
* If you wish to use this software or functionality therein that may be
* covered by patents for commercial use, please contact:
* Director of Intellectual Property Licensing
* Office of Strategy and Technology
* Hewlett-Packard Company
* 1501 Page Mill Road
* Palo Alto, California 94304
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer. Redistributions
* in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution. Neither the name of
* the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission. No right of
* sublicense is granted herewith. Derivatives of the software and
* output created using the software may be prepared, but only for
* Non-Commercial Uses. Derivatives of the software may be shared with
* others provided: (i) the others agree to abide by the list of
* conditions herein which includes the Non-Commercial Use restrictions;
* and (ii) such Derivatives of the software include the above copyright
* notice to acknowledge the contribution from this software where
* applicable, this list of conditions and the disclaimer below.
*
* 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.
*
* Authors: Gabe Black
*/
#include "arch/x86/intregs.hh"
#include "arch/x86/linux/system.hh"
#include "arch/vtophys.hh"
#include "base/trace.hh"
#include "cpu/thread_context.hh"
#include "mem/physical.hh"
#include "params/LinuxX86System.hh"
using namespace LittleEndianGuest;
using namespace X86ISA;
LinuxX86System::LinuxX86System(Params *p)
: X86System(p), commandLine(p->command_line)
{
}
LinuxX86System::~LinuxX86System()
{
}
void
LinuxX86System::startup()
{
X86System::startup();
// The location of the real mode data structure.
const Addr realModeData = 0x90200;
// A port to write to memory.
FunctionalPort * physPort = threadContexts[0]->getPhysPort();
/*
* Deal with the command line stuff.
*/
// A buffer to store the command line.
const Addr commandLineBuff = 0x90000;
// A pointer to the commandLineBuff stored in the real mode data.
const Addr commandLinePointer = realModeData + 0x228;
if (commandLine.length() + 1 > realModeData - commandLineBuff)
panic("Command line \"%s\" is longer than %d characters.\n",
commandLine, realModeData - commandLineBuff - 1);
physPort->writeBlob(commandLineBuff,
(uint8_t *)commandLine.c_str(), commandLine.length() + 1);
// Generate a pointer of the right size and endianness to put into
// commandLinePointer.
uint32_t guestCommandLineBuff =
X86ISA::htog((uint32_t)commandLineBuff);
physPort->writeBlob(commandLinePointer,
(uint8_t *)&guestCommandLineBuff, sizeof(guestCommandLineBuff));
/*
* Screen Info.
*/
// We'll skip on this for now because it's only needed for framebuffers,
// something we don't support at the moment.
/*
* EDID info
*/
// Skipping for now.
/*
* Saved video mode
*/
// Skipping for now.
/*
* Loader type.
*/
// Skipping for now.
/*
* E820 memory map
*/
// A pointer to the number of E820 entries there are.
const Addr e820MapNrPointer = realModeData + 0x1e8;
// A pointer to the buffer for E820 entries.
const Addr e820MapPointer = realModeData + 0x2d0;
struct e820Entry
{
Addr addr;
Addr size;
uint32_t type;
};
// The size is computed this way to ensure no padding sneaks in.
int e820EntrySize =
sizeof(e820Entry().addr) +
sizeof(e820Entry().size) +
sizeof(e820Entry().type);
// I'm not sure what these should actually be. On a real machine they
// would be generated by the BIOS, and they need to reflect the regions
// which are actually available/reserved. These values are copied from
// my development machine.
e820Entry e820Map[] = {
{ULL(0x0), ULL(0x9d400), 1},
{ULL(0x9d400), ULL(0xa0000) - ULL(0x9d400), 2},
{ULL(0xe8000), ULL(0x100000) - ULL(0xe8000), 2},
{ULL(0x100000), ULL(0xcfff9300) - ULL(0x100000), 1},
{ULL(0xcfff9300), ULL(0xd0000000) - ULL(0xcfff9300), 2},
{ULL(0xfec00000), ULL(0x100000000) - ULL(0xfec00000), 2}
};
uint8_t e820Nr = sizeof(e820Map) / sizeof(e820Entry);
// Make sure the number of entries isn't bigger than what the kernel
// would be capable of providing.
assert(e820Nr <= 128);
uint8_t guestE820Nr = X86ISA::htog(e820Nr);
physPort->writeBlob(e820MapNrPointer,
(uint8_t *)&guestE820Nr, sizeof(guestE820Nr));
for (int i = 0; i < e820Nr; i++) {
e820Entry guestE820Entry;
guestE820Entry.addr = X86ISA::htog(e820Map[i].addr);
guestE820Entry.size = X86ISA::htog(e820Map[i].size);
guestE820Entry.type = X86ISA::htog(e820Map[i].type);
physPort->writeBlob(e820MapPointer + e820EntrySize * i,
(uint8_t *)&guestE820Entry.addr,
sizeof(guestE820Entry.addr));
physPort->writeBlob(
e820MapPointer + e820EntrySize * i +
sizeof(guestE820Entry.addr),
(uint8_t *)&guestE820Entry.size,
sizeof(guestE820Entry.size));
physPort->writeBlob(
e820MapPointer + e820EntrySize * i +
sizeof(guestE820Entry.addr) +
sizeof(guestE820Entry.size),
(uint8_t *)&guestE820Entry.type,
sizeof(guestE820Entry.type));
}
/*
* Pass the location of the real mode data structure to the kernel
* using register %esi. We'll use %rsi which should be equivalent.
*/
threadContexts[0]->setIntReg(INTREG_RSI, realModeData);
}
LinuxX86System *
LinuxX86SystemParams::create()
{
return new LinuxX86System(this);
}
<|endoftext|> |
<commit_before>// Copyright 2017 Adam Smith
//
// 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 <cctype>
#include <sstream>
#include "as/serial_value/json.hpp"
#define ASMITH_SERIAL_PTR "as::serial_value::pointer_t="
void write_value(std::ostream& aStream, const as::serial_value& aValue) {
switch (aValue.get_type()) {
case as::serial_value::NULL_T:
aStream << "null";
break;
case as::serial_value::CHAR_T:
aStream << '"' << aValue.get_char() << "'";
break;
case as::serial_value::BOOL_T:
aStream << aValue.get_bool() ? "true" : "false";
break;
case as::serial_value::UNSIGNED_T:
aStream << aValue.get_unsigned();
break;
case as::serial_value::SIGNED_T:
aStream << aValue.get_signed();
break;
case as::serial_value::FLOAT_T:
aStream << aValue.get_float();
break;
case as::serial_value::POINTER_T:
aStream << '"' << ASMITH_SERIAL_PTR << aValue.get_pointer() << '"';
break;
case as::serial_value::STRING_T:
aStream << '"' << aValue.get_string() << '"';
break;
case as::serial_value::ARRAY_T:
{
aStream << '[';
const as::serial_value::array_t& tmp = aValue.get_array();
const size_t s = tmp.size();
for(size_t i = 0; i < s; ++i) {
write_value(aStream, tmp[i]);
if(i + 1 != s) aStream << ',';
}
aStream << ']';
}
break;
case as::serial_value::OBJECT_T:
{
aStream << '{';
const as::serial_value::object_t& tmp = aValue.get_object();
const auto end = tmp.end();
for(auto i = tmp.begin(); i != end; ++i) {
aStream << '"' << i->first << '"' << ':';
write_value(aStream, i->second);
auto j = i;
++j;
if(j != end) aStream << ',';
}
aStream << '}';
}
break;
}
}
void ignore_whitespace(std::istream& aStream) {
char c = aStream.peek();
while(std::isspace(c)) {
aStream >> c;
c = aStream.peek();
}
}
as::serial_value read_unknown(std::istream&);
as::serial_value read_null(std::istream& aStream) {
const auto pos = aStream.tellg();
char tmp[4];
aStream.read(tmp, 4);
if(memcmp(tmp, "null", 4) != 0) {
aStream.seekg(pos);
throw std::runtime_error("as::deserialise_json : Expected 'null'");
}
return as::serial_value();
}
as::serial_value read_bool(std::istream& aStream) {
const auto pos = aStream.tellg();
char tmp[4];
aStream.read(tmp, 4);
const bool t = memcmp(tmp, "true", 4) == 0;
const bool f = memcmp(tmp, "fals", 4) == 0;
if(t) {
return as::serial_value(true);
}else if(f) {
aStream >> tmp[0];
if(tmp[0] == 'e') return as::serial_value(false);
}
aStream.seekg(pos);
throw std::runtime_error("as::deserialise_json : Expected 'true' or 'false'");
}
as::serial_value read_number(std::istream& aStream) {
as::serial_value::float_t tmp;
aStream >> tmp;
return as::serial_value(tmp);
}
as::serial_value read_string(std::istream& aStream) {
auto pos = aStream.tellg();
char c;
aStream >> c;
if(c != '"') {
aStream.seekg(pos);
throw std::runtime_error("as::deserialise_json : Expected string to begin with '\"'");
}
as::serial_value tmp;
as::serial_value::string_t& str = tmp.set_string();
aStream >> c;
while(c != '"') {
if(aStream.eof()) {
aStream.seekg(pos);
throw std::runtime_error("as::deserialise_json : Expected string to end with'\"'");
}
str += c;
aStream >> c;
}
// The string is a char
if(str.size() == 1) return as::serial_value(str[0]);
// If the string is a pointer
if(str.find_first_of(ASMITH_SERIAL_PTR) == 0) {
std::stringstream ss;
ss << str.substr(strlen(ASMITH_SERIAL_PTR));
as::serial_value::pointer_t ptr;
ss >> ptr;
return as::serial_value(ptr);
}
return tmp;
}
as::serial_value read_array(std::istream& aStream) {
auto pos = aStream.tellg();
char c;
aStream >> c;
if (c != '[') {
aStream.seekg(pos);
throw std::runtime_error("as::deserialise_json : Expected array to begin with '['");
}
as::serial_value tmp;
as::serial_value::array_t& values = tmp.set_array();
c = aStream.peek();
while(c != ']') {
ignore_whitespace(aStream);
c = aStream.peek();
if(c == ',') aStream >> c;
try {
values.push_back(read_unknown(aStream));
}catch (std::exception& e) {
aStream.seekg(pos);
throw e;
}
if(aStream.eof()) {
aStream.seekg(pos);
throw std::runtime_error("as::deserialise_json : Expected array to end with ']'");
}
c = aStream.peek();
}
aStream >> c;
return tmp;
}
as::serial_value read_object(std::istream& aStream) {
auto pos = aStream.tellg();
char c;
aStream >> c;
if (c != '{') {
aStream.seekg(pos);
throw std::runtime_error("as::deserialise_json : Expected object to begin with '{'");
}
as::serial_value tmp;
as::serial_value::object_t& values = tmp.set_object();
c = aStream.peek();
while(c != '}') {
ignore_whitespace(aStream);
c = aStream.peek();
if(c == ',') aStream >> c;
try {
as::serial_value::string_t name = read_string(aStream).get_string();
ignore_whitespace(aStream);
aStream >> c;
if(c != ':') throw std::runtime_error("as::deserialise_json : Expected object members to be seperated with ':'");
values.emplace(name, read_unknown(aStream));
}catch (std::exception& e) {
aStream.seekg(pos);
throw e;
}
if(aStream.eof()) {
aStream.seekg(pos);
throw std::runtime_error("as::deserialise_json : Expected object to end with '}'");
}
c = aStream.peek();
}
aStream >> c;
return tmp;
}
as::serial_value read_unknown(std::istream& aStream) {
ignore_whitespace(aStream);
switch(aStream.peek())
{
case 'n':
return read_null(aStream);
case 't':
case 'f':
return read_bool(aStream);
case '-':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return read_number(aStream);
case '"':
return read_string(aStream);
case '[':
return read_array(aStream);
case '{':
return read_object(aStream);
default:
throw std::runtime_error("as::deserialise_json : Could not determine type of JSON value");
break;
}
}
namespace as {
void serialise_json(std::ostream& aStream, const serial_value& aValue) {
write_value(aStream, aValue);
}
serial_value deserialise_json(std::istream& aStream) {
return read_unknown(aStream);
}
}<commit_msg>Fixed bug in read_string<commit_after>// Copyright 2017 Adam Smith
//
// 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 <cctype>
#include <sstream>
#include "as/serial_value/json.hpp"
#define ASMITH_SERIAL_PTR "as::serial_value::pointer_t="
void write_value(std::ostream& aStream, const as::serial_value& aValue) {
switch (aValue.get_type()) {
case as::serial_value::NULL_T:
aStream << "null";
break;
case as::serial_value::CHAR_T:
aStream << '"' << aValue.get_char() << "'";
break;
case as::serial_value::BOOL_T:
aStream << aValue.get_bool() ? "true" : "false";
break;
case as::serial_value::UNSIGNED_T:
aStream << aValue.get_unsigned();
break;
case as::serial_value::SIGNED_T:
aStream << aValue.get_signed();
break;
case as::serial_value::FLOAT_T:
aStream << aValue.get_float();
break;
case as::serial_value::POINTER_T:
aStream << '"' << ASMITH_SERIAL_PTR << aValue.get_pointer() << '"';
break;
case as::serial_value::STRING_T:
aStream << '"' << aValue.get_string() << '"';
break;
case as::serial_value::ARRAY_T:
{
aStream << '[';
const as::serial_value::array_t& tmp = aValue.get_array();
const size_t s = tmp.size();
for(size_t i = 0; i < s; ++i) {
write_value(aStream, tmp[i]);
if(i + 1 != s) aStream << ',';
}
aStream << ']';
}
break;
case as::serial_value::OBJECT_T:
{
aStream << '{';
const as::serial_value::object_t& tmp = aValue.get_object();
const auto end = tmp.end();
for(auto i = tmp.begin(); i != end; ++i) {
aStream << '"' << i->first << '"' << ':';
write_value(aStream, i->second);
auto j = i;
++j;
if(j != end) aStream << ',';
}
aStream << '}';
}
break;
}
}
void ignore_whitespace(std::istream& aStream) {
char c = aStream.peek();
while(std::isspace(c)) {
aStream >> c;
c = aStream.peek();
}
}
as::serial_value read_unknown(std::istream&);
as::serial_value read_null(std::istream& aStream) {
const auto pos = aStream.tellg();
char tmp[4];
aStream.read(tmp, 4);
if(memcmp(tmp, "null", 4) != 0) {
aStream.seekg(pos);
throw std::runtime_error("as::deserialise_json : Expected 'null'");
}
return as::serial_value();
}
as::serial_value read_bool(std::istream& aStream) {
const auto pos = aStream.tellg();
char tmp[4];
aStream.read(tmp, 4);
const bool t = memcmp(tmp, "true", 4) == 0;
const bool f = memcmp(tmp, "fals", 4) == 0;
if(t) {
return as::serial_value(true);
}else if(f) {
aStream >> tmp[0];
if(tmp[0] == 'e') return as::serial_value(false);
}
aStream.seekg(pos);
throw std::runtime_error("as::deserialise_json : Expected 'true' or 'false'");
}
as::serial_value read_number(std::istream& aStream) {
as::serial_value::float_t tmp;
aStream >> tmp;
return as::serial_value(tmp);
}
as::serial_value read_string(std::istream& aStream) {
auto pos = aStream.tellg();
char c;
aStream >> c;
if(c != '"') {
aStream.seekg(pos);
throw std::runtime_error("as::deserialise_json : Expected string to begin with '\"'");
}
as::serial_value tmp;
as::serial_value::string_t& str = tmp.set_string();
aStream >> c;
while(c != '"') {
if(aStream.eof()) {
aStream.seekg(pos);
throw std::runtime_error("as::deserialise_json : Expected string to end with'\"'");
}
str += c;
aStream >> c;
}
// The string is a char
if(str.size() == 1) return as::serial_value(str[0]);
// If the string is a pointer
if(str.find(ASMITH_SERIAL_PTR) == 0) {
std::stringstream ss;
ss << str.substr(strlen(ASMITH_SERIAL_PTR));
as::serial_value::pointer_t ptr;
ss >> ptr;
return as::serial_value(ptr);
}
return tmp;
}
as::serial_value read_array(std::istream& aStream) {
auto pos = aStream.tellg();
char c;
aStream >> c;
if (c != '[') {
aStream.seekg(pos);
throw std::runtime_error("as::deserialise_json : Expected array to begin with '['");
}
as::serial_value tmp;
as::serial_value::array_t& values = tmp.set_array();
c = aStream.peek();
while(c != ']') {
ignore_whitespace(aStream);
c = aStream.peek();
if(c == ',') aStream >> c;
try {
values.push_back(read_unknown(aStream));
}catch (std::exception& e) {
aStream.seekg(pos);
throw e;
}
if(aStream.eof()) {
aStream.seekg(pos);
throw std::runtime_error("as::deserialise_json : Expected array to end with ']'");
}
c = aStream.peek();
}
aStream >> c;
return tmp;
}
as::serial_value read_object(std::istream& aStream) {
auto pos = aStream.tellg();
char c;
aStream >> c;
if (c != '{') {
aStream.seekg(pos);
throw std::runtime_error("as::deserialise_json : Expected object to begin with '{'");
}
as::serial_value tmp;
as::serial_value::object_t& values = tmp.set_object();
c = aStream.peek();
while(c != '}') {
ignore_whitespace(aStream);
c = aStream.peek();
if(c == ',') aStream >> c;
try {
as::serial_value::string_t name = read_string(aStream).get_string();
ignore_whitespace(aStream);
aStream >> c;
if(c != ':') throw std::runtime_error("as::deserialise_json : Expected object members to be seperated with ':'");
values.emplace(name, read_unknown(aStream));
}catch (std::exception& e) {
aStream.seekg(pos);
throw e;
}
if(aStream.eof()) {
aStream.seekg(pos);
throw std::runtime_error("as::deserialise_json : Expected object to end with '}'");
}
c = aStream.peek();
}
aStream >> c;
return tmp;
}
as::serial_value read_unknown(std::istream& aStream) {
ignore_whitespace(aStream);
switch(aStream.peek())
{
case 'n':
return read_null(aStream);
case 't':
case 'f':
return read_bool(aStream);
case '-':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return read_number(aStream);
case '"':
return read_string(aStream);
case '[':
return read_array(aStream);
case '{':
return read_object(aStream);
default:
throw std::runtime_error("as::deserialise_json : Could not determine type of JSON value");
break;
}
}
namespace as {
void serialise_json(std::ostream& aStream, const serial_value& aValue) {
write_value(aStream, aValue);
}
serial_value deserialise_json(std::istream& aStream) {
return read_unknown(aStream);
}
}<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information ([email protected])
**
** This file is part of the Qt Linguist of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
** $QT_END_LICENSE$
**
****************************************************************************/
#include "mainwindow.h"
#include <QtCore/QFile>
#include <QtCore/QLibraryInfo>
#include <QtCore/QLocale>
#include <QtCore/QSettings>
#include <QtCore/QTextCodec>
#include <QtCore/QTranslator>
#include <QtGui/QApplication>
#include <QtGui/QDesktopWidget>
#include <QtGui/QPixmap>
#include <QtGui/QSplashScreen>
QT_USE_NAMESPACE
int main(int argc, char **argv)
{
Q_INIT_RESOURCE(linguist);
QApplication app(argc, argv);
QApplication::setOverrideCursor(Qt::WaitCursor);
QStringList files;
QString resourceDir = QLibraryInfo::location(QLibraryInfo::TranslationsPath);
QStringList args = app.arguments();
for (int i = 1; i < args.count(); ++i) {
QString argument = args.at(i);
if (argument == QLatin1String("-resourcedir")) {
if (i + 1 < args.count()) {
resourceDir = QFile::decodeName(args.at(++i).toLocal8Bit());
} else {
// issue a warning
}
} else if (!files.contains(argument)) {
files.append(argument);
}
}
QTranslator translator;
translator.load(QLatin1String("linguist_") + QLocale::system().name(), resourceDir);
app.installTranslator(&translator);
QTranslator qtTranslator;
qtTranslator.load(QLatin1String("qt_") + QLocale::system().name(), resourceDir);
app.installTranslator(&qtTranslator);
app.setOrganizationName(QLatin1String("Trolltech"));
app.setApplicationName(QLatin1String("Linguist"));
QString keybase(QString::number( (QT_VERSION >> 16) & 0xff ) +
QLatin1Char('.') + QString::number( (QT_VERSION >> 8) & 0xff ) + QLatin1Char('/') );
QSettings config;
QWidget tmp;
tmp.restoreGeometry(config.value(keybase + QLatin1String("Geometry/WindowGeometry")).toByteArray());
QSplashScreen *splash = 0;
int screenId = QApplication::desktop()->screenNumber(tmp.geometry().center());
splash = new QSplashScreen(QApplication::desktop()->screen(screenId),
QPixmap(QLatin1String(":/images/splash.png")));
if (QApplication::desktop()->isVirtualDesktop()) {
QRect srect(0, 0, splash->width(), splash->height());
splash->move(QApplication::desktop()->availableGeometry(screenId).center() - srect.center());
}
splash->setAttribute(Qt::WA_DeleteOnClose);
splash->show();
MainWindow mw;
mw.show();
splash->finish(&mw);
QApplication::restoreOverrideCursor();
mw.openFiles(files, true);
return app.exec();
}
<commit_msg>fix 223949: Qt's translation should be installed only if Linguists translation is found<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information ([email protected])
**
** This file is part of the Qt Linguist of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
** $QT_END_LICENSE$
**
****************************************************************************/
#include "mainwindow.h"
#include <QtCore/QFile>
#include <QtCore/QLibraryInfo>
#include <QtCore/QLocale>
#include <QtCore/QSettings>
#include <QtCore/QTextCodec>
#include <QtCore/QTranslator>
#include <QtGui/QApplication>
#include <QtGui/QDesktopWidget>
#include <QtGui/QPixmap>
#include <QtGui/QSplashScreen>
QT_USE_NAMESPACE
int main(int argc, char **argv)
{
Q_INIT_RESOURCE(linguist);
QApplication app(argc, argv);
QApplication::setOverrideCursor(Qt::WaitCursor);
QStringList files;
QString resourceDir = QLibraryInfo::location(QLibraryInfo::TranslationsPath);
QStringList args = app.arguments();
for (int i = 1; i < args.count(); ++i) {
QString argument = args.at(i);
if (argument == QLatin1String("-resourcedir")) {
if (i + 1 < args.count()) {
resourceDir = QFile::decodeName(args.at(++i).toLocal8Bit());
} else {
// issue a warning
}
} else if (!files.contains(argument)) {
files.append(argument);
}
}
QTranslator translator;
QTranslator qtTranslator;
QString sysLocale = QLocale::system().name();
if (translator.load(QLatin1String("linguist_") + sysLocale, resourceDir)) {
app.installTranslator(&translator);
if (qtTranslator.load(QLatin1String("qt_") + sysLocale, resourceDir))
app.installTranslator(&qtTranslator);
else
app.removeTranslator(&translator);
}
app.setOrganizationName(QLatin1String("Trolltech"));
app.setApplicationName(QLatin1String("Linguist"));
QString keybase(QString::number( (QT_VERSION >> 16) & 0xff ) +
QLatin1Char('.') + QString::number( (QT_VERSION >> 8) & 0xff ) + QLatin1Char('/') );
QSettings config;
QWidget tmp;
tmp.restoreGeometry(config.value(keybase + QLatin1String("Geometry/WindowGeometry")).toByteArray());
QSplashScreen *splash = 0;
int screenId = QApplication::desktop()->screenNumber(tmp.geometry().center());
splash = new QSplashScreen(QApplication::desktop()->screen(screenId),
QPixmap(QLatin1String(":/images/splash.png")));
if (QApplication::desktop()->isVirtualDesktop()) {
QRect srect(0, 0, splash->width(), splash->height());
splash->move(QApplication::desktop()->availableGeometry(screenId).center() - srect.center());
}
splash->setAttribute(Qt::WA_DeleteOnClose);
splash->show();
MainWindow mw;
mw.show();
splash->finish(&mw);
QApplication::restoreOverrideCursor();
mw.openFiles(files, true);
return app.exec();
}
<|endoftext|> |
<commit_before>#ifndef RECURSE_HPP
#define RECURSE_HPP
#include <QCoreApplication>
#include <QObject>
#include <QTcpServer>
#include <QTcpSocket>
#include <QHostAddress>
#include <QHash>
#include <QVector>
#include <functional>
using std::function;
using std::bind;
struct Request {
// tpc request data
QString data;
// higher level data
QHash<QString, QString> headers;
QHash<QString, QString> body;
};
typedef function<void(Request &request, QString &response, function<void()> next)> next_f;
//!
//! \brief The Recurse class
//! main class of the app
//!
class Recurse : public QObject
{
public:
Recurse(int & argc, char ** argv, QObject *parent = NULL);
~Recurse();
bool listen(quint64 port, QHostAddress address = QHostAddress::Any);
void use(next_f next);
private:
QCoreApplication app;
QTcpServer m_tcp_server;
quint64 m_port;
QVector<next_f> m_middleware;
int current_middleware = 0;
void m_next();
Request request;
QString response;
};
Recurse::Recurse(int & argc, char ** argv, QObject *parent) : app(argc, argv)
{
Q_UNUSED(parent);
};
Recurse::~Recurse()
{
};
//!
//! \brief Recurse::listen
//! listen for tcp requests
//!
//! \param port tcp server port
//! \param address tcp server listening address
//!
//! \return true on success
//!
bool Recurse::listen(quint64 port, QHostAddress address)
{
m_port = port;
int bound = m_tcp_server.listen(address, port);
if (!bound)
return false;
connect(&m_tcp_server, &QTcpServer::newConnection, [this] {
qDebug() << "client connected";
QTcpSocket *client = m_tcp_server.nextPendingConnection();
connect(client, &QTcpSocket::readyRead, [this, client] {
request.data = client->readAll();
qDebug() << "client request: " << request.body["data"];
if (m_middleware.count() > 0)
m_middleware[current_middleware](request, response, bind(&Recurse::m_next, this));
qDebug() << "middleware end";
current_middleware = 0;
// handle response
client->write(response.toStdString().c_str(), response.size());
});
});
return app.exec();
};
//!
//! \brief Recurse::m_next
//! call next middleware
//!
void Recurse::m_next()
{
qDebug() << "calling next:" << current_middleware << " num:" << m_middleware.size();
if (++current_middleware >= m_middleware.size()) {
return;
};
m_middleware[current_middleware](request, response, bind(&Recurse::m_next, this));
};
//!
//! \brief Recurse::use
//! add new middleware
//!
//! \param f middleware function that will be called later
//!
void Recurse::use(next_f f)
{
m_middleware.push_back(f);
};
#endif // RECURSE_HPP
<commit_msg>add parse_http private method (TODO: don't parse if not HTTP)<commit_after>#ifndef RECURSE_HPP
#define RECURSE_HPP
#include <QCoreApplication>
#include <QObject>
#include <QTcpServer>
#include <QTcpSocket>
#include <QHostAddress>
#include <QHash>
#include <QVector>
#include <functional>
using std::function;
using std::bind;
struct Request {
// tpc request data
QString data;
// higher level data
QHash<QString, QString> headers;
QString body;
};
typedef function<void(Request &request, QString &response, function<void()> next)> next_f;
//!
//! \brief The Recurse class
//! main class of the app
//!
class Recurse : public QObject
{
public:
Recurse(int & argc, char ** argv, QObject *parent = NULL);
~Recurse();
bool listen(quint64 port, QHostAddress address = QHostAddress::Any);
void use(next_f next);
private:
QCoreApplication app;
QTcpServer m_tcp_server;
quint64 m_port;
QVector<next_f> m_middleware;
int current_middleware = 0;
void m_next();
void parse_http(QString &data);
Request request;
QString response;
};
Recurse::Recurse(int & argc, char ** argv, QObject *parent) : app(argc, argv)
{
Q_UNUSED(parent);
};
Recurse::~Recurse()
{
};
//!
//! \brief Recurse::listen
//! listen for tcp requests
//!
//! \param port tcp server port
//! \param address tcp server listening address
//!
//! \return true on success
//!
bool Recurse::listen(quint64 port, QHostAddress address)
{
m_port = port;
int bound = m_tcp_server.listen(address, port);
if (!bound)
return false;
connect(&m_tcp_server, &QTcpServer::newConnection, [this] {
qDebug() << "client connected";
QTcpSocket *client = m_tcp_server.nextPendingConnection();
connect(client, &QTcpSocket::readyRead, [this, client] {
request.data = client->readAll();
parse_http(request.data);
qDebug() << "client request: " << request.data;
if (m_middleware.count() > 0)
m_middleware[current_middleware](request, response, bind(&Recurse::m_next, this));
qDebug() << "middleware end";
current_middleware = 0;
// handle response
client->write(response.toStdString().c_str(), response.size());
});
});
return app.exec();
};
//!
//! \brief Recurse::m_next
//! call next middleware
//!
void Recurse::m_next()
{
qDebug() << "calling next:" << current_middleware << " num:" << m_middleware.size();
if (++current_middleware >= m_middleware.size()) {
return;
};
m_middleware[current_middleware](request, response, bind(&Recurse::m_next, this));
};
//!
//! \brief Recurse::use
//! add new middleware
//!
//! \param f middleware function that will be called later
//!
void Recurse::use(next_f f)
{
m_middleware.push_back(f);
};
//!
//! \brief Recurse::parse_http
//! parse http data
//!
//! \param data reference to data received from the tcp connection
//!
void Recurse::parse_http(QString &data)
{
qDebug() << "parser:" << data;
QStringList data_list = data.split("\r\n");
qDebug() << "parser after split:" << data_list;
bool isBody = false;
for (int i = 0; i < data_list.size(); ++i) {
QStringList item_list = data_list.at(i).split(":");
if (item_list.length() < 2 && item_list.at(0).size() < 1 && !isBody) {
isBody = true;
continue;
}
else if (i == 0 && item_list.length() < 2) {
request.headers["method"] = item_list.at(0);
}
else if (!isBody) {
qDebug() << "header: " << item_list.at(0);
request.headers[item_list.at(0)] = item_list.at(1);
}
else {
request.body.append(item_list.at(0));
}
qDebug() << item_list;
}
qDebug() << "headers ready: " << request.headers;
qDebug() << "body ready: " << request.body;
};
#endif // RECURSE_HPP
<|endoftext|> |
<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id:
#include "ballviewDemo.h"
#include <BALL/VIEW/KERNEL/mainControl.h>
#include <BALL/VIEW/KERNEL/common.h>
#include <BALL/KERNEL/system.h>
#include <BALL/VIEW/DIALOGS/displayProperties.h>
#include <BALL/VIEW/WIDGETS/molecularStructure.h>
#include <BALL/VIEW/DIALOGS/FDPBDialog.h>
#include <BALL/FORMAT/PDBFile.h>
#include <BALL/FORMAT/HINFile.h>
#include <BALL/DATATYPE/contourSurface.h>
#include <BALL/VIEW/PRIMITIVES/mesh.h>
#include <BALL/STRUCTURE/HBondProcessor.h>
#include <BALL/VIEW/WIDGETS/scene.h>
#include <BALL/VIEW/DATATYPE/colorTable.h>
#include <BALL/VIEW/DIALOGS/colorMeshDialog.h>
#include <BALL/VIEW/DIALOGS/molecularFileDialog.h>
#include <qlabel.h>
#include <qpushbutton.h>
#include <qwidgetstack.h>
namespace BALL
{
namespace VIEW
{
BALLViewDemo::BALLViewDemo(QWidget* parent, const char* name)
throw()
: BALLViewDemoData(parent, name),
ModularWidget(name)
{
#ifdef BALL_VIEW_DEBUG
Log.error() << "new BALLViewDemo " << this << std::endl;
#endif
// register the widget with the MainControl
ModularWidget::registerWidget(this);
hide();
}
BALLViewDemo::~BALLViewDemo()
throw()
{
#ifdef BALL_VIEW_DEBUG
Log.error() << "deleting BALLViewDemo " << this << std::endl;
#endif
}
void BALLViewDemo::show()
{
widget_stack->raiseWidget(0);
buttonOk->setEnabled(true);
DisplayProperties* dp = DisplayProperties::getInstance(0);
dp->setDrawingPrecision(DRAWING_PRECISION_HIGH);
dp->setSurfaceDrawingPrecision(6.5);
dp->enableCreationForNewMolecules(false);
system_ = new System();
try
{
Path path;
String file_name(path.getDataPath());
file_name = file_name.before("data");
file_name += "data";
file_name += FileSystem::PATH_SEPARATOR;
file_name += String("structures");
file_name += FileSystem::PATH_SEPARATOR;
file_name += "bpti.pdb";
MolecularFileDialog* dialog = MolecularFileDialog::getInstance(0);
system_ = dialog->openFile(file_name);
system_->apply(getFragmentDB().add_hydrogens);
system_->apply(getFragmentDB().build_bonds);
getMainControl()->update(*system_, true);
}
catch(Exception::FileNotFound e)
{
Log.error() << "Could not open " << e.getFilename() << std::endl;
return;
}
composites_.clear();
composites_.push_back(system_);
QDialog::show();
raise();
}
void BALLViewDemo::onNotify(Message *message)
throw()
{
#ifdef BALL_VIEW_DEBUG
Log.error() << "BALLViewDemo " << this << " onNotify " << message << std::endl;
#endif
if (!isVisible()) return;
RepresentationMessage* rmsg = RTTI::castTo<RepresentationMessage>(*message);
Index id = widget_stack->id(widget_stack->visibleWidget());
if (id == 12)
{
if (RTTI::isKindOf<FinishedSimulationMessage>(*message))
{
nextStep_();
}
return;
}
if (id == 13)
{
RegularData3DMessage* msg = RTTI::castTo<RegularData3DMessage>(*message);
if (msg != 0 &&
((RegularData3DMessage::RegularDataMessageType)msg->getType()) == RegularDataMessage::NEW)
{
grid_ = msg->getData();
nextStep_();
}
return;
}
if (rmsg != 0 &&
rmsg->getType() == RepresentationMessage::UPDATE)
{
nextStep_();
}
}
void BALLViewDemo::nextStep_()
{
buttonOk->setEnabled(true);
widget_stack->raiseWidget(widget_stack->id(widget_stack->visibleWidget()) + 1);
}
void BALLViewDemo::accept()
{
Index id = widget_stack->id(widget_stack->visibleWidget());
if (id == 15) // last page
{
hide();
return;
}
MolecularStructure* ms = MolecularStructure::getInstance(0);
bool disable_button = true;
// remove representations
PrimitiveManager& pm = getMainControl()->getPrimitiveManager();
Size nr = pm.getNumberOfRepresentations();
list<Representation*> reps = pm.getRepresentations();
for (Position p = 0; p < nr; p++)
{
getMainControl()->remove(**reps.begin());
reps.pop_front();
}
if (id < 7)
{
ModelType type = (ModelType) id;
if (type >= MODEL_SA_SURFACE)
{
type = (ModelType)((Index)type + 1);
}
CreateRepresentationMessage* crmsg = new CreateRepresentationMessage(composites_, type, COLORING_ELEMENT);
notify_(crmsg);
}
else if (id == 7)
{
HBondProcessor proc;
system_->apply(proc);
CreateRepresentationMessage* crmsg = new CreateRepresentationMessage(composites_, MODEL_STICK, COLORING_ELEMENT);
notify_(crmsg);
crmsg = new CreateRepresentationMessage(composites_, MODEL_HBONDS, COLORING_ELEMENT);
notify_(crmsg);
}
else if (id == 8)
{
CreateRepresentationMessage* crmsg = new CreateRepresentationMessage(composites_, MODEL_VDW, COLORING_TEMPERATURE_FACTOR);
notify_(crmsg);
}
else if (id == 9)
{
CreateRepresentationMessage* crmsg = new CreateRepresentationMessage(composites_, MODEL_CARTOON, COLORING_SECONDARY_STRUCTURE);
notify_(crmsg);
}
else if (id == 10)
{
CreateRepresentationMessage* crmsg = new CreateRepresentationMessage(composites_, MODEL_CARTOON, COLORING_RESIDUE_INDEX);
notify_(crmsg);
}
else if (id == 11)
{
CreateRepresentationMessage* crmsg = new CreateRepresentationMessage(composites_, MODEL_STICK, COLORING_RESIDUE_NAME);
notify_(crmsg);
}
else if (id == 12)
{
CreateRepresentationMessage* crmsg = new CreateRepresentationMessage(composites_, MODEL_STICK, COLORING_ELEMENT);
notify_(crmsg);
ms->chooseAmberFF();
ms->getMDSimulationDialog().setTimeStep(0.001);
ms->getMDSimulationDialog().setNumberOfSteps(30);
ms->MDSimulation(false);
}
else if (id == 13) //FDPB
{
ms->calculateFDPB();
ms->getFDPBDialog()->okPressed();
disable_button = false;
}
else if (id == 14) // SES colored
{
getMainControl()->getPrimitiveManager().setMultithreadingMode(false);
CreateRepresentationMessage* crmsg = new CreateRepresentationMessage(composites_, MODEL_SE_SURFACE, COLORING_ELEMENT);
notify_(crmsg);
Representation* rep = *getMainControl()->getPrimitiveManager().begin();
Mesh* mesh = dynamic_cast<Mesh*> (*rep->getGeometricObjects().begin());
ColorMeshDialog* cdialog = ColorMeshDialog::getInstance(0);
cdialog->setMesh(mesh, rep);
cdialog->setGrid(grid_);
cdialog->setMinValue(-0.7);
cdialog->setMaxValue(3.0);
cdialog->applyPressed();
rep->setColorProcessor(0);
getMainControl()->getPrimitiveManager().setMultithreadingMode(false);
SceneMessage* smsg = new SceneMessage(SceneMessage::REBUILD_DISPLAY_LISTS);
notify_(smsg);
/*
ContourSurface cs(*grid_, 0.01);
Mesh* mesh = new Mesh;
mesh->Surface::operator = (static_cast<Surface&>(cs));
Vector3 center;
for (Position i = 0; i < mesh->vertex.size(); i++)
{
center += mesh->vertex[i];
}
center /= mesh->vertex.size();
Size nr_of_strange_normals = 0;
for (Position i = 0; i < mesh->normal.size(); i++)
{
if ((mesh->vertex[i] + mesh->normal[i]).getDistance(center) < (mesh->vertex[i] - mesh->normal[i]).getDistance(center))
{
nr_of_strange_normals ++;
}
}
if (nr_of_strange_normals > mesh->normal.size() / 2.0)
{
for (Position i = 0; i < mesh->normal.size(); i++)
{
mesh->normal[i] *= -1;
}
}
Stage stage = *Scene::getInstance(0)->getStage();
stage.clearLightSources();
LightSource ls;
ls.setPosition(Vector3(0,0,4000));
ls.setDirection(Vector3(0,0,0));
stage.addLightSource(ls);
SceneMessage* smsg = new SceneMessage(SceneMessage::UPDATE_CAMERA);
smsg->setStage(stage);
notify_(smsg);
// Create a new representation containing the contour surface.
Representation* rep = getMainControl()->getPrimitiveManager().createRepresentation();
rep->insert(*mesh);
rep->setModelType(MODEL_CONTOUR_SURFACE);
// Make sure BALLView knows about the new representation.
RepresentationMessage* message = new RepresentationMessage(*rep, RepresentationMessage::ADD);
notify_(message);
*/
disable_button = false;
}
buttonOk->setEnabled(true);
}
} } // namespaces
<commit_msg>no message<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id:
#include "ballviewDemo.h"
#include <BALL/VIEW/KERNEL/mainControl.h>
#include <BALL/VIEW/KERNEL/common.h>
#include <BALL/KERNEL/system.h>
#include <BALL/VIEW/DIALOGS/displayProperties.h>
#include <BALL/VIEW/WIDGETS/molecularStructure.h>
#include <BALL/VIEW/DIALOGS/FDPBDialog.h>
#include <BALL/FORMAT/PDBFile.h>
#include <BALL/FORMAT/HINFile.h>
#include <BALL/DATATYPE/contourSurface.h>
#include <BALL/VIEW/PRIMITIVES/mesh.h>
#include <BALL/STRUCTURE/HBondProcessor.h>
#include <BALL/VIEW/WIDGETS/scene.h>
#include <BALL/VIEW/DATATYPE/colorTable.h>
#include <BALL/VIEW/DIALOGS/colorMeshDialog.h>
#include <BALL/VIEW/DIALOGS/molecularFileDialog.h>
#include <qlabel.h>
#include <qpushbutton.h>
#include <qwidgetstack.h>
namespace BALL
{
namespace VIEW
{
BALLViewDemo::BALLViewDemo(QWidget* parent, const char* name)
throw()
: BALLViewDemoData(parent, name),
ModularWidget(name)
{
#ifdef BALL_VIEW_DEBUG
Log.error() << "new BALLViewDemo " << this << std::endl;
#endif
// register the widget with the MainControl
ModularWidget::registerWidget(this);
hide();
}
BALLViewDemo::~BALLViewDemo()
throw()
{
#ifdef BALL_VIEW_DEBUG
Log.error() << "deleting BALLViewDemo " << this << std::endl;
#endif
}
void BALLViewDemo::show()
{
widget_stack->raiseWidget(0);
buttonOk->setEnabled(true);
DisplayProperties* dp = DisplayProperties::getInstance(0);
dp->setDrawingPrecision(DRAWING_PRECISION_HIGH);
dp->setSurfaceDrawingPrecision(6.5);
dp->enableCreationForNewMolecules(false);
system_ = new System();
try
{
Path path;
String file_name(path.getDataPath());
file_name = file_name.before("data");
file_name += "data";
file_name += FileSystem::PATH_SEPARATOR;
file_name += String("structures");
file_name += FileSystem::PATH_SEPARATOR;
file_name += "bpti.pdb";
MolecularFileDialog* dialog = MolecularFileDialog::getInstance(0);
system_ = dialog->openFile(file_name);
system_->apply(getFragmentDB().add_hydrogens);
system_->apply(getFragmentDB().build_bonds);
getMainControl()->update(*system_, true);
}
catch(Exception::FileNotFound e)
{
Log.error() << "Could not open " << e.getFilename() << std::endl;
return;
}
composites_.clear();
composites_.push_back(system_);
QDialog::show();
raise();
}
void BALLViewDemo::onNotify(Message *message)
throw()
{
#ifdef BALL_VIEW_DEBUG
Log.error() << "BALLViewDemo " << this << " onNotify " << message << std::endl;
#endif
if (!isVisible()) return;
RepresentationMessage* rmsg = RTTI::castTo<RepresentationMessage>(*message);
Index id = widget_stack->id(widget_stack->visibleWidget());
if (id == 12)
{
if (RTTI::isKindOf<FinishedSimulationMessage>(*message))
{
nextStep_();
}
return;
}
if (id == 13)
{
RegularData3DMessage* msg = RTTI::castTo<RegularData3DMessage>(*message);
if (msg != 0 &&
((RegularData3DMessage::RegularDataMessageType)msg->getType()) == RegularDataMessage::NEW)
{
grid_ = msg->getData();
nextStep_();
}
return;
}
if (rmsg != 0 &&
rmsg->getType() == RepresentationMessage::UPDATE)
{
nextStep_();
}
}
void BALLViewDemo::nextStep_()
{
buttonOk->setEnabled(true);
widget_stack->raiseWidget(widget_stack->id(widget_stack->visibleWidget()) + 1);
}
void BALLViewDemo::accept()
{
Index id = widget_stack->id(widget_stack->visibleWidget());
if (id == 15) // last page
{
CreateRepresentationMessage* crmsg = new CreateRepresentationMessage(composites_, MODEL_LINE, COLORING_ELEMENT);
notify_(crmsg);
hide();
return;
}
MolecularStructure* ms = MolecularStructure::getInstance(0);
bool disable_button = true;
// remove representations
PrimitiveManager& pm = getMainControl()->getPrimitiveManager();
Size nr = pm.getNumberOfRepresentations();
list<Representation*> reps = pm.getRepresentations();
for (Position p = 0; p < nr; p++)
{
getMainControl()->remove(**reps.begin());
reps.pop_front();
}
if (id < 7)
{
ModelType type = (ModelType) id;
if (type >= MODEL_SA_SURFACE)
{
type = (ModelType)((Index)type + 1);
}
CreateRepresentationMessage* crmsg = new CreateRepresentationMessage(composites_, type, COLORING_ELEMENT);
notify_(crmsg);
}
else if (id == 7)
{
HBondProcessor proc;
system_->apply(proc);
CreateRepresentationMessage* crmsg = new CreateRepresentationMessage(composites_, MODEL_STICK, COLORING_ELEMENT);
notify_(crmsg);
crmsg = new CreateRepresentationMessage(composites_, MODEL_HBONDS, COLORING_ELEMENT);
notify_(crmsg);
}
else if (id == 8)
{
CreateRepresentationMessage* crmsg = new CreateRepresentationMessage(composites_, MODEL_VDW, COLORING_TEMPERATURE_FACTOR);
notify_(crmsg);
}
else if (id == 9)
{
CreateRepresentationMessage* crmsg = new CreateRepresentationMessage(composites_, MODEL_CARTOON, COLORING_SECONDARY_STRUCTURE);
notify_(crmsg);
}
else if (id == 10)
{
CreateRepresentationMessage* crmsg = new CreateRepresentationMessage(composites_, MODEL_CARTOON, COLORING_RESIDUE_INDEX);
notify_(crmsg);
}
else if (id == 11)
{
CreateRepresentationMessage* crmsg = new CreateRepresentationMessage(composites_, MODEL_STICK, COLORING_RESIDUE_NAME);
notify_(crmsg);
}
else if (id == 12)
{
CreateRepresentationMessage* crmsg = new CreateRepresentationMessage(composites_, MODEL_STICK, COLORING_ELEMENT);
notify_(crmsg);
ms->chooseAmberFF();
ms->getMDSimulationDialog().setTimeStep(0.001);
ms->getMDSimulationDialog().setNumberOfSteps(30);
ms->MDSimulation(false);
}
else if (id == 13) //FDPB
{
ms->calculateFDPB();
ms->getFDPBDialog()->okPressed();
disable_button = false;
}
else if (id == 14) // SES colored
{
getMainControl()->getPrimitiveManager().setMultithreadingMode(false);
CreateRepresentationMessage* crmsg = new CreateRepresentationMessage(composites_, MODEL_SE_SURFACE, COLORING_ELEMENT);
notify_(crmsg);
Representation* rep = *getMainControl()->getPrimitiveManager().begin();
Mesh* mesh = dynamic_cast<Mesh*> (*rep->getGeometricObjects().begin());
ColorMeshDialog* cdialog = ColorMeshDialog::getInstance(0);
cdialog->setMesh(mesh, rep);
cdialog->setGrid(grid_);
cdialog->setMinValue(-0.7);
cdialog->setMaxValue(3.0);
cdialog->applyPressed();
rep->setColorProcessor(0);
getMainControl()->getPrimitiveManager().setMultithreadingMode(false);
SceneMessage* smsg = new SceneMessage(SceneMessage::REBUILD_DISPLAY_LISTS);
notify_(smsg);
/*
ContourSurface cs(*grid_, 0.01);
Mesh* mesh = new Mesh;
mesh->Surface::operator = (static_cast<Surface&>(cs));
Vector3 center;
for (Position i = 0; i < mesh->vertex.size(); i++)
{
center += mesh->vertex[i];
}
center /= mesh->vertex.size();
Size nr_of_strange_normals = 0;
for (Position i = 0; i < mesh->normal.size(); i++)
{
if ((mesh->vertex[i] + mesh->normal[i]).getDistance(center) < (mesh->vertex[i] - mesh->normal[i]).getDistance(center))
{
nr_of_strange_normals ++;
}
}
if (nr_of_strange_normals > mesh->normal.size() / 2.0)
{
for (Position i = 0; i < mesh->normal.size(); i++)
{
mesh->normal[i] *= -1;
}
}
Stage stage = *Scene::getInstance(0)->getStage();
stage.clearLightSources();
LightSource ls;
ls.setPosition(Vector3(0,0,4000));
ls.setDirection(Vector3(0,0,0));
stage.addLightSource(ls);
SceneMessage* smsg = new SceneMessage(SceneMessage::UPDATE_CAMERA);
smsg->setStage(stage);
notify_(smsg);
// Create a new representation containing the contour surface.
Representation* rep = getMainControl()->getPrimitiveManager().createRepresentation();
rep->insert(*mesh);
rep->setModelType(MODEL_CONTOUR_SURFACE);
// Make sure BALLView knows about the new representation.
RepresentationMessage* message = new RepresentationMessage(*rep, RepresentationMessage::ADD);
notify_(message);
*/
disable_button = false;
}
buttonOk->setEnabled(true);
}
} } // namespaces
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2012, 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 the 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: Ioan Sucan */
#include "moveit/robot_interaction/robot_interaction.h"
#include "moveit/robot_interaction/interactive_marker_helpers.h"
#include <planning_models/transforms.h>
#include <interactive_markers/interactive_marker_server.h>
#include <boost/lexical_cast.hpp>
#include <limits>
namespace robot_interaction
{
const std::string RobotInteraction::INTERACTIVE_MARKER_TOPIC = "robot_interaction_interactive_marker_topic";
RobotInteraction::RobotInteraction(const planning_models::KinematicModelConstPtr &kmodel,
const InteractionHandlerPtr &handler) :
kmodel_(kmodel), handler_(handler)
{
int_marker_server_ = new interactive_markers::InteractiveMarkerServer(INTERACTIVE_MARKER_TOPIC);
}
RobotInteraction::~RobotInteraction(void)
{
clear();
delete int_marker_server_;
}
void RobotInteraction::decideActiveComponents(const std::string &group)
{
decideActiveEndEffectors(group);
decideActiveVirtualJoints(group);
}
double RobotInteraction::computeGroupScale(const std::string &group)
{
const planning_models::KinematicModel::JointModelGroup *jmg = kmodel_->getJointModelGroup(group);
if (!jmg)
return 0.0;
const std::vector<std::string> &links = jmg->getLinkModelNames();
if (links.empty())
return 0.0;
std::vector<double> scale(3, 0.0);
std::vector<double> low(3, std::numeric_limits<double>::infinity());
std::vector<double> hi(3, -std::numeric_limits<double>::infinity());
planning_models::KinematicState default_state(kmodel_);
default_state.setToDefaultValues();
for (std::size_t i = 0 ; i < links.size() ; ++i)
{
planning_models::KinematicState::LinkState *ls = default_state.getLinkState(links[i]);
if (!ls)
continue;
const Eigen::Vector3d &ext = ls->getLinkModel()->getShapeExtentsAtOrigin();
Eigen::Vector3d corner1 = ext/2.0;
corner1 = ls->getGlobalLinkTransform() * corner1;
Eigen::Vector3d corner2 = ext/-2.0;
corner2 = ls->getGlobalLinkTransform() * corner2;
for (int k = 0 ; k < 3 ; ++k)
{
if (low[k] > corner2[k])
low[k] = corner2[k];
if (hi[k] < corner1[k])
hi[k] = corner1[k];
}
}
for (int i = 0 ; i < 3 ; ++i)
scale[i] = hi[i] - low[i];
static const double sqrt_3 = 1.732050808;
return std::max(std::max(scale[0], scale[1]), scale[2]) * sqrt_3;
}
void RobotInteraction::decideActiveVirtualJoints(const std::string &group)
{
active_vj_.clear();
if (group.empty())
return;
const boost::shared_ptr<const srdf::Model> &srdf = kmodel_->getSRDF();
const planning_models::KinematicModel::JointModelGroup *jmg = kmodel_->getJointModelGroup(group);
if (!jmg || !srdf)
return;
if (!jmg->hasJointModel(kmodel_->getRootJointName()))
return;
planning_models::KinematicState default_state(kmodel_);
default_state.setToDefaultValues();
std::vector<double> aabb;
default_state.computeAABB(aabb);
const std::vector<srdf::Model::VirtualJoint> &vj = srdf->getVirtualJoints();
for (std::size_t i = 0 ; i < vj.size() ; ++i)
if (vj[i].name_ == kmodel_->getRootJointName())
{
if (vj[i].type_ == "planar" || vj[i].type_ == "floating")
{
VirtualJoint v;
v.connecting_link = vj[i].child_link_;
v.joint_name = vj[i].name_;
if (vj[i].type_ == "planar")
v.dof = 3;
else
v.dof = 6;
// take the max of the X extent and the Y extent
v.scale = std::max(aabb[1] - aabb[0], aabb[3] - aabb[2]);
active_vj_.push_back(v);
}
}
}
void RobotInteraction::decideActiveEndEffectors(const std::string &group)
{
active_eef_.clear();
if (group.empty())
return;
const boost::shared_ptr<const srdf::Model> &srdf = kmodel_->getSRDF();
const planning_models::KinematicModel::JointModelGroup *jmg = kmodel_->getJointModelGroup(group);
if (!jmg || !srdf)
return;
const std::vector<srdf::Model::EndEffector> &eef = srdf->getEndEffectors();
const std::pair<planning_models::KinematicModel::SolverAllocatorFn, planning_models::KinematicModel::SolverAllocatorMapFn> &smap = jmg->getSolverAllocators();
// if we have an IK solver for the selected group, we check if there are any end effectors attached to this group
if (smap.first)
{
for (std::size_t i = 0 ; i < eef.size() ; ++i)
if (jmg->hasLinkModel(eef[i].parent_link_) && jmg->canSetStateFromIK(eef[i].parent_link_))
{
// we found an end-effector for the selected group
EndEffector ee;
ee.group = group;
ee.tip_link = eef[i].parent_link_;
ee.eef_group = eef[i].component_group_;
active_eef_.push_back(ee);
break;
}
}
else
if (!smap.second.empty())
{
for (std::map<const planning_models::KinematicModel::JointModelGroup*, planning_models::KinematicModel::SolverAllocatorFn>::const_iterator it = smap.second.begin() ;
it != smap.second.end() ; ++it)
{
for (std::size_t i = 0 ; i < eef.size() ; ++i)
if (it->first->hasLinkModel(eef[i].parent_link_) && it->first->canSetStateFromIK(eef[i].parent_link_))
{
// we found an end-effector for the selected group;
EndEffector ee;
ee.group = it->first->getName();
ee.tip_link = eef[i].parent_link_;
ee.eef_group = eef[i].component_group_;
active_eef_.push_back(ee);
break;
}
}
}
for (std::size_t i = 0 ; i < active_eef_.size() ; ++i)
{
active_eef_[i].scale = computeGroupScale(active_eef_[i].eef_group);
ROS_DEBUG("Found active end-effector '%s', of scale %lf", active_eef_[i].eef_group.c_str(), active_eef_[i].scale);
}
}
void RobotInteraction::clear(void)
{
active_eef_.clear();
active_vj_.clear();
clearInteractiveMarkers();
publishInteractiveMarkers();
}
void RobotInteraction::clearInteractiveMarkers(void)
{
shown_markers_.clear();
int_marker_server_->clear();
}
void RobotInteraction::addInteractiveMarkers(const planning_models::KinematicState &state, int id)
{
// ros::WallTime start = ros::WallTime::now();
for (std::size_t i = 0 ; i < active_eef_.size() ; ++i)
{
geometry_msgs::PoseStamped pose;
pose.header.frame_id = kmodel_->getModelFrame();
pose.header.stamp = ros::Time::now();
const planning_models::KinematicState::LinkState *ls = state.getLinkState(active_eef_[i].tip_link);
planning_models::msgFromPose(ls->getGlobalLinkTransform(), pose.pose);
std::string marker_name = "IK" + boost::lexical_cast<std::string>(id) + "_" + active_eef_[i].tip_link;
shown_markers_[marker_name] = i;
visualization_msgs::InteractiveMarker im = make6DOFMarker(marker_name, pose, active_eef_[i].scale);
if (handler_ && handler_->inError(active_eef_[i], id))
addErrorMarker(im);
int_marker_server_->insert(im);
int_marker_server_->setCallback(im.name, boost::bind(&RobotInteraction::processInteractiveMarkerFeedback, this, _1));
ROS_DEBUG("Publishing interactive marker %s (scale = %lf)", marker_name.c_str(), active_eef_[i].scale);
}
for (std::size_t i = 0 ; i < active_vj_.size() ; ++i)
if (active_vj_[i].dof == 3)
{
geometry_msgs::PoseStamped pose;
pose.header.frame_id = kmodel_->getModelFrame();
pose.header.stamp = ros::Time::now();
const planning_models::KinematicState::LinkState *ls = state.getLinkState(active_vj_[i].connecting_link);
planning_models::msgFromPose(ls->getGlobalLinkTransform(), pose.pose);
std::string marker_name = "XY" + boost::lexical_cast<std::string>(id) + "_" + active_vj_[i].connecting_link;
shown_markers_[marker_name] = i;
visualization_msgs::InteractiveMarker im = make3DOFMarker(marker_name, pose, active_vj_[i].scale);
int_marker_server_->insert(im);
int_marker_server_->setCallback(im.name, boost::bind(&RobotInteraction::processInteractiveMarkerFeedback, this, _1));
ROS_DEBUG("Publishing interactive marker %s (scale = %lf)", marker_name.c_str(), active_vj_[i].scale);
}
// ROS_INFO("Spent %0.5lf s to publish markers", (ros::WallTime::now() - start).toSec());
}
void RobotInteraction::publishInteractiveMarkers(void)
{
int_marker_server_->applyChanges();
}
bool RobotInteraction::updateState(planning_models::KinematicState &state, const VirtualJoint &vj, const geometry_msgs::Pose &pose)
{
Eigen::Quaterniond q;
if (!planning_models::quatFromMsg(pose.orientation, q))
return false;
std::map<std::string, double> vals;
vals[ vj.joint_name + "/x"] = pose.position.x;
vals[ vj.joint_name + "/y"] = pose.position.y;
Eigen::Vector3d xyz = q.matrix().eulerAngles(0, 1, 2);
vals[ vj.joint_name + "/theta"] = xyz[2];
state.getJointState(vj.joint_name)->setVariableValues(vals);
state.updateLinkTransforms();
return true;
}
bool RobotInteraction::updateState(planning_models::KinematicState &state, const EndEffector &eef, const geometry_msgs::Pose &pose)
{
static const double IK_TIMEOUT = 0.1;
return state.getJointStateGroup(eef.group)->setFromIK(pose, eef.tip_link, IK_TIMEOUT);
}
void RobotInteraction::processInteractiveMarkerFeedback(const visualization_msgs::InteractiveMarkerFeedbackConstPtr& feedback)
{
if (!handler_)
return;
std::map<std::string, std::size_t>::const_iterator it = shown_markers_.find(feedback->marker_name);
if (it == shown_markers_.end())
{
ROS_ERROR("Unknown marker name: '%s' (not published by RobotInteraction class)", feedback->marker_name.c_str());
return;
}
std::size_t u = feedback->marker_name.find_first_of("_");
if (u == std::string::npos || u < 3)
{
ROS_ERROR("Invalid marker name: '%s'", feedback->marker_name.c_str());
return;
}
std::string marker_class = feedback->marker_name.substr(0, 2);
int marker_id = 0;
try
{
marker_id = boost::lexical_cast<int>(feedback->marker_name.substr(2, u - 2));
}
catch(boost::bad_lexical_cast &ex)
{
ROS_ERROR("Invalid marker name ('%s') : %s", feedback->marker_name.c_str(), ex.what());
return;
}
if (marker_class == "IK")
handler_->handleEndEffector(active_eef_[it->second], marker_id, feedback);
else
if (marker_class == "XY")
handler_->handleVirtualJoint(active_vj_[it->second], marker_id, feedback);
else
ROS_ERROR("Unknown marker class ('%s') for marker '%s'", marker_class.c_str(), feedback->marker_name.c_str());
}
}
<commit_msg>default scale for interactive markers<commit_after>/*
* Copyright (c) 2012, 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 the 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: Ioan Sucan */
#include "moveit/robot_interaction/robot_interaction.h"
#include "moveit/robot_interaction/interactive_marker_helpers.h"
#include <planning_models/transforms.h>
#include <interactive_markers/interactive_marker_server.h>
#include <boost/lexical_cast.hpp>
#include <limits>
namespace robot_interaction
{
const std::string RobotInteraction::INTERACTIVE_MARKER_TOPIC = "robot_interaction_interactive_marker_topic";
RobotInteraction::RobotInteraction(const planning_models::KinematicModelConstPtr &kmodel,
const InteractionHandlerPtr &handler) :
kmodel_(kmodel), handler_(handler)
{
int_marker_server_ = new interactive_markers::InteractiveMarkerServer(INTERACTIVE_MARKER_TOPIC);
}
RobotInteraction::~RobotInteraction(void)
{
clear();
delete int_marker_server_;
}
void RobotInteraction::decideActiveComponents(const std::string &group)
{
decideActiveEndEffectors(group);
decideActiveVirtualJoints(group);
}
double RobotInteraction::computeGroupScale(const std::string &group)
{
static const double DEFAULT_SCALE = 0.2;
const planning_models::KinematicModel::JointModelGroup *jmg = kmodel_->getJointModelGroup(group);
if (!jmg)
return 0.0;
const std::vector<std::string> &links = jmg->getLinkModelNames();
if (links.empty())
return DEFAULT_SCALE;
std::vector<double> scale(3, 0.0);
std::vector<double> low(3, std::numeric_limits<double>::infinity());
std::vector<double> hi(3, -std::numeric_limits<double>::infinity());
planning_models::KinematicState default_state(kmodel_);
default_state.setToDefaultValues();
for (std::size_t i = 0 ; i < links.size() ; ++i)
{
planning_models::KinematicState::LinkState *ls = default_state.getLinkState(links[i]);
if (!ls)
continue;
const Eigen::Vector3d &ext = ls->getLinkModel()->getShapeExtentsAtOrigin();
Eigen::Vector3d corner1 = ext/2.0;
corner1 = ls->getGlobalLinkTransform() * corner1;
Eigen::Vector3d corner2 = ext/-2.0;
corner2 = ls->getGlobalLinkTransform() * corner2;
for (int k = 0 ; k < 3 ; ++k)
{
if (low[k] > corner2[k])
low[k] = corner2[k];
if (hi[k] < corner1[k])
hi[k] = corner1[k];
}
}
for (int i = 0 ; i < 3 ; ++i)
scale[i] = hi[i] - low[i];
static const double sqrt_3 = 1.732050808;
double s = std::max(std::max(scale[0], scale[1]), scale[2]) * sqrt_3;
// if the scale is less than 1mm, set it to default
if (s < 1e-3)
s = DEFAULT_SCALE;
return s;
}
void RobotInteraction::decideActiveVirtualJoints(const std::string &group)
{
active_vj_.clear();
if (group.empty())
return;
const boost::shared_ptr<const srdf::Model> &srdf = kmodel_->getSRDF();
const planning_models::KinematicModel::JointModelGroup *jmg = kmodel_->getJointModelGroup(group);
if (!jmg || !srdf)
return;
if (!jmg->hasJointModel(kmodel_->getRootJointName()))
return;
planning_models::KinematicState default_state(kmodel_);
default_state.setToDefaultValues();
std::vector<double> aabb;
default_state.computeAABB(aabb);
const std::vector<srdf::Model::VirtualJoint> &vj = srdf->getVirtualJoints();
for (std::size_t i = 0 ; i < vj.size() ; ++i)
if (vj[i].name_ == kmodel_->getRootJointName())
{
if (vj[i].type_ == "planar" || vj[i].type_ == "floating")
{
VirtualJoint v;
v.connecting_link = vj[i].child_link_;
v.joint_name = vj[i].name_;
if (vj[i].type_ == "planar")
v.dof = 3;
else
v.dof = 6;
// take the max of the X extent and the Y extent
v.scale = std::max(aabb[1] - aabb[0], aabb[3] - aabb[2]);
active_vj_.push_back(v);
}
}
}
void RobotInteraction::decideActiveEndEffectors(const std::string &group)
{
active_eef_.clear();
if (group.empty())
return;
const boost::shared_ptr<const srdf::Model> &srdf = kmodel_->getSRDF();
const planning_models::KinematicModel::JointModelGroup *jmg = kmodel_->getJointModelGroup(group);
if (!jmg || !srdf)
return;
const std::vector<srdf::Model::EndEffector> &eef = srdf->getEndEffectors();
const std::pair<planning_models::KinematicModel::SolverAllocatorFn, planning_models::KinematicModel::SolverAllocatorMapFn> &smap = jmg->getSolverAllocators();
// if we have an IK solver for the selected group, we check if there are any end effectors attached to this group
if (smap.first)
{
for (std::size_t i = 0 ; i < eef.size() ; ++i)
if (jmg->hasLinkModel(eef[i].parent_link_) && jmg->canSetStateFromIK(eef[i].parent_link_))
{
// we found an end-effector for the selected group
EndEffector ee;
ee.group = group;
ee.tip_link = eef[i].parent_link_;
ee.eef_group = eef[i].component_group_;
active_eef_.push_back(ee);
break;
}
}
else
if (!smap.second.empty())
{
for (std::map<const planning_models::KinematicModel::JointModelGroup*, planning_models::KinematicModel::SolverAllocatorFn>::const_iterator it = smap.second.begin() ;
it != smap.second.end() ; ++it)
{
for (std::size_t i = 0 ; i < eef.size() ; ++i)
if (it->first->hasLinkModel(eef[i].parent_link_) && it->first->canSetStateFromIK(eef[i].parent_link_))
{
// we found an end-effector for the selected group;
EndEffector ee;
ee.group = it->first->getName();
ee.tip_link = eef[i].parent_link_;
ee.eef_group = eef[i].component_group_;
active_eef_.push_back(ee);
break;
}
}
}
for (std::size_t i = 0 ; i < active_eef_.size() ; ++i)
{
active_eef_[i].scale = computeGroupScale(active_eef_[i].eef_group);
ROS_DEBUG("Found active end-effector '%s', of scale %lf", active_eef_[i].eef_group.c_str(), active_eef_[i].scale);
}
}
void RobotInteraction::clear(void)
{
active_eef_.clear();
active_vj_.clear();
clearInteractiveMarkers();
publishInteractiveMarkers();
}
void RobotInteraction::clearInteractiveMarkers(void)
{
shown_markers_.clear();
int_marker_server_->clear();
}
void RobotInteraction::addInteractiveMarkers(const planning_models::KinematicState &state, int id)
{
// ros::WallTime start = ros::WallTime::now();
for (std::size_t i = 0 ; i < active_eef_.size() ; ++i)
{
geometry_msgs::PoseStamped pose;
pose.header.frame_id = kmodel_->getModelFrame();
pose.header.stamp = ros::Time::now();
const planning_models::KinematicState::LinkState *ls = state.getLinkState(active_eef_[i].tip_link);
planning_models::msgFromPose(ls->getGlobalLinkTransform(), pose.pose);
std::string marker_name = "IK" + boost::lexical_cast<std::string>(id) + "_" + active_eef_[i].tip_link;
shown_markers_[marker_name] = i;
visualization_msgs::InteractiveMarker im = make6DOFMarker(marker_name, pose, active_eef_[i].scale);
if (handler_ && handler_->inError(active_eef_[i], id))
addErrorMarker(im);
int_marker_server_->insert(im);
int_marker_server_->setCallback(im.name, boost::bind(&RobotInteraction::processInteractiveMarkerFeedback, this, _1));
ROS_DEBUG("Publishing interactive marker %s (scale = %lf)", marker_name.c_str(), active_eef_[i].scale);
}
for (std::size_t i = 0 ; i < active_vj_.size() ; ++i)
if (active_vj_[i].dof == 3)
{
geometry_msgs::PoseStamped pose;
pose.header.frame_id = kmodel_->getModelFrame();
pose.header.stamp = ros::Time::now();
const planning_models::KinematicState::LinkState *ls = state.getLinkState(active_vj_[i].connecting_link);
planning_models::msgFromPose(ls->getGlobalLinkTransform(), pose.pose);
std::string marker_name = "XY" + boost::lexical_cast<std::string>(id) + "_" + active_vj_[i].connecting_link;
shown_markers_[marker_name] = i;
visualization_msgs::InteractiveMarker im = make3DOFMarker(marker_name, pose, active_vj_[i].scale);
int_marker_server_->insert(im);
int_marker_server_->setCallback(im.name, boost::bind(&RobotInteraction::processInteractiveMarkerFeedback, this, _1));
ROS_DEBUG("Publishing interactive marker %s (scale = %lf)", marker_name.c_str(), active_vj_[i].scale);
}
// ROS_INFO("Spent %0.5lf s to publish markers", (ros::WallTime::now() - start).toSec());
}
void RobotInteraction::publishInteractiveMarkers(void)
{
int_marker_server_->applyChanges();
}
bool RobotInteraction::updateState(planning_models::KinematicState &state, const VirtualJoint &vj, const geometry_msgs::Pose &pose)
{
Eigen::Quaterniond q;
if (!planning_models::quatFromMsg(pose.orientation, q))
return false;
std::map<std::string, double> vals;
vals[ vj.joint_name + "/x"] = pose.position.x;
vals[ vj.joint_name + "/y"] = pose.position.y;
Eigen::Vector3d xyz = q.matrix().eulerAngles(0, 1, 2);
vals[ vj.joint_name + "/theta"] = xyz[2];
state.getJointState(vj.joint_name)->setVariableValues(vals);
state.updateLinkTransforms();
return true;
}
bool RobotInteraction::updateState(planning_models::KinematicState &state, const EndEffector &eef, const geometry_msgs::Pose &pose)
{
static const double IK_TIMEOUT = 0.1;
return state.getJointStateGroup(eef.group)->setFromIK(pose, eef.tip_link, IK_TIMEOUT);
}
void RobotInteraction::processInteractiveMarkerFeedback(const visualization_msgs::InteractiveMarkerFeedbackConstPtr& feedback)
{
if (!handler_)
return;
std::map<std::string, std::size_t>::const_iterator it = shown_markers_.find(feedback->marker_name);
if (it == shown_markers_.end())
{
ROS_ERROR("Unknown marker name: '%s' (not published by RobotInteraction class)", feedback->marker_name.c_str());
return;
}
std::size_t u = feedback->marker_name.find_first_of("_");
if (u == std::string::npos || u < 3)
{
ROS_ERROR("Invalid marker name: '%s'", feedback->marker_name.c_str());
return;
}
std::string marker_class = feedback->marker_name.substr(0, 2);
int marker_id = 0;
try
{
marker_id = boost::lexical_cast<int>(feedback->marker_name.substr(2, u - 2));
}
catch(boost::bad_lexical_cast &ex)
{
ROS_ERROR("Invalid marker name ('%s') : %s", feedback->marker_name.c_str(), ex.what());
return;
}
if (marker_class == "IK")
handler_->handleEndEffector(active_eef_[it->second], marker_id, feedback);
else
if (marker_class == "XY")
handler_->handleVirtualJoint(active_vj_[it->second], marker_id, feedback);
else
ROS_ERROR("Unknown marker class ('%s') for marker '%s'", marker_class.c_str(), feedback->marker_name.c_str());
}
}
<|endoftext|> |
<commit_before>/// HEADER
#include <csapex_ros/ros_message_conversion.h>
/// COMPONENT
#include <csapex_ros/generic_ros_message.h>
#include <csapex/msg/generic_pointer_message.hpp>
/// PROJECT
#include <csapex/msg/io.h>
/// SYSTEM
#include <topic_tools/shape_shifter.h>
using namespace csapex;
RosMessageConversion::RosMessageConversion()
{
}
bool RosMessageConversion::isTopicTypeRegistered(const ros::master::TopicInfo &topic)
{
return converters_.find(topic.datatype) != converters_.end();
}
void RosMessageConversion::doRegisterConversion(const std::string& apex_type, const std::string& ros_type, Convertor::Ptr c)
{
ros_types_.push_back(ros_type);
converters_[ros_type] = c;
converters_inv_[apex_type] = c;
}
ros::Subscriber RosMessageConversion::subscribe(const ros::master::TopicInfo &topic, int queue, Callback output)
{
if(isTopicTypeRegistered(topic)) {
return converters_.at(topic.datatype)->subscribe(topic, queue, output);
} else {
std::shared_ptr<ros::NodeHandle> nh = ROSHandler::instance().nh();
if(!nh) {
throw std::runtime_error("no ros connection");
}
ros::SubscribeOptions ops;
ops.template init<topic_tools::ShapeShifter>(topic.name, queue, [output](const boost::shared_ptr<topic_tools::ShapeShifter const>& ros_msg) {
auto msg = std::make_shared<connection_types::GenericRosMessage>();
msg->value = shared_ptr_tools::to_std_shared(ros_msg);
if(msg->value) {
output(msg);
}
});
ops.transport_hints = ros::TransportHints();
return nh->subscribe(ops);
}
}
ros::Publisher RosMessageConversion::advertise(ConnectionType::ConstPtr type, const std::string &topic, int queue, bool latch)
{
auto gen_ros = std::dynamic_pointer_cast<connection_types::GenericRosMessage const>(type);
if(gen_ros) {
return advertiseGenericRos(gen_ros, topic, queue, latch);
} else {
std::map<std::string, Convertor::Ptr>::iterator it = converters_inv_.find(type->descriptiveName());
if(it == converters_inv_.end()) {
throw std::runtime_error(std::string("cannot advertise type ") + type->descriptiveName() + " on topic " + topic);
}
return it->second->advertise(topic, queue, latch);
}
}
ros::Publisher RosMessageConversion::advertiseGenericRos(const connection_types::GenericRosMessage::ConstPtr& gen_ros, const std::string &topic, int queue, bool latch)
{
if(!gen_ros->value) {
throw std::runtime_error("generic ros message is null");
}
std::shared_ptr<ros::NodeHandle> nh = ROSHandler::instance().nh();
if(!nh) {
throw std::runtime_error("no ros connection");
}
return gen_ros->value->advertise(*nh, topic, queue, latch);
}
void RosMessageConversion::publish(ros::Publisher &pub, ConnectionType::ConstPtr msg)
{
auto gen_ros = std::dynamic_pointer_cast<connection_types::GenericRosMessage const>(msg);
if(gen_ros) {
if(!gen_ros->value) {
throw std::runtime_error("generic ros message is null");
}
pub.publish(*gen_ros->value);
} else {
std::map<std::string, Convertor::Ptr>::iterator it = converters_inv_.find(msg->descriptiveName());
if(it == converters_inv_.end()) {
throw std::runtime_error(std::string("cannot publish message of type ") + msg->descriptiveName());
}
it->second->publish(pub, msg);
}
}
connection_types::Message::Ptr RosMessageConversion::instantiate(const rosbag::MessageInstance &source)
{
return converters_[source.getDataType()]->instantiate(source);
}
//std::vector<std::string> RosMessageConversion::getRegisteredRosTypes()
//{
// return ros_types_;
//}
void Convertor::publish_apex(Callback callback, ConnectionType::ConstPtr msg)
{
callback(msg);
}
<commit_msg>bugfix: rosbag import of unregistered message types was not implemetned<commit_after>/// HEADER
#include <csapex_ros/ros_message_conversion.h>
/// COMPONENT
#include <csapex_ros/generic_ros_message.h>
#include <csapex/msg/generic_pointer_message.hpp>
/// PROJECT
#include <csapex/msg/io.h>
/// SYSTEM
#include <topic_tools/shape_shifter.h>
using namespace csapex;
RosMessageConversion::RosMessageConversion()
{
}
bool RosMessageConversion::isTopicTypeRegistered(const ros::master::TopicInfo &topic)
{
return converters_.find(topic.datatype) != converters_.end();
}
void RosMessageConversion::doRegisterConversion(const std::string& apex_type, const std::string& ros_type, Convertor::Ptr c)
{
ros_types_.push_back(ros_type);
converters_[ros_type] = c;
converters_inv_[apex_type] = c;
}
ros::Subscriber RosMessageConversion::subscribe(const ros::master::TopicInfo &topic, int queue, Callback output)
{
if(isTopicTypeRegistered(topic)) {
return converters_.at(topic.datatype)->subscribe(topic, queue, output);
} else {
std::shared_ptr<ros::NodeHandle> nh = ROSHandler::instance().nh();
if(!nh) {
throw std::runtime_error("no ros connection");
}
ros::SubscribeOptions ops;
ops.template init<topic_tools::ShapeShifter>(topic.name, queue, [output](const boost::shared_ptr<topic_tools::ShapeShifter const>& ros_msg) {
auto msg = std::make_shared<connection_types::GenericRosMessage>();
msg->value = shared_ptr_tools::to_std_shared(ros_msg);
if(msg->value) {
output(msg);
}
});
ops.transport_hints = ros::TransportHints();
return nh->subscribe(ops);
}
}
ros::Publisher RosMessageConversion::advertise(ConnectionType::ConstPtr type, const std::string &topic, int queue, bool latch)
{
auto gen_ros = std::dynamic_pointer_cast<connection_types::GenericRosMessage const>(type);
if(gen_ros) {
return advertiseGenericRos(gen_ros, topic, queue, latch);
} else {
std::map<std::string, Convertor::Ptr>::iterator it = converters_inv_.find(type->descriptiveName());
if(it == converters_inv_.end()) {
throw std::runtime_error(std::string("cannot advertise type ") + type->descriptiveName() + " on topic " + topic);
}
return it->second->advertise(topic, queue, latch);
}
}
ros::Publisher RosMessageConversion::advertiseGenericRos(const connection_types::GenericRosMessage::ConstPtr& gen_ros, const std::string &topic, int queue, bool latch)
{
if(!gen_ros->value) {
throw std::runtime_error("generic ros message is null");
}
std::shared_ptr<ros::NodeHandle> nh = ROSHandler::instance().nh();
if(!nh) {
throw std::runtime_error("no ros connection");
}
return gen_ros->value->advertise(*nh, topic, queue, latch);
}
void RosMessageConversion::publish(ros::Publisher &pub, ConnectionType::ConstPtr msg)
{
auto gen_ros = std::dynamic_pointer_cast<connection_types::GenericRosMessage const>(msg);
if(gen_ros) {
if(!gen_ros->value) {
throw std::runtime_error("generic ros message is null");
}
pub.publish(*gen_ros->value);
} else {
std::map<std::string, Convertor::Ptr>::iterator it = converters_inv_.find(msg->descriptiveName());
if(it == converters_inv_.end()) {
throw std::runtime_error(std::string("cannot publish message of type ") + msg->descriptiveName());
}
it->second->publish(pub, msg);
}
}
connection_types::Message::Ptr RosMessageConversion::instantiate(const rosbag::MessageInstance &source)
{
auto pos = converters_.find(source.getDataType());
if(pos != converters_.end()) {
return pos->second->instantiate(source);
} else {
auto msg = std::make_shared<connection_types::GenericRosMessage>();
auto ros_msg = source.instantiate<topic_tools::ShapeShifter>();
msg->value = shared_ptr_tools::to_std_shared(ros_msg);
return msg;
}
}
//std::vector<std::string> RosMessageConversion::getRegisteredRosTypes()
//{
// return ros_types_;
//}
void Convertor::publish_apex(Callback callback, ConnectionType::ConstPtr msg)
{
callback(msg);
}
<|endoftext|> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.