text stringlengths 54 60.6k |
|---|
<commit_before>/*
* Copyright 2014 Open Connectome Project (http://openconnecto.me)
* Written by Da Zheng (zhengda1936@gmail.com)
*
* This file is part of FlashGraph.
*
* 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 <stdlib.h>
#include <malloc.h>
#include <boost/format.hpp>
#include "log.h"
#include "safs_file.h"
#include "cache.h"
#include "slab_allocator.h"
#include "native_file.h"
#include "in_mem_storage.h"
#include "graph_file_header.h"
using namespace safs;
namespace fg
{
class in_mem_byte_array: public page_byte_array
{
off_t off;
size_t size;
const char *pages;
void assign(in_mem_byte_array &arr) {
this->off = arr.off;
this->size = arr.size;
this->pages = arr.pages;
}
in_mem_byte_array(in_mem_byte_array &arr) {
assign(arr);
}
in_mem_byte_array &operator=(in_mem_byte_array &arr) {
assign(arr);
return *this;
}
public:
in_mem_byte_array(byte_array_allocator &alloc): page_byte_array(alloc) {
off = 0;
size = 0;
pages = NULL;
}
in_mem_byte_array(const io_request &req, char *pages,
byte_array_allocator &alloc): page_byte_array(alloc) {
this->off = req.get_offset();
this->size = req.get_size();
this->pages = pages;
}
virtual off_t get_offset() const {
return off;
}
virtual off_t get_offset_in_first_page() const {
return off % PAGE_SIZE;
}
virtual const char *get_page(int pg_idx) const {
return pages + pg_idx * PAGE_SIZE;
}
virtual size_t get_size() const {
return size;
}
void lock() {
ABORT_MSG("lock isn't implemented");
}
void unlock() {
ABORT_MSG("unlock isn't implemented");
}
page_byte_array *clone() {
in_mem_byte_array *arr = (in_mem_byte_array *) get_allocator().alloc();
*arr = *this;
return arr;
}
};
class in_mem_byte_array_allocator: public byte_array_allocator
{
class array_initiator: public obj_initiator<in_mem_byte_array>
{
in_mem_byte_array_allocator *alloc;
public:
array_initiator(in_mem_byte_array_allocator *alloc) {
this->alloc = alloc;
}
virtual void init(in_mem_byte_array *obj) {
new (obj) in_mem_byte_array(*alloc);
}
};
class array_destructor: public obj_destructor<in_mem_byte_array>
{
public:
void destroy(in_mem_byte_array *obj) {
obj->~in_mem_byte_array();
}
};
obj_allocator<in_mem_byte_array> allocator;
public:
in_mem_byte_array_allocator(thread *t): allocator(
"byte-array-allocator", t->get_node_id(), false, 1024 * 1024,
params.get_max_obj_alloc_size(),
obj_initiator<in_mem_byte_array>::ptr(new array_initiator(this)),
obj_destructor<in_mem_byte_array>::ptr(new array_destructor())) {
}
virtual page_byte_array *alloc() {
return allocator.alloc_obj();
}
virtual void free(page_byte_array *arr) {
allocator.free((in_mem_byte_array *) arr);
}
};
class in_mem_io: public io_interface
{
const in_mem_graph &graph;
int file_id;
fifo_queue<io_request> req_buf;
fifo_queue<user_compute *> compute_buf;
fifo_queue<user_compute *> incomp_computes;
std::unique_ptr<byte_array_allocator> array_allocator;
void process_req(const io_request &req);
void process_computes();
public:
in_mem_io(const in_mem_graph &_graph, int file_id,
thread *t): io_interface(t), graph(_graph), req_buf(
get_node_id(), 1024), compute_buf(get_node_id(), 1024,
true), incomp_computes(get_node_id(), 1024, true) {
this->file_id = file_id;
array_allocator = std::unique_ptr<byte_array_allocator>(
new in_mem_byte_array_allocator(t));
}
virtual int get_file_id() const {
return file_id;
}
virtual bool support_aio() {
return true;
}
virtual void flush_requests() { }
virtual int num_pending_ios() const {
return 0;
}
virtual io_status access(char *buf, off_t off, ssize_t size,
int access_method) {
assert(access_method == READ);
memcpy(buf, graph.graph_data + off, size);
return IO_OK;
}
virtual void access(io_request *requests, int num, io_status *status);
virtual int wait4complete(int) {
assert(compute_buf.is_empty());
if (!incomp_computes.is_empty()) {
compute_buf.add(&incomp_computes);
assert(incomp_computes.is_empty());
process_computes();
}
return 0;
}
};
enum
{
IN_QUEUE,
};
void in_mem_io::process_req(const io_request &req)
{
assert(req.get_req_type() == io_request::USER_COMPUTE);
in_mem_byte_array byte_arr(req,
graph.graph_data + ROUND_PAGE(req.get_offset()), *array_allocator);
user_compute *compute = req.get_compute();
compute->run(byte_arr);
// If the user compute hasn't completed and it's not in the queue,
// add it to the queue.
if (!compute->has_completed() && !compute->test_flag(IN_QUEUE)) {
compute->set_flag(IN_QUEUE, true);
if (compute_buf.is_full())
compute_buf.expand_queue(compute_buf.get_size() * 2);
compute_buf.push_back(compute);
}
else
compute->dec_ref();
if (compute->has_completed() && !compute->test_flag(IN_QUEUE)) {
assert(compute->get_ref() == 0);
// It might still be referenced by the graph engine.
if (compute->get_ref() == 0) {
compute_allocator *alloc = compute->get_allocator();
alloc->free(compute);
}
}
}
void in_mem_io::process_computes()
{
while (!compute_buf.is_empty()) {
user_compute *compute = compute_buf.pop_front();
assert(compute->get_ref() > 0);
while (compute->has_requests()) {
compute->fetch_requests(this, req_buf, req_buf.get_size());
while (!req_buf.is_empty()) {
io_request new_req = req_buf.pop_front();
process_req(new_req);
}
}
if (compute->has_completed()) {
compute->dec_ref();
compute->set_flag(IN_QUEUE, false);
assert(compute->get_ref() == 0);
if (compute->get_ref() == 0) {
compute_allocator *alloc = compute->get_allocator();
alloc->free(compute);
}
}
else
incomp_computes.push_back(compute);
}
}
void in_mem_io::access(io_request *requests, int num, io_status *)
{
for (int i = 0; i < num; i++) {
io_request &req = requests[i];
assert(req.get_req_type() == io_request::USER_COMPUTE);
// Let's possess a reference to the user compute first. process_req()
// will release the reference when the user compute is completed.
req.get_compute()->inc_ref();
process_req(req);
}
process_computes();
}
class in_mem_io_factory: public file_io_factory
{
const in_mem_graph &graph;
int file_id;
public:
in_mem_io_factory(const in_mem_graph &_graph, int file_id,
const std::string file_name): file_io_factory(file_name), graph(_graph) {
this->file_id = file_id;
}
virtual int get_file_id() const {
return file_id;
}
virtual io_interface::ptr create_io(thread *t) {
return io_interface::ptr(new in_mem_io(graph, file_id, t));
}
virtual void destroy_io(io_interface *) {
}
};
in_mem_graph::ptr in_mem_graph::load_graph(const std::string &file_name)
{
native_file local_f(file_name);
if (!local_f.exist())
throw io_exception(file_name + std::string(" doesn't exist"));
ssize_t size = local_f.get_size();
assert(size > 0);
in_mem_graph::ptr graph = in_mem_graph::ptr(new in_mem_graph());
graph->graph_size = size;
graph->graph_data = (char *) malloc(size);
assert(graph->graph_data);
graph->graph_file_name = file_name;
BOOST_LOG_TRIVIAL(info) << boost::format("load a graph of %1% bytes")
% graph->graph_size;
FILE *fd = fopen(file_name.c_str(), "r");
if (fd == NULL)
throw io_exception(std::string("can't open ") + file_name);
if (fread(graph->graph_data, size, 1, fd) != 1)
throw io_exception(std::string("can't read from ") + file_name);
fclose(fd);
graph_header *header = (graph_header *) graph->graph_data;
header->verify();
return graph;
}
in_mem_graph::ptr in_mem_graph::load_safs_graph(const std::string &file_name)
{
file_io_factory::shared_ptr io_factory = ::create_io_factory(file_name,
REMOTE_ACCESS);
in_mem_graph::ptr graph = in_mem_graph::ptr(new in_mem_graph());
graph->graph_size = io_factory->get_file_size();
size_t num_pages = ROUNDUP_PAGE(graph->graph_size) / PAGE_SIZE;
graph->graph_data = (char *) memalign(PAGE_SIZE, num_pages * PAGE_SIZE);
assert(graph->graph_data);
graph->graph_file_name = file_name;
BOOST_LOG_TRIVIAL(info) << boost::format("load a graph of %1% bytes")
% graph->graph_size;
#if 0
graph->graph_file_id = io_factory->get_file_id();
#endif
io_interface::ptr io = io_factory->create_io(thread::get_curr_thread());
const size_t MAX_IO_SIZE = 256 * 1024 * 1024;
for (off_t off = 0; (size_t) off < graph->graph_size; off += MAX_IO_SIZE) {
data_loc_t loc(io_factory->get_file_id(), off);
size_t req_size = min(MAX_IO_SIZE, graph->graph_size - off);
io_request req(graph->graph_data + off, loc, req_size, READ);
io->access(&req, 1);
io->wait4complete(1);
}
graph_header *header = (graph_header *) graph->graph_data;
header->verify();
return graph;
}
file_io_factory::shared_ptr in_mem_graph::create_io_factory() const
{
return file_io_factory::shared_ptr(new in_mem_io_factory(*this,
graph_file_id, graph_file_name));
}
}
<commit_msg>[Graph]: in-mem graph support async I/O with callback.<commit_after>/*
* Copyright 2014 Open Connectome Project (http://openconnecto.me)
* Written by Da Zheng (zhengda1936@gmail.com)
*
* This file is part of FlashGraph.
*
* 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 <stdlib.h>
#include <malloc.h>
#include <boost/format.hpp>
#include "log.h"
#include "safs_file.h"
#include "cache.h"
#include "slab_allocator.h"
#include "native_file.h"
#include "in_mem_storage.h"
#include "graph_file_header.h"
using namespace safs;
namespace fg
{
class in_mem_byte_array: public page_byte_array
{
off_t off;
size_t size;
const char *pages;
void assign(in_mem_byte_array &arr) {
this->off = arr.off;
this->size = arr.size;
this->pages = arr.pages;
}
in_mem_byte_array(in_mem_byte_array &arr) {
assign(arr);
}
in_mem_byte_array &operator=(in_mem_byte_array &arr) {
assign(arr);
return *this;
}
public:
in_mem_byte_array(byte_array_allocator &alloc): page_byte_array(alloc) {
off = 0;
size = 0;
pages = NULL;
}
in_mem_byte_array(const io_request &req, char *pages,
byte_array_allocator &alloc): page_byte_array(alloc) {
this->off = req.get_offset();
this->size = req.get_size();
this->pages = pages;
}
virtual off_t get_offset() const {
return off;
}
virtual off_t get_offset_in_first_page() const {
return off % PAGE_SIZE;
}
virtual const char *get_page(int pg_idx) const {
return pages + pg_idx * PAGE_SIZE;
}
virtual size_t get_size() const {
return size;
}
void lock() {
ABORT_MSG("lock isn't implemented");
}
void unlock() {
ABORT_MSG("unlock isn't implemented");
}
page_byte_array *clone() {
in_mem_byte_array *arr = (in_mem_byte_array *) get_allocator().alloc();
*arr = *this;
return arr;
}
};
class in_mem_byte_array_allocator: public byte_array_allocator
{
class array_initiator: public obj_initiator<in_mem_byte_array>
{
in_mem_byte_array_allocator *alloc;
public:
array_initiator(in_mem_byte_array_allocator *alloc) {
this->alloc = alloc;
}
virtual void init(in_mem_byte_array *obj) {
new (obj) in_mem_byte_array(*alloc);
}
};
class array_destructor: public obj_destructor<in_mem_byte_array>
{
public:
void destroy(in_mem_byte_array *obj) {
obj->~in_mem_byte_array();
}
};
obj_allocator<in_mem_byte_array> allocator;
public:
in_mem_byte_array_allocator(thread *t): allocator(
"byte-array-allocator", t->get_node_id(), false, 1024 * 1024,
params.get_max_obj_alloc_size(),
obj_initiator<in_mem_byte_array>::ptr(new array_initiator(this)),
obj_destructor<in_mem_byte_array>::ptr(new array_destructor())) {
}
virtual page_byte_array *alloc() {
return allocator.alloc_obj();
}
virtual void free(page_byte_array *arr) {
allocator.free((in_mem_byte_array *) arr);
}
};
class in_mem_io: public io_interface
{
const in_mem_graph &graph;
int file_id;
fifo_queue<io_request> req_buf;
fifo_queue<user_compute *> compute_buf;
fifo_queue<user_compute *> incomp_computes;
std::unique_ptr<byte_array_allocator> array_allocator;
callback *cb;
void process_req(const io_request &req);
void process_computes();
public:
in_mem_io(const in_mem_graph &_graph, int file_id,
thread *t): io_interface(t), graph(_graph), req_buf(
get_node_id(), 1024), compute_buf(get_node_id(), 1024,
true), incomp_computes(get_node_id(), 1024, true) {
this->file_id = file_id;
array_allocator = std::unique_ptr<byte_array_allocator>(
new in_mem_byte_array_allocator(t));
cb = NULL;
}
virtual int get_file_id() const {
return file_id;
}
virtual bool support_aio() {
return true;
}
virtual bool set_callback(callback *cb) {
this->cb = cb;
}
virtual callback *get_callback() {
return cb;
}
virtual void flush_requests() { }
virtual int num_pending_ios() const {
return 0;
}
virtual io_status access(char *buf, off_t off, ssize_t size,
int access_method) {
assert(access_method == READ);
memcpy(buf, graph.graph_data + off, size);
return IO_OK;
}
virtual void access(io_request *requests, int num, io_status *status);
virtual int wait4complete(int) {
assert(compute_buf.is_empty());
if (!incomp_computes.is_empty()) {
compute_buf.add(&incomp_computes);
assert(incomp_computes.is_empty());
process_computes();
}
return 0;
}
};
enum
{
IN_QUEUE,
};
void in_mem_io::process_req(const io_request &req)
{
assert(req.get_req_type() == io_request::USER_COMPUTE);
in_mem_byte_array byte_arr(req,
graph.graph_data + ROUND_PAGE(req.get_offset()), *array_allocator);
user_compute *compute = req.get_compute();
compute->run(byte_arr);
// If the user compute hasn't completed and it's not in the queue,
// add it to the queue.
if (!compute->has_completed() && !compute->test_flag(IN_QUEUE)) {
compute->set_flag(IN_QUEUE, true);
if (compute_buf.is_full())
compute_buf.expand_queue(compute_buf.get_size() * 2);
compute_buf.push_back(compute);
}
else
compute->dec_ref();
if (compute->has_completed() && !compute->test_flag(IN_QUEUE)) {
assert(compute->get_ref() == 0);
// It might still be referenced by the graph engine.
if (compute->get_ref() == 0) {
compute_allocator *alloc = compute->get_allocator();
alloc->free(compute);
}
}
}
void in_mem_io::process_computes()
{
while (!compute_buf.is_empty()) {
user_compute *compute = compute_buf.pop_front();
assert(compute->get_ref() > 0);
while (compute->has_requests()) {
compute->fetch_requests(this, req_buf, req_buf.get_size());
while (!req_buf.is_empty()) {
io_request new_req = req_buf.pop_front();
process_req(new_req);
}
}
if (compute->has_completed()) {
compute->dec_ref();
compute->set_flag(IN_QUEUE, false);
assert(compute->get_ref() == 0);
if (compute->get_ref() == 0) {
compute_allocator *alloc = compute->get_allocator();
alloc->free(compute);
}
}
else
incomp_computes.push_back(compute);
}
}
void in_mem_io::access(io_request *requests, int num, io_status *)
{
for (int i = 0; i < num; i++) {
io_request &req = requests[i];
if (req.get_req_type() == io_request::USER_COMPUTE) {
// Let's possess a reference to the user compute first. process_req()
// will release the reference when the user compute is completed.
req.get_compute()->inc_ref();
process_req(req);
}
else {
assert(req.get_req_type() == io_request::BASIC_REQ);
memcpy(req.get_buf(), graph.graph_data + req.get_offset(), req.get_size());
io_request *reqs[1];
reqs[0] = &req;
this->get_callback()->invoke(reqs, 1);
}
}
process_computes();
}
class in_mem_io_factory: public file_io_factory
{
const in_mem_graph &graph;
int file_id;
public:
in_mem_io_factory(const in_mem_graph &_graph, int file_id,
const std::string file_name): file_io_factory(file_name), graph(_graph) {
this->file_id = file_id;
}
virtual int get_file_id() const {
return file_id;
}
virtual io_interface::ptr create_io(thread *t) {
return io_interface::ptr(new in_mem_io(graph, file_id, t));
}
virtual void destroy_io(io_interface *) {
}
};
in_mem_graph::ptr in_mem_graph::load_graph(const std::string &file_name)
{
native_file local_f(file_name);
if (!local_f.exist())
throw io_exception(file_name + std::string(" doesn't exist"));
ssize_t size = local_f.get_size();
assert(size > 0);
in_mem_graph::ptr graph = in_mem_graph::ptr(new in_mem_graph());
graph->graph_size = size;
graph->graph_data = (char *) malloc(size);
assert(graph->graph_data);
graph->graph_file_name = file_name;
BOOST_LOG_TRIVIAL(info) << boost::format("load a graph of %1% bytes")
% graph->graph_size;
FILE *fd = fopen(file_name.c_str(), "r");
if (fd == NULL)
throw io_exception(std::string("can't open ") + file_name);
if (fread(graph->graph_data, size, 1, fd) != 1)
throw io_exception(std::string("can't read from ") + file_name);
fclose(fd);
graph_header *header = (graph_header *) graph->graph_data;
header->verify();
return graph;
}
in_mem_graph::ptr in_mem_graph::load_safs_graph(const std::string &file_name)
{
file_io_factory::shared_ptr io_factory = ::create_io_factory(file_name,
REMOTE_ACCESS);
in_mem_graph::ptr graph = in_mem_graph::ptr(new in_mem_graph());
graph->graph_size = io_factory->get_file_size();
size_t num_pages = ROUNDUP_PAGE(graph->graph_size) / PAGE_SIZE;
graph->graph_data = (char *) memalign(PAGE_SIZE, num_pages * PAGE_SIZE);
assert(graph->graph_data);
graph->graph_file_name = file_name;
BOOST_LOG_TRIVIAL(info) << boost::format("load a graph of %1% bytes")
% graph->graph_size;
#if 0
graph->graph_file_id = io_factory->get_file_id();
#endif
io_interface::ptr io = io_factory->create_io(thread::get_curr_thread());
const size_t MAX_IO_SIZE = 256 * 1024 * 1024;
for (off_t off = 0; (size_t) off < graph->graph_size; off += MAX_IO_SIZE) {
data_loc_t loc(io_factory->get_file_id(), off);
size_t req_size = min(MAX_IO_SIZE, graph->graph_size - off);
io_request req(graph->graph_data + off, loc, req_size, READ);
io->access(&req, 1);
io->wait4complete(1);
}
graph_header *header = (graph_header *) graph->graph_data;
header->verify();
return graph;
}
file_io_factory::shared_ptr in_mem_graph::create_io_factory() const
{
return file_io_factory::shared_ptr(new in_mem_io_factory(*this,
graph_file_id, graph_file_name));
}
}
<|endoftext|> |
<commit_before>#include "Connection.h"
#include "StableHeaders.h"
#include "RexLogicModule.h" // chat
#include "RexProtocolMsgIDs.h"
#include "OpensimProtocolModule.h"
#include "ConnectionProvider.h"
namespace OpensimIM
{
Connection::Connection(Foundation::Framework* framework, const QString &agentID)
: framework_(framework), agent_uuid_(agentID), name_(""), protocol_(OPENSIM_IM_PROTOCOL), server_(""), reason_("")
{
// OpensimIM connection is automatically established when connected to world so
// initial state is always STATE_READY
state_ = STATE_OPEN;
RequestFriendlist();
RegisterConsoleCommands();
OpenWorldChatSession();
}
Connection::~Connection()
{
for( ChatSessionVector::iterator i = public_chat_sessions_.begin(); i != public_chat_sessions_.end(); ++i)
{
delete (*i);
*i = NULL;
}
public_chat_sessions_.clear();
for( ChatSessionVector::iterator i = im_chat_sessions_.begin(); i != im_chat_sessions_.end(); ++i)
{
delete *i;
*i = NULL;
}
im_chat_sessions_.clear();
for( ContactVector::iterator i = contacts_.begin(); i != contacts_.end(); ++i)
{
delete *i;
*i = NULL;
}
contacts_.clear();
state_ = STATE_CLOSED;
}
QString Connection::GetName() const
{
return name_;
}
QString Connection::GetProtocol() const
{
return protocol_;
}
Communication::ConnectionInterface::State Connection::GetState() const
{
return state_;
}
QString Connection::GetServer() const
{
return server_;
}
QString Connection::GetUserID() const
{
return agent_uuid_;
}
QString Connection::GetReason() const
{
return reason_;
}
Communication::ContactGroupInterface& Connection::GetContacts()
{
if (state_ != STATE_OPEN)
throw Core::Exception("The connection is closed.");
return friend_list_;
}
QStringList Connection::GetPresenceStatusOptionsForContact() const
{
if (state_ != STATE_OPEN)
throw Core::Exception("The connection is closed.");
QStringList options;
//! Opensim provides just two online state options
options.append("online");
options.append("offline");
return QStringList();
}
QStringList Connection::GetPresenceStatusOptionsForUser() const
{
if (state_ != STATE_OPEN)
throw Core::Exception("The connection is closed.");
// In Opensim user cannot set the presence status
QStringList options;
return QStringList();
}
Communication::ChatSessionInterface* Connection::OpenPrivateChatSession(const Communication::ContactInterface &contact)
{
if (state_ != STATE_OPEN)
throw Core::Exception("The connection is closed.");
return OpenPrivateChatSession( contact.GetID() );
}
Communication::ChatSessionInterface* Connection::OpenPrivateChatSession(const QString &user_id)
{
if (state_ != STATE_OPEN)
throw Core::Exception("The connection is closed.");
ChatSession* session = GetPrivateChatSession(user_id);
if (!session)
{
session = new ChatSession(framework_, user_id, false);
im_chat_sessions_.push_back(session);
}
return session;
}
Communication::ChatSessionInterface* Connection::OpenChatSession(const QString &channel)
{
if (state_ != STATE_OPEN)
throw Core::Exception("The connection is closed.");
for (ChatSessionVector::iterator i = public_chat_sessions_.begin(); i != public_chat_sessions_.end(); ++i)
{
if ( (*i)->GetID().compare( channel ) == 0 )
{
return (*i);
}
}
ChatSession* session = new ChatSession(framework_, channel, true);
public_chat_sessions_.push_back(session);
return session;
}
Communication::VoiceSessionInterface* Connection::OpenVoiceSession(const Communication::ContactInterface &contact)
{
//! @todo IMPLEMENT
return NULL;
}
void Connection::SendFriendRequest(const QString &target, const QString &message)
{
if (state_ != STATE_OPEN)
throw Core::Exception("Cannot send text message, the connection is closed.");
RexLogic::RexLogicModule *rexlogic_ = dynamic_cast<RexLogic::RexLogicModule *>(framework_->GetModuleManager()->GetModule(Foundation::Module::MT_WorldLogic).lock().get());
if (rexlogic_ == NULL)
throw Core::Exception("Cannot send text message, RexLogicModule is not found");
RexLogic::RexServerConnectionPtr connection = rexlogic_->GetServerConnection();
if ( connection == NULL )
throw Core::Exception("Cannot send text message, rex server connection is not found");
if ( !connection->IsConnected() )
throw Core::Exception("Cannot send text message, rex server connection is not established");
connection->SendFormFriendshipPacket(RexTypes::RexUUID( target.toStdString() ));
}
Communication::FriendRequestVector Connection::GetFriendRequests() const
{
return Communication::FriendRequestVector();
}
void Connection::SetPresenceStatus(const QString &status)
{
//! Not supported by Opensim
}
void Connection::SetPresenceMessage(const QString &message)
{
//! Not supported by Opensim
}
void Connection::Close()
{
state_ = STATE_CLOSED;
emit ConnectionClosed( *this );
}
void Connection::RegisterConsoleCommands()
{
boost::shared_ptr<Console::CommandService> console_service = framework_->GetService<Console::CommandService>(Foundation::Service::ST_ConsoleCommand).lock();
if ( !console_service )
{
LogError("Cannot register console commands :command service not found.");
return;
}
}
void Connection::RequestFriendlist()
{
OpenSimProtocol::OpenSimProtocolModule *opensim_protocol_ = dynamic_cast<OpenSimProtocol::OpenSimProtocolModule *>(framework_->GetModuleManager()->GetModule(Foundation::Module::MT_OpenSimProtocol).lock().get());
if ( !opensim_protocol_ )
return;
OpenSimProtocol::BuddyListPtr buddy_list = opensim_protocol_->GetClientParameters().buddy_list;
OpenSimProtocol::BuddyVector buddies = buddy_list->GetBuddies();
for (OpenSimProtocol::BuddyVector::iterator i = buddies.begin(); i != buddies.end(); ++i)
{
//! @todo Fetch name of this buddy
Contact* contact = new Contact( (*i)->GetID().ToString().c_str(), "" );
friend_list_.AddContact(contact);
contacts_.push_back(contact);
}
}
bool Connection::HandleNetworkEvent(Foundation::EventDataInterface* data)
{
OpenSimProtocol::NetworkEventInboundData *event_data = dynamic_cast<OpenSimProtocol::NetworkEventInboundData *>(data);
if (!event_data)
return false;
const NetMsgID msgID = event_data->messageID;
NetInMessage *msg = event_data->message;
switch(msgID)
{
case RexNetMsgChatFromSimulator: return HandleOSNEChatFromSimulator(*msg); break;
case RexNetMsgImprovedInstantMessage: return HandleRexNetMsgImprovedInstantMessage(*msg); break;
// case RexNetMsgTerminateFriendship: return false; break;
// case RexNetMsgDeclineFriendship: return false;
case RexNetMsgOnlineNotification: return HandleOnlineNotification(*msg); break;
case RexNetMsgOfflineNotification: return HandleOfflineNotification(*msg); break;
}
return false;
}
bool Connection::HandleRexNetMsgImprovedInstantMessage(NetInMessage& msg)
{
try
{
msg.ResetReading();
RexTypes::RexUUID agent_id = msg.ReadUUID();
RexTypes::RexUUID session_id = msg.ReadUUID();
bool is_group_message = msg.ReadBool();
RexTypes::RexUUID to_agent_id = msg.ReadUUID();
msg.SkipToNextVariable(); // ParentEstateID
RexTypes::RexUUID region_id = msg.ReadUUID();
RexTypes::Vector3 position = msg.ReadVector3();
int offline = msg.ReadU8();
int dialog_type = msg.ReadU8();
RexTypes::RexUUID id = msg.ReadUUID();
msg.SkipToNextVariable(); // Timestamp
std::string from_agent_name = msg.ReadString();
std::string message = msg.ReadString();
msg.SkipToNextVariable(); // BinaryBucket
switch (dialog_type)
{
case DT_FriendshipOffered:
{
QString calling_card_folder = ""; //! @todo get the right value
FriendRequest* request = new FriendRequest(framework_, agent_id.ToString().c_str(), from_agent_name.c_str(), calling_card_folder);
friend_requests_.push_back(request);
emit( FriendRequestReceived(*request) );
}
break;
case DT_MessageFromAgent:
{
QString from_id = agent_id.ToString().c_str();
OnIMMessage( from_id, QString(from_agent_name.c_str()), QString( message.c_str() ) );
}
break;
case DT_FriendshipAccepted:
{
QString from_id = agent_id.ToString().c_str();
OnFriendshipAccepted(from_id);
}
break;
case DT_FriendshipDeclined:
{
QString from_id = agent_id.ToString().c_str();
OnFriendshipDeclined(from_id);
}
break;
}
}
catch(NetMessageException)
{
return false;
}
return true;
}
bool Connection::HandleNetworkStateEvent(Foundation::EventDataInterface* data)
{
return false;
}
bool Connection::HandleOSNEChatFromSimulator(NetInMessage& msg)
{
try
{
msg.ResetReading();
std::size_t size = 0;
const boost::uint8_t* buffer = msg.ReadBuffer(&size);
std::string from_name = std::string((char*)buffer);
RexTypes::RexUUID source = msg.ReadUUID();
RexTypes::RexUUID object_owner = msg.ReadUUID();
ChatSourceType source_type = static_cast<ChatSourceType>( msg.ReadU8() );
ChatType chat_type = static_cast<ChatType>( msg.ReadU8() );
ChatAudibleLevel audible = static_cast<ChatAudibleLevel>( msg.ReadU8() );
RexTypes::Vector3 position = msg.ReadVector3();
std::string message = msg.ReadString();
if ( message.size() > 0 )
{
for (ChatSessionVector::iterator i = public_chat_sessions_.begin(); i != public_chat_sessions_.end(); ++i)
{
if ( (*i)->GetID().compare("0") != 0 )
continue;
QString source_uuid = source.ToString().c_str();
QString source_name = from_name.c_str();
QString message_text = message.c_str();
switch (source_type)
{
case Connection::Agent:
case Connection::Object:
case Connection::System:
(*i)->MessageFromAgent(source_uuid, source_name, message_text);
break;
}
}
}
}
catch(NetMessageException /*&e*/)
{
return false;
}
return true;
}
bool Connection::HandleOnlineNotification(NetInMessage& msg)
{
msg.ResetReading();
size_t instance_count = msg.ReadCurrentBlockInstanceCount();
for (int i = 0; i < instance_count; ++i)
{
QString agent_id = msg.ReadUUID().ToString().c_str();
for (ContactVector::iterator i = contacts_.begin(); i != contacts_.end(); ++i)
{
if ((*i)->GetID().compare(agent_id) == 0)
(*i)->SetOnlineStatus(true);
}
}
return false;
}
bool Connection::HandleOfflineNotification(NetInMessage& msg)
{
msg.ResetReading();
size_t instance_count = msg.ReadCurrentBlockInstanceCount();
for (int i = 0; i < instance_count; ++i)
{
QString agent_id = msg.ReadUUID().ToString().c_str();
for (ContactVector::iterator i = contacts_.begin(); i != contacts_.end(); ++i)
{
if ((*i)->GetID().compare(agent_id) == 0)
(*i)->SetOnlineStatus(false);
}
}
return false;
}
void Connection::OpenWorldChatSession()
{
Communication::ChatSessionInterface* world_chat = OpenChatSession("0");
connect( world_chat, SIGNAL(MessageReceived(const QString&, const Communication::ChatSessionParticipantInterface&)), SLOT(OnWorldChatMessageReceived(const QString&, const Communication::ChatSessionParticipantInterface&)) );
}
void Connection::OnWorldChatMessageReceived(const QString& text, const Communication::ChatSessionParticipantInterface& participant)
{
QString message = "OpensimIM, public chat: ";
message.append( participant.GetName() );
message.append(" : ");
message.append( text );
LogDebug( message.toStdString() );
}
void Connection::OnIMMessage(const QString &from_id, const QString &from_name, const QString &text)
{
ChatSession* session = GetPrivateChatSession(from_id);
if ( !session )
{
// This IM message was first from this user
session = new ChatSession(framework_, from_id, false);
im_chat_sessions_.push_back(session);
}
session->MessageFromAgent(from_id, from_name, text);
}
ChatSession* Connection::GetPrivateChatSession(const QString &user_id)
{
for (ChatSessionVector::iterator i = im_chat_sessions_.begin(); i != im_chat_sessions_.end(); ++i)
{
Communication::ChatSessionParticipantVector participants = (*i)->GetParticipants();
assert( participants.size() == 1); // Opensim IM chat sessions are always between two user
Communication::ChatSessionParticipantInterface* participant = participants[0];
if ( participant->GetID().compare(user_id) == 0 )
{
return (*i);
}
}
return NULL;
}
void Connection::OnFriendshipAccepted(const QString &from_id)
{
Contact* contact = new Contact(from_id, "");
contacts_.push_back(contact);
friend_list_.AddContact(contact);
emit( FriendRequestAccepted(from_id) );
}
void Connection::OnFriendshipDeclined(const QString &from_id)
{
emit( FriendRequestRejected(from_id) );
}
} // end of namespace: OpensimIM
<commit_msg>Fix: Opensim world-chat didn't work after relogin to a world.<commit_after>#include "Connection.h"
#include "StableHeaders.h"
#include "RexLogicModule.h" // chat
#include "RexProtocolMsgIDs.h"
#include "OpensimProtocolModule.h"
#include "ConnectionProvider.h"
namespace OpensimIM
{
Connection::Connection(Foundation::Framework* framework, const QString &agentID)
: framework_(framework), agent_uuid_(agentID), name_(""), protocol_(OPENSIM_IM_PROTOCOL), server_(""), reason_("")
{
// OpensimIM connection is automatically established when connected to world so
// initial state is always STATE_READY
state_ = STATE_OPEN;
RequestFriendlist();
RegisterConsoleCommands();
OpenWorldChatSession();
}
Connection::~Connection()
{
for( ChatSessionVector::iterator i = public_chat_sessions_.begin(); i != public_chat_sessions_.end(); ++i)
{
delete (*i);
*i = NULL;
}
public_chat_sessions_.clear();
for( ChatSessionVector::iterator i = im_chat_sessions_.begin(); i != im_chat_sessions_.end(); ++i)
{
delete *i;
*i = NULL;
}
im_chat_sessions_.clear();
for( ContactVector::iterator i = contacts_.begin(); i != contacts_.end(); ++i)
{
delete *i;
*i = NULL;
}
contacts_.clear();
state_ = STATE_CLOSED;
}
QString Connection::GetName() const
{
return name_;
}
QString Connection::GetProtocol() const
{
return protocol_;
}
Communication::ConnectionInterface::State Connection::GetState() const
{
return state_;
}
QString Connection::GetServer() const
{
return server_;
}
QString Connection::GetUserID() const
{
return agent_uuid_;
}
QString Connection::GetReason() const
{
return reason_;
}
Communication::ContactGroupInterface& Connection::GetContacts()
{
if (state_ != STATE_OPEN)
throw Core::Exception("The connection is closed.");
return friend_list_;
}
QStringList Connection::GetPresenceStatusOptionsForContact() const
{
if (state_ != STATE_OPEN)
throw Core::Exception("The connection is closed.");
QStringList options;
//! Opensim provides just two online state options
options.append("online");
options.append("offline");
return QStringList();
}
QStringList Connection::GetPresenceStatusOptionsForUser() const
{
if (state_ != STATE_OPEN)
throw Core::Exception("The connection is closed.");
// In Opensim user cannot set the presence status
QStringList options;
return QStringList();
}
Communication::ChatSessionInterface* Connection::OpenPrivateChatSession(const Communication::ContactInterface &contact)
{
if (state_ != STATE_OPEN)
throw Core::Exception("The connection is closed.");
return OpenPrivateChatSession( contact.GetID() );
}
Communication::ChatSessionInterface* Connection::OpenPrivateChatSession(const QString &user_id)
{
if (state_ != STATE_OPEN)
throw Core::Exception("The connection is closed.");
ChatSession* session = GetPrivateChatSession(user_id);
if (!session)
{
session = new ChatSession(framework_, user_id, false);
im_chat_sessions_.push_back(session);
}
return session;
}
Communication::ChatSessionInterface* Connection::OpenChatSession(const QString &channel)
{
if (state_ != STATE_OPEN)
throw Core::Exception("The connection is closed.");
for (ChatSessionVector::iterator i = public_chat_sessions_.begin(); i != public_chat_sessions_.end(); ++i)
{
if ( (*i)->GetID().compare( channel ) == 0 )
{
return (*i);
}
}
ChatSession* session = new ChatSession(framework_, channel, true);
public_chat_sessions_.push_back(session);
return session;
}
Communication::VoiceSessionInterface* Connection::OpenVoiceSession(const Communication::ContactInterface &contact)
{
//! @todo IMPLEMENT
return NULL;
}
void Connection::SendFriendRequest(const QString &target, const QString &message)
{
if (state_ != STATE_OPEN)
throw Core::Exception("Cannot send text message, the connection is closed.");
RexLogic::RexLogicModule *rexlogic_ = dynamic_cast<RexLogic::RexLogicModule *>(framework_->GetModuleManager()->GetModule(Foundation::Module::MT_WorldLogic).lock().get());
if (rexlogic_ == NULL)
throw Core::Exception("Cannot send text message, RexLogicModule is not found");
RexLogic::RexServerConnectionPtr connection = rexlogic_->GetServerConnection();
if ( connection == NULL )
throw Core::Exception("Cannot send text message, rex server connection is not found");
if ( !connection->IsConnected() )
throw Core::Exception("Cannot send text message, rex server connection is not established");
connection->SendFormFriendshipPacket(RexTypes::RexUUID( target.toStdString() ));
}
Communication::FriendRequestVector Connection::GetFriendRequests() const
{
return Communication::FriendRequestVector();
}
void Connection::SetPresenceStatus(const QString &status)
{
//! Not supported by Opensim
}
void Connection::SetPresenceMessage(const QString &message)
{
//! Not supported by Opensim
}
void Connection::Close()
{
state_ = STATE_CLOSED;
emit ConnectionClosed( *this );
}
void Connection::RegisterConsoleCommands()
{
boost::shared_ptr<Console::CommandService> console_service = framework_->GetService<Console::CommandService>(Foundation::Service::ST_ConsoleCommand).lock();
if ( !console_service )
{
LogError("Cannot register console commands :command service not found.");
return;
}
}
void Connection::RequestFriendlist()
{
OpenSimProtocol::OpenSimProtocolModule *opensim_protocol_ = dynamic_cast<OpenSimProtocol::OpenSimProtocolModule *>(framework_->GetModuleManager()->GetModule(Foundation::Module::MT_OpenSimProtocol).lock().get());
if ( !opensim_protocol_ )
return;
OpenSimProtocol::BuddyListPtr buddy_list = opensim_protocol_->GetClientParameters().buddy_list;
OpenSimProtocol::BuddyVector buddies = buddy_list->GetBuddies();
for (OpenSimProtocol::BuddyVector::iterator i = buddies.begin(); i != buddies.end(); ++i)
{
//! @todo Fetch name of this buddy
Contact* contact = new Contact( (*i)->GetID().ToString().c_str(), "" );
friend_list_.AddContact(contact);
contacts_.push_back(contact);
}
}
bool Connection::HandleNetworkEvent(Foundation::EventDataInterface* data)
{
OpenSimProtocol::NetworkEventInboundData *event_data = dynamic_cast<OpenSimProtocol::NetworkEventInboundData *>(data);
if (!event_data)
return false;
const NetMsgID msgID = event_data->messageID;
NetInMessage *msg = event_data->message;
switch(msgID)
{
case RexNetMsgChatFromSimulator: return HandleOSNEChatFromSimulator(*msg); break;
case RexNetMsgImprovedInstantMessage: return HandleRexNetMsgImprovedInstantMessage(*msg); break;
// case RexNetMsgTerminateFriendship: return false; break;
// case RexNetMsgDeclineFriendship: return false;
case RexNetMsgOnlineNotification: return HandleOnlineNotification(*msg); break;
case RexNetMsgOfflineNotification: return HandleOfflineNotification(*msg); break;
}
return false;
}
bool Connection::HandleRexNetMsgImprovedInstantMessage(NetInMessage& msg)
{
try
{
msg.ResetReading();
RexTypes::RexUUID agent_id = msg.ReadUUID();
RexTypes::RexUUID session_id = msg.ReadUUID();
bool is_group_message = msg.ReadBool();
RexTypes::RexUUID to_agent_id = msg.ReadUUID();
msg.SkipToNextVariable(); // ParentEstateID
RexTypes::RexUUID region_id = msg.ReadUUID();
RexTypes::Vector3 position = msg.ReadVector3();
int offline = msg.ReadU8();
int dialog_type = msg.ReadU8();
RexTypes::RexUUID id = msg.ReadUUID();
msg.SkipToNextVariable(); // Timestamp
std::string from_agent_name = msg.ReadString();
std::string message = msg.ReadString();
msg.SkipToNextVariable(); // BinaryBucket
switch (dialog_type)
{
case DT_FriendshipOffered:
{
QString calling_card_folder = ""; //! @todo get the right value
FriendRequest* request = new FriendRequest(framework_, agent_id.ToString().c_str(), from_agent_name.c_str(), calling_card_folder);
friend_requests_.push_back(request);
emit( FriendRequestReceived(*request) );
}
break;
case DT_MessageFromAgent:
{
QString from_id = agent_id.ToString().c_str();
OnIMMessage( from_id, QString(from_agent_name.c_str()), QString( message.c_str() ) );
}
break;
case DT_FriendshipAccepted:
{
QString from_id = agent_id.ToString().c_str();
OnFriendshipAccepted(from_id);
}
break;
case DT_FriendshipDeclined:
{
QString from_id = agent_id.ToString().c_str();
OnFriendshipDeclined(from_id);
}
break;
}
}
catch(NetMessageException)
{
return false;
}
return false;
}
bool Connection::HandleNetworkStateEvent(Foundation::EventDataInterface* data)
{
return false;
}
bool Connection::HandleOSNEChatFromSimulator(NetInMessage& msg)
{
try
{
msg.ResetReading();
std::size_t size = 0;
const boost::uint8_t* buffer = msg.ReadBuffer(&size);
std::string from_name = std::string((char*)buffer);
RexTypes::RexUUID source = msg.ReadUUID();
RexTypes::RexUUID object_owner = msg.ReadUUID();
ChatSourceType source_type = static_cast<ChatSourceType>( msg.ReadU8() );
ChatType chat_type = static_cast<ChatType>( msg.ReadU8() );
ChatAudibleLevel audible = static_cast<ChatAudibleLevel>( msg.ReadU8() );
RexTypes::Vector3 position = msg.ReadVector3();
std::string message = msg.ReadString();
if ( message.size() > 0 )
{
for (ChatSessionVector::iterator i = public_chat_sessions_.begin(); i != public_chat_sessions_.end(); ++i)
{
if ( (*i)->GetID().compare("0") != 0 )
continue;
QString source_uuid = source.ToString().c_str();
QString source_name = from_name.c_str();
QString message_text = message.c_str();
switch (source_type)
{
case Connection::Agent:
case Connection::Object:
case Connection::System:
(*i)->MessageFromAgent(source_uuid, source_name, message_text);
break;
}
}
}
}
catch(NetMessageException /*&e*/)
{
return false;
}
return false;
}
bool Connection::HandleOnlineNotification(NetInMessage& msg)
{
msg.ResetReading();
size_t instance_count = msg.ReadCurrentBlockInstanceCount();
for (int i = 0; i < instance_count; ++i)
{
QString agent_id = msg.ReadUUID().ToString().c_str();
for (ContactVector::iterator i = contacts_.begin(); i != contacts_.end(); ++i)
{
if ((*i)->GetID().compare(agent_id) == 0)
(*i)->SetOnlineStatus(true);
}
}
return false;
}
bool Connection::HandleOfflineNotification(NetInMessage& msg)
{
msg.ResetReading();
size_t instance_count = msg.ReadCurrentBlockInstanceCount();
for (int i = 0; i < instance_count; ++i)
{
QString agent_id = msg.ReadUUID().ToString().c_str();
for (ContactVector::iterator i = contacts_.begin(); i != contacts_.end(); ++i)
{
if ((*i)->GetID().compare(agent_id) == 0)
(*i)->SetOnlineStatus(false);
}
}
return false;
}
void Connection::OpenWorldChatSession()
{
Communication::ChatSessionInterface* world_chat = OpenChatSession("0");
connect( world_chat, SIGNAL(MessageReceived(const QString&, const Communication::ChatSessionParticipantInterface&)), SLOT(OnWorldChatMessageReceived(const QString&, const Communication::ChatSessionParticipantInterface&)) );
}
void Connection::OnWorldChatMessageReceived(const QString& text, const Communication::ChatSessionParticipantInterface& participant)
{
QString message = "OpensimIM, public chat: ";
message.append( participant.GetName() );
message.append(" : ");
message.append( text );
LogDebug( message.toStdString() );
}
void Connection::OnIMMessage(const QString &from_id, const QString &from_name, const QString &text)
{
ChatSession* session = GetPrivateChatSession(from_id);
if ( !session )
{
// This IM message was first from this user
session = new ChatSession(framework_, from_id, false);
im_chat_sessions_.push_back(session);
}
session->MessageFromAgent(from_id, from_name, text);
}
ChatSession* Connection::GetPrivateChatSession(const QString &user_id)
{
for (ChatSessionVector::iterator i = im_chat_sessions_.begin(); i != im_chat_sessions_.end(); ++i)
{
Communication::ChatSessionParticipantVector participants = (*i)->GetParticipants();
assert( participants.size() == 1); // Opensim IM chat sessions are always between two user
Communication::ChatSessionParticipantInterface* participant = participants[0];
if ( participant->GetID().compare(user_id) == 0 )
{
return (*i);
}
}
return NULL;
}
void Connection::OnFriendshipAccepted(const QString &from_id)
{
Contact* contact = new Contact(from_id, "");
contacts_.push_back(contact);
friend_list_.AddContact(contact);
emit( FriendRequestAccepted(from_id) );
}
void Connection::OnFriendshipDeclined(const QString &from_id)
{
emit( FriendRequestRejected(from_id) );
}
} // end of namespace: OpensimIM
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "documentfocuslistener.hxx"
#include <com/sun/star/accessibility/XAccessibleEventBroadcaster.hpp>
#include <com/sun/star/accessibility/AccessibleEventId.hpp>
#include <com/sun/star/accessibility/AccessibleStateType.hpp>
using namespace ::com::sun::star::accessibility;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::uno;
//------------------------------------------------------------------------------
DocumentFocusListener::DocumentFocusListener(AquaA11yFocusTracker& rTracker) :
m_aFocusTracker(rTracker)
{
}
//------------------------------------------------------------------------------
void SAL_CALL
DocumentFocusListener::disposing( const EventObject& aEvent )
throw (RuntimeException)
{
// Unref the object here, but do not remove as listener since the object
// might no longer be in a state that safely allows this.
if( aEvent.Source.is() )
m_aRefList.erase(aEvent.Source);
}
//------------------------------------------------------------------------------
void SAL_CALL
DocumentFocusListener::notifyEvent( const AccessibleEventObject& aEvent )
throw( RuntimeException )
{
switch( aEvent.EventId )
{
case AccessibleEventId::STATE_CHANGED:
try
{
sal_Int16 nState = AccessibleStateType::INVALID;
aEvent.NewValue >>= nState;
if( AccessibleStateType::FOCUSED == nState )
m_aFocusTracker.setFocusedObject( getAccessible(aEvent) );
}
catch(const IndexOutOfBoundsException &e)
{
OSL_TRACE("Focused object has invalid index in parent");
}
break;
case AccessibleEventId::CHILD:
{
Reference< XAccessible > xChild;
if( (aEvent.OldValue >>= xChild) && xChild.is() )
detachRecursive(xChild);
if( (aEvent.NewValue >>= xChild) && xChild.is() )
attachRecursive(xChild);
}
break;
case AccessibleEventId::INVALIDATE_ALL_CHILDREN:
{
Reference< XAccessible > xAccessible( getAccessible(aEvent) );
detachRecursive(xAccessible);
attachRecursive(xAccessible);
}
OSL_TRACE( "Invalidate all children called\n" );
break;
default:
break;
}
}
//------------------------------------------------------------------------------
Reference< XAccessible > DocumentFocusListener::getAccessible(const EventObject& aEvent )
throw (IndexOutOfBoundsException, RuntimeException)
{
Reference< XAccessible > xAccessible(aEvent.Source, UNO_QUERY);
if( xAccessible.is() )
return xAccessible;
Reference< XAccessibleContext > xContext(aEvent.Source, UNO_QUERY);
if( xContext.is() )
{
Reference< XAccessible > xParent( xContext->getAccessibleParent() );
if( xParent.is() )
{
Reference< XAccessibleContext > xParentContext( xParent->getAccessibleContext() );
if( xParentContext.is() )
{
return xParentContext->getAccessibleChild( xContext->getAccessibleIndexInParent() );
}
}
}
return Reference< XAccessible >();
}
//------------------------------------------------------------------------------
void DocumentFocusListener::attachRecursive(const Reference< XAccessible >& xAccessible)
throw (IndexOutOfBoundsException, RuntimeException)
{
Reference< XAccessibleContext > xContext = xAccessible->getAccessibleContext();
if( xContext.is() )
attachRecursive(xAccessible, xContext);
}
//------------------------------------------------------------------------------
void DocumentFocusListener::attachRecursive(
const Reference< XAccessible >& xAccessible,
const Reference< XAccessibleContext >& xContext
) throw (IndexOutOfBoundsException, RuntimeException)
{
if( xContext.is() )
{
Reference< XAccessibleStateSet > xStateSet = xContext->getAccessibleStateSet();
if( xStateSet.is() )
attachRecursive(xAccessible, xContext, xStateSet);
}
}
//------------------------------------------------------------------------------
void DocumentFocusListener::attachRecursive(
const Reference< XAccessible >& xAccessible,
const Reference< XAccessibleContext >& xContext,
const Reference< XAccessibleStateSet >& xStateSet
) throw (IndexOutOfBoundsException,RuntimeException)
{
if( xStateSet->contains(AccessibleStateType::FOCUSED ) )
m_aFocusTracker.setFocusedObject( xAccessible );
Reference< XAccessibleEventBroadcaster > xBroadcaster =
Reference< XAccessibleEventBroadcaster >(xContext, UNO_QUERY);
// If not already done, add the broadcaster to the list and attach as listener.
if( xBroadcaster.is() && m_aRefList.insert(xBroadcaster).second )
{
xBroadcaster->addEventListener(static_cast< XAccessibleEventListener *>(this));
if( ! xStateSet->contains(AccessibleStateType::MANAGES_DESCENDANTS ) )
{
sal_Int32 n, nmax = xContext->getAccessibleChildCount();
for( n = 0; n < nmax; n++ )
{
Reference< XAccessible > xChild( xContext->getAccessibleChild( n ) );
if( xChild.is() )
attachRecursive(xChild);
}
}
}
}
//------------------------------------------------------------------------------
void DocumentFocusListener::detachRecursive(const Reference< XAccessible >& xAccessible)
throw (IndexOutOfBoundsException, RuntimeException)
{
Reference< XAccessibleContext > xContext = xAccessible->getAccessibleContext();
if( xContext.is() )
detachRecursive(xAccessible, xContext);
}
//------------------------------------------------------------------------------
void DocumentFocusListener::detachRecursive(
const Reference< XAccessible >& xAccessible,
const Reference< XAccessibleContext >& xContext
) throw (IndexOutOfBoundsException, RuntimeException)
{
Reference< XAccessibleStateSet > xStateSet = xContext->getAccessibleStateSet();
if( xStateSet.is() )
detachRecursive(xAccessible, xContext, xStateSet);
}
//------------------------------------------------------------------------------
void DocumentFocusListener::detachRecursive(
const Reference< XAccessible >&,
const Reference< XAccessibleContext >& xContext,
const Reference< XAccessibleStateSet >& xStateSet
) throw (IndexOutOfBoundsException, RuntimeException)
{
Reference< XAccessibleEventBroadcaster > xBroadcaster =
Reference< XAccessibleEventBroadcaster >(xContext, UNO_QUERY);
if( xBroadcaster.is() && 0 < m_aRefList.erase(xBroadcaster) )
{
xBroadcaster->removeEventListener(static_cast< XAccessibleEventListener *>(this));
if( ! xStateSet->contains(AccessibleStateType::MANAGES_DESCENDANTS ) )
{
sal_Int32 n, nmax = xContext->getAccessibleChildCount();
for( n = 0; n < nmax; n++ )
{
Reference< XAccessible > xChild( xContext->getAccessibleChild( n ) );
if( xChild.is() )
detachRecursive(xChild);
}
}
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>potential WaE<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "documentfocuslistener.hxx"
#include <com/sun/star/accessibility/XAccessibleEventBroadcaster.hpp>
#include <com/sun/star/accessibility/AccessibleEventId.hpp>
#include <com/sun/star/accessibility/AccessibleStateType.hpp>
using namespace ::com::sun::star::accessibility;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::uno;
//------------------------------------------------------------------------------
DocumentFocusListener::DocumentFocusListener(AquaA11yFocusTracker& rTracker) :
m_aFocusTracker(rTracker)
{
}
//------------------------------------------------------------------------------
void SAL_CALL
DocumentFocusListener::disposing( const EventObject& aEvent )
throw (RuntimeException)
{
// Unref the object here, but do not remove as listener since the object
// might no longer be in a state that safely allows this.
if( aEvent.Source.is() )
m_aRefList.erase(aEvent.Source);
}
//------------------------------------------------------------------------------
void SAL_CALL
DocumentFocusListener::notifyEvent( const AccessibleEventObject& aEvent )
throw( RuntimeException )
{
switch( aEvent.EventId )
{
case AccessibleEventId::STATE_CHANGED:
try
{
sal_Int16 nState = AccessibleStateType::INVALID;
aEvent.NewValue >>= nState;
if( AccessibleStateType::FOCUSED == nState )
m_aFocusTracker.setFocusedObject( getAccessible(aEvent) );
}
catch(const IndexOutOfBoundsException &)
{
OSL_TRACE("Focused object has invalid index in parent");
}
break;
case AccessibleEventId::CHILD:
{
Reference< XAccessible > xChild;
if( (aEvent.OldValue >>= xChild) && xChild.is() )
detachRecursive(xChild);
if( (aEvent.NewValue >>= xChild) && xChild.is() )
attachRecursive(xChild);
}
break;
case AccessibleEventId::INVALIDATE_ALL_CHILDREN:
{
Reference< XAccessible > xAccessible( getAccessible(aEvent) );
detachRecursive(xAccessible);
attachRecursive(xAccessible);
}
OSL_TRACE( "Invalidate all children called\n" );
break;
default:
break;
}
}
//------------------------------------------------------------------------------
Reference< XAccessible > DocumentFocusListener::getAccessible(const EventObject& aEvent )
throw (IndexOutOfBoundsException, RuntimeException)
{
Reference< XAccessible > xAccessible(aEvent.Source, UNO_QUERY);
if( xAccessible.is() )
return xAccessible;
Reference< XAccessibleContext > xContext(aEvent.Source, UNO_QUERY);
if( xContext.is() )
{
Reference< XAccessible > xParent( xContext->getAccessibleParent() );
if( xParent.is() )
{
Reference< XAccessibleContext > xParentContext( xParent->getAccessibleContext() );
if( xParentContext.is() )
{
return xParentContext->getAccessibleChild( xContext->getAccessibleIndexInParent() );
}
}
}
return Reference< XAccessible >();
}
//------------------------------------------------------------------------------
void DocumentFocusListener::attachRecursive(const Reference< XAccessible >& xAccessible)
throw (IndexOutOfBoundsException, RuntimeException)
{
Reference< XAccessibleContext > xContext = xAccessible->getAccessibleContext();
if( xContext.is() )
attachRecursive(xAccessible, xContext);
}
//------------------------------------------------------------------------------
void DocumentFocusListener::attachRecursive(
const Reference< XAccessible >& xAccessible,
const Reference< XAccessibleContext >& xContext
) throw (IndexOutOfBoundsException, RuntimeException)
{
if( xContext.is() )
{
Reference< XAccessibleStateSet > xStateSet = xContext->getAccessibleStateSet();
if( xStateSet.is() )
attachRecursive(xAccessible, xContext, xStateSet);
}
}
//------------------------------------------------------------------------------
void DocumentFocusListener::attachRecursive(
const Reference< XAccessible >& xAccessible,
const Reference< XAccessibleContext >& xContext,
const Reference< XAccessibleStateSet >& xStateSet
) throw (IndexOutOfBoundsException,RuntimeException)
{
if( xStateSet->contains(AccessibleStateType::FOCUSED ) )
m_aFocusTracker.setFocusedObject( xAccessible );
Reference< XAccessibleEventBroadcaster > xBroadcaster =
Reference< XAccessibleEventBroadcaster >(xContext, UNO_QUERY);
// If not already done, add the broadcaster to the list and attach as listener.
if( xBroadcaster.is() && m_aRefList.insert(xBroadcaster).second )
{
xBroadcaster->addEventListener(static_cast< XAccessibleEventListener *>(this));
if( ! xStateSet->contains(AccessibleStateType::MANAGES_DESCENDANTS ) )
{
sal_Int32 n, nmax = xContext->getAccessibleChildCount();
for( n = 0; n < nmax; n++ )
{
Reference< XAccessible > xChild( xContext->getAccessibleChild( n ) );
if( xChild.is() )
attachRecursive(xChild);
}
}
}
}
//------------------------------------------------------------------------------
void DocumentFocusListener::detachRecursive(const Reference< XAccessible >& xAccessible)
throw (IndexOutOfBoundsException, RuntimeException)
{
Reference< XAccessibleContext > xContext = xAccessible->getAccessibleContext();
if( xContext.is() )
detachRecursive(xAccessible, xContext);
}
//------------------------------------------------------------------------------
void DocumentFocusListener::detachRecursive(
const Reference< XAccessible >& xAccessible,
const Reference< XAccessibleContext >& xContext
) throw (IndexOutOfBoundsException, RuntimeException)
{
Reference< XAccessibleStateSet > xStateSet = xContext->getAccessibleStateSet();
if( xStateSet.is() )
detachRecursive(xAccessible, xContext, xStateSet);
}
//------------------------------------------------------------------------------
void DocumentFocusListener::detachRecursive(
const Reference< XAccessible >&,
const Reference< XAccessibleContext >& xContext,
const Reference< XAccessibleStateSet >& xStateSet
) throw (IndexOutOfBoundsException, RuntimeException)
{
Reference< XAccessibleEventBroadcaster > xBroadcaster =
Reference< XAccessibleEventBroadcaster >(xContext, UNO_QUERY);
if( xBroadcaster.is() && 0 < m_aRefList.erase(xBroadcaster) )
{
xBroadcaster->removeEventListener(static_cast< XAccessibleEventListener *>(this));
if( ! xStateSet->contains(AccessibleStateType::MANAGES_DESCENDANTS ) )
{
sal_Int32 n, nmax = xContext->getAccessibleChildCount();
for( n = 0; n < nmax; n++ )
{
Reference< XAccessible > xChild( xContext->getAccessibleChild( n ) );
if( xChild.is() )
detachRecursive(xChild);
}
}
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkForceLinking.h"
#include "SkImageDecoder.h"
// This method is required to fool the linker into not discarding the pre-main
// initialization and registration of the decoder classes. Passing true will
// cause memory leaks.
int SkForceLinking(bool doNotPassTrue) {
if (doNotPassTrue) {
SkASSERT(false);
CreateJPEGImageDecoder();
CreateWEBPImageDecoder();
CreateBMPImageDecoder();
CreateICOImageDecoder();
CreateWBMPImageDecoder();
// Only link GIF and PNG on platforms that build them. See images.gyp
#if !defined(SK_BUILD_FOR_MAC) && !defined(SK_BUILD_FOR_WIN) && !defined(SK_BUILD_FOR_NACL)
CreateGIFImageDecoder();
#endif
#if !defined(SK_BUILD_FOR_MAC) && !defined(SK_BUILD_FOR_WIN)
CreatePNGImageDecoder();
#endif
return -1;
}
return 0;
}
<commit_msg>Fix iOS build.<commit_after>/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkForceLinking.h"
#include "SkImageDecoder.h"
// This method is required to fool the linker into not discarding the pre-main
// initialization and registration of the decoder classes. Passing true will
// cause memory leaks.
int SkForceLinking(bool doNotPassTrue) {
if (doNotPassTrue) {
SkASSERT(false);
CreateJPEGImageDecoder();
CreateWEBPImageDecoder();
CreateBMPImageDecoder();
CreateICOImageDecoder();
CreateWBMPImageDecoder();
// Only link GIF and PNG on platforms that build them. See images.gyp
#if !defined(SK_BUILD_FOR_MAC) && !defined(SK_BUILD_FOR_WIN) && !defined(SK_BUILD_FOR_NACL) \
&& !defined(SK_BUILD_FOR_IOS)
CreateGIFImageDecoder();
#endif
#if !defined(SK_BUILD_FOR_MAC) && !defined(SK_BUILD_FOR_WIN) && !defined(SK_BUILD_FOR_IOS)
CreatePNGImageDecoder();
#endif
return -1;
}
return 0;
}
<|endoftext|> |
<commit_before>
/*
* Copyright 2006 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkImageDecoder.h"
#include "SkBitmap.h"
#include "SkPixelRef.h"
#include "SkStream.h"
#include "SkTemplates.h"
static SkBitmap::Config gDeviceConfig = SkBitmap::kNo_Config;
SkBitmap::Config SkImageDecoder::GetDeviceConfig()
{
return gDeviceConfig;
}
void SkImageDecoder::SetDeviceConfig(SkBitmap::Config config)
{
gDeviceConfig = config;
}
///////////////////////////////////////////////////////////////////////////////
SkImageDecoder::SkImageDecoder()
: fPeeker(NULL), fChooser(NULL), fAllocator(NULL), fSampleSize(1),
fDefaultPref(SkBitmap::kNo_Config), fDitherImage(true),
fUsePrefTable(false) {
}
SkImageDecoder::~SkImageDecoder() {
SkSafeUnref(fPeeker);
SkSafeUnref(fChooser);
SkSafeUnref(fAllocator);
}
SkImageDecoder::Format SkImageDecoder::getFormat() const {
return kUnknown_Format;
}
SkImageDecoder::Peeker* SkImageDecoder::setPeeker(Peeker* peeker) {
SkRefCnt_SafeAssign(fPeeker, peeker);
return peeker;
}
SkImageDecoder::Chooser* SkImageDecoder::setChooser(Chooser* chooser) {
SkRefCnt_SafeAssign(fChooser, chooser);
return chooser;
}
SkBitmap::Allocator* SkImageDecoder::setAllocator(SkBitmap::Allocator* alloc) {
SkRefCnt_SafeAssign(fAllocator, alloc);
return alloc;
}
void SkImageDecoder::setSampleSize(int size) {
if (size < 1) {
size = 1;
}
fSampleSize = size;
}
bool SkImageDecoder::chooseFromOneChoice(SkBitmap::Config config, int width,
int height) const {
Chooser* chooser = fChooser;
if (NULL == chooser) { // no chooser, we just say YES to decoding :)
return true;
}
chooser->begin(1);
chooser->inspect(0, config, width, height);
return chooser->choose() == 0;
}
bool SkImageDecoder::allocPixelRef(SkBitmap* bitmap,
SkColorTable* ctable) const {
return bitmap->allocPixels(fAllocator, ctable);
}
///////////////////////////////////////////////////////////////////////////////
void SkImageDecoder::setPrefConfigTable(const SkBitmap::Config pref[6]) {
if (NULL == pref) {
fUsePrefTable = false;
} else {
fUsePrefTable = true;
memcpy(fPrefTable, pref, sizeof(fPrefTable));
}
}
SkBitmap::Config SkImageDecoder::getPrefConfig(SrcDepth srcDepth,
bool srcHasAlpha) const {
SkBitmap::Config config;
if (fUsePrefTable) {
int index = 0;
switch (srcDepth) {
case kIndex_SrcDepth:
index = 0;
break;
case k16Bit_SrcDepth:
index = 2;
break;
case k32Bit_SrcDepth:
index = 4;
break;
}
if (srcHasAlpha) {
index += 1;
}
config = fPrefTable[index];
} else {
config = fDefaultPref;
}
if (SkBitmap::kNo_Config == config) {
config = SkImageDecoder::GetDeviceConfig();
}
return config;
}
bool SkImageDecoder::decode(SkStream* stream, SkBitmap* bm,
SkBitmap::Config pref, Mode mode) {
// pass a temporary bitmap, so that if we return false, we are assured of
// leaving the caller's bitmap untouched.
SkBitmap tmp;
// we reset this to false before calling onDecode
fShouldCancelDecode = false;
// assign this, for use by getPrefConfig(), in case fUsePrefTable is false
fDefaultPref = pref;
if (!this->onDecode(stream, &tmp, mode)) {
return false;
}
bm->swap(tmp);
return true;
}
///////////////////////////////////////////////////////////////////////////////
bool SkImageDecoder::DecodeFile(const char file[], SkBitmap* bm,
SkBitmap::Config pref, Mode mode, Format* format) {
SkASSERT(file);
SkASSERT(bm);
SkFILEStream stream(file);
if (stream.isValid()) {
if (SkImageDecoder::DecodeStream(&stream, bm, pref, mode, format)) {
bm->pixelRef()->setURI(file);
}
return true;
}
return false;
}
bool SkImageDecoder::DecodeMemory(const void* buffer, size_t size, SkBitmap* bm,
SkBitmap::Config pref, Mode mode, Format* format) {
if (0 == size) {
return false;
}
SkASSERT(buffer);
SkMemoryStream stream(buffer, size);
return SkImageDecoder::DecodeStream(&stream, bm, pref, mode, format);
}
bool SkImageDecoder::DecodeStream(SkStream* stream, SkBitmap* bm,
SkBitmap::Config pref, Mode mode, Format* format) {
SkASSERT(stream);
SkASSERT(bm);
bool success = false;
SkImageDecoder* codec = SkImageDecoder::Factory(stream);
if (NULL != codec) {
success = codec->decode(stream, bm, pref, mode);
if (success && format) {
*format = codec->getFormat();
}
delete codec;
}
return success;
}
<commit_msg>Fix return value from SkImageDecoder::DecodeFile(): false even in case of *partial* failure.<commit_after>
/*
* Copyright 2006 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkImageDecoder.h"
#include "SkBitmap.h"
#include "SkPixelRef.h"
#include "SkStream.h"
#include "SkTemplates.h"
static SkBitmap::Config gDeviceConfig = SkBitmap::kNo_Config;
SkBitmap::Config SkImageDecoder::GetDeviceConfig()
{
return gDeviceConfig;
}
void SkImageDecoder::SetDeviceConfig(SkBitmap::Config config)
{
gDeviceConfig = config;
}
///////////////////////////////////////////////////////////////////////////////
SkImageDecoder::SkImageDecoder()
: fPeeker(NULL), fChooser(NULL), fAllocator(NULL), fSampleSize(1),
fDefaultPref(SkBitmap::kNo_Config), fDitherImage(true),
fUsePrefTable(false) {
}
SkImageDecoder::~SkImageDecoder() {
SkSafeUnref(fPeeker);
SkSafeUnref(fChooser);
SkSafeUnref(fAllocator);
}
SkImageDecoder::Format SkImageDecoder::getFormat() const {
return kUnknown_Format;
}
SkImageDecoder::Peeker* SkImageDecoder::setPeeker(Peeker* peeker) {
SkRefCnt_SafeAssign(fPeeker, peeker);
return peeker;
}
SkImageDecoder::Chooser* SkImageDecoder::setChooser(Chooser* chooser) {
SkRefCnt_SafeAssign(fChooser, chooser);
return chooser;
}
SkBitmap::Allocator* SkImageDecoder::setAllocator(SkBitmap::Allocator* alloc) {
SkRefCnt_SafeAssign(fAllocator, alloc);
return alloc;
}
void SkImageDecoder::setSampleSize(int size) {
if (size < 1) {
size = 1;
}
fSampleSize = size;
}
bool SkImageDecoder::chooseFromOneChoice(SkBitmap::Config config, int width,
int height) const {
Chooser* chooser = fChooser;
if (NULL == chooser) { // no chooser, we just say YES to decoding :)
return true;
}
chooser->begin(1);
chooser->inspect(0, config, width, height);
return chooser->choose() == 0;
}
bool SkImageDecoder::allocPixelRef(SkBitmap* bitmap,
SkColorTable* ctable) const {
return bitmap->allocPixels(fAllocator, ctable);
}
///////////////////////////////////////////////////////////////////////////////
void SkImageDecoder::setPrefConfigTable(const SkBitmap::Config pref[6]) {
if (NULL == pref) {
fUsePrefTable = false;
} else {
fUsePrefTable = true;
memcpy(fPrefTable, pref, sizeof(fPrefTable));
}
}
SkBitmap::Config SkImageDecoder::getPrefConfig(SrcDepth srcDepth,
bool srcHasAlpha) const {
SkBitmap::Config config;
if (fUsePrefTable) {
int index = 0;
switch (srcDepth) {
case kIndex_SrcDepth:
index = 0;
break;
case k16Bit_SrcDepth:
index = 2;
break;
case k32Bit_SrcDepth:
index = 4;
break;
}
if (srcHasAlpha) {
index += 1;
}
config = fPrefTable[index];
} else {
config = fDefaultPref;
}
if (SkBitmap::kNo_Config == config) {
config = SkImageDecoder::GetDeviceConfig();
}
return config;
}
bool SkImageDecoder::decode(SkStream* stream, SkBitmap* bm,
SkBitmap::Config pref, Mode mode) {
// pass a temporary bitmap, so that if we return false, we are assured of
// leaving the caller's bitmap untouched.
SkBitmap tmp;
// we reset this to false before calling onDecode
fShouldCancelDecode = false;
// assign this, for use by getPrefConfig(), in case fUsePrefTable is false
fDefaultPref = pref;
if (!this->onDecode(stream, &tmp, mode)) {
return false;
}
bm->swap(tmp);
return true;
}
///////////////////////////////////////////////////////////////////////////////
bool SkImageDecoder::DecodeFile(const char file[], SkBitmap* bm,
SkBitmap::Config pref, Mode mode, Format* format) {
SkASSERT(file);
SkASSERT(bm);
SkFILEStream stream(file);
if (stream.isValid()) {
if (SkImageDecoder::DecodeStream(&stream, bm, pref, mode, format)) {
bm->pixelRef()->setURI(file);
return true;
}
}
return false;
}
bool SkImageDecoder::DecodeMemory(const void* buffer, size_t size, SkBitmap* bm,
SkBitmap::Config pref, Mode mode, Format* format) {
if (0 == size) {
return false;
}
SkASSERT(buffer);
SkMemoryStream stream(buffer, size);
return SkImageDecoder::DecodeStream(&stream, bm, pref, mode, format);
}
bool SkImageDecoder::DecodeStream(SkStream* stream, SkBitmap* bm,
SkBitmap::Config pref, Mode mode, Format* format) {
SkASSERT(stream);
SkASSERT(bm);
bool success = false;
SkImageDecoder* codec = SkImageDecoder::Factory(stream);
if (NULL != codec) {
success = codec->decode(stream, bm, pref, mode);
if (success && format) {
*format = codec->getFormat();
}
delete codec;
}
return success;
}
<|endoftext|> |
<commit_before>#ifndef GUARD_MLOPEN_HANDLE_HPP
#define GUARD_MLOPEN_HANDLE_HPP
#define MLOPEN_DEFINE_OBJECT(object, ...) \
inline __VA_ARGS__& mlopen_get_object(object& obj) \
{ \
return static_cast<__VA_ARGS__&>(obj); \
} \
inline const __VA_ARGS__& mlopen_get_object(const object& obj) \
{ \
return static_cast<const __VA_ARGS__&>(obj); \
} \
inline void mlopen_destroy_object(object* p) \
{ \
delete static_cast<__VA_ARGS__*>(p); \
}
#endif<commit_msg>Add return at EOF<commit_after>#ifndef GUARD_MLOPEN_HANDLE_HPP
#define GUARD_MLOPEN_HANDLE_HPP
#define MLOPEN_DEFINE_OBJECT(object, ...) \
inline __VA_ARGS__& mlopen_get_object(object& obj) \
{ \
return static_cast<__VA_ARGS__&>(obj); \
} \
inline const __VA_ARGS__& mlopen_get_object(const object& obj) \
{ \
return static_cast<const __VA_ARGS__&>(obj); \
} \
inline void mlopen_destroy_object(object* p) \
{ \
delete static_cast<__VA_ARGS__*>(p); \
}
#endif
<|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 <mitkImageToSurfaceFilter.h>
#include <vtkImageData.h>
#include <vtkDecimatePro.h>
#include <vtkImageChangeInformation.h>
#include <vtkLinearTransform.h>
#include <vtkMath.h>
#include <vtkMatrix4x4.h>
#if (VTK_MAJOR_VERSION < 5)
#include <vtkDecimate.h>
#endif
mitk::ImageToSurfaceFilter::ImageToSurfaceFilter():
m_Smooth(false),
m_Decimate( NoDecimation),
m_Threshold(1.0),
m_TargetReduction(0.95f),
m_SmoothIteration(50),
m_SmoothRelaxation(0.1)
{
}
mitk::ImageToSurfaceFilter::~ImageToSurfaceFilter()
{
}
void mitk::ImageToSurfaceFilter::CreateSurface(int time, vtkImageData *vtkimage, mitk::Surface * surface, const ScalarType threshold)
{
vtkImageChangeInformation *indexCoordinatesImageFilter = vtkImageChangeInformation::New();
indexCoordinatesImageFilter->SetInput(vtkimage);
indexCoordinatesImageFilter->SetOutputOrigin(0.0,0.0,0.0);
//MarchingCube -->create Surface
vtkMarchingCubes *skinExtractor = vtkMarchingCubes::New();
skinExtractor->SetInput(indexCoordinatesImageFilter->GetOutput());//RC++
indexCoordinatesImageFilter->Delete();
skinExtractor->SetValue(0, threshold);
vtkPolyData *polydata;
polydata = skinExtractor->GetOutput();
polydata->Register(NULL);//RC++
skinExtractor->Delete();
if (m_Smooth)
{
vtkSmoothPolyDataFilter *smoother = vtkSmoothPolyDataFilter::New();
//read poly1 (poly1 can be the original polygon, or the decimated polygon)
smoother->SetInput(polydata);//RC++
smoother->SetNumberOfIterations( m_SmoothIteration );
smoother->SetRelaxationFactor( m_SmoothRelaxation );
smoother->SetFeatureAngle( 60 );
smoother->FeatureEdgeSmoothingOff();
smoother->BoundarySmoothingOff();
smoother->SetConvergence( 0 );
polydata->Delete();//RC--
polydata = smoother->GetOutput();
polydata->Register(NULL);//RC++
smoother->Delete();
}
#if (VTK_MAJOR_VERSION >= 5)
if (m_Decimate == Decimate )
{
std::cerr << "vtkDecimate not available for VTK 5.0 and above.";
std::cerr << " Using vtkDecimatePro instead." << std::endl;
m_Decimate = DecimatePro;
}
#endif
//decimate = to reduce number of polygons
if(m_Decimate==DecimatePro)
{
vtkDecimatePro *decimate = vtkDecimatePro::New();
decimate->SplittingOff();
decimate->SetErrorIsAbsolute(5);
decimate->SetFeatureAngle(30);
decimate->PreserveTopologyOn();
decimate->BoundaryVertexDeletionOff();
decimate->SetDegree(10); //std-value is 25!
decimate->SetInput(polydata);//RC++
decimate->SetTargetReduction(m_TargetReduction);
decimate->SetMaximumError(0.002);
polydata->Delete();//RC--
polydata = decimate->GetOutput();
polydata->Register(NULL);//RC++
decimate->Delete();
}
#if (VTK_MAJOR_VERSION < 5)
else if (m_Decimate==Decimate)
{
vtkDecimate *decimate = vtkDecimate::New();
decimate->SetInput( polydata );
decimate->PreserveTopologyOn();
decimate->BoundaryVertexDeletionOff();
decimate->SetTargetReduction( m_TargetReduction );
polydata->Delete();//RC--
polydata = decimate->GetOutput();
polydata->Register(NULL);//RC++
decimate->Delete();
}
#endif
polydata->Update();
polydata->SetSource(NULL);
if(polydata->GetNumberOfPoints() > 0)
{
mitk::Vector3D spacing = GetInput()->GetGeometry(time)->GetSpacing();
vtkPoints * points = polydata->GetPoints();
vtkMatrix4x4 *vtkmatrix = vtkMatrix4x4::New();
GetInput()->GetGeometry(time)->GetVtkTransform()->GetMatrix(vtkmatrix);
double (*matrix)[4] = vtkmatrix->Element;
unsigned int i,j;
for(i=0;i<3;++i)
for(j=0;j<3;++j)
matrix[i][j]/=spacing[j];
unsigned int n = points->GetNumberOfPoints();
vtkFloatingPointType point[3];
for (i = 0; i < n; i++)
{
points->GetPoint(i, point);
mitkVtkLinearTransformPoint(matrix,point,point);
points->SetPoint(i, point);
}
vtkmatrix->Delete();
}
surface->SetVtkPolyData(polydata, time);
polydata->UnRegister(NULL);
}
void mitk::ImageToSurfaceFilter::GenerateData()
{
mitk::Surface *surface = this->GetOutput();
mitk::Image * image = (mitk::Image*)GetInput();
mitk::Image::RegionType outputRegion = image->GetRequestedRegion();
int tstart=outputRegion.GetIndex(3);
int tmax=tstart+outputRegion.GetSize(3); //GetSize()==1 - will aber 0 haben, wenn nicht zeitaufgeloest
int t;
for( t=tstart; t < tmax; ++t)
{
vtkImageData *vtkimagedata = image->GetVtkImageData(t);
CreateSurface(t,vtkimagedata,surface,m_Threshold);
}
}
void mitk::ImageToSurfaceFilter::SetSmoothIteration(int smoothIteration)
{
m_SmoothIteration = smoothIteration;
}
void mitk::ImageToSurfaceFilter::SetSmoothRelaxation(float smoothRelaxation)
{
m_SmoothRelaxation = smoothRelaxation;
}
void mitk::ImageToSurfaceFilter::SetInput(const mitk::Image *image)
{
// Process object is not const-correct so the const_cast is required here
this->ProcessObject::SetNthInput(0, const_cast< mitk::Image * >( image ) );
}
const mitk::Image *mitk::ImageToSurfaceFilter::GetInput(void)
{
if (this->GetNumberOfInputs() < 1)
{
return 0;
}
return static_cast<const mitk::Image * >
( this->ProcessObject::GetInput(0) );
}
void mitk::ImageToSurfaceFilter::GenerateOutputInformation()
{
mitk::Image::ConstPointer inputImage =(mitk::Image*) this->GetInput();
//mitk::Image *inputImage = (mitk::Image*)this->GetImage();
mitk::Surface::Pointer output = this->GetOutput();
itkDebugMacro(<<"GenerateOutputInformation()");
if(inputImage.IsNull()) return;
//Set Data
}
<commit_msg>BUG: Turn scalar computation OFF for surface creation (bug #7)<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 <mitkImageToSurfaceFilter.h>
#include <vtkImageData.h>
#include <vtkDecimatePro.h>
#include <vtkImageChangeInformation.h>
#include <vtkLinearTransform.h>
#include <vtkMath.h>
#include <vtkMatrix4x4.h>
#if (VTK_MAJOR_VERSION < 5)
#include <vtkDecimate.h>
#endif
mitk::ImageToSurfaceFilter::ImageToSurfaceFilter():
m_Smooth(false),
m_Decimate( NoDecimation),
m_Threshold(1.0),
m_TargetReduction(0.95f),
m_SmoothIteration(50),
m_SmoothRelaxation(0.1)
{
}
mitk::ImageToSurfaceFilter::~ImageToSurfaceFilter()
{
}
void mitk::ImageToSurfaceFilter::CreateSurface(int time, vtkImageData *vtkimage, mitk::Surface * surface, const ScalarType threshold)
{
vtkImageChangeInformation *indexCoordinatesImageFilter = vtkImageChangeInformation::New();
indexCoordinatesImageFilter->SetInput(vtkimage);
indexCoordinatesImageFilter->SetOutputOrigin(0.0,0.0,0.0);
//MarchingCube -->create Surface
vtkMarchingCubes *skinExtractor = vtkMarchingCubes::New();
skinExtractor->ComputeScalarsOff();
skinExtractor->SetInput(indexCoordinatesImageFilter->GetOutput());//RC++
indexCoordinatesImageFilter->Delete();
skinExtractor->SetValue(0, threshold);
vtkPolyData *polydata;
polydata = skinExtractor->GetOutput();
polydata->Register(NULL);//RC++
skinExtractor->Delete();
if (m_Smooth)
{
vtkSmoothPolyDataFilter *smoother = vtkSmoothPolyDataFilter::New();
//read poly1 (poly1 can be the original polygon, or the decimated polygon)
smoother->SetInput(polydata);//RC++
smoother->SetNumberOfIterations( m_SmoothIteration );
smoother->SetRelaxationFactor( m_SmoothRelaxation );
smoother->SetFeatureAngle( 60 );
smoother->FeatureEdgeSmoothingOff();
smoother->BoundarySmoothingOff();
smoother->SetConvergence( 0 );
polydata->Delete();//RC--
polydata = smoother->GetOutput();
polydata->Register(NULL);//RC++
smoother->Delete();
}
#if (VTK_MAJOR_VERSION >= 5)
if (m_Decimate == Decimate )
{
std::cerr << "vtkDecimate not available for VTK 5.0 and above.";
std::cerr << " Using vtkDecimatePro instead." << std::endl;
m_Decimate = DecimatePro;
}
#endif
//decimate = to reduce number of polygons
if(m_Decimate==DecimatePro)
{
vtkDecimatePro *decimate = vtkDecimatePro::New();
decimate->SplittingOff();
decimate->SetErrorIsAbsolute(5);
decimate->SetFeatureAngle(30);
decimate->PreserveTopologyOn();
decimate->BoundaryVertexDeletionOff();
decimate->SetDegree(10); //std-value is 25!
decimate->SetInput(polydata);//RC++
decimate->SetTargetReduction(m_TargetReduction);
decimate->SetMaximumError(0.002);
polydata->Delete();//RC--
polydata = decimate->GetOutput();
polydata->Register(NULL);//RC++
decimate->Delete();
}
#if (VTK_MAJOR_VERSION < 5)
else if (m_Decimate==Decimate)
{
vtkDecimate *decimate = vtkDecimate::New();
decimate->SetInput( polydata );
decimate->PreserveTopologyOn();
decimate->BoundaryVertexDeletionOff();
decimate->SetTargetReduction( m_TargetReduction );
polydata->Delete();//RC--
polydata = decimate->GetOutput();
polydata->Register(NULL);//RC++
decimate->Delete();
}
#endif
polydata->Update();
polydata->SetSource(NULL);
if(polydata->GetNumberOfPoints() > 0)
{
mitk::Vector3D spacing = GetInput()->GetGeometry(time)->GetSpacing();
vtkPoints * points = polydata->GetPoints();
vtkMatrix4x4 *vtkmatrix = vtkMatrix4x4::New();
GetInput()->GetGeometry(time)->GetVtkTransform()->GetMatrix(vtkmatrix);
double (*matrix)[4] = vtkmatrix->Element;
unsigned int i,j;
for(i=0;i<3;++i)
for(j=0;j<3;++j)
matrix[i][j]/=spacing[j];
unsigned int n = points->GetNumberOfPoints();
vtkFloatingPointType point[3];
for (i = 0; i < n; i++)
{
points->GetPoint(i, point);
mitkVtkLinearTransformPoint(matrix,point,point);
points->SetPoint(i, point);
}
vtkmatrix->Delete();
}
surface->SetVtkPolyData(polydata, time);
polydata->UnRegister(NULL);
}
void mitk::ImageToSurfaceFilter::GenerateData()
{
mitk::Surface *surface = this->GetOutput();
mitk::Image * image = (mitk::Image*)GetInput();
mitk::Image::RegionType outputRegion = image->GetRequestedRegion();
int tstart=outputRegion.GetIndex(3);
int tmax=tstart+outputRegion.GetSize(3); //GetSize()==1 - will aber 0 haben, wenn nicht zeitaufgeloest
int t;
for( t=tstart; t < tmax; ++t)
{
vtkImageData *vtkimagedata = image->GetVtkImageData(t);
CreateSurface(t,vtkimagedata,surface,m_Threshold);
}
}
void mitk::ImageToSurfaceFilter::SetSmoothIteration(int smoothIteration)
{
m_SmoothIteration = smoothIteration;
}
void mitk::ImageToSurfaceFilter::SetSmoothRelaxation(float smoothRelaxation)
{
m_SmoothRelaxation = smoothRelaxation;
}
void mitk::ImageToSurfaceFilter::SetInput(const mitk::Image *image)
{
// Process object is not const-correct so the const_cast is required here
this->ProcessObject::SetNthInput(0, const_cast< mitk::Image * >( image ) );
}
const mitk::Image *mitk::ImageToSurfaceFilter::GetInput(void)
{
if (this->GetNumberOfInputs() < 1)
{
return 0;
}
return static_cast<const mitk::Image * >
( this->ProcessObject::GetInput(0) );
}
void mitk::ImageToSurfaceFilter::GenerateOutputInformation()
{
mitk::Image::ConstPointer inputImage =(mitk::Image*) this->GetInput();
//mitk::Image *inputImage = (mitk::Image*)this->GetImage();
mitk::Surface::Pointer output = this->GetOutput();
itkDebugMacro(<<"GenerateOutputInformation()");
if(inputImage.IsNull()) return;
//Set Data
}
<|endoftext|> |
<commit_before>//===-- Frontend.cpp - frontend utility methods ---------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file contains utility methods for parsing and performing semantic
// on modules.
//
//===----------------------------------------------------------------------===//
#include "swift/Frontend/Frontend.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Component.h"
#include "swift/AST/Diagnostics.h"
#include "swift/AST/Module.h"
#include "swift/Parse/Lexer.h"
#include "swift/Subsystems.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/SourceMgr.h"
using namespace swift;
static Identifier getModuleIdentifier(StringRef OutputName,
ASTContext &Context,
TranslationUnit::TUKind moduleKind) {
StringRef moduleName = OutputName;
// As a special case, recognize <stdin>.
if (moduleName == "<stdin>")
return Context.getIdentifier("stdin");
// Find the stem of the filename.
moduleName = llvm::sys::path::stem(moduleName);
// Complain about non-identifier characters in the module name.
if (!Lexer::isIdentifier(moduleName)) {
if (moduleKind == TranslationUnit::Main) {
moduleName = "main";
} else {
SourceLoc Loc;
Context.Diags.diagnose(Loc, diag::bad_module_name, moduleName);
moduleName = "bad";
}
}
return Context.getIdentifier(moduleName);
}
/// \param SIL is non-null when we're parsing a .sil file instead of a .swift
/// file.
TranslationUnit*
swift::buildSingleTranslationUnit(ASTContext &Context,
StringRef OutputName,
ArrayRef<unsigned> BufferIDs,
bool ParseOnly,
bool AllowBuiltinModule,
TranslationUnit::TUKind Kind,
SILModule *SIL) {
Component *Comp = new (Context.Allocate<Component>(1)) Component();
Identifier ID = getModuleIdentifier(OutputName, Context, Kind);
TranslationUnit *TU = new (Context) TranslationUnit(ID, Comp, Context, Kind);
Context.LoadedModules[ID.str()] = TU;
TU->HasBuiltinModuleAccess = AllowBuiltinModule;
// If we're in SIL mode, don't auto import any libraries.
if (Kind != TranslationUnit::SIL)
performAutoImport(TU);
// If we have multiple source files, we must be building a module. Parse each
// file before type checking the union of them.
if (BufferIDs.size() > 1) {
assert(Kind == TranslationUnit::Library &&
"Multiple file mode can't handle early returns from the parser");
// Parse all of the files into one big translation unit.
for (auto &BufferID : BufferIDs) {
auto *Buffer = Context.SourceMgr.getMemoryBuffer(BufferID);
unsigned BufferOffset = 0;
parseIntoTranslationUnit(TU, BufferID, &BufferOffset);
assert(BufferOffset == Buffer->getBufferSize() &&
"Parser returned early?");
(void)Buffer;
}
// Finally, if enabled, type check the whole thing in one go.
if (!ParseOnly)
performTypeChecking(TU);
return TU;
}
// If there is only a single input file, it may be SIL or a main module,
// which requires pumping the parser.
assert(BufferIDs.size() == 1 && "This mode only allows one input");
unsigned BufferID = BufferIDs[0];
SILParserState SILContext(SIL);
unsigned CurTUElem = 0;
unsigned BufferOffset = 0;
auto *Buffer = Context.SourceMgr.getMemoryBuffer(BufferID);
do {
// Pump the parser multiple times if necessary. It will return early
// after parsing any top level code in a main module, or in SIL mode when
// there are chunks of swift decls (e.g. imports and types) interspersed
// with 'sil' definitions.
parseIntoTranslationUnit(TU, BufferID, &BufferOffset, 0,
SIL ? &SILContext : nullptr);
performTypeChecking(TU, CurTUElem);
CurTUElem = TU->Decls.size();
} while (BufferOffset != Buffer->getBufferSize());
return TU;
}
<commit_msg>fix -dump-parse to not run type checking in the single translation unit case.<commit_after>//===-- Frontend.cpp - frontend utility methods ---------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file contains utility methods for parsing and performing semantic
// on modules.
//
//===----------------------------------------------------------------------===//
#include "swift/Frontend/Frontend.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Component.h"
#include "swift/AST/Diagnostics.h"
#include "swift/AST/Module.h"
#include "swift/Parse/Lexer.h"
#include "swift/Subsystems.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/SourceMgr.h"
using namespace swift;
static Identifier getModuleIdentifier(StringRef OutputName,
ASTContext &Context,
TranslationUnit::TUKind moduleKind) {
StringRef moduleName = OutputName;
// As a special case, recognize <stdin>.
if (moduleName == "<stdin>")
return Context.getIdentifier("stdin");
// Find the stem of the filename.
moduleName = llvm::sys::path::stem(moduleName);
// Complain about non-identifier characters in the module name.
if (!Lexer::isIdentifier(moduleName)) {
if (moduleKind == TranslationUnit::Main) {
moduleName = "main";
} else {
SourceLoc Loc;
Context.Diags.diagnose(Loc, diag::bad_module_name, moduleName);
moduleName = "bad";
}
}
return Context.getIdentifier(moduleName);
}
/// \param SIL is non-null when we're parsing a .sil file instead of a .swift
/// file.
TranslationUnit*
swift::buildSingleTranslationUnit(ASTContext &Context,
StringRef OutputName,
ArrayRef<unsigned> BufferIDs,
bool ParseOnly,
bool AllowBuiltinModule,
TranslationUnit::TUKind Kind,
SILModule *SIL) {
Component *Comp = new (Context.Allocate<Component>(1)) Component();
Identifier ID = getModuleIdentifier(OutputName, Context, Kind);
TranslationUnit *TU = new (Context) TranslationUnit(ID, Comp, Context, Kind);
Context.LoadedModules[ID.str()] = TU;
TU->HasBuiltinModuleAccess = AllowBuiltinModule;
// If we're in SIL mode, don't auto import any libraries.
if (Kind != TranslationUnit::SIL)
performAutoImport(TU);
// If we have multiple source files, we must be building a module. Parse each
// file before type checking the union of them.
if (BufferIDs.size() > 1) {
assert(Kind == TranslationUnit::Library &&
"Multiple file mode can't handle early returns from the parser");
// Parse all of the files into one big translation unit.
for (auto &BufferID : BufferIDs) {
auto *Buffer = Context.SourceMgr.getMemoryBuffer(BufferID);
unsigned BufferOffset = 0;
parseIntoTranslationUnit(TU, BufferID, &BufferOffset);
assert(BufferOffset == Buffer->getBufferSize() &&
"Parser returned early?");
(void)Buffer;
}
// Finally, if enabled, type check the whole thing in one go.
if (!ParseOnly)
performTypeChecking(TU);
return TU;
}
// If there is only a single input file, it may be SIL or a main module,
// which requires pumping the parser.
assert(BufferIDs.size() == 1 && "This mode only allows one input");
unsigned BufferID = BufferIDs[0];
SILParserState SILContext(SIL);
unsigned CurTUElem = 0;
unsigned BufferOffset = 0;
auto *Buffer = Context.SourceMgr.getMemoryBuffer(BufferID);
do {
// Pump the parser multiple times if necessary. It will return early
// after parsing any top level code in a main module, or in SIL mode when
// there are chunks of swift decls (e.g. imports and types) interspersed
// with 'sil' definitions.
parseIntoTranslationUnit(TU, BufferID, &BufferOffset, 0,
SIL ? &SILContext : nullptr);
if (!ParseOnly)
performTypeChecking(TU, CurTUElem);
CurTUElem = TU->Decls.size();
} while (BufferOffset != Buffer->getBufferSize());
return TU;
}
<|endoftext|> |
<commit_before>//===--- PPLexerChange.cpp - Handle changing lexers in the preprocessor ---===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements pieces of the Preprocessor interface that manage the
// current lexer stack.
//
//===----------------------------------------------------------------------===//
#include "clang/Lex/Preprocessor.h"
#include "clang/Lex/HeaderSearch.h"
#include "clang/Lex/MacroInfo.h"
#include "clang/Lex/LexDiagnostic.h"
#include "clang/Basic/SourceManager.h"
#include "llvm/Support/MemoryBuffer.h"
using namespace clang;
PPCallbacks::~PPCallbacks() {}
//===----------------------------------------------------------------------===//
// Miscellaneous Methods.
//===----------------------------------------------------------------------===//
/// isInPrimaryFile - Return true if we're in the top-level file, not in a
/// #include. This looks through macro expansions and active _Pragma lexers.
bool Preprocessor::isInPrimaryFile() const {
if (IsFileLexer())
return IncludeMacroStack.empty();
// If there are any stacked lexers, we're in a #include.
assert(IsFileLexer(IncludeMacroStack[0]) &&
"Top level include stack isn't our primary lexer?");
for (unsigned i = 1, e = IncludeMacroStack.size(); i != e; ++i)
if (IsFileLexer(IncludeMacroStack[i]))
return false;
return true;
}
/// getCurrentLexer - Return the current file lexer being lexed from. Note
/// that this ignores any potentially active macro expansions and _Pragma
/// expansions going on at the time.
PreprocessorLexer *Preprocessor::getCurrentFileLexer() const {
if (IsFileLexer())
return CurPPLexer;
// Look for a stacked lexer.
for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
const IncludeStackInfo& ISI = IncludeMacroStack[i-1];
if (IsFileLexer(ISI))
return ISI.ThePPLexer;
}
return 0;
}
//===----------------------------------------------------------------------===//
// Methods for Entering and Callbacks for leaving various contexts
//===----------------------------------------------------------------------===//
/// EnterSourceFile - Add a source file to the top of the include stack and
/// start lexing tokens from it instead of the current buffer. Return true
/// on failure.
void Preprocessor::EnterSourceFile(FileID FID, const DirectoryLookup *CurDir) {
assert(CurTokenLexer == 0 && "Cannot #include a file inside a macro!");
++NumEnteredSourceFiles;
if (MaxIncludeStackDepth < IncludeMacroStack.size())
MaxIncludeStackDepth = IncludeMacroStack.size();
if (PTH) {
if (PTHLexer *PL = PTH->CreateLexer(FID))
return EnterSourceFileWithPTH(PL, CurDir);
}
EnterSourceFileWithLexer(new Lexer(FID, *this), CurDir);
}
/// EnterSourceFileWithLexer - Add a source file to the top of the include stack
/// and start lexing tokens from it instead of the current buffer.
void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
const DirectoryLookup *CurDir) {
// Add the current lexer to the include stack.
if (CurPPLexer || CurTokenLexer)
PushIncludeMacroStack();
CurLexer.reset(TheLexer);
CurPPLexer = TheLexer;
CurDirLookup = CurDir;
// Notify the client, if desired, that we are in a new source file.
if (Callbacks && !CurLexer->Is_PragmaLexer) {
SrcMgr::CharacteristicKind FileType =
SourceMgr.getFileCharacteristic(CurLexer->getFileLoc());
Callbacks->FileChanged(CurLexer->getFileLoc(),
PPCallbacks::EnterFile, FileType);
}
}
/// EnterSourceFileWithPTH - Add a source file to the top of the include stack
/// and start getting tokens from it using the PTH cache.
void Preprocessor::EnterSourceFileWithPTH(PTHLexer *PL,
const DirectoryLookup *CurDir) {
if (CurPPLexer || CurTokenLexer)
PushIncludeMacroStack();
CurDirLookup = CurDir;
CurPTHLexer.reset(PL);
CurPPLexer = CurPTHLexer.get();
// Notify the client, if desired, that we are in a new source file.
if (Callbacks) {
FileID FID = CurPPLexer->getFileID();
SourceLocation EnterLoc = SourceMgr.getLocForStartOfFile(FID);
SrcMgr::CharacteristicKind FileType =
SourceMgr.getFileCharacteristic(EnterLoc);
Callbacks->FileChanged(EnterLoc, PPCallbacks::EnterFile, FileType);
}
}
/// EnterMacro - Add a Macro to the top of the include stack and start lexing
/// tokens from it instead of the current buffer.
void Preprocessor::EnterMacro(Token &Tok, SourceLocation ILEnd,
MacroArgs *Args) {
PushIncludeMacroStack();
CurDirLookup = 0;
if (NumCachedTokenLexers == 0) {
CurTokenLexer.reset(new TokenLexer(Tok, ILEnd, Args, *this));
} else {
CurTokenLexer.reset(TokenLexerCache[--NumCachedTokenLexers]);
CurTokenLexer->Init(Tok, ILEnd, Args);
}
}
/// EnterTokenStream - Add a "macro" context to the top of the include stack,
/// which will cause the lexer to start returning the specified tokens.
///
/// If DisableMacroExpansion is true, tokens lexed from the token stream will
/// not be subject to further macro expansion. Otherwise, these tokens will
/// be re-macro-expanded when/if expansion is enabled.
///
/// If OwnsTokens is false, this method assumes that the specified stream of
/// tokens has a permanent owner somewhere, so they do not need to be copied.
/// If it is true, it assumes the array of tokens is allocated with new[] and
/// must be freed.
///
void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks,
bool DisableMacroExpansion,
bool OwnsTokens) {
// Save our current state.
PushIncludeMacroStack();
CurDirLookup = 0;
// Create a macro expander to expand from the specified token stream.
if (NumCachedTokenLexers == 0) {
CurTokenLexer.reset(new TokenLexer(Toks, NumToks, DisableMacroExpansion,
OwnsTokens, *this));
} else {
CurTokenLexer.reset(TokenLexerCache[--NumCachedTokenLexers]);
CurTokenLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens);
}
}
/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
/// the current file. This either returns the EOF token or pops a level off
/// the include stack and keeps going.
bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
assert(!CurTokenLexer &&
"Ending a file when currently in a macro!");
// See if this file had a controlling macro.
if (CurPPLexer) { // Not ending a macro, ignore it.
if (const IdentifierInfo *ControllingMacro =
CurPPLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
// Okay, this has a controlling macro, remember in HeaderFileInfo.
if (const FileEntry *FE =
SourceMgr.getFileEntryForID(CurPPLexer->getFileID()))
HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
}
}
// If this is a #include'd file, pop it off the include stack and continue
// lexing the #includer file.
if (!IncludeMacroStack.empty()) {
// We're done with the #included file.
RemoveTopOfLexerStack();
// Notify the client, if desired, that we are in a new source file.
if (Callbacks && !isEndOfMacro && CurPPLexer) {
SrcMgr::CharacteristicKind FileType =
SourceMgr.getFileCharacteristic(CurPPLexer->getSourceLocation());
Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
PPCallbacks::ExitFile, FileType);
}
// Client should lex another token.
return false;
}
// If the file ends with a newline, form the EOF token on the newline itself,
// rather than "on the line following it", which doesn't exist. This makes
// diagnostics relating to the end of file include the last file that the user
// actually typed, which is goodness.
if (CurLexer) {
const char *EndPos = CurLexer->BufferEnd;
if (EndPos != CurLexer->BufferStart &&
(EndPos[-1] == '\n' || EndPos[-1] == '\r')) {
--EndPos;
// Handle \n\r and \r\n:
if (EndPos != CurLexer->BufferStart &&
(EndPos[-1] == '\n' || EndPos[-1] == '\r') &&
EndPos[-1] != EndPos[0])
--EndPos;
}
Result.startToken();
CurLexer->BufferPtr = EndPos;
CurLexer->FormTokenWithChars(Result, EndPos, tok::eof);
// We're done with the #included file.
CurLexer.reset();
} else {
assert(CurPTHLexer && "Got EOF but no current lexer set!");
CurPTHLexer->getEOF(Result);
CurPTHLexer.reset();
}
CurPPLexer = 0;
// This is the end of the top-level file. If the diag::pp_macro_not_used
// diagnostic is enabled, look for macros that have not been used.
if (getDiagnostics().getDiagnosticLevel(diag::pp_macro_not_used) !=
Diagnostic::Ignored) {
for (macro_iterator I = macro_begin(), E = macro_end(); I != E; ++I)
if (!I->second->isUsed())
Diag(I->second->getDefinitionLoc(), diag::pp_macro_not_used);
}
return true;
}
/// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer
/// hits the end of its token stream.
bool Preprocessor::HandleEndOfTokenLexer(Token &Result) {
assert(CurTokenLexer && !CurPPLexer &&
"Ending a macro when currently in a #include file!");
// Delete or cache the now-dead macro expander.
if (NumCachedTokenLexers == TokenLexerCacheSize)
CurTokenLexer.reset();
else
TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.take();
// Handle this like a #include file being popped off the stack.
return HandleEndOfFile(Result, true);
}
/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
/// lexer stack. This should only be used in situations where the current
/// state of the top-of-stack lexer is unknown.
void Preprocessor::RemoveTopOfLexerStack() {
assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
if (CurTokenLexer) {
// Delete or cache the now-dead macro expander.
if (NumCachedTokenLexers == TokenLexerCacheSize)
CurTokenLexer.reset();
else
TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.take();
}
PopIncludeMacroStack();
}
/// HandleMicrosoftCommentPaste - When the macro expander pastes together a
/// comment (/##/) in microsoft mode, this method handles updating the current
/// state, returning the token on the next source line.
void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
assert(CurTokenLexer && !CurPPLexer &&
"Pasted comment can only be formed from macro");
// We handle this by scanning for the closest real lexer, switching it to
// raw mode and preprocessor mode. This will cause it to return \n as an
// explicit EOM token.
PreprocessorLexer *FoundLexer = 0;
bool LexerWasInPPMode = false;
for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
IncludeStackInfo &ISI = *(IncludeMacroStack.end()-i-1);
if (ISI.ThePPLexer == 0) continue; // Scan for a real lexer.
// Once we find a real lexer, mark it as raw mode (disabling macro
// expansions) and preprocessor mode (return EOM). We know that the lexer
// was *not* in raw mode before, because the macro that the comment came
// from was expanded. However, it could have already been in preprocessor
// mode (#if COMMENT) in which case we have to return it to that mode and
// return EOM.
FoundLexer = ISI.ThePPLexer;
FoundLexer->LexingRawMode = true;
LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
FoundLexer->ParsingPreprocessorDirective = true;
break;
}
// Okay, we either found and switched over the lexer, or we didn't find a
// lexer. In either case, finish off the macro the comment came from, getting
// the next token.
if (!HandleEndOfTokenLexer(Tok)) Lex(Tok);
// Discarding comments as long as we don't have EOF or EOM. This 'comments
// out' the rest of the line, including any tokens that came from other macros
// that were active, as in:
// #define submacro a COMMENT b
// submacro c
// which should lex to 'a' only: 'b' and 'c' should be removed.
while (Tok.isNot(tok::eom) && Tok.isNot(tok::eof))
Lex(Tok);
// If we got an eom token, then we successfully found the end of the line.
if (Tok.is(tok::eom)) {
assert(FoundLexer && "Can't get end of line without an active lexer");
// Restore the lexer back to normal mode instead of raw mode.
FoundLexer->LexingRawMode = false;
// If the lexer was already in preprocessor mode, just return the EOM token
// to finish the preprocessor line.
if (LexerWasInPPMode) return;
// Otherwise, switch out of PP mode and return the next lexed token.
FoundLexer->ParsingPreprocessorDirective = false;
return Lex(Tok);
}
// If we got an EOF token, then we reached the end of the token stream but
// didn't find an explicit \n. This can only happen if there was no lexer
// active (an active lexer would return EOM at EOF if there was no \n in
// preprocessor directive mode), so just return EOF as our token.
assert(!FoundLexer && "Lexer should return EOM before EOF in PP mode");
}
<commit_msg>remove stall comment<commit_after>//===--- PPLexerChange.cpp - Handle changing lexers in the preprocessor ---===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements pieces of the Preprocessor interface that manage the
// current lexer stack.
//
//===----------------------------------------------------------------------===//
#include "clang/Lex/Preprocessor.h"
#include "clang/Lex/HeaderSearch.h"
#include "clang/Lex/MacroInfo.h"
#include "clang/Lex/LexDiagnostic.h"
#include "clang/Basic/SourceManager.h"
#include "llvm/Support/MemoryBuffer.h"
using namespace clang;
PPCallbacks::~PPCallbacks() {}
//===----------------------------------------------------------------------===//
// Miscellaneous Methods.
//===----------------------------------------------------------------------===//
/// isInPrimaryFile - Return true if we're in the top-level file, not in a
/// #include. This looks through macro expansions and active _Pragma lexers.
bool Preprocessor::isInPrimaryFile() const {
if (IsFileLexer())
return IncludeMacroStack.empty();
// If there are any stacked lexers, we're in a #include.
assert(IsFileLexer(IncludeMacroStack[0]) &&
"Top level include stack isn't our primary lexer?");
for (unsigned i = 1, e = IncludeMacroStack.size(); i != e; ++i)
if (IsFileLexer(IncludeMacroStack[i]))
return false;
return true;
}
/// getCurrentLexer - Return the current file lexer being lexed from. Note
/// that this ignores any potentially active macro expansions and _Pragma
/// expansions going on at the time.
PreprocessorLexer *Preprocessor::getCurrentFileLexer() const {
if (IsFileLexer())
return CurPPLexer;
// Look for a stacked lexer.
for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
const IncludeStackInfo& ISI = IncludeMacroStack[i-1];
if (IsFileLexer(ISI))
return ISI.ThePPLexer;
}
return 0;
}
//===----------------------------------------------------------------------===//
// Methods for Entering and Callbacks for leaving various contexts
//===----------------------------------------------------------------------===//
/// EnterSourceFile - Add a source file to the top of the include stack and
/// start lexing tokens from it instead of the current buffer.
void Preprocessor::EnterSourceFile(FileID FID, const DirectoryLookup *CurDir) {
assert(CurTokenLexer == 0 && "Cannot #include a file inside a macro!");
++NumEnteredSourceFiles;
if (MaxIncludeStackDepth < IncludeMacroStack.size())
MaxIncludeStackDepth = IncludeMacroStack.size();
if (PTH) {
if (PTHLexer *PL = PTH->CreateLexer(FID))
return EnterSourceFileWithPTH(PL, CurDir);
}
EnterSourceFileWithLexer(new Lexer(FID, *this), CurDir);
}
/// EnterSourceFileWithLexer - Add a source file to the top of the include stack
/// and start lexing tokens from it instead of the current buffer.
void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
const DirectoryLookup *CurDir) {
// Add the current lexer to the include stack.
if (CurPPLexer || CurTokenLexer)
PushIncludeMacroStack();
CurLexer.reset(TheLexer);
CurPPLexer = TheLexer;
CurDirLookup = CurDir;
// Notify the client, if desired, that we are in a new source file.
if (Callbacks && !CurLexer->Is_PragmaLexer) {
SrcMgr::CharacteristicKind FileType =
SourceMgr.getFileCharacteristic(CurLexer->getFileLoc());
Callbacks->FileChanged(CurLexer->getFileLoc(),
PPCallbacks::EnterFile, FileType);
}
}
/// EnterSourceFileWithPTH - Add a source file to the top of the include stack
/// and start getting tokens from it using the PTH cache.
void Preprocessor::EnterSourceFileWithPTH(PTHLexer *PL,
const DirectoryLookup *CurDir) {
if (CurPPLexer || CurTokenLexer)
PushIncludeMacroStack();
CurDirLookup = CurDir;
CurPTHLexer.reset(PL);
CurPPLexer = CurPTHLexer.get();
// Notify the client, if desired, that we are in a new source file.
if (Callbacks) {
FileID FID = CurPPLexer->getFileID();
SourceLocation EnterLoc = SourceMgr.getLocForStartOfFile(FID);
SrcMgr::CharacteristicKind FileType =
SourceMgr.getFileCharacteristic(EnterLoc);
Callbacks->FileChanged(EnterLoc, PPCallbacks::EnterFile, FileType);
}
}
/// EnterMacro - Add a Macro to the top of the include stack and start lexing
/// tokens from it instead of the current buffer.
void Preprocessor::EnterMacro(Token &Tok, SourceLocation ILEnd,
MacroArgs *Args) {
PushIncludeMacroStack();
CurDirLookup = 0;
if (NumCachedTokenLexers == 0) {
CurTokenLexer.reset(new TokenLexer(Tok, ILEnd, Args, *this));
} else {
CurTokenLexer.reset(TokenLexerCache[--NumCachedTokenLexers]);
CurTokenLexer->Init(Tok, ILEnd, Args);
}
}
/// EnterTokenStream - Add a "macro" context to the top of the include stack,
/// which will cause the lexer to start returning the specified tokens.
///
/// If DisableMacroExpansion is true, tokens lexed from the token stream will
/// not be subject to further macro expansion. Otherwise, these tokens will
/// be re-macro-expanded when/if expansion is enabled.
///
/// If OwnsTokens is false, this method assumes that the specified stream of
/// tokens has a permanent owner somewhere, so they do not need to be copied.
/// If it is true, it assumes the array of tokens is allocated with new[] and
/// must be freed.
///
void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks,
bool DisableMacroExpansion,
bool OwnsTokens) {
// Save our current state.
PushIncludeMacroStack();
CurDirLookup = 0;
// Create a macro expander to expand from the specified token stream.
if (NumCachedTokenLexers == 0) {
CurTokenLexer.reset(new TokenLexer(Toks, NumToks, DisableMacroExpansion,
OwnsTokens, *this));
} else {
CurTokenLexer.reset(TokenLexerCache[--NumCachedTokenLexers]);
CurTokenLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens);
}
}
/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
/// the current file. This either returns the EOF token or pops a level off
/// the include stack and keeps going.
bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
assert(!CurTokenLexer &&
"Ending a file when currently in a macro!");
// See if this file had a controlling macro.
if (CurPPLexer) { // Not ending a macro, ignore it.
if (const IdentifierInfo *ControllingMacro =
CurPPLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
// Okay, this has a controlling macro, remember in HeaderFileInfo.
if (const FileEntry *FE =
SourceMgr.getFileEntryForID(CurPPLexer->getFileID()))
HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
}
}
// If this is a #include'd file, pop it off the include stack and continue
// lexing the #includer file.
if (!IncludeMacroStack.empty()) {
// We're done with the #included file.
RemoveTopOfLexerStack();
// Notify the client, if desired, that we are in a new source file.
if (Callbacks && !isEndOfMacro && CurPPLexer) {
SrcMgr::CharacteristicKind FileType =
SourceMgr.getFileCharacteristic(CurPPLexer->getSourceLocation());
Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
PPCallbacks::ExitFile, FileType);
}
// Client should lex another token.
return false;
}
// If the file ends with a newline, form the EOF token on the newline itself,
// rather than "on the line following it", which doesn't exist. This makes
// diagnostics relating to the end of file include the last file that the user
// actually typed, which is goodness.
if (CurLexer) {
const char *EndPos = CurLexer->BufferEnd;
if (EndPos != CurLexer->BufferStart &&
(EndPos[-1] == '\n' || EndPos[-1] == '\r')) {
--EndPos;
// Handle \n\r and \r\n:
if (EndPos != CurLexer->BufferStart &&
(EndPos[-1] == '\n' || EndPos[-1] == '\r') &&
EndPos[-1] != EndPos[0])
--EndPos;
}
Result.startToken();
CurLexer->BufferPtr = EndPos;
CurLexer->FormTokenWithChars(Result, EndPos, tok::eof);
// We're done with the #included file.
CurLexer.reset();
} else {
assert(CurPTHLexer && "Got EOF but no current lexer set!");
CurPTHLexer->getEOF(Result);
CurPTHLexer.reset();
}
CurPPLexer = 0;
// This is the end of the top-level file. If the diag::pp_macro_not_used
// diagnostic is enabled, look for macros that have not been used.
if (getDiagnostics().getDiagnosticLevel(diag::pp_macro_not_used) !=
Diagnostic::Ignored) {
for (macro_iterator I = macro_begin(), E = macro_end(); I != E; ++I)
if (!I->second->isUsed())
Diag(I->second->getDefinitionLoc(), diag::pp_macro_not_used);
}
return true;
}
/// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer
/// hits the end of its token stream.
bool Preprocessor::HandleEndOfTokenLexer(Token &Result) {
assert(CurTokenLexer && !CurPPLexer &&
"Ending a macro when currently in a #include file!");
// Delete or cache the now-dead macro expander.
if (NumCachedTokenLexers == TokenLexerCacheSize)
CurTokenLexer.reset();
else
TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.take();
// Handle this like a #include file being popped off the stack.
return HandleEndOfFile(Result, true);
}
/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
/// lexer stack. This should only be used in situations where the current
/// state of the top-of-stack lexer is unknown.
void Preprocessor::RemoveTopOfLexerStack() {
assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
if (CurTokenLexer) {
// Delete or cache the now-dead macro expander.
if (NumCachedTokenLexers == TokenLexerCacheSize)
CurTokenLexer.reset();
else
TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.take();
}
PopIncludeMacroStack();
}
/// HandleMicrosoftCommentPaste - When the macro expander pastes together a
/// comment (/##/) in microsoft mode, this method handles updating the current
/// state, returning the token on the next source line.
void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
assert(CurTokenLexer && !CurPPLexer &&
"Pasted comment can only be formed from macro");
// We handle this by scanning for the closest real lexer, switching it to
// raw mode and preprocessor mode. This will cause it to return \n as an
// explicit EOM token.
PreprocessorLexer *FoundLexer = 0;
bool LexerWasInPPMode = false;
for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
IncludeStackInfo &ISI = *(IncludeMacroStack.end()-i-1);
if (ISI.ThePPLexer == 0) continue; // Scan for a real lexer.
// Once we find a real lexer, mark it as raw mode (disabling macro
// expansions) and preprocessor mode (return EOM). We know that the lexer
// was *not* in raw mode before, because the macro that the comment came
// from was expanded. However, it could have already been in preprocessor
// mode (#if COMMENT) in which case we have to return it to that mode and
// return EOM.
FoundLexer = ISI.ThePPLexer;
FoundLexer->LexingRawMode = true;
LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
FoundLexer->ParsingPreprocessorDirective = true;
break;
}
// Okay, we either found and switched over the lexer, or we didn't find a
// lexer. In either case, finish off the macro the comment came from, getting
// the next token.
if (!HandleEndOfTokenLexer(Tok)) Lex(Tok);
// Discarding comments as long as we don't have EOF or EOM. This 'comments
// out' the rest of the line, including any tokens that came from other macros
// that were active, as in:
// #define submacro a COMMENT b
// submacro c
// which should lex to 'a' only: 'b' and 'c' should be removed.
while (Tok.isNot(tok::eom) && Tok.isNot(tok::eof))
Lex(Tok);
// If we got an eom token, then we successfully found the end of the line.
if (Tok.is(tok::eom)) {
assert(FoundLexer && "Can't get end of line without an active lexer");
// Restore the lexer back to normal mode instead of raw mode.
FoundLexer->LexingRawMode = false;
// If the lexer was already in preprocessor mode, just return the EOM token
// to finish the preprocessor line.
if (LexerWasInPPMode) return;
// Otherwise, switch out of PP mode and return the next lexed token.
FoundLexer->ParsingPreprocessorDirective = false;
return Lex(Tok);
}
// If we got an EOF token, then we reached the end of the token stream but
// didn't find an explicit \n. This can only happen if there was no lexer
// active (an active lexer would return EOM at EOF if there was no \n in
// preprocessor directive mode), so just return EOF as our token.
assert(!FoundLexer && "Lexer should return EOM before EOF in PP mode");
}
<|endoftext|> |
<commit_before>#include "ovpCBoxAlgorithmLevelMeasure.h"
#include "../../algorithms/simple-visualisation/ovpCAlgorithmLevelMeasure.h"
using namespace OpenViBE;
using namespace OpenViBE::Kernel;
using namespace OpenViBE::Plugins;
using namespace OpenViBEPlugins;
using namespace OpenViBEPlugins::SimpleVisualisation;
boolean CBoxAlgorithmLevelMeasure::initialize(void)
{
// CString l_sSettingValue;
// getStaticBoxContext().getSettingValue(0, l_sSettingValue);
// ...
m_pMatrix=new CMatrix();
m_pStreamedMatrixDecoder=&getAlgorithmManager().getAlgorithm(getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_StreamedMatrixStreamDecoder));
m_pLevelMeasure=&getAlgorithmManager().getAlgorithm(getAlgorithmManager().createAlgorithm(OVP_ClassId_Algorithm_LevelMeasure));
m_pStreamedMatrixDecoder->initialize();
m_pLevelMeasure->initialize();
ip_pStreamedMatrixDecoderMemoryBuffer.initialize(m_pStreamedMatrixDecoder->getInputParameter(OVP_GD_Algorithm_StreamedMatrixStreamDecoder_InputParameterId_MemoryBufferToDecode));
op_pStreamedMatrixDecoderMatrix.initialize(m_pStreamedMatrixDecoder->getOutputParameter(OVP_GD_Algorithm_StreamedMatrixStreamDecoder_OutputParameterId_Matrix));
ip_pLevelMeasureMatrix.initialize(m_pLevelMeasure->getInputParameter(OVP_Algorithm_LevelMeasure_InputParameterId_Matrix));
op_pLevelMeasureMainWidget.initialize(m_pLevelMeasure->getOutputParameter(OVP_Algorithm_LevelMeasure_OutputParameterId_MainWidget));
op_pLevelMeasureToolbarWidget.initialize(m_pLevelMeasure->getOutputParameter(OVP_Algorithm_LevelMeasure_OutputParameterId_ToolbarWidget));
op_pStreamedMatrixDecoderMatrix.setReferenceTarget(m_pMatrix);
ip_pLevelMeasureMatrix.setReferenceTarget(m_pMatrix);
return true;
}
boolean CBoxAlgorithmLevelMeasure::uninitialize(void)
{
op_pLevelMeasureToolbarWidget.uninitialize();
op_pLevelMeasureMainWidget.uninitialize();
ip_pLevelMeasureMatrix.uninitialize();
op_pStreamedMatrixDecoderMatrix.uninitialize();
ip_pStreamedMatrixDecoderMemoryBuffer.uninitialize();
m_pLevelMeasure->uninitialize();
m_pStreamedMatrixDecoder->uninitialize();
getAlgorithmManager().releaseAlgorithm(*m_pLevelMeasure);
getAlgorithmManager().releaseAlgorithm(*m_pStreamedMatrixDecoder);
delete m_pMatrix;
m_pMatrix=NULL;
return true;
}
boolean CBoxAlgorithmLevelMeasure::processInput(uint32 ui32InputIndex)
{
getBoxAlgorithmContext()->markAlgorithmAsReadyToProcess();
return true;
}
boolean CBoxAlgorithmLevelMeasure::process(void)
{
// IBox& l_rStaticBoxContext=this->getStaticBoxContext();
IBoxIO& l_rDynamicBoxContext=this->getDynamicBoxContext();
for(uint32 i=0; i<l_rDynamicBoxContext.getInputChunkCount(0); i++)
{
ip_pStreamedMatrixDecoderMemoryBuffer=l_rDynamicBoxContext.getInputChunk(0, i);
m_pStreamedMatrixDecoder->process();
if(m_pStreamedMatrixDecoder->isOutputTriggerActive(OVP_GD_Algorithm_StreamedMatrixStreamDecoder_OutputTriggerId_ReceivedHeader))
{
m_pLevelMeasure->process(OVP_Algorithm_LevelMeasure_InputTriggerId_Reset);
getVisualisationContext().setWidgets(op_pLevelMeasureMainWidget, op_pLevelMeasureToolbarWidget);
}
if(m_pStreamedMatrixDecoder->isOutputTriggerActive(OVP_GD_Algorithm_StreamedMatrixStreamDecoder_OutputTriggerId_ReceivedBuffer))
{
// ----- >8 ------------------------------------------------------------------------------------------------------------------------------------------------------
// should be done in a processing box !
float64 l_f64Min=1E10;
float64 l_f64Max=-1E10;
{
float64* l_pMatrixBuffer=m_pMatrix->getBuffer();
uint32 l_ui32ElementCount=m_pMatrix->getBufferElementCount();
while(l_ui32ElementCount--)
{
if(l_f64Max<*l_pMatrixBuffer) l_f64Max=*l_pMatrixBuffer;
if(l_f64Min>*l_pMatrixBuffer) l_f64Min=*l_pMatrixBuffer;
l_pMatrixBuffer++;
}
}
float64 l_f64Sum=0;
{
float64* l_pMatrixBuffer=m_pMatrix->getBuffer();
uint32 l_ui32ElementCount=m_pMatrix->getBufferElementCount();
while(l_ui32ElementCount--)
{
l_f64Sum+=*l_pMatrixBuffer;
l_pMatrixBuffer++;
}
}
{
float64 l_f64Factor=(l_f64Sum!=0?1./l_f64Sum:0.5);
float64* l_pMatrixBuffer=m_pMatrix->getBuffer();
uint32 l_ui32ElementCount=m_pMatrix->getBufferElementCount();
while(l_ui32ElementCount--)
{
*l_pMatrixBuffer*=l_f64Factor;
l_pMatrixBuffer++;
}
}
// ----- >8 ------------------------------------------------------------------------------------------------------------------------------------------------------
m_pLevelMeasure->process(OVP_Algorithm_LevelMeasure_InputTriggerId_Refresh);
}
if(m_pStreamedMatrixDecoder->isOutputTriggerActive(OVP_GD_Algorithm_StreamedMatrixStreamDecoder_OutputTriggerId_ReceivedEnd))
{
}
l_rDynamicBoxContext.markInputAsDeprecated(0, i);
}
return true;
}
<commit_msg><commit_after>#include "ovpCBoxAlgorithmLevelMeasure.h"
#include "../../algorithms/simple-visualisation/ovpCAlgorithmLevelMeasure.h"
using namespace OpenViBE;
using namespace OpenViBE::Kernel;
using namespace OpenViBE::Plugins;
using namespace OpenViBEPlugins;
using namespace OpenViBEPlugins::SimpleVisualisation;
boolean CBoxAlgorithmLevelMeasure::initialize(void)
{
// CString l_sSettingValue;
// getStaticBoxContext().getSettingValue(0, l_sSettingValue);
// ...
m_pMatrix=new CMatrix();
m_pStreamedMatrixDecoder=&getAlgorithmManager().getAlgorithm(getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_StreamedMatrixStreamDecoder));
m_pLevelMeasure=&getAlgorithmManager().getAlgorithm(getAlgorithmManager().createAlgorithm(OVP_ClassId_Algorithm_LevelMeasure));
m_pStreamedMatrixDecoder->initialize();
m_pLevelMeasure->initialize();
ip_pStreamedMatrixDecoderMemoryBuffer.initialize(m_pStreamedMatrixDecoder->getInputParameter(OVP_GD_Algorithm_StreamedMatrixStreamDecoder_InputParameterId_MemoryBufferToDecode));
op_pStreamedMatrixDecoderMatrix.initialize(m_pStreamedMatrixDecoder->getOutputParameter(OVP_GD_Algorithm_StreamedMatrixStreamDecoder_OutputParameterId_Matrix));
ip_pLevelMeasureMatrix.initialize(m_pLevelMeasure->getInputParameter(OVP_Algorithm_LevelMeasure_InputParameterId_Matrix));
op_pLevelMeasureMainWidget.initialize(m_pLevelMeasure->getOutputParameter(OVP_Algorithm_LevelMeasure_OutputParameterId_MainWidget));
op_pLevelMeasureToolbarWidget.initialize(m_pLevelMeasure->getOutputParameter(OVP_Algorithm_LevelMeasure_OutputParameterId_ToolbarWidget));
op_pStreamedMatrixDecoderMatrix.setReferenceTarget(m_pMatrix);
ip_pLevelMeasureMatrix.setReferenceTarget(m_pMatrix);
return true;
}
boolean CBoxAlgorithmLevelMeasure::uninitialize(void)
{
op_pLevelMeasureToolbarWidget.uninitialize();
op_pLevelMeasureMainWidget.uninitialize();
ip_pLevelMeasureMatrix.uninitialize();
op_pStreamedMatrixDecoderMatrix.uninitialize();
ip_pStreamedMatrixDecoderMemoryBuffer.uninitialize();
m_pLevelMeasure->uninitialize();
m_pStreamedMatrixDecoder->uninitialize();
getAlgorithmManager().releaseAlgorithm(*m_pLevelMeasure);
getAlgorithmManager().releaseAlgorithm(*m_pStreamedMatrixDecoder);
delete m_pMatrix;
m_pMatrix=NULL;
return true;
}
boolean CBoxAlgorithmLevelMeasure::processInput(uint32 ui32InputIndex)
{
getBoxAlgorithmContext()->markAlgorithmAsReadyToProcess();
return true;
}
boolean CBoxAlgorithmLevelMeasure::process(void)
{
// IBox& l_rStaticBoxContext=this->getStaticBoxContext();
IBoxIO& l_rDynamicBoxContext=this->getDynamicBoxContext();
for(uint32 i=0; i<l_rDynamicBoxContext.getInputChunkCount(0); i++)
{
ip_pStreamedMatrixDecoderMemoryBuffer=l_rDynamicBoxContext.getInputChunk(0, i);
m_pStreamedMatrixDecoder->process();
if(m_pStreamedMatrixDecoder->isOutputTriggerActive(OVP_GD_Algorithm_StreamedMatrixStreamDecoder_OutputTriggerId_ReceivedHeader))
{
m_pLevelMeasure->process(OVP_Algorithm_LevelMeasure_InputTriggerId_Reset);
getVisualisationContext().setWidgets(op_pLevelMeasureMainWidget, op_pLevelMeasureToolbarWidget);
}
if(m_pStreamedMatrixDecoder->isOutputTriggerActive(OVP_GD_Algorithm_StreamedMatrixStreamDecoder_OutputTriggerId_ReceivedBuffer))
{
// ----- >8 ------------------------------------------------------------------------------------------------------------------------------------------------------
// should be done in a processing box !
float64 l_f64Sum=0;
{
float64* l_pMatrixBuffer=m_pMatrix->getBuffer();
uint32 l_ui32ElementCount=m_pMatrix->getBufferElementCount();
while(l_ui32ElementCount--)
{
l_f64Sum+=*l_pMatrixBuffer;
l_pMatrixBuffer++;
}
}
{
float64 l_f64Factor=(l_f64Sum!=0?1./l_f64Sum:0.5);
float64* l_pMatrixBuffer=m_pMatrix->getBuffer();
uint32 l_ui32ElementCount=m_pMatrix->getBufferElementCount();
while(l_ui32ElementCount--)
{
*l_pMatrixBuffer*=l_f64Factor;
l_pMatrixBuffer++;
}
}
// ----- >8 ------------------------------------------------------------------------------------------------------------------------------------------------------
m_pLevelMeasure->process(OVP_Algorithm_LevelMeasure_InputTriggerId_Refresh);
}
if(m_pStreamedMatrixDecoder->isOutputTriggerActive(OVP_GD_Algorithm_StreamedMatrixStreamDecoder_OutputTriggerId_ReceivedEnd))
{
}
l_rDynamicBoxContext.markInputAsDeprecated(0, i);
}
return true;
}
<|endoftext|> |
<commit_before>///////////////////////////////////////////////////////////////////////////////
// FILE: PrecisExcite.cpp
// PROJECT: Micro-Manager
// SUBSYSTEM: DeviceAdapters
//-----------------------------------------------------------------------------
// DESCRIPTION: PrecisExcite controller adapter
// COPYRIGHT: University of California, San Francisco, 2009
//
// AUTHOR: Arthur Edelstein, arthuredelstein@gmail.com, 3/17/2009
//
// LICENSE: This file is distributed under the BSD license.
// License text is included with the source distribution.
//
// This file 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.
//
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
//
// CVS:
//
#ifdef WIN32
#include <windows.h>
#define snprintf _snprintf
#endif
#include "../../MMDevice/MMDevice.h"
#include "PrecisExcite.h"
#include <string>
#include <math.h>
#include "../../MMDevice/ModuleInterface.h"
#include "../../MMDevice/DeviceUtils.h"
#include <sstream>
// Controller
const char* g_ControllerName = "PrecisExcite";
const char* g_Keyword_Intensity = "Intensity";
const char* g_Keyword_Trigger = "Trigger";
const char* g_Keyword_Trigger_Sequence = "TriggerSequence";
const char * carriage_return = "\r";
const char * line_feed = "\n";
///////////////////////////////////////////////////////////////////////////////
// Exported MMDevice API
///////////////////////////////////////////////////////////////////////////////
MODULE_API void InitializeModuleData()
{
RegisterDevice(g_ControllerName, MM::ShutterDevice, "PrecisExcite LED illuminator");
}
MODULE_API MM::Device* CreateDevice(const char* deviceName)
{
if (deviceName == 0)
return 0;
if (strcmp(deviceName, g_ControllerName) == 0)
{
// create Controller
Controller* pController = new Controller(g_ControllerName);
return pController;
}
return 0;
}
MODULE_API void DeleteDevice(MM::Device* pDevice)
{
delete pDevice;
}
///////////////////////////////////////////////////////////////////////////////
// Controller implementation
// ~~~~~~~~~~~~~~~~~~~~
Controller::Controller(const char* name) :
initialized_(false),
intensity_(0),
state_(0),
name_(name),
busy_(false),
error_(0),
changedTime_(0.0)
{
assert(strlen(name) < (unsigned int) MM::MaxStrLength);
InitializeDefaultErrorMessages();
// create pre-initialization properties
// ------------------------------------
// Name
CreateProperty(MM::g_Keyword_Name, name_.c_str(), MM::String, true);
// Description
CreateProperty(MM::g_Keyword_Description, "PrecisExcite LED Illuminator", MM::String, true);
// Port
CPropertyAction* pAct = new CPropertyAction (this, &Controller::OnPort);
CreateProperty(MM::g_Keyword_Port, "Undefined", MM::String, false, pAct, true);
EnableDelay(); // signals that the delay setting will be used
UpdateStatus();
}
Controller::~Controller()
{
Shutdown();
}
bool Controller::Busy()
{
MM::MMTime interval = GetCurrentMMTime() - changedTime_;
MM::MMTime delay(GetDelayMs()*1000.0);
if (interval < delay)
return true;
else
return false;
}
void Controller::GetName(char* name) const
{
assert(name_.length() < CDeviceUtils::GetMaxStringLength());
CDeviceUtils::CopyLimitedString(name, name_.c_str());
}
int Controller::Initialize()
{
// set property list
// -----------------
/*
MM::Device* serialDevice = GetCoreCallback()->GetDevice(this, port_.c_str());
if (serialDevice == NULL) {
LogMessage("Serial port not found");
return DEVICE_SERIAL_COMMAND_FAILED;
}
*/
this->LogMessage("Controller::Initialize()");
currentChannel_ = 0;
ReadGreeting();
int result = ReadChannelLabels();
if (result != DEVICE_OK)
return result;
GenerateChannelChooser();
GeneratePropertyIntensity();
GeneratePropertyState();
GeneratePropertyTrigger();
GeneratePropertyTriggerSequence();
initialized_ = true;
return HandleErrors();
}
void Controller::ReadGreeting()
{
do {
ReceiveOneLine();
} while (! buf_string_.empty());
}
int Controller::ReadChannelLabels()
{
buf_tokens_.clear();
string label;
Purge();
Send("LAMS");
do {
ReceiveOneLine();
buf_tokens_.push_back(buf_string_);
}
while(! buf_string_.empty());
for (unsigned int i=0;i<buf_tokens_.size();i++)
{
if (buf_tokens_[i].substr(0,3).compare("LAM")==0) {
string label = buf_tokens_[i].substr(6);
StripString(label);
//This skips invalid channels.
//Invalid names seem to have a different number of dashes.
//pe2: First invalid is called ----, then second is -----
if (label.substr(0,4).compare("----") == 0)
continue;
channelLetters_.push_back(buf_tokens_[i][4]); // Read 4th character
// This is a temporary log entry to debug an issue with channel labels
// that appear to contain an invalid character at the end.
std::ostringstream ss;
ss << "debug: last char of stripped label is: \'" <<
static_cast<int>(label[label.size()]) << "\' (as decimal int)";
LogMessage(ss.str().c_str(), true);
channelLabels_.push_back(label);
}
}
if (channelLabels_.size() == 0)
return DEVICE_ERR;
else
return DEVICE_OK;
}
/////////////////////////////////////////////
// Property Generators
/////////////////////////////////////////////
void Controller::GeneratePropertyState()
{
CPropertyAction* pAct = new CPropertyAction (this, &Controller::OnState);
CreateProperty(MM::g_Keyword_State, "0", MM::Integer, false, pAct);
AddAllowedValue(MM::g_Keyword_State, "0");
AddAllowedValue(MM::g_Keyword_State, "1");
}
void Controller::GeneratePropertyTrigger()
{
CPropertyAction* pAct = new CPropertyAction (this, &Controller::OnTrigger);
CreateProperty("Trigger", "Off", MM::String, false, pAct);
for (TriggerType i=OFF;i<=FOLLOW_PULSE;i=TriggerType(i+1))
AddAllowedValue("Trigger", TriggerLabels[i].c_str());
SetProperty("Trigger","Off");
}
void Controller::GenerateChannelChooser()
{
if (! channelLabels_.empty()) {
CPropertyAction* pAct;
pAct = new CPropertyAction (this, &Controller::OnChannelLabel);
CreateProperty("ChannelLabel", channelLabels_[0].c_str(), MM::String, false, pAct);
SetAllowedValues("ChannelLabel",channelLabels_);
SetProperty("ChannelLabel",channelLabels_[0].c_str());
}
}
void Controller::GeneratePropertyIntensity()
{
string intensityName;
CPropertyActionEx* pAct;
for (unsigned i=0;i<channelLetters_.size();i++)
{
pAct = new CPropertyActionEx(this, &Controller::OnIntensity, i);
intensityName = g_Keyword_Intensity;
intensityName.push_back(channelLetters_[i]);
CreateProperty(intensityName.c_str(), "0", MM::Integer, false, pAct);
SetPropertyLimits(intensityName.c_str(), 0, 100);
}
}
int Controller::Shutdown()
{
if (initialized_)
{
initialized_ = false;
}
return HandleErrors();
}
void Controller::GeneratePropertyTriggerSequence()
{
int ret;
CPropertyAction* pAct = new CPropertyAction (this, &Controller::OnTriggerSequence);
ret = CreateProperty(g_Keyword_Trigger_Sequence, "ABCD0", MM::String, false, pAct);
SetProperty(g_Keyword_Trigger_Sequence, "ABCD0");
}
///////////////////////////////////////////////////////////////////////////////
// String utilities
///////////////////////////////////////////////////////////////////////////////
void Controller::StripString(string& StringToModify)
{
if(StringToModify.empty()) return;
const char* spaces = " \f\n\r\t\v";
size_t startIndex = StringToModify.find_first_not_of(spaces);
size_t endIndex = StringToModify.find_last_not_of(spaces);
string tempString = StringToModify;
StringToModify.erase();
StringToModify = tempString.substr(startIndex, (endIndex-startIndex+ 1) );
}
///////////////////////////////////////////////////////////////////////////////
// Action handlers
///////////////////////////////////////////////////////////////////////////////
int Controller::OnPort(MM::PropertyBase* pProp, MM::ActionType eAct)
{
if (eAct == MM::BeforeGet)
{
pProp->Set(port_.c_str());
}
else if (eAct == MM::AfterSet)
{
if (initialized_)
{
// revert
pProp->Set(port_.c_str());
return ERR_PORT_CHANGE_FORBIDDEN;
}
pProp->Get(port_);
}
return HandleErrors();
}
int Controller::OnIntensity(MM::PropertyBase* pProp, MM::ActionType eAct, long index)
{
long intensity;
if (eAct == MM::BeforeGet)
{
GetIntensity(intensity,index);
pProp->Set(intensity);
}
else if (eAct == MM::AfterSet)
{
pProp->Get(intensity);
SetIntensity(intensity, index);
}
return HandleErrors();
}
int Controller::OnChannelLabel(MM::PropertyBase* pProp, MM::ActionType eAct)
{
if (eAct == MM::BeforeGet)
{
pProp->Set(currentChannelLabel_.c_str());
}
else if (eAct == MM::AfterSet)
{
GetState(state_);
pProp->Get(currentChannelLabel_);
for (unsigned int i=0;i<channelLabels_.size();i++)
if (channelLabels_[i].compare(currentChannelLabel_) == 0)
{
currentChannel_ = i;
SetState(state_);
}
}
return HandleErrors();
}
int Controller::OnState(MM::PropertyBase* pProp, MM::ActionType eAct)
{
if (eAct == MM::BeforeGet)
{
GetState(state_);
pProp->Set(state_);
}
else if (eAct == MM::AfterSet)
{
pProp->Get(state_);
SetState(state_);
}
return HandleErrors();
}
int Controller::OnTrigger(MM::PropertyBase* pProp, MM::ActionType eAct)
{
if (eAct == MM::BeforeGet)
{
pProp->Set(trigger_.c_str());
}
else if (eAct == MM::AfterSet)
{
char cmd=0;
pProp->Get(trigger_);
for (int i=0;i<5;i++)
{
if (trigger_.compare(TriggerLabels[i])==0)
{
cmd = TriggerCmd[i];
triggerMode_ = (TriggerType) i;
}
}
SetTrigger();
}
return HandleErrors();
}
int Controller::OnTriggerSequence(MM::PropertyBase* pProp, MM::ActionType eAct)
{
if (eAct == MM::BeforeGet)
{
pProp->Set(triggerSequence_.c_str());
}
else if (eAct == MM::AfterSet)
{
pProp->Get(triggerSequence_);
SetTrigger();
}
return HandleErrors();
}
///////////////////////////////////////////////////////////////////////////////
// Utility methods
///////////////////////////////////////////////////////////////////////////////
void Controller::SetTrigger()
{
stringstream msg;
msg << "SQX" << carriage_return;
for (unsigned int i=0;i<triggerSequence_.size();i++)
{
msg << "SQ" << triggerSequence_[i] << carriage_return;
}
triggerMessage_ = msg.str();
Illuminate();
}
void Controller::Illuminate()
{
stringstream msg;
if (state_==0)
{
if (triggerMode_ == OFF || triggerMode_ == FOLLOW_PULSE)
msg << "SQX" << carriage_return << "C" << channelLetters_[currentChannel_] << "F" << carriage_return << "AZ";
else
msg << "SQX" << "AZ";
}
else if (state_==1)
{
if (triggerMode_ == OFF) {
msg << "SQZ" << carriage_return;
for (unsigned int i=0; i<channelLetters_.size(); i++) {
msg << "C" << channelLetters_[i];
if (i == currentChannel_)
msg << "N";
else
msg << "F";
msg << carriage_return;
}
}
else if (triggerMode_ == FOLLOW_PULSE)
msg << "SQZ" << carriage_return << "A" << channelLetters_[currentChannel_] << "#";
else
msg << triggerMessage_ << "SQ" << TriggerCmd[triggerMode_];
}
Send(msg.str());
}
void Controller::SetIntensity(long intensity, long index)
{
stringstream msg;
msg << "C" << channelLetters_[index] << "I" << intensity;
Purge();
Send(msg.str());
ReceiveOneLine();
}
void Controller::GetIntensity(long& intensity, long index)
{
stringstream msg;
string ans;
msg << "C" << channelLetters_[index] << "?";
Purge();
Send(msg.str());
ReceiveOneLine();
if (! buf_string_.empty())
if (0 == buf_string_.compare(0,2,msg.str(),0,2))
{
intensity = atol(buf_string_.substr(2,3).c_str());
}
}
void Controller::SetState(long state)
{
state_ = state;
stringstream msg;
Illuminate();
// Set timer for the Busy signal
changedTime_ = GetCurrentMMTime();
}
void Controller::GetState(long &state)
{
if (triggerMode_ == OFF) {
Purge();
Send("C?");
long stateTmp = 0;
for (unsigned int i=0;i<channelLetters_.size();i++)
{
ReceiveOneLine();
if (! buf_string_.empty())
if (buf_string_[5]=='N')
stateTmp = 1;
}
state = stateTmp;
}
else
state = state_;
}
int Controller::HandleErrors()
{
int lastError = error_;
error_ = 0;
return lastError;
}
/////////////////////////////////////
// Communications
/////////////////////////////////////
void Controller::Send(string cmd)
{
int ret = SendSerialCommand(port_.c_str(), cmd.c_str(), carriage_return);
if (ret!=DEVICE_OK)
error_ = DEVICE_SERIAL_COMMAND_FAILED;
}
void Controller::ReceiveOneLine()
{
buf_string_ = "";
GetSerialAnswer(port_.c_str(), line_feed, buf_string_);
}
void Controller::Purge()
{
int ret = PurgeComPort(port_.c_str());
if (ret!=0)
error_ = DEVICE_SERIAL_COMMAND_FAILED;
}
//********************
// Shutter API
//********************
int Controller::SetOpen(bool open)
{
SetState((long) open);
return HandleErrors();
}
int Controller::GetOpen(bool& open)
{
long state;
GetState(state);
if (state==1)
open = true;
else if (state==0)
open = false;
else
error_ = DEVICE_UNKNOWN_POSITION;
return HandleErrors();
}
int Controller::Fire(double deltaT)
{
deltaT=0; // Suppress warning
error_ = DEVICE_UNSUPPORTED_COMMAND;
return HandleErrors();
}
<commit_msg>PrecisExcite: Fixed warning about signed / unsigned comparison (Egor Zindy)<commit_after>///////////////////////////////////////////////////////////////////////////////
// FILE: PrecisExcite.cpp
// PROJECT: Micro-Manager
// SUBSYSTEM: DeviceAdapters
//-----------------------------------------------------------------------------
// DESCRIPTION: PrecisExcite controller adapter
// COPYRIGHT: University of California, San Francisco, 2009
//
// AUTHOR: Arthur Edelstein, arthuredelstein@gmail.com, 3/17/2009
//
// LICENSE: This file is distributed under the BSD license.
// License text is included with the source distribution.
//
// This file 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.
//
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
//
// CVS:
//
#ifdef WIN32
#include <windows.h>
#define snprintf _snprintf
#endif
#include "../../MMDevice/MMDevice.h"
#include "PrecisExcite.h"
#include <string>
#include <math.h>
#include "../../MMDevice/ModuleInterface.h"
#include "../../MMDevice/DeviceUtils.h"
#include <sstream>
// Controller
const char* g_ControllerName = "PrecisExcite";
const char* g_Keyword_Intensity = "Intensity";
const char* g_Keyword_Trigger = "Trigger";
const char* g_Keyword_Trigger_Sequence = "TriggerSequence";
const char * carriage_return = "\r";
const char * line_feed = "\n";
///////////////////////////////////////////////////////////////////////////////
// Exported MMDevice API
///////////////////////////////////////////////////////////////////////////////
MODULE_API void InitializeModuleData()
{
RegisterDevice(g_ControllerName, MM::ShutterDevice, "PrecisExcite LED illuminator");
}
MODULE_API MM::Device* CreateDevice(const char* deviceName)
{
if (deviceName == 0)
return 0;
if (strcmp(deviceName, g_ControllerName) == 0)
{
// create Controller
Controller* pController = new Controller(g_ControllerName);
return pController;
}
return 0;
}
MODULE_API void DeleteDevice(MM::Device* pDevice)
{
delete pDevice;
}
///////////////////////////////////////////////////////////////////////////////
// Controller implementation
// ~~~~~~~~~~~~~~~~~~~~
Controller::Controller(const char* name) :
initialized_(false),
intensity_(0),
state_(0),
name_(name),
busy_(false),
error_(0),
changedTime_(0.0)
{
assert(strlen(name) < (unsigned int) MM::MaxStrLength);
InitializeDefaultErrorMessages();
// create pre-initialization properties
// ------------------------------------
// Name
CreateProperty(MM::g_Keyword_Name, name_.c_str(), MM::String, true);
// Description
CreateProperty(MM::g_Keyword_Description, "PrecisExcite LED Illuminator", MM::String, true);
// Port
CPropertyAction* pAct = new CPropertyAction (this, &Controller::OnPort);
CreateProperty(MM::g_Keyword_Port, "Undefined", MM::String, false, pAct, true);
EnableDelay(); // signals that the delay setting will be used
UpdateStatus();
}
Controller::~Controller()
{
Shutdown();
}
bool Controller::Busy()
{
MM::MMTime interval = GetCurrentMMTime() - changedTime_;
MM::MMTime delay(GetDelayMs()*1000.0);
if (interval < delay)
return true;
else
return false;
}
void Controller::GetName(char* name) const
{
assert(name_.length() < CDeviceUtils::GetMaxStringLength());
CDeviceUtils::CopyLimitedString(name, name_.c_str());
}
int Controller::Initialize()
{
// set property list
// -----------------
/*
MM::Device* serialDevice = GetCoreCallback()->GetDevice(this, port_.c_str());
if (serialDevice == NULL) {
LogMessage("Serial port not found");
return DEVICE_SERIAL_COMMAND_FAILED;
}
*/
this->LogMessage("Controller::Initialize()");
currentChannel_ = 0;
ReadGreeting();
int result = ReadChannelLabels();
if (result != DEVICE_OK)
return result;
GenerateChannelChooser();
GeneratePropertyIntensity();
GeneratePropertyState();
GeneratePropertyTrigger();
GeneratePropertyTriggerSequence();
initialized_ = true;
return HandleErrors();
}
void Controller::ReadGreeting()
{
do {
ReceiveOneLine();
} while (! buf_string_.empty());
}
int Controller::ReadChannelLabels()
{
buf_tokens_.clear();
string label;
Purge();
Send("LAMS");
do {
ReceiveOneLine();
buf_tokens_.push_back(buf_string_);
}
while(! buf_string_.empty());
for (unsigned int i=0;i<buf_tokens_.size();i++)
{
if (buf_tokens_[i].substr(0,3).compare("LAM")==0) {
string label = buf_tokens_[i].substr(6);
StripString(label);
//This skips invalid channels.
//Invalid names seem to have a different number of dashes.
//pe2: First invalid is called ----, then second is -----
if (label.substr(0,4).compare("----") == 0)
continue;
channelLetters_.push_back(buf_tokens_[i][4]); // Read 4th character
// This is a temporary log entry to debug an issue with channel labels
// that appear to contain an invalid character at the end.
std::ostringstream ss;
ss << "debug: last char of stripped label is: \'" <<
static_cast<int>(label[label.size()]) << "\' (as decimal int)";
LogMessage(ss.str().c_str(), true);
channelLabels_.push_back(label);
}
}
if (channelLabels_.size() == 0)
return DEVICE_ERR;
else
return DEVICE_OK;
}
/////////////////////////////////////////////
// Property Generators
/////////////////////////////////////////////
void Controller::GeneratePropertyState()
{
CPropertyAction* pAct = new CPropertyAction (this, &Controller::OnState);
CreateProperty(MM::g_Keyword_State, "0", MM::Integer, false, pAct);
AddAllowedValue(MM::g_Keyword_State, "0");
AddAllowedValue(MM::g_Keyword_State, "1");
}
void Controller::GeneratePropertyTrigger()
{
CPropertyAction* pAct = new CPropertyAction (this, &Controller::OnTrigger);
CreateProperty("Trigger", "Off", MM::String, false, pAct);
for (TriggerType i=OFF;i<=FOLLOW_PULSE;i=TriggerType(i+1))
AddAllowedValue("Trigger", TriggerLabels[i].c_str());
SetProperty("Trigger","Off");
}
void Controller::GenerateChannelChooser()
{
if (! channelLabels_.empty()) {
CPropertyAction* pAct;
pAct = new CPropertyAction (this, &Controller::OnChannelLabel);
CreateProperty("ChannelLabel", channelLabels_[0].c_str(), MM::String, false, pAct);
SetAllowedValues("ChannelLabel",channelLabels_);
SetProperty("ChannelLabel",channelLabels_[0].c_str());
}
}
void Controller::GeneratePropertyIntensity()
{
string intensityName;
CPropertyActionEx* pAct;
for (unsigned i=0;i<channelLetters_.size();i++)
{
pAct = new CPropertyActionEx(this, &Controller::OnIntensity, i);
intensityName = g_Keyword_Intensity;
intensityName.push_back(channelLetters_[i]);
CreateProperty(intensityName.c_str(), "0", MM::Integer, false, pAct);
SetPropertyLimits(intensityName.c_str(), 0, 100);
}
}
int Controller::Shutdown()
{
if (initialized_)
{
initialized_ = false;
}
return HandleErrors();
}
void Controller::GeneratePropertyTriggerSequence()
{
int ret;
CPropertyAction* pAct = new CPropertyAction (this, &Controller::OnTriggerSequence);
ret = CreateProperty(g_Keyword_Trigger_Sequence, "ABCD0", MM::String, false, pAct);
SetProperty(g_Keyword_Trigger_Sequence, "ABCD0");
}
///////////////////////////////////////////////////////////////////////////////
// String utilities
///////////////////////////////////////////////////////////////////////////////
void Controller::StripString(string& StringToModify)
{
if(StringToModify.empty()) return;
const char* spaces = " \f\n\r\t\v";
size_t startIndex = StringToModify.find_first_not_of(spaces);
size_t endIndex = StringToModify.find_last_not_of(spaces);
string tempString = StringToModify;
StringToModify.erase();
StringToModify = tempString.substr(startIndex, (endIndex-startIndex+ 1) );
}
///////////////////////////////////////////////////////////////////////////////
// Action handlers
///////////////////////////////////////////////////////////////////////////////
int Controller::OnPort(MM::PropertyBase* pProp, MM::ActionType eAct)
{
if (eAct == MM::BeforeGet)
{
pProp->Set(port_.c_str());
}
else if (eAct == MM::AfterSet)
{
if (initialized_)
{
// revert
pProp->Set(port_.c_str());
return ERR_PORT_CHANGE_FORBIDDEN;
}
pProp->Get(port_);
}
return HandleErrors();
}
int Controller::OnIntensity(MM::PropertyBase* pProp, MM::ActionType eAct, long index)
{
long intensity;
if (eAct == MM::BeforeGet)
{
GetIntensity(intensity,index);
pProp->Set(intensity);
}
else if (eAct == MM::AfterSet)
{
pProp->Get(intensity);
SetIntensity(intensity, index);
}
return HandleErrors();
}
int Controller::OnChannelLabel(MM::PropertyBase* pProp, MM::ActionType eAct)
{
if (eAct == MM::BeforeGet)
{
pProp->Set(currentChannelLabel_.c_str());
}
else if (eAct == MM::AfterSet)
{
GetState(state_);
pProp->Get(currentChannelLabel_);
for (unsigned int i=0;i<channelLabels_.size();i++)
if (channelLabels_[i].compare(currentChannelLabel_) == 0)
{
currentChannel_ = i;
SetState(state_);
}
}
return HandleErrors();
}
int Controller::OnState(MM::PropertyBase* pProp, MM::ActionType eAct)
{
if (eAct == MM::BeforeGet)
{
GetState(state_);
pProp->Set(state_);
}
else if (eAct == MM::AfterSet)
{
pProp->Get(state_);
SetState(state_);
}
return HandleErrors();
}
int Controller::OnTrigger(MM::PropertyBase* pProp, MM::ActionType eAct)
{
if (eAct == MM::BeforeGet)
{
pProp->Set(trigger_.c_str());
}
else if (eAct == MM::AfterSet)
{
char cmd=0;
pProp->Get(trigger_);
for (int i=0;i<5;i++)
{
if (trigger_.compare(TriggerLabels[i])==0)
{
cmd = TriggerCmd[i];
triggerMode_ = (TriggerType) i;
}
}
SetTrigger();
}
return HandleErrors();
}
int Controller::OnTriggerSequence(MM::PropertyBase* pProp, MM::ActionType eAct)
{
if (eAct == MM::BeforeGet)
{
pProp->Set(triggerSequence_.c_str());
}
else if (eAct == MM::AfterSet)
{
pProp->Get(triggerSequence_);
SetTrigger();
}
return HandleErrors();
}
///////////////////////////////////////////////////////////////////////////////
// Utility methods
///////////////////////////////////////////////////////////////////////////////
void Controller::SetTrigger()
{
stringstream msg;
msg << "SQX" << carriage_return;
for (unsigned int i=0;i<triggerSequence_.size();i++)
{
msg << "SQ" << triggerSequence_[i] << carriage_return;
}
triggerMessage_ = msg.str();
Illuminate();
}
void Controller::Illuminate()
{
stringstream msg;
if (state_==0)
{
if (triggerMode_ == OFF || triggerMode_ == FOLLOW_PULSE)
msg << "SQX" << carriage_return << "C" << channelLetters_[currentChannel_] << "F" << carriage_return << "AZ";
else
msg << "SQX" << "AZ";
}
else if (state_==1)
{
if (triggerMode_ == OFF) {
msg << "SQZ" << carriage_return;
for (int i=0; i<channelLetters_.size(); i++) {
msg << "C" << channelLetters_[i];
if (i == currentChannel_)
msg << "N";
else
msg << "F";
msg << carriage_return;
}
}
else if (triggerMode_ == FOLLOW_PULSE)
msg << "SQZ" << carriage_return << "A" << channelLetters_[currentChannel_] << "#";
else
msg << triggerMessage_ << "SQ" << TriggerCmd[triggerMode_];
}
Send(msg.str());
}
void Controller::SetIntensity(long intensity, long index)
{
stringstream msg;
msg << "C" << channelLetters_[index] << "I" << intensity;
Purge();
Send(msg.str());
ReceiveOneLine();
}
void Controller::GetIntensity(long& intensity, long index)
{
stringstream msg;
string ans;
msg << "C" << channelLetters_[index] << "?";
Purge();
Send(msg.str());
ReceiveOneLine();
if (! buf_string_.empty())
if (0 == buf_string_.compare(0,2,msg.str(),0,2))
{
intensity = atol(buf_string_.substr(2,3).c_str());
}
}
void Controller::SetState(long state)
{
state_ = state;
stringstream msg;
Illuminate();
// Set timer for the Busy signal
changedTime_ = GetCurrentMMTime();
}
void Controller::GetState(long &state)
{
if (triggerMode_ == OFF) {
Purge();
Send("C?");
long stateTmp = 0;
for (unsigned int i=0;i<channelLetters_.size();i++)
{
ReceiveOneLine();
if (! buf_string_.empty())
if (buf_string_[5]=='N')
stateTmp = 1;
}
state = stateTmp;
}
else
state = state_;
}
int Controller::HandleErrors()
{
int lastError = error_;
error_ = 0;
return lastError;
}
/////////////////////////////////////
// Communications
/////////////////////////////////////
void Controller::Send(string cmd)
{
int ret = SendSerialCommand(port_.c_str(), cmd.c_str(), carriage_return);
if (ret!=DEVICE_OK)
error_ = DEVICE_SERIAL_COMMAND_FAILED;
}
void Controller::ReceiveOneLine()
{
buf_string_ = "";
GetSerialAnswer(port_.c_str(), line_feed, buf_string_);
}
void Controller::Purge()
{
int ret = PurgeComPort(port_.c_str());
if (ret!=0)
error_ = DEVICE_SERIAL_COMMAND_FAILED;
}
//********************
// Shutter API
//********************
int Controller::SetOpen(bool open)
{
SetState((long) open);
return HandleErrors();
}
int Controller::GetOpen(bool& open)
{
long state;
GetState(state);
if (state==1)
open = true;
else if (state==0)
open = false;
else
error_ = DEVICE_UNKNOWN_POSITION;
return HandleErrors();
}
int Controller::Fire(double deltaT)
{
deltaT=0; // Suppress warning
error_ = DEVICE_UNSUPPORTED_COMMAND;
return HandleErrors();
}
<|endoftext|> |
<commit_before>/**
* @file SimpleMotionBehaviorControl.cpp
*
* @author <a href="mailto:mellmann@informatik.hu-berlin.de">Heinrich Mellmann</a>
* @author <a href="mailto:goehring@informatik.hu-berlin.de">Daniel Goehring</a>
* Implementation of class SimpleMotionBehaviorControl
*/
#include "SimpleMotionBehaviorControl.h"
#include "Tools/Debug/DebugRequest.h"
#include "Tools/Debug/DebugModify.h"
SimpleMotionBehaviorControl::SimpleMotionBehaviorControl()
{
// test head control
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:head:Search", "Set the HeadMotion-Request to 'search'.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:head:reverseSearchDirection", "Set the head search direction to counterclockwise.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:head:LookAtBall_image", "Set the HeadMotion-Request to 'look_at_ball'.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:head:LookAtBall_field", "Set the HeadMotion-Request to 'look_at_ball'.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:head:Stabilize", "Set the HeadMotion-Request to 'stabilize'.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:head:SwitchToBottomCamera", "Switch to bottom camera", true);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:head:look_at_ball_modell", "Search for ball if not seen", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:head:look_straight_ahead", "look straight ahead", false);
// test motion control
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:standard_stand", "stand as standard or not", true);
// walk
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:walk_forward", "Walk foraward as fast as possible", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:walk_backward", "Walk backward as fast as possible", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:strafe_left", "Set the motion request to 'strafe'.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:strafe_right", "Set the motion request to 'strafe'.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:turn_left", "Set the motion request to 'turn_right'.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:turn_right", "Set the motion request to 'turn_right'.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:walk_forward", "Walk foraward as fast as possible", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:stepping", "walk with zero speed", false);
// key frame motion
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:stand_up_from_front", "Set the motion request to 'stand_up_from_front'", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:stand_up_from_back", "Set the motion request to 'stand_up_from_back'", false);
// other motions
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:dead", "Set the robot dead.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:stand", "The default motion, otherwise do nothing", true);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:sit", "sit down, has a rest", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:init", "Set the robot init.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:dance", "Let's dance", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:protect_falling", "Don't hurt me!", false);
}
void SimpleMotionBehaviorControl::execute()
{
// reset some stuff by default
getMotionRequest().forced = false;
getMotionRequest().standHeight = -1; // sit in a stable position
testHead();
testMotion();
}//end execute
void SimpleMotionBehaviorControl::testHead()
{
getHeadMotionRequest().cameraID = CameraInfo::Top;
DEBUG_REQUEST("SimpleMotionBehaviorControl:head:SwitchToBottomCamera",
getHeadMotionRequest().cameraID = CameraInfo::Bottom;
);
// keep the head as forced by default
getHeadMotionRequest().id = HeadMotionRequest::hold;
DEBUG_REQUEST("SimpleMotionBehaviorControl:head:Search",
getHeadMotionRequest().id = HeadMotionRequest::search;
getHeadMotionRequest().searchCenter = Vector3<double>(2000, 0, 0);
getHeadMotionRequest().searchSize = Vector3<double>(1500, 2000, 0);
);
getHeadMotionRequest().searchDirection = true;
DEBUG_REQUEST("SimpleMotionBehaviorControl:head:reverseSearchDirection",
getHeadMotionRequest().searchDirection = false;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:head:Stabilize",
getHeadMotionRequest().id = HeadMotionRequest::stabilize;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:head:LookAtBall_image",
if (getBallPercept().ballWasSeen)
{
getHeadMotionRequest().id = HeadMotionRequest::look_at_point;
getHeadMotionRequest().targetPointInImage = getBallPercept().centerInImage;
}
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:head:LookAtBall_field",
if (getBallPercept().ballWasSeen)
{
getHeadMotionRequest().id = HeadMotionRequest::look_at_world_point;
getHeadMotionRequest().targetPointInTheWorld.x = getBallPercept().bearingBasedOffsetOnField.x;
getHeadMotionRequest().targetPointInTheWorld.y = getBallPercept().bearingBasedOffsetOnField.y;
getHeadMotionRequest().targetPointInTheWorld.z = getFieldInfo().ballRadius;
}
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:head:look_straight_ahead",
getHeadMotionRequest().id = HeadMotionRequest::look_straight_ahead;
);
}//end testHead
void SimpleMotionBehaviorControl::testMotion()
{
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:stand",
getMotionRequest().id = motion::stand;
);
getMotionRequest().standardStand = false;
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:standard_stand",
getMotionRequest().standardStand = true;
getMotionRequest().standHeight = -1; // minus means the same value as walk
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:sit",
getMotionRequest().standardStand = true;
getMotionRequest().standHeight = 160;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:walk_forward",
getMotionRequest().id = motion::walk;
getMotionRequest().walkRequest.target = Pose2D(0, 500, 0);
getMotionRequest().walkRequest.coordinate = WalkRequest::Hip;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:walk_backward",
getMotionRequest().id = motion::walk;
getMotionRequest().walkRequest.target = Pose2D(0, -500, 0);
getMotionRequest().walkRequest.coordinate = WalkRequest::Hip;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:strafe_right",
getMotionRequest().id = motion::walk;
getMotionRequest().walkRequest.target = Pose2D(0, 0, -500);
getMotionRequest().walkRequest.coordinate = WalkRequest::Hip;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:strafe_left",
getMotionRequest().id = motion::walk;
getMotionRequest().walkRequest.target = Pose2D(0, 0, 500);
getMotionRequest().walkRequest.coordinate = WalkRequest::Hip;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:turn_right",
getMotionRequest().id = motion::walk;
getMotionRequest().walkRequest.target = Pose2D(Math::fromDegrees(-179), 0, 0);
getMotionRequest().walkRequest.coordinate = WalkRequest::Hip;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:turn_left",
getMotionRequest().id = motion::walk;
getMotionRequest().walkRequest.target = Pose2D(Math::fromDegrees(180), 0, 0);
getMotionRequest().walkRequest.coordinate = WalkRequest::Hip;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:stepping",
getMotionRequest().id = motion::walk;
getMotionRequest().walkRequest.target = Pose2D();
getMotionRequest().walkRequest.coordinate = WalkRequest::Hip;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:stand_up_from_front",
getMotionRequest().id = motion::stand_up_from_front;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:stand_up_from_back",
getMotionRequest().id = motion::stand_up_from_back;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:dead",
getMotionRequest().id = motion::dead;
getMotionRequest().forced = true;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:init",
getMotionRequest().id = motion::init;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:dance",
getMotionRequest().id = motion::dance;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:protect_falling",
getMotionRequest().id = motion::protect_falling;
);
}//end testMotion
<commit_msg>can set walk request by combined debug request<commit_after>/**
* @file SimpleMotionBehaviorControl.cpp
*
* @author <a href="mailto:mellmann@informatik.hu-berlin.de">Heinrich Mellmann</a>
* @author <a href="mailto:goehring@informatik.hu-berlin.de">Daniel Goehring</a>
* Implementation of class SimpleMotionBehaviorControl
*/
#include "SimpleMotionBehaviorControl.h"
#include "Tools/Debug/DebugRequest.h"
#include "Tools/Debug/DebugModify.h"
SimpleMotionBehaviorControl::SimpleMotionBehaviorControl()
{
// test head control
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:head:Search", "Set the HeadMotion-Request to 'search'.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:head:reverseSearchDirection", "Set the head search direction to counterclockwise.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:head:LookAtBall_image", "Set the HeadMotion-Request to 'look_at_ball'.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:head:LookAtBall_field", "Set the HeadMotion-Request to 'look_at_ball'.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:head:Stabilize", "Set the HeadMotion-Request to 'stabilize'.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:head:SwitchToBottomCamera", "Switch to bottom camera", true);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:head:look_at_ball_modell", "Search for ball if not seen", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:head:look_straight_ahead", "look straight ahead", false);
// test motion control
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:standard_stand", "stand as standard or not", true);
// walk
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:walk_forward", "Walk foraward as fast as possible", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:walk_backward", "Walk backward as fast as possible", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:strafe_left", "Set the motion request to 'strafe'.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:strafe_right", "Set the motion request to 'strafe'.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:turn_left", "Set the motion request to 'turn_right'.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:turn_right", "Set the motion request to 'turn_right'.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:walk_forward", "Walk foraward as fast as possible", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:stepping", "walk with zero speed", false);
// key frame motion
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:stand_up_from_front", "Set the motion request to 'stand_up_from_front'", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:stand_up_from_back", "Set the motion request to 'stand_up_from_back'", false);
// other motions
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:dead", "Set the robot dead.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:stand", "The default motion, otherwise do nothing", true);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:sit", "sit down, has a rest", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:init", "Set the robot init.", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:dance", "Let's dance", false);
DEBUG_REQUEST_REGISTER("SimpleMotionBehaviorControl:motion:protect_falling", "Don't hurt me!", false);
}
void SimpleMotionBehaviorControl::execute()
{
// reset some stuff by default
getMotionRequest().forced = false;
getMotionRequest().standHeight = -1; // sit in a stable position
testHead();
testMotion();
}//end execute
void SimpleMotionBehaviorControl::testHead()
{
getHeadMotionRequest().cameraID = CameraInfo::Top;
DEBUG_REQUEST("SimpleMotionBehaviorControl:head:SwitchToBottomCamera",
getHeadMotionRequest().cameraID = CameraInfo::Bottom;
);
// keep the head as forced by default
getHeadMotionRequest().id = HeadMotionRequest::hold;
DEBUG_REQUEST("SimpleMotionBehaviorControl:head:Search",
getHeadMotionRequest().id = HeadMotionRequest::search;
getHeadMotionRequest().searchCenter = Vector3<double>(2000, 0, 0);
getHeadMotionRequest().searchSize = Vector3<double>(1500, 2000, 0);
);
getHeadMotionRequest().searchDirection = true;
DEBUG_REQUEST("SimpleMotionBehaviorControl:head:reverseSearchDirection",
getHeadMotionRequest().searchDirection = false;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:head:Stabilize",
getHeadMotionRequest().id = HeadMotionRequest::stabilize;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:head:LookAtBall_image",
if (getBallPercept().ballWasSeen)
{
getHeadMotionRequest().id = HeadMotionRequest::look_at_point;
getHeadMotionRequest().targetPointInImage = getBallPercept().centerInImage;
}
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:head:LookAtBall_field",
if (getBallPercept().ballWasSeen)
{
getHeadMotionRequest().id = HeadMotionRequest::look_at_world_point;
getHeadMotionRequest().targetPointInTheWorld.x = getBallPercept().bearingBasedOffsetOnField.x;
getHeadMotionRequest().targetPointInTheWorld.y = getBallPercept().bearingBasedOffsetOnField.y;
getHeadMotionRequest().targetPointInTheWorld.z = getFieldInfo().ballRadius;
}
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:head:look_straight_ahead",
getHeadMotionRequest().id = HeadMotionRequest::look_straight_ahead;
);
}//end testHead
void SimpleMotionBehaviorControl::testMotion()
{
getMotionRequest().walkRequest.target = Pose2D();
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:stand",
getMotionRequest().id = motion::stand;
);
getMotionRequest().standardStand = false;
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:standard_stand",
getMotionRequest().standardStand = true;
getMotionRequest().standHeight = -1; // minus means the same value as walk
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:sit",
getMotionRequest().standardStand = true;
getMotionRequest().standHeight = 160;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:walk_forward",
getMotionRequest().id = motion::walk;
getMotionRequest().walkRequest.target.translation.x = 500;
getMotionRequest().walkRequest.coordinate = WalkRequest::Hip;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:walk_backward",
getMotionRequest().id = motion::walk;
getMotionRequest().walkRequest.target.translation.x = -500;
getMotionRequest().walkRequest.coordinate = WalkRequest::Hip;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:strafe_right",
getMotionRequest().id = motion::walk;
getMotionRequest().walkRequest.target.translation.y = -500;
getMotionRequest().walkRequest.coordinate = WalkRequest::Hip;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:strafe_left",
getMotionRequest().id = motion::walk;
getMotionRequest().walkRequest.target.translation.y = 500;
getMotionRequest().walkRequest.coordinate = WalkRequest::Hip;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:turn_right",
getMotionRequest().id = motion::walk;
getMotionRequest().walkRequest.target.rotation = Math::fromDegrees(-60);
getMotionRequest().walkRequest.coordinate = WalkRequest::Hip;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:turn_left",
getMotionRequest().id = motion::walk;
getMotionRequest().walkRequest.target.rotation = Math::fromDegrees(60);
getMotionRequest().walkRequest.coordinate = WalkRequest::Hip;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:stepping",
getMotionRequest().id = motion::walk;
getMotionRequest().walkRequest.target = Pose2D();
getMotionRequest().walkRequest.coordinate = WalkRequest::Hip;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:stand_up_from_front",
getMotionRequest().id = motion::stand_up_from_front;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:stand_up_from_back",
getMotionRequest().id = motion::stand_up_from_back;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:dead",
getMotionRequest().id = motion::dead;
getMotionRequest().forced = true;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:init",
getMotionRequest().id = motion::init;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:dance",
getMotionRequest().id = motion::dance;
);
DEBUG_REQUEST("SimpleMotionBehaviorControl:motion:protect_falling",
getMotionRequest().id = motion::protect_falling;
);
}//end testMotion
<|endoftext|> |
<commit_before>//---------------------------------------------------------
// Copyright 2015 Ontario Institute for Cancer Research
// Written by Jared Simpson (jared.simpson@oicr.on.ca)
//---------------------------------------------------------
//
// nanopolish_common -- Data structures and definitions
// shared across files
//
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "nanopolish_common.h"
#include "nanopolish_squiggle_read.h"
// Split a string into parts based on the delimiter
std::vector<std::string> split(std::string in, char delimiter)
{
std::vector<std::string> out;
size_t lastPos = 0;
size_t pos = in.find_first_of(delimiter);
while(pos != std::string::npos)
{
out.push_back(in.substr(lastPos, pos - lastPos));
lastPos = pos + 1;
pos = in.find_first_of(delimiter, lastPos);
}
out.push_back(in.substr(lastPos));
return out;
}
void parse_region_string(const std::string& region, std::string& contig, int& start, int& end)
{
std::string region_copy = region;
// Parse the window string
// Replace ":" and "-" with spaces to make it parseable with stringstream
std::replace(region_copy.begin(), region_copy.end(), ':', ' ');
std::replace(region_copy.begin(), region_copy.end(), '-', ' ');
std::stringstream parser(region_copy);
parser >> contig >> start >> end;
}
SemVer parse_semver_string(const std::string& semver_str)
{
SemVer out;
const auto& vec = split(semver_str, '.');
if(vec.size() == 3) {
out = { atoi(vec[0].c_str()),
atoi(vec[1].c_str()),
atoi(vec[2].c_str())
};
} else {
out = { 0, 0, 0 };
}
return out;
}
bool ends_with(const std::string& str, const std::string& suffix)
{
if(suffix.empty()) {
return true;
}
size_t pos = str.find(suffix);
if(pos == std::string::npos) {
return false;
}
return pos + suffix.size() == str.length();
}
// from: http://stackoverflow.com/questions/9330915/number-of-combinations-n-choose-r-in-c
size_t nChoosek(size_t n, size_t k)
{
if (k > n) return 0;
if (k * 2 > n) k = n-k;
if (k == 0) return 1;
int result = n;
for( int i = 2; i <= k; ++i ) {
result *= (n-i+1);
result /= i;
}
return result;
}
<commit_msg>support commas in region strings<commit_after>//---------------------------------------------------------
// Copyright 2015 Ontario Institute for Cancer Research
// Written by Jared Simpson (jared.simpson@oicr.on.ca)
//---------------------------------------------------------
//
// nanopolish_common -- Data structures and definitions
// shared across files
//
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "nanopolish_common.h"
#include "nanopolish_squiggle_read.h"
// Split a string into parts based on the delimiter
std::vector<std::string> split(std::string in, char delimiter)
{
std::vector<std::string> out;
size_t lastPos = 0;
size_t pos = in.find_first_of(delimiter);
while(pos != std::string::npos)
{
out.push_back(in.substr(lastPos, pos - lastPos));
lastPos = pos + 1;
pos = in.find_first_of(delimiter, lastPos);
}
out.push_back(in.substr(lastPos));
return out;
}
void parse_region_string(const std::string& region, std::string& contig, int& start, int& end)
{
std::string region_copy = region;
// Parse the window string
// Delete commas
region_copy.erase(std::remove(region_copy.begin(), region_copy.end(), ','), region_copy.end());
// Replace ":" and "-" with spaces to make it parseable with stringstream
std::replace(region_copy.begin(), region_copy.end(), ':', ' ');
std::replace(region_copy.begin(), region_copy.end(), '-', ' ');
std::stringstream parser(region_copy);
parser >> contig >> start >> end;
}
SemVer parse_semver_string(const std::string& semver_str)
{
SemVer out;
const auto& vec = split(semver_str, '.');
if(vec.size() == 3) {
out = { atoi(vec[0].c_str()),
atoi(vec[1].c_str()),
atoi(vec[2].c_str())
};
} else {
out = { 0, 0, 0 };
}
return out;
}
bool ends_with(const std::string& str, const std::string& suffix)
{
if(suffix.empty()) {
return true;
}
size_t pos = str.find(suffix);
if(pos == std::string::npos) {
return false;
}
return pos + suffix.size() == str.length();
}
// from: http://stackoverflow.com/questions/9330915/number-of-combinations-n-choose-r-in-c
size_t nChoosek(size_t n, size_t k)
{
if (k > n) return 0;
if (k * 2 > n) k = n-k;
if (k == 0) return 1;
int result = n;
for( int i = 2; i <= k; ++i ) {
result *= (n-i+1);
result /= i;
}
return result;
}
<|endoftext|> |
<commit_before>#include <stan/math.hpp>
#include <test/unit/util.hpp>
#include <gtest/gtest.h>
TEST(AgradRev, arena_matrix_matrix_test) {
using Eigen::MatrixXd;
using stan::math::arena_matrix;
// construction
arena_matrix<MatrixXd> a;
arena_matrix<MatrixXd> a2;
arena_matrix<MatrixXd> a3;
arena_matrix<MatrixXd> b(3, 2);
arena_matrix<MatrixXd> b2(4, 5);
arena_matrix<MatrixXd> c(MatrixXd::Ones(3, 2));
arena_matrix<MatrixXd> d(c);
arena_matrix<MatrixXd> e(2 * d);
// assignment
a = c;
a2 = std::move(d);
a3 = 2 * a;
b = d;
b2 = std::move(c);
e = e + a;
a = MatrixXd::Ones(3, 2);
EXPECT_MATRIX_EQ(a + a2 + a3 + b + b2 + e, MatrixXd::Ones(3, 2) * 9);
stan::math::recover_memory();
}
TEST(AgradRev, arena_matrix_vector_test) {
using Eigen::VectorXd;
using stan::math::arena_matrix;
// construction
arena_matrix<VectorXd> a;
arena_matrix<VectorXd> a2;
arena_matrix<VectorXd> a3;
arena_matrix<VectorXd> b(3);
arena_matrix<VectorXd> b2(4);
arena_matrix<VectorXd> c(VectorXd::Ones(3));
arena_matrix<VectorXd> d(c);
arena_matrix<VectorXd> e(2 * d);
// assignment
a = c;
a2 = std::move(d);
a3 = 2 * a;
b = d;
b2 = std::move(c);
e = e + a;
a = VectorXd::Ones(3);
EXPECT_MATRIX_EQ(a + a2 + a3 + b + b2 + e, VectorXd::Ones(3) * 9);
stan::math::recover_memory();
}
TEST(AgradRev, arena_matrix_row_vector_test) {
using Eigen::RowVectorXd;
using stan::math::arena_matrix;
// construction
arena_matrix<RowVectorXd> a;
arena_matrix<RowVectorXd> a2;
arena_matrix<RowVectorXd> a3;
arena_matrix<RowVectorXd> b(3);
arena_matrix<RowVectorXd> b2(4);
arena_matrix<RowVectorXd> c(RowVectorXd::Ones(3));
arena_matrix<RowVectorXd> d(c);
arena_matrix<RowVectorXd> e(2 * d);
// assignment
a = c;
a2 = std::move(d);
a3 = 2 * a;
b = d;
b2 = std::move(c);
e = e + a;
a = RowVectorXd::Ones(3);
EXPECT_MATRIX_EQ(a + a2 + a3 + b + b2 + e, RowVectorXd::Ones(3) * 9);
stan::math::recover_memory();
}
<commit_msg>Test vector/row vector arena matrices can be assigned to each other<commit_after>#include <stan/math.hpp>
#include <test/unit/util.hpp>
#include <gtest/gtest.h>
TEST(AgradRev, arena_matrix_matrix_test) {
using Eigen::MatrixXd;
using stan::math::arena_matrix;
// construction
arena_matrix<MatrixXd> a;
arena_matrix<MatrixXd> a2;
arena_matrix<MatrixXd> a3;
arena_matrix<MatrixXd> b(3, 2);
arena_matrix<MatrixXd> b2(4, 5);
arena_matrix<MatrixXd> c(MatrixXd::Ones(3, 2));
arena_matrix<MatrixXd> d(c);
arena_matrix<MatrixXd> e(2 * d);
// assignment
a = c;
a2 = std::move(d);
a3 = 2 * a;
b = d;
b2 = std::move(c);
e = e + a;
a = MatrixXd::Ones(3, 2);
EXPECT_MATRIX_EQ(a + a2 + a3 + b + b2 + e, MatrixXd::Ones(3, 2) * 9);
stan::math::recover_memory();
}
TEST(AgradRev, arena_matrix_vector_test) {
using Eigen::VectorXd;
using stan::math::arena_matrix;
// construction
arena_matrix<VectorXd> a;
arena_matrix<VectorXd> a2;
arena_matrix<VectorXd> a3;
arena_matrix<VectorXd> b(3);
arena_matrix<VectorXd> b2(4);
arena_matrix<VectorXd> c(VectorXd::Ones(3));
arena_matrix<VectorXd> d(c);
arena_matrix<VectorXd> e(2 * d);
// assignment
a = c;
a2 = std::move(d);
a3 = 2 * a;
b = d;
b2 = std::move(c);
e = e + a;
a = VectorXd::Ones(3);
EXPECT_MATRIX_EQ(a + a2 + a3 + b + b2 + e, VectorXd::Ones(3) * 9);
stan::math::recover_memory();
}
TEST(AgradRev, arena_matrix_row_vector_test) {
using Eigen::RowVectorXd;
using stan::math::arena_matrix;
// construction
arena_matrix<RowVectorXd> a;
arena_matrix<RowVectorXd> a2;
arena_matrix<RowVectorXd> a3;
arena_matrix<RowVectorXd> b(3);
arena_matrix<RowVectorXd> b2(4);
arena_matrix<RowVectorXd> c(RowVectorXd::Ones(3));
arena_matrix<RowVectorXd> d(c);
arena_matrix<RowVectorXd> e(2 * d);
// assignment
a = c;
a2 = std::move(d);
a3 = 2 * a;
b = d;
b2 = std::move(c);
e = e + a;
a = RowVectorXd::Ones(3);
EXPECT_MATRIX_EQ(a + a2 + a3 + b + b2 + e, RowVectorXd::Ones(3) * 9);
stan::math::recover_memory();
}
TEST(AgradRev, arena_matrix_transpose_test) {
using stan::math::arena_matrix;
Eigen::VectorXd c = Eigen::VectorXd::Random(3);
Eigen::RowVectorXd d = Eigen::RowVectorXd::Random(3);
// The VectorXd/RowVectorXd mixup here is on purpose to test a vector can initialize a row vector and visa versa
arena_matrix<Eigen::VectorXd> a = d;
arena_matrix<Eigen::RowVectorXd> b = c;
EXPECT_MATRIX_EQ(a, d.transpose());
EXPECT_MATRIX_EQ(b, c.transpose());
EXPECT_NO_THROW(a = b);
EXPECT_MATRIX_EQ(a, b.transpose());
a = Eigen::VectorXd::Random(3);
EXPECT_NO_THROW(b = a);
EXPECT_MATRIX_EQ(a, b.transpose());
stan::math::recover_memory();
}
<|endoftext|> |
<commit_before>//
// Copyright Silvin Lubecki 2010
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef OPENCLAM_CL_HPP_INCLUDED
#define OPENCLAM_CL_HPP_INCLUDED
#include <CL/cl.h>
#include "context.hpp"
#include "kernel.hpp"
#include "for_each.hpp"
#include "unary_function.hpp"
#include "opencl.hpp"
#endif // #ifndef OPENCLAM_KERNEL_HPP_INCLUDED
<commit_msg>cleaning<commit_after>//
// Copyright Silvin Lubecki 2010
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef OPENCLAM_CL_HPP_INCLUDED
#define OPENCLAM_CL_HPP_INCLUDED
#include <CL/cl.h>
#include "context.hpp"
#include "kernel.hpp"
#include "for_each.hpp"
#include "opencl.hpp"
#endif // #ifndef OPENCLAM_KERNEL_HPP_INCLUDED
<|endoftext|> |
<commit_before>//===-- StringRef.cpp - Lightweight String References ---------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/StringRef.h"
using namespace llvm;
const size_t StringRef::npos;
//===----------------------------------------------------------------------===//
// String Searching
//===----------------------------------------------------------------------===//
/// find - Search for the first string \arg Str in the string.
///
/// \return - The index of the first occurence of \arg Str, or npos if not
/// found.
size_t StringRef::find(const StringRef &Str) const {
size_t N = Str.size();
if (N > Length)
return npos;
for (size_t i = 0, e = Length - N + 1; i != e; ++i)
if (substr(i, N).equals(Str))
return i;
return npos;
}
/// rfind - Search for the last string \arg Str in the string.
///
/// \return - The index of the last occurence of \arg Str, or npos if not
/// found.
size_t StringRef::rfind(const StringRef &Str) const {
size_t N = Str.size();
if (N > Length)
return npos;
for (size_t i = Length - N + 1, e = 0; i != e;) {
--i;
if (substr(i, N).equals(Str))
return i;
}
return npos;
}
/// find_first_of - Find the first character from the string 'Chars' in the
/// current string or return npos if not in string.
StringRef::size_type StringRef::find_first_of(StringRef Chars) const {
for (size_type i = 0, e = Length; i != e; ++i)
if (Chars.find(Data[i]) != npos)
return i;
return npos;
}
/// find_first_not_of - Find the first character in the string that is not
/// in the string 'Chars' or return npos if all are in string. Same as find.
StringRef::size_type StringRef::find_first_not_of(StringRef Chars) const {
for (size_type i = 0, e = Length; i != e; ++i)
if (Chars.find(Data[i]) == npos)
return i;
return npos;
}
//===----------------------------------------------------------------------===//
// Helpful Algorithms
//===----------------------------------------------------------------------===//
/// count - Return the number of non-overlapped occurrences of \arg Str in
/// the string.
size_t StringRef::count(const StringRef &Str) const {
size_t Count = 0;
size_t N = Str.size();
if (N > Length)
return 0;
for (size_t i = 0, e = Length - N + 1; i != e; ++i)
if (substr(i, N).equals(Str))
++Count;
return Count;
}
/// GetAsUnsignedInteger - Workhorse method that converts a integer character
/// sequence of radix up to 36 to an unsigned long long value.
static bool GetAsUnsignedInteger(StringRef Str, unsigned Radix,
unsigned long long &Result) {
// Autosense radix if not specified.
if (Radix == 0) {
if (Str[0] != '0') {
Radix = 10;
} else {
if (Str.size() < 2) {
Radix = 8;
} else {
if (Str[1] == 'x') {
Str = Str.substr(2);
Radix = 16;
} else if (Str[1] == 'b') {
Str = Str.substr(2);
Radix = 2;
} else {
Radix = 8;
}
}
}
}
// Empty strings (after the radix autosense) are invalid.
if (Str.empty()) return true;
// Parse all the bytes of the string given this radix. Watch for overflow.
Result = 0;
while (!Str.empty()) {
unsigned CharVal;
if (Str[0] >= '0' && Str[0] <= '9')
CharVal = Str[0]-'0';
else if (Str[0] >= 'a' && Str[0] <= 'z')
CharVal = Str[0]-'a'+10;
else if (Str[0] >= 'A' && Str[0] <= 'Z')
CharVal = Str[0]-'A'+10;
else
return true;
// If the parsed value is larger than the integer radix, the string is
// invalid.
if (CharVal >= Radix)
return true;
// Add in this character.
unsigned long long PrevResult = Result;
Result = Result*Radix+CharVal;
// Check for overflow.
if (Result < PrevResult)
return true;
Str = Str.substr(1);
}
return false;
}
bool StringRef::getAsInteger(unsigned Radix, unsigned long long &Result) const {
return GetAsUnsignedInteger(*this, Radix, Result);
}
bool StringRef::getAsInteger(unsigned Radix, long long &Result) const {
unsigned long long ULLVal;
// Handle positive strings first.
if (empty() || front() != '-') {
if (GetAsUnsignedInteger(*this, Radix, ULLVal) ||
// Check for value so large it overflows a signed value.
(long long)ULLVal < 0)
return true;
Result = ULLVal;
return false;
}
// Get the positive part of the value.
if (GetAsUnsignedInteger(substr(1), Radix, ULLVal) ||
// Reject values so large they'd overflow as negative signed, but allow
// "-0". This negates the unsigned so that the negative isn't undefined
// on signed overflow.
(long long)-ULLVal > 0)
return true;
Result = -ULLVal;
return false;
}
bool StringRef::getAsInteger(unsigned Radix, int &Result) const {
long long Val;
if (getAsInteger(Radix, Val) ||
(int)Val != Val)
return true;
Result = Val;
return false;
}
bool StringRef::getAsInteger(unsigned Radix, unsigned &Result) const {
unsigned long long Val;
if (getAsInteger(Radix, Val) ||
(unsigned)Val != Val)
return true;
Result = Val;
return false;
}
<commit_msg>simplify as daniel suggests<commit_after>//===-- StringRef.cpp - Lightweight String References ---------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/StringRef.h"
using namespace llvm;
const size_t StringRef::npos;
//===----------------------------------------------------------------------===//
// String Searching
//===----------------------------------------------------------------------===//
/// find - Search for the first string \arg Str in the string.
///
/// \return - The index of the first occurence of \arg Str, or npos if not
/// found.
size_t StringRef::find(const StringRef &Str) const {
size_t N = Str.size();
if (N > Length)
return npos;
for (size_t i = 0, e = Length - N + 1; i != e; ++i)
if (substr(i, N).equals(Str))
return i;
return npos;
}
/// rfind - Search for the last string \arg Str in the string.
///
/// \return - The index of the last occurence of \arg Str, or npos if not
/// found.
size_t StringRef::rfind(const StringRef &Str) const {
size_t N = Str.size();
if (N > Length)
return npos;
for (size_t i = Length - N + 1, e = 0; i != e;) {
--i;
if (substr(i, N).equals(Str))
return i;
}
return npos;
}
/// find_first_of - Find the first character from the string 'Chars' in the
/// current string or return npos if not in string.
StringRef::size_type StringRef::find_first_of(StringRef Chars) const {
for (size_type i = 0, e = Length; i != e; ++i)
if (Chars.find(Data[i]) != npos)
return i;
return npos;
}
/// find_first_not_of - Find the first character in the string that is not
/// in the string 'Chars' or return npos if all are in string. Same as find.
StringRef::size_type StringRef::find_first_not_of(StringRef Chars) const {
for (size_type i = 0, e = Length; i != e; ++i)
if (Chars.find(Data[i]) == npos)
return i;
return npos;
}
//===----------------------------------------------------------------------===//
// Helpful Algorithms
//===----------------------------------------------------------------------===//
/// count - Return the number of non-overlapped occurrences of \arg Str in
/// the string.
size_t StringRef::count(const StringRef &Str) const {
size_t Count = 0;
size_t N = Str.size();
if (N > Length)
return 0;
for (size_t i = 0, e = Length - N + 1; i != e; ++i)
if (substr(i, N).equals(Str))
++Count;
return Count;
}
/// GetAsUnsignedInteger - Workhorse method that converts a integer character
/// sequence of radix up to 36 to an unsigned long long value.
static bool GetAsUnsignedInteger(StringRef Str, unsigned Radix,
unsigned long long &Result) {
// Autosense radix if not specified.
if (Radix == 0) {
if (Str.startswith("0x")) {
Str = Str.substr(2);
Radix = 16;
} else if (Str.startswith("0b")) {
Str = Str.substr(2);
Radix = 2;
} else if (Str.startswith("0"))
Radix = 8;
else
Radix = 10;
}
// Empty strings (after the radix autosense) are invalid.
if (Str.empty()) return true;
// Parse all the bytes of the string given this radix. Watch for overflow.
Result = 0;
while (!Str.empty()) {
unsigned CharVal;
if (Str[0] >= '0' && Str[0] <= '9')
CharVal = Str[0]-'0';
else if (Str[0] >= 'a' && Str[0] <= 'z')
CharVal = Str[0]-'a'+10;
else if (Str[0] >= 'A' && Str[0] <= 'Z')
CharVal = Str[0]-'A'+10;
else
return true;
// If the parsed value is larger than the integer radix, the string is
// invalid.
if (CharVal >= Radix)
return true;
// Add in this character.
unsigned long long PrevResult = Result;
Result = Result*Radix+CharVal;
// Check for overflow.
if (Result < PrevResult)
return true;
Str = Str.substr(1);
}
return false;
}
bool StringRef::getAsInteger(unsigned Radix, unsigned long long &Result) const {
return GetAsUnsignedInteger(*this, Radix, Result);
}
bool StringRef::getAsInteger(unsigned Radix, long long &Result) const {
unsigned long long ULLVal;
// Handle positive strings first.
if (empty() || front() != '-') {
if (GetAsUnsignedInteger(*this, Radix, ULLVal) ||
// Check for value so large it overflows a signed value.
(long long)ULLVal < 0)
return true;
Result = ULLVal;
return false;
}
// Get the positive part of the value.
if (GetAsUnsignedInteger(substr(1), Radix, ULLVal) ||
// Reject values so large they'd overflow as negative signed, but allow
// "-0". This negates the unsigned so that the negative isn't undefined
// on signed overflow.
(long long)-ULLVal > 0)
return true;
Result = -ULLVal;
return false;
}
bool StringRef::getAsInteger(unsigned Radix, int &Result) const {
long long Val;
if (getAsInteger(Radix, Val) ||
(int)Val != Val)
return true;
Result = Val;
return false;
}
bool StringRef::getAsInteger(unsigned Radix, unsigned &Result) const {
unsigned long long Val;
if (getAsInteger(Radix, Val) ||
(unsigned)Val != Val)
return true;
Result = Val;
return false;
}
<|endoftext|> |
<commit_before>#include <sliding_window.hpp>
#include <vector>
#include <array>
#include <string>
#include <utility>
#include "helpers.hpp"
#include "catch.hpp"
using iter::sliding_window;
using Vec = const std::vector<int>;
TEST_CASE("sliding_window: window of size 3", "[sliding_window]") {
Vec ns = { 10, 20, 30, 40, 50};
auto sw = sliding_window(ns, 3);
auto it = std::begin(sw);
REQUIRE( it != std::end(sw) );
{
Vec v(std::begin(*it), std::end(*it));
Vec vc = {10, 20, 30};
REQUIRE( v == vc );
}
++it;
REQUIRE( it != std::end(sw) );
{
Vec v(std::begin(*it), std::end(*it));
Vec vc = {20, 30, 40};
REQUIRE( v == vc );
}
++it;
REQUIRE( it != std::end(sw) );
{
Vec v(std::begin(*it), std::end(*it));
Vec vc = {30, 40, 50};
REQUIRE( v == vc );
}
++it;
REQUIRE( it == std::end(sw) );
}
TEST_CASE("sliding window: oversized window is empty", "[sliding_window]") {
Vec ns = {10, 20, 30};
auto sw = sliding_window(ns, 5);
REQUIRE( std::begin(sw) == std::end(sw) );
}
TEST_CASE("sliding window: window size == len(iterable)", "[sliding_window]") {
Vec ns = {10, 20, 30};
auto sw = sliding_window(ns, 3);
auto it = std::begin(sw);
REQUIRE( it != std::end(sw) );
Vec v(std::begin(*it), std::end(*it));
REQUIRE( ns == v );
++it;
REQUIRE( it == std::end(sw) );
}
TEST_CASE("sliding window: empty iterable is empty", "[sliding_window]") {
Vec ns{};
auto sw = sliding_window(ns, 1);
REQUIRE( std::begin(sw) == std::end(sw) );
}
TEST_CASE("sliding window: window size of 1", "[sliding_window]") {
Vec ns = {10, 20, 30};
auto sw = sliding_window(ns, 1);
auto it = std::begin(sw);
REQUIRE( *std::begin(*it) == 10 );
++it;
REQUIRE( *std::begin(*it) == 20 );
++it;
REQUIRE( *std::begin(*it) == 30 );
++it;
REQUIRE( it == std::end(sw) );
}
TEST_CASE("sliding window: window size of 0", "[sliding_window]") {
Vec ns = {10, 20, 30};
auto sw = sliding_window(ns, 0);
REQUIRE( std::begin(sw) == std::end(sw) );
}
TEST_CASE("sliding window: moves rvalues and binds to lvalues",
"[sliding_window]") {
itertest::BasicIterable<int> bi{1, 2};
sliding_window(bi, 1);
REQUIRE_FALSE( bi.was_moved_from() );
sliding_window(std::move(bi), 1);
REQUIRE( bi.was_moved_from() );
}
<commit_msg>tests sliding window doesn't copy elements<commit_after>#include <sliding_window.hpp>
#include <vector>
#include <array>
#include <string>
#include <utility>
#include "helpers.hpp"
#include "catch.hpp"
using iter::sliding_window;
using Vec = const std::vector<int>;
TEST_CASE("sliding_window: window of size 3", "[sliding_window]") {
Vec ns = { 10, 20, 30, 40, 50};
auto sw = sliding_window(ns, 3);
auto it = std::begin(sw);
REQUIRE( it != std::end(sw) );
{
Vec v(std::begin(*it), std::end(*it));
Vec vc = {10, 20, 30};
REQUIRE( v == vc );
}
++it;
REQUIRE( it != std::end(sw) );
{
Vec v(std::begin(*it), std::end(*it));
Vec vc = {20, 30, 40};
REQUIRE( v == vc );
}
++it;
REQUIRE( it != std::end(sw) );
{
Vec v(std::begin(*it), std::end(*it));
Vec vc = {30, 40, 50};
REQUIRE( v == vc );
}
++it;
REQUIRE( it == std::end(sw) );
}
TEST_CASE("sliding window: oversized window is empty", "[sliding_window]") {
Vec ns = {10, 20, 30};
auto sw = sliding_window(ns, 5);
REQUIRE( std::begin(sw) == std::end(sw) );
}
TEST_CASE("sliding window: window size == len(iterable)", "[sliding_window]") {
Vec ns = {10, 20, 30};
auto sw = sliding_window(ns, 3);
auto it = std::begin(sw);
REQUIRE( it != std::end(sw) );
Vec v(std::begin(*it), std::end(*it));
REQUIRE( ns == v );
++it;
REQUIRE( it == std::end(sw) );
}
TEST_CASE("sliding window: empty iterable is empty", "[sliding_window]") {
Vec ns{};
auto sw = sliding_window(ns, 1);
REQUIRE( std::begin(sw) == std::end(sw) );
}
TEST_CASE("sliding window: window size of 1", "[sliding_window]") {
Vec ns = {10, 20, 30};
auto sw = sliding_window(ns, 1);
auto it = std::begin(sw);
REQUIRE( *std::begin(*it) == 10 );
++it;
REQUIRE( *std::begin(*it) == 20 );
++it;
REQUIRE( *std::begin(*it) == 30 );
++it;
REQUIRE( it == std::end(sw) );
}
TEST_CASE("sliding window: window size of 0", "[sliding_window]") {
Vec ns = {10, 20, 30};
auto sw = sliding_window(ns, 0);
REQUIRE( std::begin(sw) == std::end(sw) );
}
TEST_CASE("sliding window: moves rvalues and binds to lvalues",
"[sliding_window]") {
itertest::BasicIterable<int> bi{1, 2};
sliding_window(bi, 1);
REQUIRE_FALSE( bi.was_moved_from() );
sliding_window(std::move(bi), 1);
REQUIRE( bi.was_moved_from() );
}
TEST_CASE("sliding window: doesn't copy elements", "[sliding_window]") {
constexpr std::array<itertest::SolidInt, 3> arr{{{6}, {7}, {8}}};
for (auto&& i : sliding_window(arr, 1)) {
(void)*std::begin(i);
}
}
<|endoftext|> |
<commit_before>//===- Dominators.cpp - Dominator Calculation -----------------------------===//
//
// This file implements simple dominator construction algorithms for finding
// forward dominators. Postdominators are available in libanalysis, but are not
// included in libvmcore, because it's not needed. Forward dominators are
// needed to support the Verifier pass.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/Dominators.h"
#include "llvm/Support/CFG.h"
#include "llvm/Assembly/Writer.h"
#include "Support/DepthFirstIterator.h"
#include "Support/SetOperations.h"
using std::set;
//===----------------------------------------------------------------------===//
// DominatorSet Implementation
//===----------------------------------------------------------------------===//
static RegisterAnalysis<DominatorSet>
A("domset", "Dominator Set Construction", true);
// dominates - Return true if A dominates B. This performs the special checks
// neccesary if A and B are in the same basic block.
//
bool DominatorSetBase::dominates(Instruction *A, Instruction *B) const {
BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
if (BBA != BBB) return dominates(BBA, BBB);
// Loop through the basic block until we find A or B.
BasicBlock::iterator I = BBA->begin();
for (; &*I != A && &*I != B; ++I) /*empty*/;
// A dominates B if it is found first in the basic block...
return &*I == A;
}
void DominatorSet::calculateDominatorsFromBlock(BasicBlock *RootBB) {
bool Changed;
Doms[RootBB].insert(RootBB); // Root always dominates itself...
do {
Changed = false;
DomSetType WorkingSet;
df_iterator<BasicBlock*> It = df_begin(RootBB), End = df_end(RootBB);
for ( ; It != End; ++It) {
BasicBlock *BB = *It;
pred_iterator PI = pred_begin(BB), PEnd = pred_end(BB);
if (PI != PEnd) { // Is there SOME predecessor?
// Loop until we get to a predecessor that has had it's dom set filled
// in at least once. We are guaranteed to have this because we are
// traversing the graph in DFO and have handled start nodes specially.
//
while (Doms[*PI].empty()) ++PI;
WorkingSet = Doms[*PI];
for (++PI; PI != PEnd; ++PI) { // Intersect all of the predecessor sets
DomSetType &PredSet = Doms[*PI];
if (PredSet.size())
set_intersect(WorkingSet, PredSet);
}
}
WorkingSet.insert(BB); // A block always dominates itself
DomSetType &BBSet = Doms[BB];
if (BBSet != WorkingSet) {
BBSet.swap(WorkingSet); // Constant time operation!
Changed = true; // The sets changed.
}
WorkingSet.clear(); // Clear out the set for next iteration
}
} while (Changed);
}
// runOnFunction - This method calculates the forward dominator sets for the
// specified function.
//
bool DominatorSet::runOnFunction(Function &F) {
Doms.clear(); // Reset from the last time we were run...
Root = &F.getEntryNode();
assert(pred_begin(Root) == pred_end(Root) &&
"Root node has predecessors in function!");
// Calculate dominator sets for the reachable basic blocks...
calculateDominatorsFromBlock(Root);
// Every basic block in the function should at least dominate themselves, and
// thus every basic block should have an entry in Doms. The one case where we
// miss this is when a basic block is unreachable. To get these we now do an
// extra pass over the function, calculating dominator information for
// unreachable blocks.
//
for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
if (Doms[I].empty()) {
calculateDominatorsFromBlock(I);
}
return false;
}
static std::ostream &operator<<(std::ostream &o, const set<BasicBlock*> &BBs) {
for (set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
I != E; ++I) {
o << " ";
WriteAsOperand(o, *I, false);
o << "\n";
}
return o;
}
void DominatorSetBase::print(std::ostream &o) const {
for (const_iterator I = begin(), E = end(); I != E; ++I) {
o << "=============================--------------------------------\n"
<< "\nDominator Set For Basic Block: ";
WriteAsOperand(o, I->first, false);
o << "\n-------------------------------\n" << I->second << "\n";
}
}
//===----------------------------------------------------------------------===//
// ImmediateDominators Implementation
//===----------------------------------------------------------------------===//
static RegisterAnalysis<ImmediateDominators>
C("idom", "Immediate Dominators Construction", true);
// calcIDoms - Calculate the immediate dominator mapping, given a set of
// dominators for every basic block.
void ImmediateDominatorsBase::calcIDoms(const DominatorSetBase &DS) {
// Loop over all of the nodes that have dominators... figuring out the IDOM
// for each node...
//
for (DominatorSet::const_iterator DI = DS.begin(), DEnd = DS.end();
DI != DEnd; ++DI) {
BasicBlock *BB = DI->first;
const DominatorSet::DomSetType &Dominators = DI->second;
unsigned DomSetSize = Dominators.size();
if (DomSetSize == 1) continue; // Root node... IDom = null
// Loop over all dominators of this node. This corresponds to looping over
// nodes in the dominator chain, looking for a node whose dominator set is
// equal to the current nodes, except that the current node does not exist
// in it. This means that it is one level higher in the dom chain than the
// current node, and it is our idom!
//
DominatorSet::DomSetType::const_iterator I = Dominators.begin();
DominatorSet::DomSetType::const_iterator End = Dominators.end();
for (; I != End; ++I) { // Iterate over dominators...
// All of our dominators should form a chain, where the number of elements
// in the dominator set indicates what level the node is at in the chain.
// We want the node immediately above us, so it will have an identical
// dominator set, except that BB will not dominate it... therefore it's
// dominator set size will be one less than BB's...
//
if (DS.getDominators(*I).size() == DomSetSize - 1) {
IDoms[BB] = *I;
break;
}
}
}
}
void ImmediateDominatorsBase::print(std::ostream &o) const {
for (const_iterator I = begin(), E = end(); I != E; ++I)
o << "=============================--------------------------------\n"
<< "\nImmediate Dominator For Basic Block\n" << *I->first
<< "is: \n" << *I->second << "\n";
}
//===----------------------------------------------------------------------===//
// DominatorTree Implementation
//===----------------------------------------------------------------------===//
static RegisterAnalysis<DominatorTree>
E("domtree", "Dominator Tree Construction", true);
// DominatorTreeBase::reset - Free all of the tree node memory.
//
void DominatorTreeBase::reset() {
for (NodeMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
delete I->second;
Nodes.clear();
}
void DominatorTreeBase::Node2::setIDom(Node2 *NewIDom) {
assert(IDom && "No immediate dominator?");
if (IDom != NewIDom) {
std::vector<Node*>::iterator I =
std::find(IDom->Children.begin(), IDom->Children.end(), this);
assert(I != IDom->Children.end() &&
"Not in immediate dominator children set!");
// I am no longer your child...
IDom->Children.erase(I);
// Switch to new dominator
IDom = NewIDom;
IDom->Children.push_back(this);
}
}
void DominatorTree::calculate(const DominatorSet &DS) {
Nodes[Root] = new Node(Root, 0); // Add a node for the root...
// Iterate over all nodes in depth first order...
for (df_iterator<BasicBlock*> I = df_begin(Root), E = df_end(Root);
I != E; ++I) {
BasicBlock *BB = *I;
const DominatorSet::DomSetType &Dominators = DS.getDominators(BB);
unsigned DomSetSize = Dominators.size();
if (DomSetSize == 1) continue; // Root node... IDom = null
// Loop over all dominators of this node. This corresponds to looping over
// nodes in the dominator chain, looking for a node whose dominator set is
// equal to the current nodes, except that the current node does not exist
// in it. This means that it is one level higher in the dom chain than the
// current node, and it is our idom! We know that we have already added
// a DominatorTree node for our idom, because the idom must be a
// predecessor in the depth first order that we are iterating through the
// function.
//
DominatorSet::DomSetType::const_iterator I = Dominators.begin();
DominatorSet::DomSetType::const_iterator End = Dominators.end();
for (; I != End; ++I) { // Iterate over dominators...
// All of our dominators should form a chain, where the number of
// elements in the dominator set indicates what level the node is at in
// the chain. We want the node immediately above us, so it will have
// an identical dominator set, except that BB will not dominate it...
// therefore it's dominator set size will be one less than BB's...
//
if (DS.getDominators(*I).size() == DomSetSize - 1) {
// We know that the immediate dominator should already have a node,
// because we are traversing the CFG in depth first order!
//
Node *IDomNode = Nodes[*I];
assert(IDomNode && "No node for IDOM?");
// Add a new tree node for this BasicBlock, and link it as a child of
// IDomNode
Nodes[BB] = IDomNode->addChild(new Node(BB, IDomNode));
break;
}
}
}
}
static std::ostream &operator<<(std::ostream &o,
const DominatorTreeBase::Node *Node) {
return o << Node->getNode()
<< "\n------------------------------------------\n";
}
static void PrintDomTree(const DominatorTreeBase::Node *N, std::ostream &o,
unsigned Lev) {
o << "Level #" << Lev << ": " << N;
for (DominatorTreeBase::Node::const_iterator I = N->begin(), E = N->end();
I != E; ++I) {
PrintDomTree(*I, o, Lev+1);
}
}
void DominatorTreeBase::print(std::ostream &o) const {
o << "=============================--------------------------------\n"
<< "Inorder Dominator Tree:\n";
PrintDomTree(Nodes.find(getRoot())->second, o, 1);
}
//===----------------------------------------------------------------------===//
// DominanceFrontier Implementation
//===----------------------------------------------------------------------===//
static RegisterAnalysis<DominanceFrontier>
G("domfrontier", "Dominance Frontier Construction", true);
const DominanceFrontier::DomSetType &
DominanceFrontier::calculate(const DominatorTree &DT,
const DominatorTree::Node *Node) {
// Loop over CFG successors to calculate DFlocal[Node]
BasicBlock *BB = Node->getNode();
DomSetType &S = Frontiers[BB]; // The new set to fill in...
for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
SI != SE; ++SI) {
// Does Node immediately dominate this successor?
if (DT[*SI]->getIDom() != Node)
S.insert(*SI);
}
// At this point, S is DFlocal. Now we union in DFup's of our children...
// Loop through and visit the nodes that Node immediately dominates (Node's
// children in the IDomTree)
//
for (DominatorTree::Node::const_iterator NI = Node->begin(), NE = Node->end();
NI != NE; ++NI) {
DominatorTree::Node *IDominee = *NI;
const DomSetType &ChildDF = calculate(DT, IDominee);
DomSetType::const_iterator CDFI = ChildDF.begin(), CDFE = ChildDF.end();
for (; CDFI != CDFE; ++CDFI) {
if (!Node->dominates(DT[*CDFI]))
S.insert(*CDFI);
}
}
return S;
}
void DominanceFrontierBase::print(std::ostream &o) const {
for (const_iterator I = begin(), E = end(); I != E; ++I) {
o << "=============================--------------------------------\n"
<< "\nDominance Frontier For Basic Block\n";
WriteAsOperand(o, I->first, false);
o << " is: \n" << I->second << "\n";
}
}
<commit_msg>Fix a nasty problem with dominance calculation for unreachable blocks. If we had a CFG that look like Entry -> B, Unreachable -> B, then we would not correctly determine that Entry dominated B, because Entry did not apparently dominate "unreachable". This patch fixes this by making the entry node dominate all blocks, including unreachable ones.<commit_after>//===- Dominators.cpp - Dominator Calculation -----------------------------===//
//
// This file implements simple dominator construction algorithms for finding
// forward dominators. Postdominators are available in libanalysis, but are not
// included in libvmcore, because it's not needed. Forward dominators are
// needed to support the Verifier pass.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/Dominators.h"
#include "llvm/Support/CFG.h"
#include "llvm/Assembly/Writer.h"
#include "Support/DepthFirstIterator.h"
#include "Support/SetOperations.h"
using std::set;
//===----------------------------------------------------------------------===//
// DominatorSet Implementation
//===----------------------------------------------------------------------===//
static RegisterAnalysis<DominatorSet>
A("domset", "Dominator Set Construction", true);
// dominates - Return true if A dominates B. This performs the special checks
// neccesary if A and B are in the same basic block.
//
bool DominatorSetBase::dominates(Instruction *A, Instruction *B) const {
BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
if (BBA != BBB) return dominates(BBA, BBB);
// Loop through the basic block until we find A or B.
BasicBlock::iterator I = BBA->begin();
for (; &*I != A && &*I != B; ++I) /*empty*/;
// A dominates B if it is found first in the basic block...
return &*I == A;
}
void DominatorSet::calculateDominatorsFromBlock(BasicBlock *RootBB) {
bool Changed;
Doms[RootBB].insert(RootBB); // Root always dominates itself...
do {
Changed = false;
DomSetType WorkingSet;
df_iterator<BasicBlock*> It = df_begin(RootBB), End = df_end(RootBB);
for ( ; It != End; ++It) {
BasicBlock *BB = *It;
pred_iterator PI = pred_begin(BB), PEnd = pred_end(BB);
if (PI != PEnd) { // Is there SOME predecessor?
// Loop until we get to a predecessor that has had it's dom set filled
// in at least once. We are guaranteed to have this because we are
// traversing the graph in DFO and have handled start nodes specially.
//
while (Doms[*PI].empty()) ++PI;
WorkingSet = Doms[*PI];
for (++PI; PI != PEnd; ++PI) { // Intersect all of the predecessor sets
DomSetType &PredSet = Doms[*PI];
if (PredSet.size())
set_intersect(WorkingSet, PredSet);
}
} else if (BB != Root) {
// If this isn't the root basic block and it has no predecessors, it
// must be an unreachable block. Fib a bit by saying that the root node
// dominates this unreachable node. This isn't exactly true, because
// there is no path from the entry node to this node, but it is sorta
// true because any paths to this node would have to go through the
// entry node.
//
// This allows for dominator properties to be built for unreachable code
// in a reasonable manner.
//
WorkingSet = Doms[Root];
}
WorkingSet.insert(BB); // A block always dominates itself
DomSetType &BBSet = Doms[BB];
if (BBSet != WorkingSet) {
BBSet.swap(WorkingSet); // Constant time operation!
Changed = true; // The sets changed.
}
WorkingSet.clear(); // Clear out the set for next iteration
}
} while (Changed);
}
// runOnFunction - This method calculates the forward dominator sets for the
// specified function.
//
bool DominatorSet::runOnFunction(Function &F) {
Doms.clear(); // Reset from the last time we were run...
Root = &F.getEntryNode();
assert(pred_begin(Root) == pred_end(Root) &&
"Root node has predecessors in function!");
// Calculate dominator sets for the reachable basic blocks...
calculateDominatorsFromBlock(Root);
// Every basic block in the function should at least dominate themselves, and
// thus every basic block should have an entry in Doms. The one case where we
// miss this is when a basic block is unreachable. To get these we now do an
// extra pass over the function, calculating dominator information for
// unreachable blocks.
//
for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
if (Doms[I].count(I) == 0)
calculateDominatorsFromBlock(I);
return false;
}
static std::ostream &operator<<(std::ostream &o, const set<BasicBlock*> &BBs) {
for (set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
I != E; ++I) {
o << " ";
WriteAsOperand(o, *I, false);
o << "\n";
}
return o;
}
void DominatorSetBase::print(std::ostream &o) const {
for (const_iterator I = begin(), E = end(); I != E; ++I) {
o << "=============================--------------------------------\n"
<< "\nDominator Set For Basic Block: ";
WriteAsOperand(o, I->first, false);
o << "\n-------------------------------\n" << I->second << "\n";
}
}
//===----------------------------------------------------------------------===//
// ImmediateDominators Implementation
//===----------------------------------------------------------------------===//
static RegisterAnalysis<ImmediateDominators>
C("idom", "Immediate Dominators Construction", true);
// calcIDoms - Calculate the immediate dominator mapping, given a set of
// dominators for every basic block.
void ImmediateDominatorsBase::calcIDoms(const DominatorSetBase &DS) {
// Loop over all of the nodes that have dominators... figuring out the IDOM
// for each node...
//
for (DominatorSet::const_iterator DI = DS.begin(), DEnd = DS.end();
DI != DEnd; ++DI) {
BasicBlock *BB = DI->first;
const DominatorSet::DomSetType &Dominators = DI->second;
unsigned DomSetSize = Dominators.size();
if (DomSetSize == 1) continue; // Root node... IDom = null
// Loop over all dominators of this node. This corresponds to looping over
// nodes in the dominator chain, looking for a node whose dominator set is
// equal to the current nodes, except that the current node does not exist
// in it. This means that it is one level higher in the dom chain than the
// current node, and it is our idom!
//
DominatorSet::DomSetType::const_iterator I = Dominators.begin();
DominatorSet::DomSetType::const_iterator End = Dominators.end();
for (; I != End; ++I) { // Iterate over dominators...
// All of our dominators should form a chain, where the number of elements
// in the dominator set indicates what level the node is at in the chain.
// We want the node immediately above us, so it will have an identical
// dominator set, except that BB will not dominate it... therefore it's
// dominator set size will be one less than BB's...
//
if (DS.getDominators(*I).size() == DomSetSize - 1) {
IDoms[BB] = *I;
break;
}
}
}
}
void ImmediateDominatorsBase::print(std::ostream &o) const {
for (const_iterator I = begin(), E = end(); I != E; ++I) {
o << "=============================--------------------------------\n"
<< "\nImmediate Dominator For Basic Block:";
WriteAsOperand(o, I->first, false);
o << " is:";
WriteAsOperand(o, I->second, false);
o << "\n";
}
}
//===----------------------------------------------------------------------===//
// DominatorTree Implementation
//===----------------------------------------------------------------------===//
static RegisterAnalysis<DominatorTree>
E("domtree", "Dominator Tree Construction", true);
// DominatorTreeBase::reset - Free all of the tree node memory.
//
void DominatorTreeBase::reset() {
for (NodeMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
delete I->second;
Nodes.clear();
}
void DominatorTreeBase::Node2::setIDom(Node2 *NewIDom) {
assert(IDom && "No immediate dominator?");
if (IDom != NewIDom) {
std::vector<Node*>::iterator I =
std::find(IDom->Children.begin(), IDom->Children.end(), this);
assert(I != IDom->Children.end() &&
"Not in immediate dominator children set!");
// I am no longer your child...
IDom->Children.erase(I);
// Switch to new dominator
IDom = NewIDom;
IDom->Children.push_back(this);
}
}
void DominatorTree::calculate(const DominatorSet &DS) {
Nodes[Root] = new Node(Root, 0); // Add a node for the root...
// Iterate over all nodes in depth first order...
for (df_iterator<BasicBlock*> I = df_begin(Root), E = df_end(Root);
I != E; ++I) {
BasicBlock *BB = *I;
const DominatorSet::DomSetType &Dominators = DS.getDominators(BB);
unsigned DomSetSize = Dominators.size();
if (DomSetSize == 1) continue; // Root node... IDom = null
// Loop over all dominators of this node. This corresponds to looping over
// nodes in the dominator chain, looking for a node whose dominator set is
// equal to the current nodes, except that the current node does not exist
// in it. This means that it is one level higher in the dom chain than the
// current node, and it is our idom! We know that we have already added
// a DominatorTree node for our idom, because the idom must be a
// predecessor in the depth first order that we are iterating through the
// function.
//
DominatorSet::DomSetType::const_iterator I = Dominators.begin();
DominatorSet::DomSetType::const_iterator End = Dominators.end();
for (; I != End; ++I) { // Iterate over dominators...
// All of our dominators should form a chain, where the number of
// elements in the dominator set indicates what level the node is at in
// the chain. We want the node immediately above us, so it will have
// an identical dominator set, except that BB will not dominate it...
// therefore it's dominator set size will be one less than BB's...
//
if (DS.getDominators(*I).size() == DomSetSize - 1) {
// We know that the immediate dominator should already have a node,
// because we are traversing the CFG in depth first order!
//
Node *IDomNode = Nodes[*I];
assert(IDomNode && "No node for IDOM?");
// Add a new tree node for this BasicBlock, and link it as a child of
// IDomNode
Nodes[BB] = IDomNode->addChild(new Node(BB, IDomNode));
break;
}
}
}
}
static std::ostream &operator<<(std::ostream &o,
const DominatorTreeBase::Node *Node) {
return o << Node->getNode()
<< "\n------------------------------------------\n";
}
static void PrintDomTree(const DominatorTreeBase::Node *N, std::ostream &o,
unsigned Lev) {
o << "Level #" << Lev << ": " << N;
for (DominatorTreeBase::Node::const_iterator I = N->begin(), E = N->end();
I != E; ++I) {
PrintDomTree(*I, o, Lev+1);
}
}
void DominatorTreeBase::print(std::ostream &o) const {
o << "=============================--------------------------------\n"
<< "Inorder Dominator Tree:\n";
PrintDomTree(Nodes.find(getRoot())->second, o, 1);
}
//===----------------------------------------------------------------------===//
// DominanceFrontier Implementation
//===----------------------------------------------------------------------===//
static RegisterAnalysis<DominanceFrontier>
G("domfrontier", "Dominance Frontier Construction", true);
const DominanceFrontier::DomSetType &
DominanceFrontier::calculate(const DominatorTree &DT,
const DominatorTree::Node *Node) {
// Loop over CFG successors to calculate DFlocal[Node]
BasicBlock *BB = Node->getNode();
DomSetType &S = Frontiers[BB]; // The new set to fill in...
for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
SI != SE; ++SI) {
// Does Node immediately dominate this successor?
if (DT[*SI]->getIDom() != Node)
S.insert(*SI);
}
// At this point, S is DFlocal. Now we union in DFup's of our children...
// Loop through and visit the nodes that Node immediately dominates (Node's
// children in the IDomTree)
//
for (DominatorTree::Node::const_iterator NI = Node->begin(), NE = Node->end();
NI != NE; ++NI) {
DominatorTree::Node *IDominee = *NI;
const DomSetType &ChildDF = calculate(DT, IDominee);
DomSetType::const_iterator CDFI = ChildDF.begin(), CDFE = ChildDF.end();
for (; CDFI != CDFE; ++CDFI) {
if (!Node->dominates(DT[*CDFI]))
S.insert(*CDFI);
}
}
return S;
}
void DominanceFrontierBase::print(std::ostream &o) const {
for (const_iterator I = begin(), E = end(); I != E; ++I) {
o << "=============================--------------------------------\n"
<< "\nDominance Frontier For Basic Block\n";
WriteAsOperand(o, I->first, false);
o << " is: \n" << I->second << "\n";
}
}
<|endoftext|> |
<commit_before>#include <pcl/features/normal_3d.h>
#include <pcl/io/pcd_io.h>
#include <vtkLidarScanner.h>
#include <vtkPolyData.h>
#include <vtkSmartPointer.h>
#include <vtkTransform.h>
#include "proctor/proctor.h"
#include "proctor/scanner.h"
#if 0
#include "SyntheticLidarScanner/vtkRay.cxx"
#include "SyntheticLidarScanner/vtkLidarPoint.cxx"
#include "SyntheticLidarScanner/vtkLidarScanner.cxx"
#endif
/** convert radians to degrees. thanks a lot, vtk */
template <typename T>
static inline T deg(T rad) {
return rad / M_PI * 180;
}
/** prepare the transform to use for a scan (camera, not object) */
static vtkSmartPointer<vtkTransform> compute_transform(Scanner::Scan scan) {
vtkSmartPointer<vtkTransform> spt = vtkSmartPointer<vtkTransform>::New();
Proctor::Model &model = Proctor::models[scan.mi];
spt->Translate(model.cx, model.cy, model.cz);
spt->RotateY(-deg(scan.phi));
spt->RotateX(-deg(scan.theta));
spt->Translate(0, 0, Scanner::distance_multiplier * model.scale);
spt->RotateX(-90); // the default is looking in the +y direction. rotate to -z direction.
return spt;
}
/** simulate lidar scanning to get a point cloud (without normals) */
static PointCloud<PointXYZ>::Ptr compute_pcxyz(int model, vtkSmartPointer<vtkTransform> transform) {
// TODO: investigate replacing vtkLidarScanner with vtkRenderWindow::GetZbufferData
// I think this function leaks memory.
PointCloud<PointXYZ>::Ptr pcxyz (new PointCloud<PointXYZ>());
#if 0
vtkLidarScanner *ls = vtkLidarScanner::New();
vtkPolyData *pd = vtkPolyData::New();
ls->SetThetaSpan(Scanner::fov_y);
ls->SetPhiSpan(Scanner::fov_x);
ls->SetNumberOfThetaPoints(Scanner::res_y);
ls->SetNumberOfPhiPoints(Scanner::res_x);
ls->SetTransform(transform);
ls->SetInputConnection(Proctor::models[model].mesh->GetProducerPort());
ls->Update();
ls->GetValidOutputPoints(pd);
float (*points)[3] = reinterpret_cast<float (*)[3]>(vtkFloatArray::SafeDownCast(pd->GetPoints()->GetData())->GetPointer(0));
int num_points = pd->GetPoints()->GetData()->GetNumberOfTuples();
pcxyz->points.resize(num_points);
for (int i = 0; i < num_points; i++) {
pcxyz->points[i].x = points[i][0];
pcxyz->points[i].y = points[i][1];
pcxyz->points[i].z = points[i][2];
}
ls->Delete();
pd->Delete();
#endif
return pcxyz;
}
/** estimate the normals of a point cloud */
static PointCloud<Normal>::Ptr compute_pcn(PointCloud<PointXYZ>::ConstPtr in, float vx, float vy, float vz) {
PointCloud<Normal>::Ptr pcn (new PointCloud<Normal>());
NormalEstimation<PointXYZ, Normal> ne;
search::KdTree<PointXYZ>::Ptr kdt (new search::KdTree<PointXYZ>());
ne.setInputCloud(in);
ne.setSearchMethod(kdt);
ne.setKSearch(20);
ne.setViewPoint(vx, vy, vz);
ne.compute(*pcn);
return pcn;
}
/** Scanner */
const float Scanner::distance_multiplier = 3.0f;
const double Scanner::fov_x = M_PI / 3;
const double Scanner::fov_y = M_PI / 4;
const unsigned int Scanner::res_x = 320;
const unsigned int Scanner::res_y = 240;
PointCloud<PointNormal>::Ptr Scanner::getCloud(Scan scan) {
PointCloud<PointNormal>::Ptr cloud (new PointCloud<PointNormal>());
vtkSmartPointer<vtkTransform> transform = compute_transform(scan);
PointCloud<PointXYZ>::Ptr pcxyz = compute_pcxyz(scan.mi, transform);
float v[3];
transform->GetPosition(v);
PointCloud<Normal>::Ptr pcn = compute_pcn(pcxyz, v[0], v[1], v[2]);
concatenateFields(*pcxyz, *pcn, *cloud);
return cloud;
}
PointCloud<PointNormal>::Ptr Scanner::getCloudCached(int mi, int ti, int pi) {
Scan scan = {
mi,
Proctor::theta_start + ti * Proctor::theta_step,
Proctor::phi_start + pi * Proctor::phi_step
};
char name[22];
sprintf(name, "scan_%04d_%03.0f_%03.0f.pcd", Proctor::models[scan.mi].id, deg(scan.theta), deg(scan.phi));
if (ifstream(name)) {
PointCloud<PointNormal>::Ptr cloud (new PointCloud<PointNormal>());
io::loadPCDFile(name, *cloud);
return cloud;
} else {
PointCloud<PointNormal>::Ptr cloud = getCloud(scan);
io::savePCDFileBinary(name, *cloud);
return cloud;
}
}
<commit_msg>enabled lidar scanner for VTK 5.8+<commit_after>#include <pcl/features/normal_3d.h>
#include <pcl/io/pcd_io.h>
#include <vtkLidarScanner.h>
#include <vtkPolyData.h>
#include <vtkSmartPointer.h>
#include <vtkTransform.h>
#include "proctor/proctor.h"
#include "proctor/scanner.h"
#if ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION >= 8))
#include "SyntheticLidarScanner/vtkRay.cxx"
#include "SyntheticLidarScanner/vtkLidarPoint.cxx"
#include "SyntheticLidarScanner/vtkLidarScanner.cxx"
#endif
/** convert radians to degrees. thanks a lot, vtk */
template <typename T>
static inline T deg(T rad) {
return rad / M_PI * 180;
}
/** prepare the transform to use for a scan (camera, not object) */
static vtkSmartPointer<vtkTransform> compute_transform(Scanner::Scan scan) {
vtkSmartPointer<vtkTransform> spt = vtkSmartPointer<vtkTransform>::New();
Proctor::Model &model = Proctor::models[scan.mi];
spt->Translate(model.cx, model.cy, model.cz);
spt->RotateY(-deg(scan.phi));
spt->RotateX(-deg(scan.theta));
spt->Translate(0, 0, Scanner::distance_multiplier * model.scale);
spt->RotateX(-90); // the default is looking in the +y direction. rotate to -z direction.
return spt;
}
/** simulate lidar scanning to get a point cloud (without normals) */
static PointCloud<PointXYZ>::Ptr compute_pcxyz(int model, vtkSmartPointer<vtkTransform> transform) {
// TODO: investigate replacing vtkLidarScanner with vtkRenderWindow::GetZbufferData
// I think this function leaks memory.
PointCloud<PointXYZ>::Ptr pcxyz (new PointCloud<PointXYZ>());
#if ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION >= 8))
vtkLidarScanner *ls = vtkLidarScanner::New();
vtkPolyData *pd = vtkPolyData::New();
ls->SetThetaSpan(Scanner::fov_y);
ls->SetPhiSpan(Scanner::fov_x);
ls->SetNumberOfThetaPoints(Scanner::res_y);
ls->SetNumberOfPhiPoints(Scanner::res_x);
ls->SetTransform(transform);
ls->SetInputConnection(Proctor::models[model].mesh->GetProducerPort());
ls->Update();
ls->GetValidOutputPoints(pd);
float (*points)[3] = reinterpret_cast<float (*)[3]>(vtkFloatArray::SafeDownCast(pd->GetPoints()->GetData())->GetPointer(0));
int num_points = pd->GetPoints()->GetData()->GetNumberOfTuples();
pcxyz->points.resize(num_points);
for (int i = 0; i < num_points; i++) {
pcxyz->points[i].x = points[i][0];
pcxyz->points[i].y = points[i][1];
pcxyz->points[i].z = points[i][2];
}
ls->Delete();
pd->Delete();
#endif
return pcxyz;
}
/** estimate the normals of a point cloud */
static PointCloud<Normal>::Ptr compute_pcn(PointCloud<PointXYZ>::ConstPtr in, float vx, float vy, float vz) {
PointCloud<Normal>::Ptr pcn (new PointCloud<Normal>());
NormalEstimation<PointXYZ, Normal> ne;
search::KdTree<PointXYZ>::Ptr kdt (new search::KdTree<PointXYZ>());
ne.setInputCloud(in);
ne.setSearchMethod(kdt);
ne.setKSearch(20);
ne.setViewPoint(vx, vy, vz);
ne.compute(*pcn);
return pcn;
}
/** Scanner */
const float Scanner::distance_multiplier = 3.0f;
const double Scanner::fov_x = M_PI / 3;
const double Scanner::fov_y = M_PI / 4;
const unsigned int Scanner::res_x = 320;
const unsigned int Scanner::res_y = 240;
PointCloud<PointNormal>::Ptr Scanner::getCloud(Scan scan) {
PointCloud<PointNormal>::Ptr cloud (new PointCloud<PointNormal>());
vtkSmartPointer<vtkTransform> transform = compute_transform(scan);
PointCloud<PointXYZ>::Ptr pcxyz = compute_pcxyz(scan.mi, transform);
float v[3];
transform->GetPosition(v);
PointCloud<Normal>::Ptr pcn = compute_pcn(pcxyz, v[0], v[1], v[2]);
concatenateFields(*pcxyz, *pcn, *cloud);
return cloud;
}
PointCloud<PointNormal>::Ptr Scanner::getCloudCached(int mi, int ti, int pi) {
Scan scan = {
mi,
Proctor::theta_start + ti * Proctor::theta_step,
Proctor::phi_start + pi * Proctor::phi_step
};
char name[22];
sprintf(name, "scan_%04d_%03.0f_%03.0f.pcd", Proctor::models[scan.mi].id, deg(scan.theta), deg(scan.phi));
if (ifstream(name)) {
PointCloud<PointNormal>::Ptr cloud (new PointCloud<PointNormal>());
io::loadPCDFile(name, *cloud);
return cloud;
} else {
PointCloud<PointNormal>::Ptr cloud = getCloud(scan);
io::savePCDFileBinary(name, *cloud);
return cloud;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015-2016, Andy Deng <theandy.deng@gmail.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <iostream>
using std::cout; using std::flush;
using std::cerr; using std::endl;
#include <string>
using std::string; using std::stoi;
#include <fstream>
using std::fstream; using std::getline;
#include <SDL_mixer.h>
#include "print.h"
#include "cursor.h"
#include "time.h"
#include "music.h"
const char SCRIPT_NAME[] = "script.txt";
bool Print::open(const std::string &name)
{
script_name = name;
file.open(script_name, fstream::in);
if (!file) {
cerr << "Unable to open " << script_name
<< "!" << endl;
return false;
}
return true;
}
void Print::close()
{
if (file.is_open())
file.close();
}
void Print::read()
{
while (file && get()) {
if (line.front() == '$') {
command(line);
} else if (line.front() == '[' && line.back() == ']') {
sub(line);
} else if (line.substr(0, 2) == "--") {
string tmp = line.substr(2);
if (line.back() == '\\') {
tmp.pop_back();
tmp += '\n';
while (get()) {
if (line.back() != '\\') {
tmp += line.substr(2);
break;
} else {
line.pop_back();
tmp += line.substr(2) + '\n';
}
}
}
mono(line.substr(2));
} else if (line.substr(0, 2) == "=T") {
title(line.substr(2));
} else if (line.substr(0, 2) == ";;") {
continue;
} else if (!line.empty()) {
if (line.back() == '\\') {
string tmp = line;
tmp.pop_back();
tmp += '\n';
while (get()) {
if (line.back() != '\\') {
tmp += line;
break;
} else {
line.pop_back();
tmp += line + '\n';
}
}
info(tmp);
} else {
info(line);
}
}
}
}
void Print::command(const std::string &cmd)
{
const string sleep("$sleep ");
const string music("$music ");
const string video("$video ");
const auto nofound = std::string::npos;
if (cmd.find(sleep) != nofound) {
rwsleep(cmd.substr(sleep.size()));
} else if (cmd.find(music) != nofound) {
rwmusic(cmd.substr(music.size()));
}
// FIXME: Unsupport video play now!
else if (cmd.find(video) != nofound) {
;
}
}
bool Print::get()
{
if (getline(file, line)) {
mark = file.tellg();
} else {
return false;
}
return true;
}
void Print::title(const string &s)
{
clscr();
goto_xy(1, 1);
cout << s;
}
void Print::sub(const string &s)
{
clsub();
goto_xy(1, 5);
cout << s;
}
void Print::view(const string &s, int del, int char_del)
{
for (auto i : s) {
cout << i << flush;
if (char_del != NO_DELAY)
per_char_delay(char_del);
}
if (del == RUN_AUTO)
delay(auto_sleep(s));
else
delay(del);
}
void Print::info(const string &s, int del, int char_del)
{
clinfo();
goto_xy(1, 7);
view(s, del, char_del);
}
void Print::mono(const string &s, int del, int char_del)
{
clsub();
goto_xy(1, 7);
view(s, del, char_del);
}
int Print::auto_sleep(const string &s)
{
bool is_long_cn_str = s.size() > CHAR_CN_SIZE * 15;
return is_long_cn_str ? 3 : 2;
}
void Print::delay(int del)
{
#ifndef RWDEBUG
sleep(del);
#else
msleep(10);
#endif
}
void Print::per_char_delay(int del)
{
#ifndef RWDEBUG
msleep(del);
#else
msleep(10);
#endif
}
void Print::rwsleep(const string &s)
{
#ifndef RWDEBUG
sleep(stoi(s));
#else
msleep(500);
#endif
}
void Print::rwmusic(const string &file)
{
play_bgm(file);
}
<commit_msg>print: fix multi-line monologue output issue<commit_after>/*
* Copyright (c) 2015-2016, Andy Deng <theandy.deng@gmail.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <iostream>
using std::cout; using std::flush;
using std::cerr; using std::endl;
#include <string>
using std::string; using std::stoi;
#include <fstream>
using std::fstream; using std::getline;
#include <SDL_mixer.h>
#include "print.h"
#include "cursor.h"
#include "time.h"
#include "music.h"
const char SCRIPT_NAME[] = "script.txt";
bool Print::open(const std::string &name)
{
script_name = name;
file.open(script_name, fstream::in);
if (!file) {
cerr << "Unable to open " << script_name
<< "!" << endl;
return false;
}
return true;
}
void Print::close()
{
if (file.is_open())
file.close();
}
void Print::read()
{
while (file && get()) {
if (line.front() == '$') {
command(line);
} else if (line.front() == '[' && line.back() == ']') {
sub(line);
} else if (line.substr(0, 2) == "--") {
string tmp = line.substr(2);
if (line.back() == '\\') {
tmp.pop_back();
tmp += '\n';
while (get()) {
if (line.back() != '\\') {
tmp += line.substr(2);
break;
} else {
line.pop_back();
tmp += line.substr(2) + '\n';
}
}
}
mono(tmp);
} else if (line.substr(0, 2) == "=T") {
title(line.substr(2));
} else if (line.substr(0, 2) == ";;") {
continue;
} else if (!line.empty()) {
if (line.back() == '\\') {
string tmp = line;
tmp.pop_back();
tmp += '\n';
while (get()) {
if (line.back() != '\\') {
tmp += line;
break;
} else {
line.pop_back();
tmp += line + '\n';
}
}
info(tmp);
} else {
info(line);
}
}
}
}
void Print::command(const std::string &cmd)
{
const string sleep("$sleep ");
const string music("$music ");
const string video("$video ");
const auto nofound = std::string::npos;
if (cmd.find(sleep) != nofound) {
rwsleep(cmd.substr(sleep.size()));
} else if (cmd.find(music) != nofound) {
rwmusic(cmd.substr(music.size()));
}
// FIXME: Unsupport video play now!
else if (cmd.find(video) != nofound) {
;
}
}
bool Print::get()
{
if (getline(file, line)) {
mark = file.tellg();
} else {
return false;
}
return true;
}
void Print::title(const string &s)
{
clscr();
goto_xy(1, 1);
cout << s;
}
void Print::sub(const string &s)
{
clsub();
goto_xy(1, 5);
cout << s;
}
void Print::view(const string &s, int del, int char_del)
{
for (auto i : s) {
cout << i << flush;
if (char_del != NO_DELAY)
per_char_delay(char_del);
}
if (del == RUN_AUTO)
delay(auto_sleep(s));
else
delay(del);
}
void Print::info(const string &s, int del, int char_del)
{
clinfo();
goto_xy(1, 7);
view(s, del, char_del);
}
void Print::mono(const string &s, int del, int char_del)
{
clsub();
goto_xy(1, 7);
view(s, del, char_del);
}
int Print::auto_sleep(const string &s)
{
bool is_long_cn_str = s.size() > CHAR_CN_SIZE * 15;
return is_long_cn_str ? 3 : 2;
}
void Print::delay(int del)
{
#ifndef RWDEBUG
sleep(del);
#else
msleep(10);
#endif
}
void Print::per_char_delay(int del)
{
#ifndef RWDEBUG
msleep(del);
#else
msleep(10);
#endif
}
void Print::rwsleep(const string &s)
{
#ifndef RWDEBUG
sleep(stoi(s));
#else
msleep(500);
#endif
}
void Print::rwmusic(const string &file)
{
play_bgm(file);
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2022 Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANNTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNNESS 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 INN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR INN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/**
Testcase Scenarios :
Functional ::
1) Pass different types of valid nodes and get the corresponding type of the node
2) Add Graph node, destroy the graph node and add the same node of different type.
hipGraphNodeGetTye should return the new type
3) Add graph node, overwrite new type to the same graph node and trigger
hipGraphNodeGetType which should return the updated type.
Negative ::
1) Pass nullptr to graph node
2) Pass nullptr to node type
3) Pass invalid to graph node
*/
#include <hip_test_common.hh>
#include <hip_test_checkers.hh>
#include <hip_test_kernels.hh>
TEST_CASE("Unit_hipGraphNodeGetType_Negative") {
SECTION("Pass nullptr to graph node") {
hipGraphNodeType nodeType;
REQUIRE(hipGraphNodeGetType(nullptr, &nodeType) == hipErrorInvalidValue);
}
SECTION("Pass nullptr to node type") {
hipGraphNode_t memcpyNode;
hipGraph_t graph;
HIP_CHECK(hipGraphCreate(&graph, 0));
HIP_CHECK(hipGraphAddEmptyNode(&memcpyNode, graph, nullptr , 0));
REQUIRE(hipGraphNodeGetType(memcpyNode, nullptr) == hipErrorInvalidValue);
}
SECTION("Pass invalid node") {
hipGraphNode_t Node = {};
hipGraphNodeType nodeType;
REQUIRE(hipGraphNodeGetType(Node, &nodeType) == hipErrorInvalidValue);
}
}
TEST_CASE("Unit_hipGraphNodeGetType_Functional") {
constexpr size_t N = 1024;
hipGraphNodeType nodeType;
hipGraph_t graph;
HIP_CHECK(hipGraphCreate(&graph, 0));
int *A_d, *B_d, *C_d;
int *A_h, *B_h, *C_h;
HipTest::initArrays(&A_d, &B_d, &C_d, &A_h, &B_h, &C_h, N, false);
hipEvent_t event;
hipGraphNode_t waiteventNode;
HIP_CHECK(hipEventCreate(&event));
hipStream_t stream;
HIP_CHECK(hipStreamCreate(&stream));
SECTION("Delete Node and Assign different Node Type") {
HIP_CHECK(hipStreamWaitEvent(stream, event, 0));
HIP_CHECK(hipGraphAddEventWaitNode(&waiteventNode, graph, nullptr, 0,
event));
HIP_CHECK(hipGraphNodeGetType(waiteventNode, &nodeType));
HIP_CHECK(hipGraphAddEmptyNode(&waiteventNode, graph, nullptr , 0));
HIP_CHECK(hipGraphNodeGetType(waiteventNode, &nodeType));
REQUIRE(nodeType == hipGraphNodeTypeEmpty);
}
SECTION("Override the graph node and get Node Type") {
HIP_CHECK(hipStreamWaitEvent(stream, event, 0));
HIP_CHECK(hipGraphAddEventWaitNode(&waiteventNode, graph, nullptr, 0,
event));
HIP_CHECK(hipGraphNodeGetType(waiteventNode, &nodeType));
HIP_CHECK(hipGraphAddEmptyNode(&waiteventNode, graph, nullptr , 0));
HIP_CHECK(hipGraphNodeGetType(waiteventNode, &nodeType));
REQUIRE(nodeType == hipGraphNodeTypeEmpty);
}
HIP_CHECK(hipStreamDestroy(stream));
HIP_CHECK(hipEventDestroy(event));
}
/**
* Functional Test for hipGraphNodeGetType API
*/
TEST_CASE("Unit_hipGraphNodeGetType_NodeType") {
constexpr size_t N = 1024;
constexpr size_t Nbytes = N * sizeof(int);
constexpr auto blocksPerCU = 6; // to hide latency
constexpr auto threadsPerBlock = 256;
hipGraph_t graph;
int *A_d, *B_d, *C_d;
int *A_h, *B_h, *C_h;
size_t NElem{N};
HipTest::initArrays(&A_d, &B_d, &C_d, &A_h, &B_h, &C_h, N, false);
unsigned blocks = HipTest::setNumBlocks(blocksPerCU, threadsPerBlock, N);
HIP_CHECK(hipGraphCreate(&graph, 0));
hipGraphNodeType nodeType;
hipGraphNode_t memcpyNode, kernelNode;
SECTION("Get Memcpy NodeType") {
HIP_CHECK(hipGraphAddMemcpyNode1D(&memcpyNode, graph, NULL, 0, A_d, A_h,
Nbytes, hipMemcpyHostToDevice));
HIP_CHECK(hipGraphNodeGetType(memcpyNode, &nodeType));
#if HT_AMD
REQUIRE(nodeType == hipGraphNodeTypeMemcpy1D);
#else
REQUIRE(nodeType == cudaGraphNodeTypeMemcpy);
#endif
HIP_CHECK(hipGraphAddEmptyNode(&memcpyNode, graph, nullptr , 0));
HIP_CHECK(hipGraphNodeGetType(memcpyNode, &nodeType));
REQUIRE(nodeType == hipGraphNodeTypeEmpty);
}
SECTION("Get Kernel NodeType") {
hipKernelNodeParams kernelNodeParams{};
void* kernelArgs[] = {&A_d, &B_d, &C_d, reinterpret_cast<void *>(&NElem)};
kernelNodeParams.func = reinterpret_cast<void *>(HipTest::vectorADD<int>);
kernelNodeParams.gridDim = dim3(blocks);
kernelNodeParams.blockDim = dim3(threadsPerBlock);
kernelNodeParams.sharedMemBytes = 0;
kernelNodeParams.kernelParams = reinterpret_cast<void**>(kernelArgs);
kernelNodeParams.extra = nullptr;
HIP_CHECK(hipGraphAddKernelNode(&kernelNode, graph, nullptr,
0, &kernelNodeParams));
HIP_CHECK(hipGraphNodeGetType(kernelNode, &nodeType));
REQUIRE(nodeType == hipGraphNodeTypeKernel);
}
SECTION("Get Empty NodeType") {
hipGraphNode_t emptyNode;
HIP_CHECK(hipGraphAddEmptyNode(&emptyNode, graph, nullptr , 0));
HIP_CHECK(hipGraphNodeGetType(emptyNode, &nodeType));
REQUIRE(nodeType == hipGraphNodeTypeEmpty);
}
SECTION("Get Memset NodeType") {
hipGraphNode_t memsetNode;
hipMemsetParams memsetParams{};
memset(&memsetParams, 0, sizeof(memsetParams));
memsetParams.dst = reinterpret_cast<void*>(A_d);
memsetParams.value = 10;
memsetParams.pitch = 0;
memsetParams.elementSize = sizeof(char);
memsetParams.width = Nbytes;
memsetParams.height = 1;
HIP_CHECK(hipGraphAddMemsetNode(&memsetNode, graph, nullptr, 0,
&memsetParams));
HIP_CHECK(hipGraphNodeGetType(memsetNode, &nodeType));
REQUIRE(nodeType == hipGraphNodeTypeMemset);
}
SECTION("Get WaitEvent NodeType") {
hipEvent_t event;
hipGraphNode_t waiteventNode;
HIP_CHECK(hipEventCreate(&event));
hipStream_t stream;
HIP_CHECK(hipStreamCreate(&stream));
HIP_CHECK(hipStreamWaitEvent(stream, event, 0));
HIP_CHECK(hipGraphAddEventWaitNode(&waiteventNode, graph, nullptr, 0,
event));
HIP_CHECK(hipGraphNodeGetType(waiteventNode, &nodeType));
REQUIRE(nodeType == hipGraphNodeTypeWaitEvent);
HIP_CHECK(hipStreamDestroy(stream));
HIP_CHECK(hipEventDestroy(event));
}
SECTION("Get EventRecord NodeType") {
hipEvent_t event;
hipGraphNode_t recordeventNode;
HIP_CHECK(hipEventCreate(&event));
hipStream_t stream;
HIP_CHECK(hipStreamCreate(&stream));
HIP_CHECK(hipEventRecord(event, stream));
HIP_CHECK(hipGraphAddEventRecordNode(&recordeventNode, graph, nullptr, 0,
event));
HIP_CHECK(hipGraphNodeGetType(recordeventNode, &nodeType));
REQUIRE(nodeType == hipGraphNodeTypeEventRecord);
HIP_CHECK(hipStreamDestroy(stream));
HIP_CHECK(hipEventDestroy(event));
}
HipTest::freeArrays(A_d, B_d, C_d, A_h, B_h, C_h, false);
HIP_CHECK(hipGraphDestroy(graph));
}
<commit_msg>SWDEV-321698 - Correct node type (#2692)<commit_after>/*
Copyright (c) 2022 Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANNTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNNESS 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 INN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR INN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/**
Testcase Scenarios :
Functional ::
1) Pass different types of valid nodes and get the corresponding type of the node
2) Add Graph node, destroy the graph node and add the same node of different type.
hipGraphNodeGetTye should return the new type
3) Add graph node, overwrite new type to the same graph node and trigger
hipGraphNodeGetType which should return the updated type.
Negative ::
1) Pass nullptr to graph node
2) Pass nullptr to node type
3) Pass invalid to graph node
*/
#include <hip_test_common.hh>
#include <hip_test_checkers.hh>
#include <hip_test_kernels.hh>
TEST_CASE("Unit_hipGraphNodeGetType_Negative") {
SECTION("Pass nullptr to graph node") {
hipGraphNodeType nodeType;
REQUIRE(hipGraphNodeGetType(nullptr, &nodeType) == hipErrorInvalidValue);
}
SECTION("Pass nullptr to node type") {
hipGraphNode_t memcpyNode;
hipGraph_t graph;
HIP_CHECK(hipGraphCreate(&graph, 0));
HIP_CHECK(hipGraphAddEmptyNode(&memcpyNode, graph, nullptr , 0));
REQUIRE(hipGraphNodeGetType(memcpyNode, nullptr) == hipErrorInvalidValue);
}
SECTION("Pass invalid node") {
hipGraphNode_t Node = {};
hipGraphNodeType nodeType;
REQUIRE(hipGraphNodeGetType(Node, &nodeType) == hipErrorInvalidValue);
}
}
TEST_CASE("Unit_hipGraphNodeGetType_Functional") {
constexpr size_t N = 1024;
hipGraphNodeType nodeType;
hipGraph_t graph;
HIP_CHECK(hipGraphCreate(&graph, 0));
int *A_d, *B_d, *C_d;
int *A_h, *B_h, *C_h;
HipTest::initArrays(&A_d, &B_d, &C_d, &A_h, &B_h, &C_h, N, false);
hipEvent_t event;
hipGraphNode_t waiteventNode;
HIP_CHECK(hipEventCreate(&event));
hipStream_t stream;
HIP_CHECK(hipStreamCreate(&stream));
SECTION("Delete Node and Assign different Node Type") {
HIP_CHECK(hipStreamWaitEvent(stream, event, 0));
HIP_CHECK(hipGraphAddEventWaitNode(&waiteventNode, graph, nullptr, 0,
event));
HIP_CHECK(hipGraphNodeGetType(waiteventNode, &nodeType));
HIP_CHECK(hipGraphAddEmptyNode(&waiteventNode, graph, nullptr , 0));
HIP_CHECK(hipGraphNodeGetType(waiteventNode, &nodeType));
REQUIRE(nodeType == hipGraphNodeTypeEmpty);
}
SECTION("Override the graph node and get Node Type") {
HIP_CHECK(hipStreamWaitEvent(stream, event, 0));
HIP_CHECK(hipGraphAddEventWaitNode(&waiteventNode, graph, nullptr, 0,
event));
HIP_CHECK(hipGraphNodeGetType(waiteventNode, &nodeType));
HIP_CHECK(hipGraphAddEmptyNode(&waiteventNode, graph, nullptr , 0));
HIP_CHECK(hipGraphNodeGetType(waiteventNode, &nodeType));
REQUIRE(nodeType == hipGraphNodeTypeEmpty);
}
HIP_CHECK(hipStreamDestroy(stream));
HIP_CHECK(hipEventDestroy(event));
}
/**
* Functional Test for hipGraphNodeGetType API
*/
TEST_CASE("Unit_hipGraphNodeGetType_NodeType") {
constexpr size_t N = 1024;
constexpr size_t Nbytes = N * sizeof(int);
constexpr auto blocksPerCU = 6; // to hide latency
constexpr auto threadsPerBlock = 256;
hipGraph_t graph;
int *A_d, *B_d, *C_d;
int *A_h, *B_h, *C_h;
size_t NElem{N};
HipTest::initArrays(&A_d, &B_d, &C_d, &A_h, &B_h, &C_h, N, false);
unsigned blocks = HipTest::setNumBlocks(blocksPerCU, threadsPerBlock, N);
HIP_CHECK(hipGraphCreate(&graph, 0));
hipGraphNodeType nodeType;
hipGraphNode_t memcpyNode, kernelNode;
SECTION("Get Memcpy NodeType") {
HIP_CHECK(hipGraphAddMemcpyNode1D(&memcpyNode, graph, NULL, 0, A_d, A_h,
Nbytes, hipMemcpyHostToDevice));
HIP_CHECK(hipGraphNodeGetType(memcpyNode, &nodeType));
// temp disable it until correct node is set
// REQUIRE(nodeType == hipGraphNodeTypeMemcpy);
HIP_CHECK(hipGraphAddEmptyNode(&memcpyNode, graph, nullptr , 0));
HIP_CHECK(hipGraphNodeGetType(memcpyNode, &nodeType));
REQUIRE(nodeType == hipGraphNodeTypeEmpty);
}
SECTION("Get Kernel NodeType") {
hipKernelNodeParams kernelNodeParams{};
void* kernelArgs[] = {&A_d, &B_d, &C_d, reinterpret_cast<void *>(&NElem)};
kernelNodeParams.func = reinterpret_cast<void *>(HipTest::vectorADD<int>);
kernelNodeParams.gridDim = dim3(blocks);
kernelNodeParams.blockDim = dim3(threadsPerBlock);
kernelNodeParams.sharedMemBytes = 0;
kernelNodeParams.kernelParams = reinterpret_cast<void**>(kernelArgs);
kernelNodeParams.extra = nullptr;
HIP_CHECK(hipGraphAddKernelNode(&kernelNode, graph, nullptr,
0, &kernelNodeParams));
HIP_CHECK(hipGraphNodeGetType(kernelNode, &nodeType));
REQUIRE(nodeType == hipGraphNodeTypeKernel);
}
SECTION("Get Empty NodeType") {
hipGraphNode_t emptyNode;
HIP_CHECK(hipGraphAddEmptyNode(&emptyNode, graph, nullptr , 0));
HIP_CHECK(hipGraphNodeGetType(emptyNode, &nodeType));
REQUIRE(nodeType == hipGraphNodeTypeEmpty);
}
SECTION("Get Memset NodeType") {
hipGraphNode_t memsetNode;
hipMemsetParams memsetParams{};
memset(&memsetParams, 0, sizeof(memsetParams));
memsetParams.dst = reinterpret_cast<void*>(A_d);
memsetParams.value = 10;
memsetParams.pitch = 0;
memsetParams.elementSize = sizeof(char);
memsetParams.width = Nbytes;
memsetParams.height = 1;
HIP_CHECK(hipGraphAddMemsetNode(&memsetNode, graph, nullptr, 0,
&memsetParams));
HIP_CHECK(hipGraphNodeGetType(memsetNode, &nodeType));
REQUIRE(nodeType == hipGraphNodeTypeMemset);
}
SECTION("Get WaitEvent NodeType") {
hipEvent_t event;
hipGraphNode_t waiteventNode;
HIP_CHECK(hipEventCreate(&event));
hipStream_t stream;
HIP_CHECK(hipStreamCreate(&stream));
HIP_CHECK(hipStreamWaitEvent(stream, event, 0));
HIP_CHECK(hipGraphAddEventWaitNode(&waiteventNode, graph, nullptr, 0,
event));
HIP_CHECK(hipGraphNodeGetType(waiteventNode, &nodeType));
REQUIRE(nodeType == hipGraphNodeTypeWaitEvent);
HIP_CHECK(hipStreamDestroy(stream));
HIP_CHECK(hipEventDestroy(event));
}
SECTION("Get EventRecord NodeType") {
hipEvent_t event;
hipGraphNode_t recordeventNode;
HIP_CHECK(hipEventCreate(&event));
hipStream_t stream;
HIP_CHECK(hipStreamCreate(&stream));
HIP_CHECK(hipEventRecord(event, stream));
HIP_CHECK(hipGraphAddEventRecordNode(&recordeventNode, graph, nullptr, 0,
event));
HIP_CHECK(hipGraphNodeGetType(recordeventNode, &nodeType));
REQUIRE(nodeType == hipGraphNodeTypeEventRecord);
HIP_CHECK(hipStreamDestroy(stream));
HIP_CHECK(hipEventDestroy(event));
}
HipTest::freeArrays(A_d, B_d, C_d, A_h, B_h, C_h, false);
HIP_CHECK(hipGraphDestroy(graph));
}
<|endoftext|> |
<commit_before><commit_msg>ensure string accesses are in bounds<commit_after><|endoftext|> |
<commit_before>#pragma once
#include <ostream>
#include <vector>
using std::ostream;
using std::vector;
namespace seq {
static constexpr const auto delimBegin = '[';
static constexpr const auto delimEnd = ']';
static constexpr const auto delimSep = ',';
template <typename T, template <class> typename Seq>
static inline ostream& operator<<(ostream& os, conref<Seq<T>> vec) noexcept {
os << delimBegin;
if (vec.size() > 0) {
os << vec.front();
for (auto &&it = vec.cbegin() + 1; it < vec.cend(); ++it) {
os << delimSep << *it;
}
}
return os << delimEnd;
}
}
<commit_msg>added seq impl for array<commit_after>#pragma once
#include <ostream>
#include "../util/def.hxx"
using std::ostream;
namespace seq {
static constexpr const auto delimBegin = '[';
static constexpr const auto delimEnd = ']';
static constexpr const auto delimSep = ',';
template <typename T, template <class> typename Seq>
static inline ostream& operator<<(ostream& os, conref<Seq<T>> vec) noexcept {
os << delimBegin;
if (vec.size() > 0) {
os << vec.front();
for (auto &&it = vec.cbegin() + 1; it < vec.cend(); ++it) {
os << delimSep << *it;
}
}
return os << delimEnd;
}
template <typename T, template <class, size_t n> typename Seq, size_t n>
static inline ostream& operator<<(ostream& os, conref<Seq<T,n>> vec) noexcept {
os << delimBegin;
if (vec.size() > 0) {
os << vec.front();
for (auto &&it = vec.cbegin() + 1; it < vec.cend(); ++it) {
os << delimSep << *it;
}
}
return os << delimEnd;
}
}
<|endoftext|> |
<commit_before>/*
* ServerOptions.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <server/ServerOptions.hpp>
#include <core/ProgramStatus.hpp>
#include <core/ProgramOptions.hpp>
#include <core/FilePath.hpp>
#include <core/system/PosixUser.hpp>
#include <core/system/PosixSystem.hpp>
#include "ServerAppArmor.hpp"
using namespace core ;
namespace server {
namespace {
const char * const kDefaultProgramUser = "rstudio-server";
} // anonymous namespace
Options& options()
{
static Options instance ;
return instance ;
}
ProgramStatus Options::read(int argc, char * const argv[])
{
using namespace boost::program_options ;
// compute install path
Error error = core::system::installPath("..", argc, argv, &installPath_);
if (error)
{
LOG_ERROR_MESSAGE("Unable to determine install path: "+error.summary());
return ProgramStatus::exitFailure();
}
// verify installation flag
options_description verify("verify");
verify.add_options()
("verify-installation",
value<bool>(&verifyInstallation_)->default_value(false),
"verify the current installation");
// special program offline option (based on file existence at
// startup for easy bash script enable/disable of offline state)
serverOffline_ = FilePath("/var/lib/rstudio-server/offline").exists();
// program - name and execution
options_description server("server");
server.add_options()
("server-working-dir",
value<std::string>(&serverWorkingDir_)->default_value("/"),
"program working directory")
("server-user",
value<std::string>(&serverUser_)->default_value(kDefaultProgramUser),
"program user")
("server-daemonize",
value<bool>(&serverDaemonize_)->default_value(1),
"run program as daemon")
("server-app-armor-enabled",
value<bool>(&serverAppArmorEnabled_)->default_value(1),
"is app armor enabled for this session");
// www - web server options
options_description www("www") ;
www.add_options()
("www-address",
value<std::string>(&wwwAddress_)->default_value("0.0.0.0"),
"server address")
("www-port",
value<std::string>(&wwwPort_)->default_value(""),
"port to listen on")
("www-local-path",
value<std::string>(&wwwLocalPath_)->default_value("www"),
"www files path")
("www-thread-pool-size",
value<int>(&wwwThreadPoolSize_)->default_value(2),
"thread pool size");
// rsession
options_description rsession("rsession");
rsession.add_options()
("rsession-which-r",
value<std::string>(&rsessionWhichR_)->default_value(""),
"path to main R program (e.g. /usr/bin/R)")
("rsession-path",
value<std::string>(&rsessionPath_)->default_value("bin/rsession"),
"path to rsession executable")
("rldpath-path",
value<std::string>(&rldpathPath_)->default_value("bin/r-ldpath"),
"path to r-ldpath script")
("rsession-ld-library-path",
value<std::string>(&rsessionLdLibraryPath_)->default_value(""),
"default LD_LIBRARY_PATH for rsession")
("rsession-config-file",
value<std::string>(&rsessionConfigFile_)->default_value(""),
"path to rsession config file")
("rsession-memory-limit-mb",
value<int>(&rsessionMemoryLimitMb_)->default_value(0),
"rsession memory limit (mb)")
("rsession-stack-limit-mb",
value<int>(&rsessionStackLimitMb_)->default_value(0),
"rsession stack limit (mb)")
("rsession-process-limit",
value<int>(&rsessionUserProcessLimit_)->default_value(0),
"rsession user process limit");
// still read depracated options (so we don't break config files)
bool deprecatedAuthPamRequiresPriv;
options_description auth("auth");
auth.add_options()
("auth-validate-users",
value<bool>(&authValidateUsers_)->default_value(true),
"validate that authenticated users exist on the target system")
("auth-required-user-group",
value<std::string>(&authRequiredUserGroup_)->default_value(""),
"limit to users belonging to the specified group")
("auth-pam-helper-path",
value<std::string>(&authPamHelperPath_)->default_value("bin/rserver-pam"),
"path to PAM helper binary")
("auth-pam-requires-priv",
value<bool>(&deprecatedAuthPamRequiresPriv)->default_value(true),
"deprecated: will always be true");
// define program options
FilePath defaultConfigPath("/etc/rstudio/rserver.conf");
std::string configFile = defaultConfigPath.exists() ?
defaultConfigPath.absolutePath() : "";
program_options::OptionsDescription optionsDesc("rserver", configFile);
// overlay hook
addOverlayOptions(&server, &www, &rsession, &auth);
optionsDesc.commandLine.add(verify).add(server).add(www).add(rsession).add(auth);
optionsDesc.configFile.add(server).add(www).add(rsession).add(auth);
// read options
ProgramStatus status = core::program_options::read(optionsDesc, argc, argv);
if (status.exit())
return status;
// if specified, confirm that the program user exists. however, if the
// program user is the default and it doesn't exist then allow that to pass,
// this just means that the user did a simple make install and hasn't setup
// an rserver user yet. in this case the program will run as root
if (!serverUser_.empty())
{
// if we aren't running as root then forget the programUser
if (!core::system::realUserIsRoot())
{
serverUser_ = "";
}
// if there is a program user specified and it doesn't exist....
else if (!core::system::user::exists(serverUser_))
{
if (serverUser_ == kDefaultProgramUser)
{
// administrator hasn't created an rserver system account yet
// so we'll end up running as root
serverUser_ = "";
}
else
{
LOG_ERROR_MESSAGE("Server user "+ serverUser_ +" does not exist");
return ProgramStatus::exitFailure();
}
}
}
// if app armor is enabled do a further check to see whether
// the profile exists. if it doesn't then disable it
if (serverAppArmorEnabled_)
{
if (!FilePath("/etc/apparmor.d/rstudio-server").exists())
serverAppArmorEnabled_ = false;
}
// convert relative paths by completing from the system installation
// path (this allows us to be relocatable)
resolvePath(&wwwLocalPath_);
resolvePath(&authPamHelperPath_);
resolvePath(&rsessionPath_);
resolvePath(&rldpathPath_);
resolvePath(&rsessionConfigFile_);
// overlay hook
resolveOverlayOptions();
// overlay validation
std::string errMsg;
if (!validateOverlayOptions(&errMsg))
{
LOG_ERROR_MESSAGE(errMsg);
return ProgramStatus::exitFailure();
}
// return status
return status;
}
void Options::resolvePath(std::string* pPath) const
{
if (!pPath->empty())
*pPath = installPath_.complete(*pPath).absolutePath();
}
} // namespace server
<commit_msg>resolve and validate overlay options sooner<commit_after>/*
* ServerOptions.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <server/ServerOptions.hpp>
#include <core/ProgramStatus.hpp>
#include <core/ProgramOptions.hpp>
#include <core/FilePath.hpp>
#include <core/system/PosixUser.hpp>
#include <core/system/PosixSystem.hpp>
#include "ServerAppArmor.hpp"
using namespace core ;
namespace server {
namespace {
const char * const kDefaultProgramUser = "rstudio-server";
} // anonymous namespace
Options& options()
{
static Options instance ;
return instance ;
}
ProgramStatus Options::read(int argc, char * const argv[])
{
using namespace boost::program_options ;
// compute install path
Error error = core::system::installPath("..", argc, argv, &installPath_);
if (error)
{
LOG_ERROR_MESSAGE("Unable to determine install path: "+error.summary());
return ProgramStatus::exitFailure();
}
// verify installation flag
options_description verify("verify");
verify.add_options()
("verify-installation",
value<bool>(&verifyInstallation_)->default_value(false),
"verify the current installation");
// special program offline option (based on file existence at
// startup for easy bash script enable/disable of offline state)
serverOffline_ = FilePath("/var/lib/rstudio-server/offline").exists();
// program - name and execution
options_description server("server");
server.add_options()
("server-working-dir",
value<std::string>(&serverWorkingDir_)->default_value("/"),
"program working directory")
("server-user",
value<std::string>(&serverUser_)->default_value(kDefaultProgramUser),
"program user")
("server-daemonize",
value<bool>(&serverDaemonize_)->default_value(1),
"run program as daemon")
("server-app-armor-enabled",
value<bool>(&serverAppArmorEnabled_)->default_value(1),
"is app armor enabled for this session");
// www - web server options
options_description www("www") ;
www.add_options()
("www-address",
value<std::string>(&wwwAddress_)->default_value("0.0.0.0"),
"server address")
("www-port",
value<std::string>(&wwwPort_)->default_value(""),
"port to listen on")
("www-local-path",
value<std::string>(&wwwLocalPath_)->default_value("www"),
"www files path")
("www-thread-pool-size",
value<int>(&wwwThreadPoolSize_)->default_value(2),
"thread pool size");
// rsession
options_description rsession("rsession");
rsession.add_options()
("rsession-which-r",
value<std::string>(&rsessionWhichR_)->default_value(""),
"path to main R program (e.g. /usr/bin/R)")
("rsession-path",
value<std::string>(&rsessionPath_)->default_value("bin/rsession"),
"path to rsession executable")
("rldpath-path",
value<std::string>(&rldpathPath_)->default_value("bin/r-ldpath"),
"path to r-ldpath script")
("rsession-ld-library-path",
value<std::string>(&rsessionLdLibraryPath_)->default_value(""),
"default LD_LIBRARY_PATH for rsession")
("rsession-config-file",
value<std::string>(&rsessionConfigFile_)->default_value(""),
"path to rsession config file")
("rsession-memory-limit-mb",
value<int>(&rsessionMemoryLimitMb_)->default_value(0),
"rsession memory limit (mb)")
("rsession-stack-limit-mb",
value<int>(&rsessionStackLimitMb_)->default_value(0),
"rsession stack limit (mb)")
("rsession-process-limit",
value<int>(&rsessionUserProcessLimit_)->default_value(0),
"rsession user process limit");
// still read depracated options (so we don't break config files)
bool deprecatedAuthPamRequiresPriv;
options_description auth("auth");
auth.add_options()
("auth-validate-users",
value<bool>(&authValidateUsers_)->default_value(true),
"validate that authenticated users exist on the target system")
("auth-required-user-group",
value<std::string>(&authRequiredUserGroup_)->default_value(""),
"limit to users belonging to the specified group")
("auth-pam-helper-path",
value<std::string>(&authPamHelperPath_)->default_value("bin/rserver-pam"),
"path to PAM helper binary")
("auth-pam-requires-priv",
value<bool>(&deprecatedAuthPamRequiresPriv)->default_value(true),
"deprecated: will always be true");
// define program options
FilePath defaultConfigPath("/etc/rstudio/rserver.conf");
std::string configFile = defaultConfigPath.exists() ?
defaultConfigPath.absolutePath() : "";
program_options::OptionsDescription optionsDesc("rserver", configFile);
// overlay hooks
addOverlayOptions(&server, &www, &rsession, &auth);
resolveOverlayOptions();
// overlay validation
std::string errMsg;
if (!validateOverlayOptions(&errMsg))
{
LOG_ERROR_MESSAGE(errMsg);
return ProgramStatus::exitFailure();
}
optionsDesc.commandLine.add(verify).add(server).add(www).add(rsession).add(auth);
optionsDesc.configFile.add(server).add(www).add(rsession).add(auth);
// read options
ProgramStatus status = core::program_options::read(optionsDesc, argc, argv);
if (status.exit())
return status;
// if specified, confirm that the program user exists. however, if the
// program user is the default and it doesn't exist then allow that to pass,
// this just means that the user did a simple make install and hasn't setup
// an rserver user yet. in this case the program will run as root
if (!serverUser_.empty())
{
// if we aren't running as root then forget the programUser
if (!core::system::realUserIsRoot())
{
serverUser_ = "";
}
// if there is a program user specified and it doesn't exist....
else if (!core::system::user::exists(serverUser_))
{
if (serverUser_ == kDefaultProgramUser)
{
// administrator hasn't created an rserver system account yet
// so we'll end up running as root
serverUser_ = "";
}
else
{
LOG_ERROR_MESSAGE("Server user "+ serverUser_ +" does not exist");
return ProgramStatus::exitFailure();
}
}
}
// if app armor is enabled do a further check to see whether
// the profile exists. if it doesn't then disable it
if (serverAppArmorEnabled_)
{
if (!FilePath("/etc/apparmor.d/rstudio-server").exists())
serverAppArmorEnabled_ = false;
}
// convert relative paths by completing from the system installation
// path (this allows us to be relocatable)
resolvePath(&wwwLocalPath_);
resolvePath(&authPamHelperPath_);
resolvePath(&rsessionPath_);
resolvePath(&rldpathPath_);
resolvePath(&rsessionConfigFile_);
// return status
return status;
}
void Options::resolvePath(std::string* pPath) const
{
if (!pPath->empty())
*pPath = installPath_.complete(*pPath).absolutePath();
}
} // namespace server
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2010 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: Korey Sewell
*
*/
#ifndef __CPU_INORDER_RESOURCE_SKED_HH__
#define __CPU_INORDER_RESOURCE_SKED_HH__
#include <vector>
#include <list>
/** ScheduleEntry class represents a single function that an instruction
wants to do at any pipeline stage. For example, if an instruction
needs to be decoded and do a branch prediction all in one stage
then each of those tasks would need it's own ScheduleEntry.
Each schedule entry corresponds to some resource that the instruction
wants to interact with.
The file pipeline_traits.cc shows how a typical instruction schedule is
made up of these schedule entries.
*/
class ScheduleEntry {
public:
ScheduleEntry(int stage_num, int _priority, int res_num, int _cmd = 0,
int _idx = 0) :
stageNum(stage_num), resNum(res_num), cmd(_cmd),
idx(_idx), priority(_priority)
{ }
/** Stage number to perform this service. */
int stageNum;
/** Resource ID to access */
int resNum;
/** See specific resource for meaning */
unsigned cmd;
/** See specific resource for meaning */
unsigned idx;
/** Some Resources May Need Priority */
int priority;
};
/** The ResourceSked maintains the complete schedule
for an instruction. That schedule includes what
resources an instruction wants to acquire at each
pipeline stage and is represented by a collection
of ScheduleEntry objects (described above) that
must be executed in-order.
In every pipeline stage, the InOrder model will
process all entries on the resource schedule for
that stage and then send the instruction to the next
stage if and only if the instruction successfully
completed each ScheduleEntry.
*/
class ResourceSked {
public:
typedef std::list<ScheduleEntry*>::iterator SkedIt;
ResourceSked();
/** Initializee the current entry pointer to
pipeline stage 0 and the 1st schedule entry
*/
void init();
/** Goes through the remaining stages on the schedule
and sums all the remaining entries left to be
processed
*/
int size();
/** Is the schedule empty? */
bool empty();
/** What is the next task for this instruction schedule? */
ScheduleEntry* top();
/** Top() Task is completed, remove it from schedule */
void pop();
/** Add To Schedule based on stage num and priority of
Schedule Entry
*/
void push(ScheduleEntry* sked_entry);
/** Add Schedule Entry to be in front of another Entry */
void pushBefore(ScheduleEntry* sked_entry, int sked_cmd, int sked_cmd_idx);
/** Print what's left on the instruction schedule */
void print();
private:
/** Current Schedule Entry Pointer */
SkedIt curSkedEntry;
/** The Resource Schedule: Resized to Number of Stages in
the constructor
*/
std::vector<std::list<ScheduleEntry*> > sked;
/** Find a place to insert the instruction using the
schedule entries priority
*/
SkedIt findIterByPriority(ScheduleEntry *sked_entry, int stage_num);
/** Find a place to insert the instruction using a particular command
to look for.
*/
SkedIt findIterByCommand(ScheduleEntry *sked_entry, int stage_num,
int sked_cmd, int sked_cmd_idx = -1);
};
#endif //__CPU_INORDER_RESOURCE_SKED_HH__
<commit_msg>inorder: define iterator for resource schedules resource skeds are divided into two parts: front end (all insts) and back end (inst. specific) each of those are implemented as separate lists, so this iterator wraps around the traditional list iterator so that an instruction can walk it's schedule but seamlessly transfer from front end to back end when necessary<commit_after>/*
* Copyright (c) 2010-2011 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: Korey Sewell
*
*/
#ifndef __CPU_INORDER_RESOURCE_SKED_HH__
#define __CPU_INORDER_RESOURCE_SKED_HH__
#include <vector>
#include <list>
#include <cstdlib>
/** ScheduleEntry class represents a single function that an instruction
wants to do at any pipeline stage. For example, if an instruction
needs to be decoded and do a branch prediction all in one stage
then each of those tasks would need it's own ScheduleEntry.
Each schedule entry corresponds to some resource that the instruction
wants to interact with.
The file pipeline_traits.cc shows how a typical instruction schedule is
made up of these schedule entries.
*/
class ScheduleEntry {
public:
ScheduleEntry(int stage_num, int _priority, int res_num, int _cmd = 0,
int _idx = 0) :
stageNum(stage_num), resNum(res_num), cmd(_cmd),
idx(_idx), priority(_priority)
{ }
/** Stage number to perform this service. */
int stageNum;
/** Resource ID to access */
int resNum;
/** See specific resource for meaning */
unsigned cmd;
/** See specific resource for meaning */
unsigned idx;
/** Some Resources May Need Priority */
int priority;
};
/** The ResourceSked maintains the complete schedule
for an instruction. That schedule includes what
resources an instruction wants to acquire at each
pipeline stage and is represented by a collection
of ScheduleEntry objects (described above) that
must be executed in-order.
In every pipeline stage, the InOrder model will
process all entries on the resource schedule for
that stage and then send the instruction to the next
stage if and only if the instruction successfully
completed each ScheduleEntry.
*/
class ResourceSked {
public:
typedef std::list<ScheduleEntry*>::iterator SkedIt;
typedef std::vector<std::list<ScheduleEntry*> > StageList;
ResourceSked();
/** Initializee the current entry pointer to
pipeline stage 0 and the 1st schedule entry
*/
void init();
/** Goes through the remaining stages on the schedule
and sums all the remaining entries left to be
processed
*/
int size();
/** Is the schedule empty? */
bool empty();
/** Beginning Entry of this schedule */
SkedIt begin();
/** Ending Entry of this schedule */
SkedIt end();
/** What is the next task for this instruction schedule? */
ScheduleEntry* top();
/** Top() Task is completed, remove it from schedule */
void pop();
/** Add To Schedule based on stage num and priority of
Schedule Entry
*/
void push(ScheduleEntry* sked_entry);
/** Add Schedule Entry to be in front of another Entry */
void pushBefore(ScheduleEntry* sked_entry, int sked_cmd, int sked_cmd_idx);
/** Print what's left on the instruction schedule */
void print();
StageList *getStages()
{
return &stages;
}
private:
/** Current Schedule Entry Pointer */
SkedIt curSkedEntry;
/** The Stage-by-Stage Resource Schedule:
Resized to Number of Stages in the constructor
*/
StageList stages;
/** Find a place to insert the instruction using the
schedule entries priority
*/
SkedIt findIterByPriority(ScheduleEntry *sked_entry, int stage_num);
/** Find a place to insert the instruction using a particular command
to look for.
*/
SkedIt findIterByCommand(ScheduleEntry *sked_entry, int stage_num,
int sked_cmd, int sked_cmd_idx = -1);
};
/** Wrapper class around the SkedIt iterator in the Resource Sked so that
we can use ++ operator to automatically go to the next available
resource schedule entry but otherwise maintain same functionality
as a normal iterator.
*/
class RSkedIt
{
public:
RSkedIt()
: curStage(0), numStages(0)
{ }
/** init() must be called before the use of any other member
in the RSkedIt class.
*/
void init(ResourceSked* rsked)
{
stages = rsked->getStages();
numStages = stages->size();
}
/* Update the encapsulated "myIt" iterator, but only
update curStage/curStage_end if the iterator is valid.
The iterator could be invalid in the case where
someone is saving the end of a list (i.e. std::list->end())
*/
RSkedIt operator=(ResourceSked::SkedIt const &rhs)
{
myIt = rhs;
if (myIt != (*stages)[numStages-1].end()) {
curStage = (*myIt)->stageNum;
curStage_end = (*stages)[curStage].end();
}
return *this;
}
/** Increment to the next entry in current stage.
If no more entries then find the next stage that has
resource schedule to complete.
If no more stages, then return the end() iterator from
the last stage to indicate we are done.
*/
RSkedIt &operator++(int unused)
{
if (++myIt == curStage_end) {
curStage++;
while (curStage < numStages) {
if ((*stages)[curStage].empty()) {
curStage++;
} else {
myIt = (*stages)[curStage].begin();
curStage_end = (*stages)[curStage].end();
return *this;
}
}
myIt = (*stages)[numStages - 1].end();
}
return *this;
}
/** The "pointer" operator can be used on a RSkedIt and it
will use the encapsulated iterator
*/
ScheduleEntry* operator->()
{
return *myIt;
}
/** Dereferencing a RSKedIt will access the encapsulated
iterator
*/
ScheduleEntry* operator*()
{
return *myIt;
}
/** Equality for RSkedIt only compares the "myIt" iterators,
as the other members are just ancillary
*/
bool operator==(RSkedIt const &rhs)
{
return this->myIt == rhs.myIt;
}
/** Inequality for RSkedIt only compares the "myIt" iterators,
as the other members are just ancillary
*/
bool operator!=(RSkedIt const &rhs)
{
return this->myIt != rhs.myIt;
}
/* The == and != operator overloads should be sufficient
here if need otherwise direct access to the schedule
iterator, then this can be used */
ResourceSked::SkedIt getIt()
{
return myIt;
}
private:
/** Schedule Iterator that this class is encapsulating */
ResourceSked::SkedIt myIt;
/** Ptr to resource schedule that the 'myIt' iterator
belongs to
*/
ResourceSked::StageList *stages;
/** The last iterator in the current stage. */
ResourceSked::SkedIt curStage_end;
/** Current Stage that "myIt" refers to. */
int curStage;
/** Number of stages in the "*stages" object. */
int numStages;
};
#endif //__CPU_INORDER_RESOURCE_SKED_HH__
<|endoftext|> |
<commit_before>#include "game_window.h"
#include "command_menu.h"
#include "../parser_yaml/graphics_parser.h"
using namespace std;
CommandMenu::CommandMenu(GameWindow& owner, GraphicsParser& graphicsParser) :
owner(owner),
offset(0, owner.alto_pantalla - graphicsParser.getPantalla().hud_alto),
size((owner.ancho_pantalla-graphicsParser.getPantalla().minimapa_ancho)/2, graphicsParser.getPantalla().hud_alto)
{
isVisibleProducer = false;
isVisibleWorker = false;
isVisibleUnit = false;
showOptions = false;
posicionating = false;
currentSelection = nullptr;
}
CommandMenu::~CommandMenu() {
}
void CommandMenu::visit(Entity& entity) {
}
void CommandMenu::visit(Unit& entity) {
visit((Entity&)entity);
outText = outText + owner.completeLine("[] Ir", size.x);
outText = outText + owner.completeLine("[] Atacar", size.x);
outText = outText + owner.completeLine("[s] Parar", size.x);
isVisibleUnit = true;
}
void CommandMenu::visit(Worker& entity) {
if (!showOptions) {
visit((Unit&)entity);
outText = outText + owner.completeLine("[] Reparar", size.x);
outText = outText + owner.completeLine("[] Recolectar", size.x);
outText = outText + owner.completeLine("[c] Construir", size.x);
}
else {
if (posicionating) {
outText = outText + owner.completeLine("Posicionando nueva edificacion", size.x);
}
else {
if (entity.products.size() < 1) {
outText = outText + owner.completeLine("No hay edificaciones disponibles", size.x);
}
int i = 1;
for (auto& p : entity.products) {
outText = outText + owner.completeLine("[" + intToString(i) + "] " + p.name, size.x);
for (auto& c : p.lines) {
outText = outText + owner.completeLine("--> Costo: " + c.resource_name + "=" + intToString((int)c.amount), size.x);
}
i++;
}
}
}
isVisibleWorker = true;
}
void CommandMenu::visit(Building& entity) {
if (!showOptions) {
visit((Entity&)entity);
outText = outText + owner.completeLine("[p] Producir", size.x);
}
else {
if (entity.products.size() < 1) {
outText = outText + owner.completeLine("No hay productos disponibles", size.x);
}
int i = 1;
for (auto& p : entity.products) {
outText = outText + owner.completeLine("[" + intToString(i) + "] " + p.name, size.x);
for (auto& c : p.lines) {
outText = outText + owner.completeLine("--> Costo: " + c.resource_name+ "=" + intToString((int)c.amount), size.x);
}
i++;
}
}
isVisibleProducer = true;
}
void CommandMenu::draw() {
//Dibujo fondo
SDL_Rect destinoFondoMenu = { (int)offset.x, (int)offset.y, (int)size.x, (int)size.y };
SDL_SetRenderDrawColor(owner.getRenderer(), 15, 15, 15, 255);
SDL_RenderFillRect(owner.getRenderer(), &destinoFondoMenu);
outText = "";
isVisibleProducer = false;
isVisibleUnit = false;
isVisibleWorker = false;
SDL_Color colorBlanco = { 255, 255, 255 };
if (owner.font) {
if ((owner.sController->getSelection().size() == 1) && (owner.player.name == owner.sController->getSelection().at(0)->owner.name)){
if (currentSelection != owner.sController->getSelection().at(0)) {
showOptions = false;
posicionating = false;
}
owner.sController->getSelection().at(0)->visit(*this);
currentSelection = owner.sController->getSelection().at(0);
}
else if (owner.sController->getSelection().size() > 1) {
outText = outText + owner.completeLine("[] Ir", size.x);
outText = outText + owner.completeLine("[] Atacar", size.x);
outText = outText + owner.completeLine("[s] Parar", size.x);
currentSelection = nullptr;
isVisibleUnit = true;
}
else {
currentSelection = nullptr;
showOptions = false;
posicionating = false;
}
int access1, w1, h1;
Uint32 format1;
SDL_Surface * c1 = TTF_RenderText_Blended_Wrapped(owner.font, outText.c_str(), colorBlanco, (Uint32)(size.x));
SDL_Texture * textureMenu1 = SDL_CreateTextureFromSurface(owner.getRenderer(), c1);
SDL_QueryTexture(textureMenu1, &format1, &access1, &w1, &h1);
SDL_Rect panel1 = { 0, 0, w1 , h1 };
SDL_Rect text1 = { (int)offset.x, (int)offset.y,
(int)((w1 > size.x) ? size.x : w1), (int)((h1 > size.y) ? size.y : h1) };
SDL_RenderCopy(owner.getRenderer(), textureMenu1, &panel1, &text1);
SDL_FreeSurface(c1);
SDL_DestroyTexture(textureMenu1);
}
}
std::string CommandMenu::intToString(int i) {
string resultado;
ostringstream aux;
aux << i;
resultado = aux.str();
return resultado;
}
<commit_msg>Rediseno linea de costos en command Menu<commit_after>#include "game_window.h"
#include "command_menu.h"
#include "../parser_yaml/graphics_parser.h"
using namespace std;
CommandMenu::CommandMenu(GameWindow& owner, GraphicsParser& graphicsParser) :
owner(owner),
offset(0, owner.alto_pantalla - graphicsParser.getPantalla().hud_alto),
size((owner.ancho_pantalla-graphicsParser.getPantalla().minimapa_ancho)/2, graphicsParser.getPantalla().hud_alto)
{
isVisibleProducer = false;
isVisibleWorker = false;
isVisibleUnit = false;
showOptions = false;
posicionating = false;
currentSelection = nullptr;
}
CommandMenu::~CommandMenu() {
}
void CommandMenu::visit(Entity& entity) {
}
void CommandMenu::visit(Unit& entity) {
visit((Entity&)entity);
outText = outText + owner.completeLine("[] Ir", size.x);
outText = outText + owner.completeLine("[] Atacar", size.x);
outText = outText + owner.completeLine("[s] Parar", size.x);
isVisibleUnit = true;
}
void CommandMenu::visit(Worker& entity) {
if (!showOptions) {
visit((Unit&)entity);
outText = outText + owner.completeLine("[] Reparar", size.x);
outText = outText + owner.completeLine("[] Recolectar", size.x);
outText = outText + owner.completeLine("[c] Construir", size.x);
}
else {
if (posicionating) {
outText = outText + owner.completeLine("Posicionando nueva edificacion", size.x);
}
else {
if (entity.products.size() < 1) {
outText = outText + owner.completeLine("No hay edificaciones disponibles", size.x);
}
int i = 1;
for (auto& p : entity.products) {
outText = outText + owner.completeLine("[" + intToString(i) + "] " + p.name, size.x);
std::string texto = "Costos |";
for (auto& c : p.lines) {
texto = texto + "| " + c.resource_name + ": " + intToString((int)c.amount) + " ";
}
outText = outText + owner.completeLine(texto, size.x);
i++;
}
}
}
isVisibleWorker = true;
}
void CommandMenu::visit(Building& entity) {
if (!showOptions) {
visit((Entity&)entity);
outText = outText + owner.completeLine("[p] Producir", size.x);
}
else {
if (entity.products.size() < 1) {
outText = outText + owner.completeLine("No hay productos disponibles", size.x);
}
int i = 1;
for (auto& p : entity.products) {
outText = outText + owner.completeLine("[" + intToString(i) + "] " + p.name, size.x);
std::string texto = "Costos |";
for (auto& c : p.lines) {
texto = texto + "| " + c.resource_name + ": " + intToString((int)c.amount) + " ";
}
outText = outText + owner.completeLine(texto, size.x);
i++;
}
}
isVisibleProducer = true;
}
void CommandMenu::draw() {
//Dibujo fondo
SDL_Rect destinoFondoMenu = { (int)offset.x, (int)offset.y, (int)size.x, (int)size.y };
SDL_SetRenderDrawColor(owner.getRenderer(), 15, 15, 15, 255);
SDL_RenderFillRect(owner.getRenderer(), &destinoFondoMenu);
outText = "";
isVisibleProducer = false;
isVisibleUnit = false;
isVisibleWorker = false;
SDL_Color colorBlanco = { 255, 255, 255 };
if (owner.font) {
if ((owner.sController->getSelection().size() == 1) && (owner.player.name == owner.sController->getSelection().at(0)->owner.name)){
if (currentSelection != owner.sController->getSelection().at(0)) {
showOptions = false;
posicionating = false;
}
owner.sController->getSelection().at(0)->visit(*this);
currentSelection = owner.sController->getSelection().at(0);
}
else if (owner.sController->getSelection().size() > 1) {
outText = outText + owner.completeLine("[] Ir", size.x);
outText = outText + owner.completeLine("[] Atacar", size.x);
outText = outText + owner.completeLine("[s] Parar", size.x);
currentSelection = nullptr;
isVisibleUnit = true;
}
else {
currentSelection = nullptr;
showOptions = false;
posicionating = false;
}
int access1, w1, h1;
Uint32 format1;
SDL_Surface * c1 = TTF_RenderText_Blended_Wrapped(owner.font, outText.c_str(), colorBlanco, (Uint32)(size.x));
SDL_Texture * textureMenu1 = SDL_CreateTextureFromSurface(owner.getRenderer(), c1);
SDL_QueryTexture(textureMenu1, &format1, &access1, &w1, &h1);
SDL_Rect panel1 = { 0, 0, w1 , h1 };
SDL_Rect text1 = { (int)offset.x, (int)offset.y,
(int)((w1 > size.x) ? size.x : w1), (int)((h1 > size.y) ? size.y : h1) };
SDL_RenderCopy(owner.getRenderer(), textureMenu1, &panel1, &text1);
SDL_FreeSurface(c1);
SDL_DestroyTexture(textureMenu1);
}
}
std::string CommandMenu::intToString(int i) {
string resultado;
ostringstream aux;
aux << i;
resultado = aux.str();
return resultado;
}
<|endoftext|> |
<commit_before>//===-- InMemoryAssembler.cpp -----------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "InMemoryAssembler.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineModuleInfo.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/TargetInstrInfo.h"
#include "llvm/CodeGen/TargetPassConfig.h"
#include "llvm/ExecutionEngine/ExecutionEngine.h"
#include "llvm/ExecutionEngine/MCJIT.h"
#include "llvm/ExecutionEngine/SectionMemoryManager.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/MC/MCFixup.h"
#include "llvm/MC/MCInstrDesc.h"
#include "llvm/Object/Binary.h"
#include "llvm/Object/ObjectFile.h"
#include "llvm/PassInfo.h"
#include "llvm/PassRegistry.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
namespace exegesis {
static constexpr const char ModuleID[] = "ExegesisInfoTest";
static constexpr const char FunctionID[] = "foo";
// Small utility function to add named passes.
static bool addPass(llvm::PassManagerBase &PM, llvm::StringRef PassName,
llvm::TargetPassConfig &TPC) {
const llvm::PassRegistry *PR = llvm::PassRegistry::getPassRegistry();
const llvm::PassInfo *PI = PR->getPassInfo(PassName);
if (!PI) {
llvm::errs() << " run-pass " << PassName << " is not registered.\n";
return true;
}
if (!PI->getNormalCtor()) {
llvm::errs() << " cannot create pass: " << PI->getPassName() << "\n";
return true;
}
llvm::Pass *P = PI->getNormalCtor()();
std::string Banner = std::string("After ") + std::string(P->getPassName());
PM.add(P);
TPC.printAndVerify(Banner);
return false;
}
// Creates a void MachineFunction with no argument.
static llvm::MachineFunction &
createVoidVoidMachineFunction(llvm::StringRef FunctionID, llvm::Module *Module,
llvm::MachineModuleInfo *MMI) {
llvm::Type *const ReturnType = llvm::Type::getInt32Ty(Module->getContext());
llvm::FunctionType *FunctionType = llvm::FunctionType::get(ReturnType, false);
llvm::Function *const F = llvm::Function::Create(
FunctionType, llvm::GlobalValue::InternalLinkage, FunctionID, Module);
// Making sure we can create a MachineFunction out of this Function even if it
// contains no IR.
F->setIsMaterializable(true);
return MMI->getOrCreateMachineFunction(*F);
}
static llvm::object::OwningBinary<llvm::object::ObjectFile>
assemble(llvm::Module *Module, std::unique_ptr<llvm::MachineModuleInfo> MMI,
llvm::LLVMTargetMachine *LLVMTM) {
llvm::legacy::PassManager PM;
llvm::MCContext &Context = MMI->getContext();
llvm::TargetLibraryInfoImpl TLII(llvm::Triple(Module->getTargetTriple()));
PM.add(new llvm::TargetLibraryInfoWrapperPass(TLII));
llvm::TargetPassConfig *TPC = LLVMTM->createPassConfig(PM);
PM.add(TPC);
PM.add(MMI.release());
TPC->printAndVerify("MachineFunctionGenerator::assemble");
// Adding the following passes:
// - machineverifier: checks that the MachineFunction is well formed.
// - prologepilog: saves and restore callee saved registers.
for (const char *PassName : {"machineverifier", "prologepilog"})
if (addPass(PM, PassName, *TPC))
llvm::report_fatal_error("Unable to add a mandatory pass");
TPC->setInitialized();
llvm::SmallVector<char, 4096> AsmBuffer;
llvm::raw_svector_ostream AsmStream(AsmBuffer);
// AsmPrinter is responsible for generating the assembly into AsmBuffer.
if (LLVMTM->addAsmPrinter(PM, AsmStream, llvm::TargetMachine::CGFT_ObjectFile,
Context))
llvm::report_fatal_error("Cannot add AsmPrinter passes");
PM.run(*Module); // Run all the passes
// Storing the generated assembly into a MemoryBuffer that owns the memory.
std::unique_ptr<llvm::MemoryBuffer> Buffer =
llvm::MemoryBuffer::getMemBufferCopy(AsmStream.str());
// Create the ObjectFile from the MemoryBuffer.
std::unique_ptr<llvm::object::ObjectFile> Obj = llvm::cantFail(
llvm::object::ObjectFile::createObjectFile(Buffer->getMemBufferRef()));
// Returning both the MemoryBuffer and the ObjectFile.
return llvm::object::OwningBinary<llvm::object::ObjectFile>(
std::move(Obj), std::move(Buffer));
}
static void fillMachineFunction(llvm::MachineFunction &MF,
llvm::ArrayRef<llvm::MCInst> Instructions) {
llvm::MachineBasicBlock *MBB = MF.CreateMachineBasicBlock();
MF.push_back(MBB);
const llvm::MCInstrInfo *MCII = MF.getTarget().getMCInstrInfo();
llvm::DebugLoc DL;
for (const llvm::MCInst &Inst : Instructions) {
const unsigned Opcode = Inst.getOpcode();
const llvm::MCInstrDesc &MCID = MCII->get(Opcode);
llvm::MachineInstrBuilder Builder = llvm::BuildMI(MBB, DL, MCID);
for (unsigned OpIndex = 0, E = Inst.getNumOperands(); OpIndex < E;
++OpIndex) {
const llvm::MCOperand &Op = Inst.getOperand(OpIndex);
if (Op.isReg()) {
const bool IsDef = OpIndex < MCID.getNumDefs();
unsigned Flags = 0;
const llvm::MCOperandInfo &OpInfo = MCID.operands().begin()[OpIndex];
if (IsDef && !OpInfo.isOptionalDef())
Flags |= llvm::RegState::Define;
Builder.addReg(Op.getReg(), Flags);
} else if (Op.isImm()) {
Builder.addImm(Op.getImm());
} else {
llvm_unreachable("Not yet implemented");
}
}
}
// Adding the Return Opcode.
const llvm::TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
llvm::BuildMI(MBB, DL, TII->get(TII->getReturnOpcode()));
}
namespace {
// Implementation of this class relies on the fact that a single object with a
// single function will be loaded into memory.
class TrackingSectionMemoryManager : public llvm::SectionMemoryManager {
public:
explicit TrackingSectionMemoryManager(uintptr_t *CodeSize)
: CodeSize(CodeSize) {}
uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
unsigned SectionID,
llvm::StringRef SectionName) override {
*CodeSize = Size;
return llvm::SectionMemoryManager::allocateCodeSection(
Size, Alignment, SectionID, SectionName);
}
private:
uintptr_t *const CodeSize = nullptr;
};
} // namespace
JitFunctionContext::JitFunctionContext(
std::unique_ptr<llvm::LLVMTargetMachine> TheTM)
: Context(llvm::make_unique<llvm::LLVMContext>()), TM(std::move(TheTM)),
MMI(llvm::make_unique<llvm::MachineModuleInfo>(TM.get())),
Module(llvm::make_unique<llvm::Module>(ModuleID, *Context)) {
Module->setDataLayout(TM->createDataLayout());
MF = &createVoidVoidMachineFunction(FunctionID, Module.get(), MMI.get());
// We need to instruct the passes that we're done with SSA and virtual
// registers.
auto &Properties = MF->getProperties();
Properties.set(llvm::MachineFunctionProperties::Property::NoVRegs);
Properties.reset(llvm::MachineFunctionProperties::Property::IsSSA);
Properties.reset(llvm::MachineFunctionProperties::Property::TracksLiveness);
// prologue/epilogue pass needs the reserved registers to be frozen, this is
// usually done by the SelectionDAGISel pass.
MF->getRegInfo().freezeReservedRegs(*MF);
// Saving reserved registers for client.
ReservedRegs = MF->getSubtarget().getRegisterInfo()->getReservedRegs(*MF);
}
JitFunction::JitFunction(JitFunctionContext &&Context,
llvm::ArrayRef<llvm::MCInst> Instructions)
: FunctionContext(std::move(Context)) {
fillMachineFunction(*FunctionContext.MF, Instructions);
// We create the pass manager, run the passes and returns the produced
// ObjectFile.
llvm::object::OwningBinary<llvm::object::ObjectFile> ObjHolder =
assemble(FunctionContext.Module.get(), std::move(FunctionContext.MMI),
FunctionContext.TM.get());
assert(ObjHolder.getBinary() && "cannot create object file");
// Initializing the execution engine.
// We need to use the JIT EngineKind to be able to add an object file.
LLVMLinkInMCJIT();
uintptr_t CodeSize = 0;
std::string Error;
llvm::LLVMTargetMachine *TM = FunctionContext.TM.release();
ExecEngine.reset(
llvm::EngineBuilder(std::move(FunctionContext.Module))
.setErrorStr(&Error)
.setMCPU(FunctionContext.TM->getTargetCPU())
.setEngineKind(llvm::EngineKind::JIT)
.setMCJITMemoryManager(
llvm::make_unique<TrackingSectionMemoryManager>(&CodeSize))
.create(TM));
if (!ExecEngine)
llvm::report_fatal_error(Error);
// Adding the generated object file containing the assembled function.
// The ExecutionEngine makes sure the object file is copied into an
// executable page.
ExecEngine->addObjectFile(std::move(ObjHolder));
// Setting function
FunctionBytes =
llvm::StringRef(reinterpret_cast<const char *>(
ExecEngine->getFunctionAddress(FunctionID)),
CodeSize);
}
} // namespace exegesis
<commit_msg>[llvm-exegesis] Use LLVMTargetMachine pointer everywhere. NFCI.<commit_after>//===-- InMemoryAssembler.cpp -----------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "InMemoryAssembler.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineModuleInfo.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/TargetInstrInfo.h"
#include "llvm/CodeGen/TargetPassConfig.h"
#include "llvm/ExecutionEngine/ExecutionEngine.h"
#include "llvm/ExecutionEngine/MCJIT.h"
#include "llvm/ExecutionEngine/SectionMemoryManager.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/MC/MCFixup.h"
#include "llvm/MC/MCInstrDesc.h"
#include "llvm/Object/Binary.h"
#include "llvm/Object/ObjectFile.h"
#include "llvm/PassInfo.h"
#include "llvm/PassRegistry.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
namespace exegesis {
static constexpr const char ModuleID[] = "ExegesisInfoTest";
static constexpr const char FunctionID[] = "foo";
// Small utility function to add named passes.
static bool addPass(llvm::PassManagerBase &PM, llvm::StringRef PassName,
llvm::TargetPassConfig &TPC) {
const llvm::PassRegistry *PR = llvm::PassRegistry::getPassRegistry();
const llvm::PassInfo *PI = PR->getPassInfo(PassName);
if (!PI) {
llvm::errs() << " run-pass " << PassName << " is not registered.\n";
return true;
}
if (!PI->getNormalCtor()) {
llvm::errs() << " cannot create pass: " << PI->getPassName() << "\n";
return true;
}
llvm::Pass *P = PI->getNormalCtor()();
std::string Banner = std::string("After ") + std::string(P->getPassName());
PM.add(P);
TPC.printAndVerify(Banner);
return false;
}
// Creates a void MachineFunction with no argument.
static llvm::MachineFunction &
createVoidVoidMachineFunction(llvm::StringRef FunctionID, llvm::Module *Module,
llvm::MachineModuleInfo *MMI) {
llvm::Type *const ReturnType = llvm::Type::getInt32Ty(Module->getContext());
llvm::FunctionType *FunctionType = llvm::FunctionType::get(ReturnType, false);
llvm::Function *const F = llvm::Function::Create(
FunctionType, llvm::GlobalValue::InternalLinkage, FunctionID, Module);
// Making sure we can create a MachineFunction out of this Function even if it
// contains no IR.
F->setIsMaterializable(true);
return MMI->getOrCreateMachineFunction(*F);
}
static llvm::object::OwningBinary<llvm::object::ObjectFile>
assemble(llvm::Module *Module, std::unique_ptr<llvm::MachineModuleInfo> MMI,
llvm::LLVMTargetMachine *LLVMTM) {
llvm::legacy::PassManager PM;
llvm::MCContext &Context = MMI->getContext();
llvm::TargetLibraryInfoImpl TLII(llvm::Triple(Module->getTargetTriple()));
PM.add(new llvm::TargetLibraryInfoWrapperPass(TLII));
llvm::TargetPassConfig *TPC = LLVMTM->createPassConfig(PM);
PM.add(TPC);
PM.add(MMI.release());
TPC->printAndVerify("MachineFunctionGenerator::assemble");
// Adding the following passes:
// - machineverifier: checks that the MachineFunction is well formed.
// - prologepilog: saves and restore callee saved registers.
for (const char *PassName : {"machineverifier", "prologepilog"})
if (addPass(PM, PassName, *TPC))
llvm::report_fatal_error("Unable to add a mandatory pass");
TPC->setInitialized();
llvm::SmallVector<char, 4096> AsmBuffer;
llvm::raw_svector_ostream AsmStream(AsmBuffer);
// AsmPrinter is responsible for generating the assembly into AsmBuffer.
if (LLVMTM->addAsmPrinter(PM, AsmStream, llvm::TargetMachine::CGFT_ObjectFile,
Context))
llvm::report_fatal_error("Cannot add AsmPrinter passes");
PM.run(*Module); // Run all the passes
// Storing the generated assembly into a MemoryBuffer that owns the memory.
std::unique_ptr<llvm::MemoryBuffer> Buffer =
llvm::MemoryBuffer::getMemBufferCopy(AsmStream.str());
// Create the ObjectFile from the MemoryBuffer.
std::unique_ptr<llvm::object::ObjectFile> Obj = llvm::cantFail(
llvm::object::ObjectFile::createObjectFile(Buffer->getMemBufferRef()));
// Returning both the MemoryBuffer and the ObjectFile.
return llvm::object::OwningBinary<llvm::object::ObjectFile>(
std::move(Obj), std::move(Buffer));
}
static void fillMachineFunction(llvm::MachineFunction &MF,
llvm::ArrayRef<llvm::MCInst> Instructions) {
llvm::MachineBasicBlock *MBB = MF.CreateMachineBasicBlock();
MF.push_back(MBB);
const llvm::MCInstrInfo *MCII = MF.getTarget().getMCInstrInfo();
llvm::DebugLoc DL;
for (const llvm::MCInst &Inst : Instructions) {
const unsigned Opcode = Inst.getOpcode();
const llvm::MCInstrDesc &MCID = MCII->get(Opcode);
llvm::MachineInstrBuilder Builder = llvm::BuildMI(MBB, DL, MCID);
for (unsigned OpIndex = 0, E = Inst.getNumOperands(); OpIndex < E;
++OpIndex) {
const llvm::MCOperand &Op = Inst.getOperand(OpIndex);
if (Op.isReg()) {
const bool IsDef = OpIndex < MCID.getNumDefs();
unsigned Flags = 0;
const llvm::MCOperandInfo &OpInfo = MCID.operands().begin()[OpIndex];
if (IsDef && !OpInfo.isOptionalDef())
Flags |= llvm::RegState::Define;
Builder.addReg(Op.getReg(), Flags);
} else if (Op.isImm()) {
Builder.addImm(Op.getImm());
} else {
llvm_unreachable("Not yet implemented");
}
}
}
// Adding the Return Opcode.
const llvm::TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
llvm::BuildMI(MBB, DL, TII->get(TII->getReturnOpcode()));
}
namespace {
// Implementation of this class relies on the fact that a single object with a
// single function will be loaded into memory.
class TrackingSectionMemoryManager : public llvm::SectionMemoryManager {
public:
explicit TrackingSectionMemoryManager(uintptr_t *CodeSize)
: CodeSize(CodeSize) {}
uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
unsigned SectionID,
llvm::StringRef SectionName) override {
*CodeSize = Size;
return llvm::SectionMemoryManager::allocateCodeSection(
Size, Alignment, SectionID, SectionName);
}
private:
uintptr_t *const CodeSize = nullptr;
};
} // namespace
JitFunctionContext::JitFunctionContext(
std::unique_ptr<llvm::LLVMTargetMachine> TheTM)
: Context(llvm::make_unique<llvm::LLVMContext>()), TM(std::move(TheTM)),
MMI(llvm::make_unique<llvm::MachineModuleInfo>(TM.get())),
Module(llvm::make_unique<llvm::Module>(ModuleID, *Context)) {
Module->setDataLayout(TM->createDataLayout());
MF = &createVoidVoidMachineFunction(FunctionID, Module.get(), MMI.get());
// We need to instruct the passes that we're done with SSA and virtual
// registers.
auto &Properties = MF->getProperties();
Properties.set(llvm::MachineFunctionProperties::Property::NoVRegs);
Properties.reset(llvm::MachineFunctionProperties::Property::IsSSA);
Properties.reset(llvm::MachineFunctionProperties::Property::TracksLiveness);
// prologue/epilogue pass needs the reserved registers to be frozen, this is
// usually done by the SelectionDAGISel pass.
MF->getRegInfo().freezeReservedRegs(*MF);
// Saving reserved registers for client.
ReservedRegs = MF->getSubtarget().getRegisterInfo()->getReservedRegs(*MF);
}
JitFunction::JitFunction(JitFunctionContext &&Context,
llvm::ArrayRef<llvm::MCInst> Instructions)
: FunctionContext(std::move(Context)) {
fillMachineFunction(*FunctionContext.MF, Instructions);
// We create the pass manager, run the passes and returns the produced
// ObjectFile.
llvm::object::OwningBinary<llvm::object::ObjectFile> ObjHolder =
assemble(FunctionContext.Module.get(), std::move(FunctionContext.MMI),
FunctionContext.TM.get());
assert(ObjHolder.getBinary() && "cannot create object file");
// Initializing the execution engine.
// We need to use the JIT EngineKind to be able to add an object file.
LLVMLinkInMCJIT();
uintptr_t CodeSize = 0;
std::string Error;
llvm::LLVMTargetMachine *TM = FunctionContext.TM.release();
ExecEngine.reset(
llvm::EngineBuilder(std::move(FunctionContext.Module))
.setErrorStr(&Error)
.setMCPU(TM->getTargetCPU())
.setEngineKind(llvm::EngineKind::JIT)
.setMCJITMemoryManager(
llvm::make_unique<TrackingSectionMemoryManager>(&CodeSize))
.create(TM));
if (!ExecEngine)
llvm::report_fatal_error(Error);
// Adding the generated object file containing the assembled function.
// The ExecutionEngine makes sure the object file is copied into an
// executable page.
ExecEngine->addObjectFile(std::move(ObjHolder));
// Setting function
FunctionBytes =
llvm::StringRef(reinterpret_cast<const char *>(
ExecEngine->getFunctionAddress(FunctionID)),
CodeSize);
}
} // namespace exegesis
<|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 file.
#include "chrome/browser/gtk/infobar_gtk.h"
#include <gtk/gtk.h>
#include "app/gfx/gtk_util.h"
#include "base/string_util.h"
#include "chrome/browser/gtk/custom_button.h"
#include "chrome/browser/gtk/gtk_chrome_link_button.h"
#include "chrome/browser/gtk/gtk_theme_provider.h"
#include "chrome/browser/gtk/infobar_container_gtk.h"
#include "chrome/browser/tab_contents/infobar_delegate.h"
#include "chrome/common/gtk_util.h"
#include "chrome/common/notification_service.h"
namespace {
const double kBackgroundColorTop[3] =
{255.0 / 255.0, 242.0 / 255.0, 183.0 / 255.0};
const double kBackgroundColorBottom[3] =
{250.0 / 255.0, 230.0 / 255.0, 145.0 / 255.0};
// The total height of the info bar.
const int kInfoBarHeight = 37;
// Pixels between infobar elements.
const int kElementPadding = 5;
// Extra padding on either end of info bar.
const int kLeftPadding = 5;
const int kRightPadding = 5;
static gboolean OnBackgroundExpose(GtkWidget* widget, GdkEventExpose* event,
gpointer unused) {
const int height = widget->allocation.height;
cairo_t* cr = gdk_cairo_create(GDK_DRAWABLE(widget->window));
cairo_rectangle(cr, event->area.x, event->area.y,
event->area.width, event->area.height);
cairo_clip(cr);
cairo_pattern_t* pattern = cairo_pattern_create_linear(0, 0, 0, height);
cairo_pattern_add_color_stop_rgb(
pattern, 0.0,
kBackgroundColorTop[0], kBackgroundColorTop[1], kBackgroundColorTop[2]);
cairo_pattern_add_color_stop_rgb(
pattern, 1.0,
kBackgroundColorBottom[0], kBackgroundColorBottom[1],
kBackgroundColorBottom[2]);
cairo_set_source(cr, pattern);
cairo_paint(cr);
cairo_pattern_destroy(pattern);
cairo_destroy(cr);
return FALSE;
}
} // namespace
InfoBar::InfoBar(InfoBarDelegate* delegate)
: container_(NULL),
delegate_(delegate),
theme_provider_(NULL) {
// Create |hbox_| and pad the sides.
hbox_ = gtk_hbox_new(FALSE, kElementPadding);
GtkWidget* padding = gtk_alignment_new(0, 0, 1, 1);
gtk_alignment_set_padding(GTK_ALIGNMENT(padding),
0, 0, kLeftPadding, kRightPadding);
GtkWidget* bg_box = gtk_event_box_new();
gtk_widget_set_app_paintable(bg_box, TRUE);
g_signal_connect(bg_box, "expose-event",
G_CALLBACK(OnBackgroundExpose), NULL);
gtk_container_add(GTK_CONTAINER(padding), hbox_);
gtk_container_add(GTK_CONTAINER(bg_box), padding);
// The -1 on the kInfoBarHeight is to account for the border.
gtk_widget_set_size_request(bg_box, -1, kInfoBarHeight - 1);
border_bin_.Own(gtk_util::CreateGtkBorderBin(bg_box, NULL,
0, 1, 0, 0));
// Add the icon on the left, if any.
SkBitmap* icon = delegate->GetIcon();
if (icon) {
GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(icon);
GtkWidget* image = gtk_image_new_from_pixbuf(pixbuf);
g_object_unref(pixbuf);
gtk_box_pack_start(GTK_BOX(hbox_), image, FALSE, FALSE, 0);
}
// TODO(erg): GTK theme the info bar.
close_button_.reset(CustomDrawButton::CloseButton(NULL));
gtk_util::CenterWidgetInHBox(hbox_, close_button_->widget(), true, 0);
g_signal_connect(close_button_->widget(), "clicked",
G_CALLBACK(OnCloseButton), this);
slide_widget_.reset(new SlideAnimatorGtk(border_bin_.get(),
SlideAnimatorGtk::DOWN,
0, true, true, this));
// We store a pointer back to |this| so we can refer to it from the infobar
// container.
g_object_set_data(G_OBJECT(slide_widget_->widget()), "info-bar", this);
}
InfoBar::~InfoBar() {
border_bin_.Destroy();
}
GtkWidget* InfoBar::widget() {
return slide_widget_->widget();
}
void InfoBar::AnimateOpen() {
slide_widget_->Open();
}
void InfoBar::Open() {
slide_widget_->OpenWithoutAnimation();
if (border_bin_->window)
gdk_window_lower(border_bin_->window);
}
void InfoBar::AnimateClose() {
slide_widget_->Close();
}
void InfoBar::Close() {
if (delegate_) {
delegate_->InfoBarClosed();
delegate_ = NULL;
}
delete this;
}
bool InfoBar::IsAnimating() {
return slide_widget_->IsAnimating();
}
void InfoBar::RemoveInfoBar() const {
container_->RemoveDelegate(delegate_);
}
void InfoBar::Closed() {
Close();
}
void InfoBar::SetThemeProvider(GtkThemeProvider* theme_provider) {
if (theme_provider_) {
NOTREACHED();
return;
}
theme_provider_ = theme_provider;
registrar_.Add(this, NotificationType::BROWSER_THEME_CHANGED,
NotificationService::AllSources());
UpdateBorderColor();
}
void InfoBar::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
UpdateBorderColor();
}
void InfoBar::UpdateBorderColor() {
GdkColor border_color = theme_provider_->GetBorderColor();
gtk_widget_modify_bg(border_bin_.get(), GTK_STATE_NORMAL, &border_color);
}
// static
void InfoBar::OnCloseButton(GtkWidget* button, InfoBar* info_bar) {
if (info_bar->delegate_)
info_bar->delegate_->InfoBarDismissed();
info_bar->RemoveInfoBar();
}
// AlertInfoBar ----------------------------------------------------------------
class AlertInfoBar : public InfoBar {
public:
explicit AlertInfoBar(AlertInfoBarDelegate* delegate)
: InfoBar(delegate) {
std::wstring text = delegate->GetMessageText();
GtkWidget* label = gtk_label_new(WideToUTF8(text).c_str());
gtk_widget_modify_fg(label, GTK_STATE_NORMAL, &gfx::kGdkBlack);
gtk_box_pack_start(GTK_BOX(hbox_), label, FALSE, FALSE, 0);
gtk_widget_show_all(border_bin_.get());
}
};
// LinkInfoBar -----------------------------------------------------------------
class LinkInfoBar : public InfoBar {
public:
explicit LinkInfoBar(LinkInfoBarDelegate* delegate)
: InfoBar(delegate) {
size_t link_offset;
std::wstring display_text =
delegate->GetMessageTextWithOffset(&link_offset);
std::wstring link_text = delegate->GetLinkText();
// Create the link button.
GtkWidget* link_button =
gtk_chrome_link_button_new(WideToUTF8(link_text).c_str());
gtk_chrome_link_button_set_use_gtk_theme(
GTK_CHROME_LINK_BUTTON(link_button), FALSE);
g_signal_connect(link_button, "clicked",
G_CALLBACK(OnLinkClick), this);
gtk_util::SetButtonTriggersNavigation(link_button);
// If link_offset is npos, we right-align the link instead of embedding it
// in the text.
if (link_offset == std::wstring::npos) {
gtk_box_pack_end(GTK_BOX(hbox_), link_button, FALSE, FALSE, 0);
GtkWidget* label = gtk_label_new(WideToUTF8(display_text).c_str());
gtk_widget_modify_fg(label, GTK_STATE_NORMAL, &gfx::kGdkBlack);
gtk_box_pack_start(GTK_BOX(hbox_), label, FALSE, FALSE, 0);
} else {
GtkWidget* initial_label = gtk_label_new(
WideToUTF8(display_text.substr(0, link_offset)).c_str());
GtkWidget* trailing_label = gtk_label_new(
WideToUTF8(display_text.substr(link_offset)).c_str());
gtk_widget_modify_fg(initial_label, GTK_STATE_NORMAL, &gfx::kGdkBlack);
gtk_widget_modify_fg(trailing_label, GTK_STATE_NORMAL, &gfx::kGdkBlack);
// We don't want any spacing between the elements, so we pack them into
// this hbox that doesn't use kElementPadding.
GtkWidget* hbox = gtk_hbox_new(FALSE, 0);
gtk_box_pack_start(GTK_BOX(hbox), initial_label, FALSE, FALSE, 0);
gtk_util::CenterWidgetInHBox(hbox, link_button, false, 0);
gtk_box_pack_start(GTK_BOX(hbox), trailing_label, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(hbox_), hbox, FALSE, FALSE, 0);
}
gtk_widget_show_all(border_bin_.get());
}
private:
static void OnLinkClick(GtkWidget* button, LinkInfoBar* link_info_bar) {
const GdkEventButton* button_click_event =
reinterpret_cast<GdkEventButton*>(gtk_get_current_event());
WindowOpenDisposition disposition = CURRENT_TAB;
if (button_click_event) {
disposition = event_utils::DispositionFromEventFlags(
button_click_event->state);
}
if (link_info_bar->delegate_->AsLinkInfoBarDelegate()->
LinkClicked(disposition)) {
link_info_bar->RemoveInfoBar();
}
}
};
// ConfirmInfoBar --------------------------------------------------------------
class ConfirmInfoBar : public AlertInfoBar {
public:
explicit ConfirmInfoBar(ConfirmInfoBarDelegate* delegate)
: AlertInfoBar(delegate) {
AddConfirmButton(ConfirmInfoBarDelegate::BUTTON_CANCEL);
AddConfirmButton(ConfirmInfoBarDelegate::BUTTON_OK);
gtk_widget_show_all(border_bin_.get());
}
private:
// Adds a button to the info bar by type. It will do nothing if the delegate
// doesn't specify a button of the given type.
void AddConfirmButton(ConfirmInfoBarDelegate::InfoBarButton type) {
if (delegate_->AsConfirmInfoBarDelegate()->GetButtons() & type) {
GtkWidget* button = gtk_button_new_with_label(WideToUTF8(
delegate_->AsConfirmInfoBarDelegate()->GetButtonLabel(type)).c_str());
gtk_util::CenterWidgetInHBox(hbox_, button, true, 0);
g_signal_connect(button, "clicked",
G_CALLBACK(type == ConfirmInfoBarDelegate::BUTTON_OK ?
OnOkButton : OnCancelButton),
this);
}
}
static void OnCancelButton(GtkWidget* button, ConfirmInfoBar* info_bar) {
if (info_bar->delegate_->AsConfirmInfoBarDelegate()->Cancel())
info_bar->RemoveInfoBar();
}
static void OnOkButton(GtkWidget* button, ConfirmInfoBar* info_bar) {
if (info_bar->delegate_->AsConfirmInfoBarDelegate()->Accept())
info_bar->RemoveInfoBar();
}
};
// AlertInfoBarDelegate, InfoBarDelegate overrides: ----------------------------
InfoBar* AlertInfoBarDelegate::CreateInfoBar() {
return new AlertInfoBar(this);
}
// LinkInfoBarDelegate, InfoBarDelegate overrides: -----------------------------
InfoBar* LinkInfoBarDelegate::CreateInfoBar() {
return new LinkInfoBar(this);
}
// ConfirmInfoBarDelegate, InfoBarDelegate overrides: --------------------------
InfoBar* ConfirmInfoBarDelegate::CreateInfoBar() {
return new ConfirmInfoBar(this);
}
<commit_msg>Gtk: don't occlude find bar with animating infobar.<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 file.
#include "chrome/browser/gtk/infobar_gtk.h"
#include <gtk/gtk.h>
#include "app/gfx/gtk_util.h"
#include "base/string_util.h"
#include "chrome/browser/gtk/custom_button.h"
#include "chrome/browser/gtk/gtk_chrome_link_button.h"
#include "chrome/browser/gtk/gtk_theme_provider.h"
#include "chrome/browser/gtk/infobar_container_gtk.h"
#include "chrome/browser/tab_contents/infobar_delegate.h"
#include "chrome/common/gtk_util.h"
#include "chrome/common/notification_service.h"
namespace {
const double kBackgroundColorTop[3] =
{255.0 / 255.0, 242.0 / 255.0, 183.0 / 255.0};
const double kBackgroundColorBottom[3] =
{250.0 / 255.0, 230.0 / 255.0, 145.0 / 255.0};
// The total height of the info bar.
const int kInfoBarHeight = 37;
// Pixels between infobar elements.
const int kElementPadding = 5;
// Extra padding on either end of info bar.
const int kLeftPadding = 5;
const int kRightPadding = 5;
static gboolean OnBackgroundExpose(GtkWidget* widget, GdkEventExpose* event,
gpointer unused) {
const int height = widget->allocation.height;
cairo_t* cr = gdk_cairo_create(GDK_DRAWABLE(widget->window));
cairo_rectangle(cr, event->area.x, event->area.y,
event->area.width, event->area.height);
cairo_clip(cr);
cairo_pattern_t* pattern = cairo_pattern_create_linear(0, 0, 0, height);
cairo_pattern_add_color_stop_rgb(
pattern, 0.0,
kBackgroundColorTop[0], kBackgroundColorTop[1], kBackgroundColorTop[2]);
cairo_pattern_add_color_stop_rgb(
pattern, 1.0,
kBackgroundColorBottom[0], kBackgroundColorBottom[1],
kBackgroundColorBottom[2]);
cairo_set_source(cr, pattern);
cairo_paint(cr);
cairo_pattern_destroy(pattern);
cairo_destroy(cr);
return FALSE;
}
} // namespace
InfoBar::InfoBar(InfoBarDelegate* delegate)
: container_(NULL),
delegate_(delegate),
theme_provider_(NULL) {
// Create |hbox_| and pad the sides.
hbox_ = gtk_hbox_new(FALSE, kElementPadding);
GtkWidget* padding = gtk_alignment_new(0, 0, 1, 1);
gtk_alignment_set_padding(GTK_ALIGNMENT(padding),
0, 0, kLeftPadding, kRightPadding);
GtkWidget* bg_box = gtk_event_box_new();
gtk_widget_set_app_paintable(bg_box, TRUE);
g_signal_connect(bg_box, "expose-event",
G_CALLBACK(OnBackgroundExpose), NULL);
gtk_container_add(GTK_CONTAINER(padding), hbox_);
gtk_container_add(GTK_CONTAINER(bg_box), padding);
// The -1 on the kInfoBarHeight is to account for the border.
gtk_widget_set_size_request(bg_box, -1, kInfoBarHeight - 1);
border_bin_.Own(gtk_util::CreateGtkBorderBin(bg_box, NULL,
0, 1, 0, 0));
// Add the icon on the left, if any.
SkBitmap* icon = delegate->GetIcon();
if (icon) {
GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(icon);
GtkWidget* image = gtk_image_new_from_pixbuf(pixbuf);
g_object_unref(pixbuf);
gtk_box_pack_start(GTK_BOX(hbox_), image, FALSE, FALSE, 0);
}
// TODO(erg): GTK theme the info bar.
close_button_.reset(CustomDrawButton::CloseButton(NULL));
gtk_util::CenterWidgetInHBox(hbox_, close_button_->widget(), true, 0);
g_signal_connect(close_button_->widget(), "clicked",
G_CALLBACK(OnCloseButton), this);
slide_widget_.reset(new SlideAnimatorGtk(border_bin_.get(),
SlideAnimatorGtk::DOWN,
0, true, true, this));
// We store a pointer back to |this| so we can refer to it from the infobar
// container.
g_object_set_data(G_OBJECT(slide_widget_->widget()), "info-bar", this);
}
InfoBar::~InfoBar() {
border_bin_.Destroy();
}
GtkWidget* InfoBar::widget() {
return slide_widget_->widget();
}
void InfoBar::AnimateOpen() {
slide_widget_->Open();
gdk_window_lower(border_bin_->window);
}
void InfoBar::Open() {
slide_widget_->OpenWithoutAnimation();
gdk_window_lower(border_bin_->window);
}
void InfoBar::AnimateClose() {
slide_widget_->Close();
}
void InfoBar::Close() {
if (delegate_) {
delegate_->InfoBarClosed();
delegate_ = NULL;
}
delete this;
}
bool InfoBar::IsAnimating() {
return slide_widget_->IsAnimating();
}
void InfoBar::RemoveInfoBar() const {
container_->RemoveDelegate(delegate_);
}
void InfoBar::Closed() {
Close();
}
void InfoBar::SetThemeProvider(GtkThemeProvider* theme_provider) {
if (theme_provider_) {
NOTREACHED();
return;
}
theme_provider_ = theme_provider;
registrar_.Add(this, NotificationType::BROWSER_THEME_CHANGED,
NotificationService::AllSources());
UpdateBorderColor();
}
void InfoBar::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
UpdateBorderColor();
}
void InfoBar::UpdateBorderColor() {
GdkColor border_color = theme_provider_->GetBorderColor();
gtk_widget_modify_bg(border_bin_.get(), GTK_STATE_NORMAL, &border_color);
}
// static
void InfoBar::OnCloseButton(GtkWidget* button, InfoBar* info_bar) {
if (info_bar->delegate_)
info_bar->delegate_->InfoBarDismissed();
info_bar->RemoveInfoBar();
}
// AlertInfoBar ----------------------------------------------------------------
class AlertInfoBar : public InfoBar {
public:
explicit AlertInfoBar(AlertInfoBarDelegate* delegate)
: InfoBar(delegate) {
std::wstring text = delegate->GetMessageText();
GtkWidget* label = gtk_label_new(WideToUTF8(text).c_str());
gtk_widget_modify_fg(label, GTK_STATE_NORMAL, &gfx::kGdkBlack);
gtk_box_pack_start(GTK_BOX(hbox_), label, FALSE, FALSE, 0);
gtk_widget_show_all(border_bin_.get());
}
};
// LinkInfoBar -----------------------------------------------------------------
class LinkInfoBar : public InfoBar {
public:
explicit LinkInfoBar(LinkInfoBarDelegate* delegate)
: InfoBar(delegate) {
size_t link_offset;
std::wstring display_text =
delegate->GetMessageTextWithOffset(&link_offset);
std::wstring link_text = delegate->GetLinkText();
// Create the link button.
GtkWidget* link_button =
gtk_chrome_link_button_new(WideToUTF8(link_text).c_str());
gtk_chrome_link_button_set_use_gtk_theme(
GTK_CHROME_LINK_BUTTON(link_button), FALSE);
g_signal_connect(link_button, "clicked",
G_CALLBACK(OnLinkClick), this);
gtk_util::SetButtonTriggersNavigation(link_button);
// If link_offset is npos, we right-align the link instead of embedding it
// in the text.
if (link_offset == std::wstring::npos) {
gtk_box_pack_end(GTK_BOX(hbox_), link_button, FALSE, FALSE, 0);
GtkWidget* label = gtk_label_new(WideToUTF8(display_text).c_str());
gtk_widget_modify_fg(label, GTK_STATE_NORMAL, &gfx::kGdkBlack);
gtk_box_pack_start(GTK_BOX(hbox_), label, FALSE, FALSE, 0);
} else {
GtkWidget* initial_label = gtk_label_new(
WideToUTF8(display_text.substr(0, link_offset)).c_str());
GtkWidget* trailing_label = gtk_label_new(
WideToUTF8(display_text.substr(link_offset)).c_str());
gtk_widget_modify_fg(initial_label, GTK_STATE_NORMAL, &gfx::kGdkBlack);
gtk_widget_modify_fg(trailing_label, GTK_STATE_NORMAL, &gfx::kGdkBlack);
// We don't want any spacing between the elements, so we pack them into
// this hbox that doesn't use kElementPadding.
GtkWidget* hbox = gtk_hbox_new(FALSE, 0);
gtk_box_pack_start(GTK_BOX(hbox), initial_label, FALSE, FALSE, 0);
gtk_util::CenterWidgetInHBox(hbox, link_button, false, 0);
gtk_box_pack_start(GTK_BOX(hbox), trailing_label, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(hbox_), hbox, FALSE, FALSE, 0);
}
gtk_widget_show_all(border_bin_.get());
}
private:
static void OnLinkClick(GtkWidget* button, LinkInfoBar* link_info_bar) {
const GdkEventButton* button_click_event =
reinterpret_cast<GdkEventButton*>(gtk_get_current_event());
WindowOpenDisposition disposition = CURRENT_TAB;
if (button_click_event) {
disposition = event_utils::DispositionFromEventFlags(
button_click_event->state);
}
if (link_info_bar->delegate_->AsLinkInfoBarDelegate()->
LinkClicked(disposition)) {
link_info_bar->RemoveInfoBar();
}
}
};
// ConfirmInfoBar --------------------------------------------------------------
class ConfirmInfoBar : public AlertInfoBar {
public:
explicit ConfirmInfoBar(ConfirmInfoBarDelegate* delegate)
: AlertInfoBar(delegate) {
AddConfirmButton(ConfirmInfoBarDelegate::BUTTON_CANCEL);
AddConfirmButton(ConfirmInfoBarDelegate::BUTTON_OK);
gtk_widget_show_all(border_bin_.get());
}
private:
// Adds a button to the info bar by type. It will do nothing if the delegate
// doesn't specify a button of the given type.
void AddConfirmButton(ConfirmInfoBarDelegate::InfoBarButton type) {
if (delegate_->AsConfirmInfoBarDelegate()->GetButtons() & type) {
GtkWidget* button = gtk_button_new_with_label(WideToUTF8(
delegate_->AsConfirmInfoBarDelegate()->GetButtonLabel(type)).c_str());
gtk_util::CenterWidgetInHBox(hbox_, button, true, 0);
g_signal_connect(button, "clicked",
G_CALLBACK(type == ConfirmInfoBarDelegate::BUTTON_OK ?
OnOkButton : OnCancelButton),
this);
}
}
static void OnCancelButton(GtkWidget* button, ConfirmInfoBar* info_bar) {
if (info_bar->delegate_->AsConfirmInfoBarDelegate()->Cancel())
info_bar->RemoveInfoBar();
}
static void OnOkButton(GtkWidget* button, ConfirmInfoBar* info_bar) {
if (info_bar->delegate_->AsConfirmInfoBarDelegate()->Accept())
info_bar->RemoveInfoBar();
}
};
// AlertInfoBarDelegate, InfoBarDelegate overrides: ----------------------------
InfoBar* AlertInfoBarDelegate::CreateInfoBar() {
return new AlertInfoBar(this);
}
// LinkInfoBarDelegate, InfoBarDelegate overrides: -----------------------------
InfoBar* LinkInfoBarDelegate::CreateInfoBar() {
return new LinkInfoBar(this);
}
// ConfirmInfoBarDelegate, InfoBarDelegate overrides: --------------------------
InfoBar* ConfirmInfoBarDelegate::CreateInfoBar() {
return new ConfirmInfoBar(this);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: EventOASISTContext.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2004-11-26 13:08:47 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _XMLOFF_EVENTOASISTCONTEXT_HXX
#include "EventOASISTContext.hxx"
#endif
#ifndef _XMLOFF_EVENTMAP_HXX
#include "EventMap.hxx"
#endif
#ifndef _XMLOFF_MUTABLEATTRLIST_HXX
#include "MutableAttrList.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_ACTIONMAPTYPESOASIS_HXX
#include "ActionMapTypesOASIS.hxx"
#endif
#ifndef _XMLOFF_ATTRTRANSFORMERACTION_HXX
#include "AttrTransformerAction.hxx"
#endif
#ifndef _XMLOFF_TRANSFORMERACTIONS_HXX
#include "TransformerActions.hxx"
#endif
#ifndef _XMLOFF_TRANSFORMERBASE_HXX
#include "TransformerBase.hxx"
#endif
#ifndef OASIS_FILTER_OOO_1X
// Used to parse Scripting Framework URLs
#ifndef _COM_SUN_STAR_URI_XURIREFERENCEFACTORY_HPP_
#include <com/sun/star/uri/XUriReferenceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_URI_XVNDSUNSTARSCRIPTURL_HPP_
#include <com/sun/star/uri/XVndSunStarScriptUrl.hpp>
#endif
#include <comphelper/processfactory.hxx>
#endif
#include <hash_map>
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::xml::sax;
using namespace ::xmloff::token;
class XMLTransformerOASISEventMap_Impl:
public ::std::hash_map< NameKey_Impl, ::rtl::OUString,
NameHash_Impl, NameHash_Impl >
{
public:
XMLTransformerOASISEventMap_Impl( XMLTransformerEventMapEntry *pInit );
~XMLTransformerOASISEventMap_Impl();
};
XMLTransformerOASISEventMap_Impl::XMLTransformerOASISEventMap_Impl( XMLTransformerEventMapEntry *pInit )
{
if( pInit )
{
XMLTransformerOASISEventMap_Impl::key_type aKey;
XMLTransformerOASISEventMap_Impl::data_type aData;
while( pInit->m_pOASISName )
{
aKey.m_nPrefix = pInit->m_nOASISPrefix;
aKey.m_aLocalName = OUString::createFromAscii(pInit->m_pOASISName);
OSL_ENSURE( find( aKey ) == end(), "duplicate event map entry" );
aData = OUString::createFromAscii(pInit->m_pOOoName);
XMLTransformerOASISEventMap_Impl::value_type aVal( aKey, aData );
insert( aVal );
++pInit;
}
}
}
XMLTransformerOASISEventMap_Impl::~XMLTransformerOASISEventMap_Impl()
{
}
// -----------------------------------------------------------------------------
TYPEINIT1( XMLEventOASISTransformerContext, XMLRenameElemTransformerContext);
XMLEventOASISTransformerContext::XMLEventOASISTransformerContext(
XMLTransformerBase& rImp,
const OUString& rQName ) :
XMLRenameElemTransformerContext( rImp, rQName,
rImp.GetNamespaceMap().GetKeyByAttrName( rQName ), XML_EVENT )
{
}
XMLEventOASISTransformerContext::~XMLEventOASISTransformerContext()
{
}
XMLTransformerOASISEventMap_Impl
*XMLEventOASISTransformerContext::CreateEventMap()
{
return new XMLTransformerOASISEventMap_Impl( aTransformerEventMap );
}
XMLTransformerOASISEventMap_Impl
*XMLEventOASISTransformerContext::CreateFormEventMap()
{
return new XMLTransformerOASISEventMap_Impl( aFormTransformerEventMap );
}
void XMLEventOASISTransformerContext::FlushEventMap(
XMLTransformerOASISEventMap_Impl *p )
{
delete p;
}
OUString XMLEventOASISTransformerContext::GetEventName(
sal_uInt16 nPrefix,
const OUString& rName,
XMLTransformerOASISEventMap_Impl& rMap,
XMLTransformerOASISEventMap_Impl *pMap2)
{
XMLTransformerOASISEventMap_Impl::key_type aKey( nPrefix, rName );
if( pMap2 )
{
XMLTransformerOASISEventMap_Impl::const_iterator aIter =
pMap2->find( aKey );
if( !(aIter == pMap2->end()) )
return (*aIter).second;
}
XMLTransformerOASISEventMap_Impl::const_iterator aIter = rMap.find( aKey );
if( aIter == rMap.end() )
return rName;
else
return (*aIter).second;
}
bool ParseURLAsString(
const OUString& rAttrValue,
OUString* pName, OUString* pLocation )
{
OUString SCHEME( RTL_CONSTASCII_USTRINGPARAM( "vnd.sun.star.script:" ) );
sal_Int32 params = rAttrValue.indexOf( '?' );
if ( rAttrValue.indexOf( SCHEME ) != 0 || params < 0 )
{
return FALSE;
}
sal_Int32 start = SCHEME.getLength();
*pName = rAttrValue.copy( start, params - start );
OUString aToken;
OUString aLanguage;
params++;
do
{
aToken = rAttrValue.getToken( 0, '&', params );
sal_Int32 dummy = 0;
if ( aToken.match( GetXMLToken( XML_LANGUAGE ) ) )
{
aLanguage = aToken.getToken( 1, '=', dummy );
}
else if ( aToken.match( GetXMLToken( XML_LOCATION ) ) )
{
OUString tmp = aToken.getToken( 1, '=', dummy );
if ( tmp.equalsIgnoreAsciiCase( GetXMLToken( XML_DOCUMENT ) ) )
{
*pLocation = GetXMLToken( XML_DOCUMENT );
}
else
{
*pLocation = GetXMLToken( XML_APPLICATION );
}
}
} while ( params >= 0 );
if ( aLanguage.equalsIgnoreAsciiCaseAscii( "basic" ) )
{
return TRUE;
}
return FALSE;
}
bool ParseURL(
const OUString& rAttrValue,
OUString* pName, OUString* pLocation )
{
#ifdef OASIS_FILTER_OOO_1X
return ParseURLAsString( rAttrValue, pName, pLocation );
#else
Reference< com::sun::star::lang::XMultiServiceFactory >
xSMgr = ::comphelper::getProcessServiceFactory();
Reference< com::sun::star::uri::XUriReferenceFactory >
xFactory( xSMgr->createInstance( OUString::createFromAscii(
"com.sun.star.uri.UriReferenceFactory" ) ), UNO_QUERY );
if ( xFactory.is() )
{
Reference< com::sun::star::uri::XVndSunStarScriptUrl > xUrl (
xFactory->parse( rAttrValue ), UNO_QUERY );
if ( xUrl.is() )
{
OUString aLanguageKey = GetXMLToken( XML_LANGUAGE );
if ( xUrl.is() && xUrl->hasParameter( aLanguageKey ) )
{
OUString aLanguage = xUrl->getParameter( aLanguageKey );
if ( aLanguage.equalsIgnoreAsciiCaseAscii( "basic" ) )
{
*pName = xUrl->getName();
OUString tmp =
xUrl->getParameter( GetXMLToken( XML_LOCATION ) );
OUString doc = GetXMLToken( XML_DOCUMENT );
if ( tmp.equalsIgnoreAsciiCase( doc ) )
{
*pLocation = doc;
}
else
{
*pLocation = GetXMLToken( XML_APPLICATION );
}
return TRUE;
}
}
}
return FALSE;
}
else
{
return ParseURLAsString( rAttrValue, pName, pLocation );
}
#endif
}
void XMLEventOASISTransformerContext::StartElement(
const Reference< XAttributeList >& rAttrList )
{
OSL_TRACE("XMLEventOASISTransformerContext::StartElement");
XMLTransformerActions *pActions =
GetTransformer().GetUserDefinedActions( OASIS_EVENT_ACTIONS );
OSL_ENSURE( pActions, "go no actions" );
Reference< XAttributeList > xAttrList( rAttrList );
XMLMutableAttributeList *pMutableAttrList = 0;
sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
for( sal_Int16 i=0; i < nAttrCount; i++ )
{
const OUString& rAttrName = xAttrList->getNameByIndex( i );
OUString aLocalName;
sal_uInt16 nPrefix =
GetTransformer().GetNamespaceMap().GetKeyByAttrName( rAttrName,
&aLocalName );
XMLTransformerActions::key_type aKey( nPrefix, aLocalName );
XMLTransformerActions::const_iterator aIter =
pActions->find( aKey );
if( !(aIter == pActions->end() ) )
{
if( !pMutableAttrList )
{
pMutableAttrList =
new XMLMutableAttributeList( xAttrList );
xAttrList = pMutableAttrList;
}
const OUString& rAttrValue = xAttrList->getValueByIndex( i );
switch( (*aIter).second.m_nActionType )
{
case XML_ATACTION_HREF:
{
OUString aAttrValue( rAttrValue );
OUString aName, aLocation;
bool bNeedsTransform =
ParseURL( rAttrValue, &aName, &aLocation );
if ( bNeedsTransform )
{
pMutableAttrList->RemoveAttributeByIndex( i );
OUString aAttrQName(
GetTransformer().GetNamespaceMap().GetQNameByKey(
XML_NAMESPACE_SCRIPT,
::xmloff::token::GetXMLToken( XML_MACRO_NAME ) ) );
pMutableAttrList->AddAttribute( aAttrQName, aName );
sal_Int16 idx = pMutableAttrList->GetIndexByName(
GetTransformer().GetNamespaceMap().GetQNameByKey(
XML_NAMESPACE_SCRIPT,
GetXMLToken( XML_LANGUAGE ) ) );
pMutableAttrList->SetValueByIndex( idx,
OUString::createFromAscii("StarBasic") );
OUString aLocQName(
GetTransformer().GetNamespaceMap().GetQNameByKey(
XML_NAMESPACE_SCRIPT,
GetXMLToken( XML_LOCATION ) ) );
pMutableAttrList->AddAttribute( aLocQName, aLocation );
}
}
break;
case XML_ATACTION_EVENT_NAME:
{
// Check if the event belongs to a form or control by
// cehcking the 2nd ancestor element, f.i.:
// <form:button><form:event-listeners><form:event-listener>
const XMLTransformerContext *pObjContext =
GetTransformer().GetAncestorContext( 1 );
sal_Bool bForm = pObjContext &&
pObjContext->HasNamespace(XML_NAMESPACE_FORM );
pMutableAttrList->SetValueByIndex( i,
GetTransformer().GetEventName( rAttrValue,
bForm ) );
}
break;
case XML_ATACTION_REMOVE_NAMESPACE_PREFIX:
{
OUString aAttrValue( rAttrValue );
sal_uInt16 nValPrefix =
static_cast<sal_uInt16>((*aIter).second.m_nParam1);
if( GetTransformer().RemoveNamespacePrefix(
aAttrValue, nValPrefix ) )
pMutableAttrList->SetValueByIndex( i, aAttrValue );
}
break;
case XML_ATACTION_MACRO_NAME:
{
OUString aName, aLocation;
bool bNeedsTransform =
ParseURL( rAttrValue, &aName, &aLocation );
if ( bNeedsTransform )
{
pMutableAttrList->SetValueByIndex( i, aName );
sal_Int16 idx = pMutableAttrList->GetIndexByName(
GetTransformer().GetNamespaceMap().GetQNameByKey(
XML_NAMESPACE_SCRIPT,
GetXMLToken( XML_LANGUAGE ) ) );
pMutableAttrList->SetValueByIndex( idx,
OUString::createFromAscii("StarBasic") );
OUString aLocQName(
GetTransformer().GetNamespaceMap().GetQNameByKey(
XML_NAMESPACE_SCRIPT,
GetXMLToken( XML_LOCATION ) ) );
pMutableAttrList->AddAttribute( aLocQName, aLocation );
}
else
{
const OUString& rApp = GetXMLToken( XML_APPLICATION );
const OUString& rDoc = GetXMLToken( XML_DOCUMENT );
OUString aLocation;
OUString aAttrValue;
if( rAttrValue.getLength() > rApp.getLength()+1 &&
rAttrValue.copy(0,rApp.getLength()).
equalsIgnoreAsciiCase( rApp ) &&
':' == rAttrValue[rApp.getLength()] )
{
aLocation = rApp;
aAttrValue = rAttrValue.copy( rApp.getLength()+1 );
}
else if( rAttrValue.getLength() > rDoc.getLength()+1 &&
rAttrValue.copy(0,rDoc.getLength()).
equalsIgnoreAsciiCase( rDoc ) &&
':' == rAttrValue[rDoc.getLength()] )
{
aLocation= rDoc;
aAttrValue = rAttrValue.copy( rDoc.getLength()+1 );
}
if( aAttrValue.getLength() )
pMutableAttrList->SetValueByIndex( i,
aAttrValue );
if( aLocation.getLength() )
{
OUString aAttrQName( GetTransformer().GetNamespaceMap().
GetQNameByKey( XML_NAMESPACE_SCRIPT,
::xmloff::token::GetXMLToken( XML_LOCATION ) ) );
pMutableAttrList->AddAttribute( aAttrQName, aLocation );
// draw bug
aAttrQName = GetTransformer().GetNamespaceMap().
GetQNameByKey( XML_NAMESPACE_SCRIPT,
::xmloff::token::GetXMLToken( XML_LIBRARY ) );
pMutableAttrList->AddAttribute( aAttrQName, aLocation );
}
}
}
break;
case XML_ATACTION_COPY:
break;
default:
OSL_ENSURE( !this, "unknown action" );
break;
}
}
}
XMLRenameElemTransformerContext::StartElement( xAttrList );
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.202); FILE MERGED 2005/09/05 14:40:21 rt 1.4.202.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: EventOASISTContext.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-09 15:42:23 $
*
* 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 _XMLOFF_EVENTOASISTCONTEXT_HXX
#include "EventOASISTContext.hxx"
#endif
#ifndef _XMLOFF_EVENTMAP_HXX
#include "EventMap.hxx"
#endif
#ifndef _XMLOFF_MUTABLEATTRLIST_HXX
#include "MutableAttrList.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_ACTIONMAPTYPESOASIS_HXX
#include "ActionMapTypesOASIS.hxx"
#endif
#ifndef _XMLOFF_ATTRTRANSFORMERACTION_HXX
#include "AttrTransformerAction.hxx"
#endif
#ifndef _XMLOFF_TRANSFORMERACTIONS_HXX
#include "TransformerActions.hxx"
#endif
#ifndef _XMLOFF_TRANSFORMERBASE_HXX
#include "TransformerBase.hxx"
#endif
#ifndef OASIS_FILTER_OOO_1X
// Used to parse Scripting Framework URLs
#ifndef _COM_SUN_STAR_URI_XURIREFERENCEFACTORY_HPP_
#include <com/sun/star/uri/XUriReferenceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_URI_XVNDSUNSTARSCRIPTURL_HPP_
#include <com/sun/star/uri/XVndSunStarScriptUrl.hpp>
#endif
#include <comphelper/processfactory.hxx>
#endif
#include <hash_map>
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::xml::sax;
using namespace ::xmloff::token;
class XMLTransformerOASISEventMap_Impl:
public ::std::hash_map< NameKey_Impl, ::rtl::OUString,
NameHash_Impl, NameHash_Impl >
{
public:
XMLTransformerOASISEventMap_Impl( XMLTransformerEventMapEntry *pInit );
~XMLTransformerOASISEventMap_Impl();
};
XMLTransformerOASISEventMap_Impl::XMLTransformerOASISEventMap_Impl( XMLTransformerEventMapEntry *pInit )
{
if( pInit )
{
XMLTransformerOASISEventMap_Impl::key_type aKey;
XMLTransformerOASISEventMap_Impl::data_type aData;
while( pInit->m_pOASISName )
{
aKey.m_nPrefix = pInit->m_nOASISPrefix;
aKey.m_aLocalName = OUString::createFromAscii(pInit->m_pOASISName);
OSL_ENSURE( find( aKey ) == end(), "duplicate event map entry" );
aData = OUString::createFromAscii(pInit->m_pOOoName);
XMLTransformerOASISEventMap_Impl::value_type aVal( aKey, aData );
insert( aVal );
++pInit;
}
}
}
XMLTransformerOASISEventMap_Impl::~XMLTransformerOASISEventMap_Impl()
{
}
// -----------------------------------------------------------------------------
TYPEINIT1( XMLEventOASISTransformerContext, XMLRenameElemTransformerContext);
XMLEventOASISTransformerContext::XMLEventOASISTransformerContext(
XMLTransformerBase& rImp,
const OUString& rQName ) :
XMLRenameElemTransformerContext( rImp, rQName,
rImp.GetNamespaceMap().GetKeyByAttrName( rQName ), XML_EVENT )
{
}
XMLEventOASISTransformerContext::~XMLEventOASISTransformerContext()
{
}
XMLTransformerOASISEventMap_Impl
*XMLEventOASISTransformerContext::CreateEventMap()
{
return new XMLTransformerOASISEventMap_Impl( aTransformerEventMap );
}
XMLTransformerOASISEventMap_Impl
*XMLEventOASISTransformerContext::CreateFormEventMap()
{
return new XMLTransformerOASISEventMap_Impl( aFormTransformerEventMap );
}
void XMLEventOASISTransformerContext::FlushEventMap(
XMLTransformerOASISEventMap_Impl *p )
{
delete p;
}
OUString XMLEventOASISTransformerContext::GetEventName(
sal_uInt16 nPrefix,
const OUString& rName,
XMLTransformerOASISEventMap_Impl& rMap,
XMLTransformerOASISEventMap_Impl *pMap2)
{
XMLTransformerOASISEventMap_Impl::key_type aKey( nPrefix, rName );
if( pMap2 )
{
XMLTransformerOASISEventMap_Impl::const_iterator aIter =
pMap2->find( aKey );
if( !(aIter == pMap2->end()) )
return (*aIter).second;
}
XMLTransformerOASISEventMap_Impl::const_iterator aIter = rMap.find( aKey );
if( aIter == rMap.end() )
return rName;
else
return (*aIter).second;
}
bool ParseURLAsString(
const OUString& rAttrValue,
OUString* pName, OUString* pLocation )
{
OUString SCHEME( RTL_CONSTASCII_USTRINGPARAM( "vnd.sun.star.script:" ) );
sal_Int32 params = rAttrValue.indexOf( '?' );
if ( rAttrValue.indexOf( SCHEME ) != 0 || params < 0 )
{
return FALSE;
}
sal_Int32 start = SCHEME.getLength();
*pName = rAttrValue.copy( start, params - start );
OUString aToken;
OUString aLanguage;
params++;
do
{
aToken = rAttrValue.getToken( 0, '&', params );
sal_Int32 dummy = 0;
if ( aToken.match( GetXMLToken( XML_LANGUAGE ) ) )
{
aLanguage = aToken.getToken( 1, '=', dummy );
}
else if ( aToken.match( GetXMLToken( XML_LOCATION ) ) )
{
OUString tmp = aToken.getToken( 1, '=', dummy );
if ( tmp.equalsIgnoreAsciiCase( GetXMLToken( XML_DOCUMENT ) ) )
{
*pLocation = GetXMLToken( XML_DOCUMENT );
}
else
{
*pLocation = GetXMLToken( XML_APPLICATION );
}
}
} while ( params >= 0 );
if ( aLanguage.equalsIgnoreAsciiCaseAscii( "basic" ) )
{
return TRUE;
}
return FALSE;
}
bool ParseURL(
const OUString& rAttrValue,
OUString* pName, OUString* pLocation )
{
#ifdef OASIS_FILTER_OOO_1X
return ParseURLAsString( rAttrValue, pName, pLocation );
#else
Reference< com::sun::star::lang::XMultiServiceFactory >
xSMgr = ::comphelper::getProcessServiceFactory();
Reference< com::sun::star::uri::XUriReferenceFactory >
xFactory( xSMgr->createInstance( OUString::createFromAscii(
"com.sun.star.uri.UriReferenceFactory" ) ), UNO_QUERY );
if ( xFactory.is() )
{
Reference< com::sun::star::uri::XVndSunStarScriptUrl > xUrl (
xFactory->parse( rAttrValue ), UNO_QUERY );
if ( xUrl.is() )
{
OUString aLanguageKey = GetXMLToken( XML_LANGUAGE );
if ( xUrl.is() && xUrl->hasParameter( aLanguageKey ) )
{
OUString aLanguage = xUrl->getParameter( aLanguageKey );
if ( aLanguage.equalsIgnoreAsciiCaseAscii( "basic" ) )
{
*pName = xUrl->getName();
OUString tmp =
xUrl->getParameter( GetXMLToken( XML_LOCATION ) );
OUString doc = GetXMLToken( XML_DOCUMENT );
if ( tmp.equalsIgnoreAsciiCase( doc ) )
{
*pLocation = doc;
}
else
{
*pLocation = GetXMLToken( XML_APPLICATION );
}
return TRUE;
}
}
}
return FALSE;
}
else
{
return ParseURLAsString( rAttrValue, pName, pLocation );
}
#endif
}
void XMLEventOASISTransformerContext::StartElement(
const Reference< XAttributeList >& rAttrList )
{
OSL_TRACE("XMLEventOASISTransformerContext::StartElement");
XMLTransformerActions *pActions =
GetTransformer().GetUserDefinedActions( OASIS_EVENT_ACTIONS );
OSL_ENSURE( pActions, "go no actions" );
Reference< XAttributeList > xAttrList( rAttrList );
XMLMutableAttributeList *pMutableAttrList = 0;
sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
for( sal_Int16 i=0; i < nAttrCount; i++ )
{
const OUString& rAttrName = xAttrList->getNameByIndex( i );
OUString aLocalName;
sal_uInt16 nPrefix =
GetTransformer().GetNamespaceMap().GetKeyByAttrName( rAttrName,
&aLocalName );
XMLTransformerActions::key_type aKey( nPrefix, aLocalName );
XMLTransformerActions::const_iterator aIter =
pActions->find( aKey );
if( !(aIter == pActions->end() ) )
{
if( !pMutableAttrList )
{
pMutableAttrList =
new XMLMutableAttributeList( xAttrList );
xAttrList = pMutableAttrList;
}
const OUString& rAttrValue = xAttrList->getValueByIndex( i );
switch( (*aIter).second.m_nActionType )
{
case XML_ATACTION_HREF:
{
OUString aAttrValue( rAttrValue );
OUString aName, aLocation;
bool bNeedsTransform =
ParseURL( rAttrValue, &aName, &aLocation );
if ( bNeedsTransform )
{
pMutableAttrList->RemoveAttributeByIndex( i );
OUString aAttrQName(
GetTransformer().GetNamespaceMap().GetQNameByKey(
XML_NAMESPACE_SCRIPT,
::xmloff::token::GetXMLToken( XML_MACRO_NAME ) ) );
pMutableAttrList->AddAttribute( aAttrQName, aName );
sal_Int16 idx = pMutableAttrList->GetIndexByName(
GetTransformer().GetNamespaceMap().GetQNameByKey(
XML_NAMESPACE_SCRIPT,
GetXMLToken( XML_LANGUAGE ) ) );
pMutableAttrList->SetValueByIndex( idx,
OUString::createFromAscii("StarBasic") );
OUString aLocQName(
GetTransformer().GetNamespaceMap().GetQNameByKey(
XML_NAMESPACE_SCRIPT,
GetXMLToken( XML_LOCATION ) ) );
pMutableAttrList->AddAttribute( aLocQName, aLocation );
}
}
break;
case XML_ATACTION_EVENT_NAME:
{
// Check if the event belongs to a form or control by
// cehcking the 2nd ancestor element, f.i.:
// <form:button><form:event-listeners><form:event-listener>
const XMLTransformerContext *pObjContext =
GetTransformer().GetAncestorContext( 1 );
sal_Bool bForm = pObjContext &&
pObjContext->HasNamespace(XML_NAMESPACE_FORM );
pMutableAttrList->SetValueByIndex( i,
GetTransformer().GetEventName( rAttrValue,
bForm ) );
}
break;
case XML_ATACTION_REMOVE_NAMESPACE_PREFIX:
{
OUString aAttrValue( rAttrValue );
sal_uInt16 nValPrefix =
static_cast<sal_uInt16>((*aIter).second.m_nParam1);
if( GetTransformer().RemoveNamespacePrefix(
aAttrValue, nValPrefix ) )
pMutableAttrList->SetValueByIndex( i, aAttrValue );
}
break;
case XML_ATACTION_MACRO_NAME:
{
OUString aName, aLocation;
bool bNeedsTransform =
ParseURL( rAttrValue, &aName, &aLocation );
if ( bNeedsTransform )
{
pMutableAttrList->SetValueByIndex( i, aName );
sal_Int16 idx = pMutableAttrList->GetIndexByName(
GetTransformer().GetNamespaceMap().GetQNameByKey(
XML_NAMESPACE_SCRIPT,
GetXMLToken( XML_LANGUAGE ) ) );
pMutableAttrList->SetValueByIndex( idx,
OUString::createFromAscii("StarBasic") );
OUString aLocQName(
GetTransformer().GetNamespaceMap().GetQNameByKey(
XML_NAMESPACE_SCRIPT,
GetXMLToken( XML_LOCATION ) ) );
pMutableAttrList->AddAttribute( aLocQName, aLocation );
}
else
{
const OUString& rApp = GetXMLToken( XML_APPLICATION );
const OUString& rDoc = GetXMLToken( XML_DOCUMENT );
OUString aLocation;
OUString aAttrValue;
if( rAttrValue.getLength() > rApp.getLength()+1 &&
rAttrValue.copy(0,rApp.getLength()).
equalsIgnoreAsciiCase( rApp ) &&
':' == rAttrValue[rApp.getLength()] )
{
aLocation = rApp;
aAttrValue = rAttrValue.copy( rApp.getLength()+1 );
}
else if( rAttrValue.getLength() > rDoc.getLength()+1 &&
rAttrValue.copy(0,rDoc.getLength()).
equalsIgnoreAsciiCase( rDoc ) &&
':' == rAttrValue[rDoc.getLength()] )
{
aLocation= rDoc;
aAttrValue = rAttrValue.copy( rDoc.getLength()+1 );
}
if( aAttrValue.getLength() )
pMutableAttrList->SetValueByIndex( i,
aAttrValue );
if( aLocation.getLength() )
{
OUString aAttrQName( GetTransformer().GetNamespaceMap().
GetQNameByKey( XML_NAMESPACE_SCRIPT,
::xmloff::token::GetXMLToken( XML_LOCATION ) ) );
pMutableAttrList->AddAttribute( aAttrQName, aLocation );
// draw bug
aAttrQName = GetTransformer().GetNamespaceMap().
GetQNameByKey( XML_NAMESPACE_SCRIPT,
::xmloff::token::GetXMLToken( XML_LIBRARY ) );
pMutableAttrList->AddAttribute( aAttrQName, aLocation );
}
}
}
break;
case XML_ATACTION_COPY:
break;
default:
OSL_ENSURE( !this, "unknown action" );
break;
}
}
}
XMLRenameElemTransformerContext::StartElement( xAttrList );
}
<|endoftext|> |
<commit_before>/**
MiracleGrue - Model Generator for toolpathing. <http://www.grue.makerbot.com>
Copyright (C) 2011 Far McKon <Far@makerbot.com>, Hugo Boyer (hugo@makerbot.com)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
*/
#include <iostream>
#include <string>
#include <stdlib.h>
#include <stdint.h>
#include "mgl/abstractable.h"
#include "mgl/configuration.h"
#include "mgl/miracle.h"
#include "libthing/Vector2.h"
#include "optionparser.h"
#include "mgl/log.h"
using namespace std;
using namespace mgl;
/// Extends options::Arg to specifiy limitations on arguments
struct Arg: public option::Arg
{
static void printError(const char* msg1, const option::Option& opt, const char* msg2)
{
fprintf(stderr, "%s", msg1);
fwrite(opt.name, opt.namelen, 1, stderr);
fprintf(stderr, "%s", msg2);
}
static option::ArgStatus Unknown(const option::Option& option, bool msg)
{
if (msg) printError("Unknown option '", option, "'\n");
return option::ARG_ILLEGAL;
}
static option::ArgStatus Required(const option::Option& option, bool msg)
{
if (option.arg != 0)
return option::ARG_OK;
if (msg) printError("Option '", option, "' requires an argument\n");
return option::ARG_ILLEGAL;
}
static option::ArgStatus NonEmpty(const option::Option& option, bool msg)
{
if (option.arg != 0 && option.arg[0] != 0)
return option::ARG_OK;
if (msg) printError("Option '", option, "' requires a non-empty argument\n");
return option::ARG_ILLEGAL;
}
static option::ArgStatus Numeric(const option::Option& option, bool msg)
{
char* endptr = 0;
if (option.arg != 0 && strtod(option.arg, &endptr)){};
if (endptr != option.arg && *endptr == 0)
return option::ARG_OK;
if (msg) printError("Option '", option, "' requires a numeric argument\n");
return option::ARG_ILLEGAL;
}
};
// all ID's of the options we expect
enum optionIndex {UNKNOWN, HELP, CONFIG, FIRST_Z,LAYER_H,LAYER_W, FILL_ANGLE, FILL_DENSITY,
N_SHELLS, BOTTOM_SLICE_IDX, TOP_SLICE_IDX, DEBUG_ME, START_GCODE,
END_GCODE, OUT_FILENAME};
// options descriptor table
const option::Descriptor usageDescriptor[] =
{
{UNKNOWN, 0, "", "",Arg::None, "miracle-grue [OPTIONS] FILE.STL \n\n"
"Options:" },
{HELP, 0,"", "help",Arg::None, " --help \tPrint usage and exit." },
{CONFIG, 1,"c", "config", Arg::NonEmpty, "-c \tconfig data in a config.json file."
"(default is local miracle.config)" },
{FIRST_Z, 2,"f", "firstLayerZ", Arg::Numeric,
"-f \tfirst layer height (mm)" },
{LAYER_H, 3,"h", "layerH", Arg::Numeric,
" -h \tgeneral layer height(mm)" },
{LAYER_W, 4,"w", "layerW", Arg::Numeric,
" -w \tlayer width(mm)" },
{ FILL_ANGLE, 5, "a","angle", Arg::Numeric,
" -a \tinfill grid inter slice angle(radians)" },
{ FILL_DENSITY, 6, "p", "density", Arg::Numeric,
" -p \tapprox infill density(percent), aka rho aka p" },
{ N_SHELLS, 7, "n", "nShells", Arg::Numeric,
" -n \tnumber of shells per layer" },
{ BOTTOM_SLICE_IDX, 8, "b", "bottomIdx", Arg::Numeric,
" -b \tbottom slice index" },
{ TOP_SLICE_IDX, 9, "t", "topIdx", Arg::Numeric,
" -t \ttop slice index" },
{ DEBUG_ME, 10, "d", "debug", Arg::Numeric,
" -d \tdebug level, 0 to 99. 60 is 'info'" },
{ START_GCODE, 11, "s", "header", Arg::NonEmpty,
" -s \tstart gcode file" },
{ END_GCODE, 12, "e", "footer", Arg::NonEmpty,
" -e \tend gcode file" },
{ OUT_FILENAME, 13, "o", "outFilename", Arg::NonEmpty,
" -o \twrite gcode to specific filename (defaults to <model>.gcode" },
{0,0,0,0,0,0},
};
void usage() {
Log::severe() <<" test Log::severe " <<endl;
Log::info()<<" test Log::info " <<endl;
Log::fine() <<" test Log::fine " <<endl;
Log::finer() <<" test Log::finer " <<endl;
Log::finest() <<" test Log::finest " <<endl;
cout << endl;
cout << "It is pitch black. You are likely to be eaten by a grue." << endl;
cout << endl;
cout << "This program translates a 3d model file in STL format to GCODE toolpath for a " << endl;
cout << "3D printer." << " Another fine MakerBot Industries product!"<< endl;
cout << endl;
option::printUsage(std::cout, usageDescriptor);
cout << endl;
}
int newParseArgs( Configuration &config,
int argc, char *argv[],
string &modelFile,
int &firstSliceIdx,
int &lastSliceIdx) {
string configFilename = "";
argc-=(argc>0); argv+=(argc>0); // skip program name argv[0] if present
option::Stats stats(usageDescriptor, argc, argv);
option::Option* options = new option::Option[stats.options_max];
option::Option* buffer = new option::Option[stats.buffer_max];
option::Parser parse(usageDescriptor, argc, argv, options, buffer);
if (parse.error())
return -20;
///read config file and/or help option first
for (int i = 0; i < parse.optionsCount(); ++i)
{
option::Option& opt = buffer[i];
if(opt.index() == CONFIG )
configFilename = string(opt.arg);
if(opt.index() == HELP ) {
usage();
exit(0);
}
}
// fallback to default config
if (configFilename.compare(string("")) == 0)
configFilename = "miracle.config";
config.readFromFile(configFilename);
for (int i = 0; i < parse.optionsCount(); ++i)
{
option::Option& opt = buffer[i];
fprintf(stdout, "Argument #%d name %s is #%s\n", i, opt.desc->longopt, opt.arg );
switch (opt.index())
{
case LAYER_H:
case LAYER_W:
case FILL_ANGLE:
case FILL_DENSITY:
case N_SHELLS:
case BOTTOM_SLICE_IDX:
case TOP_SLICE_IDX:
case FIRST_Z:
config["slicer"][opt.desc->longopt] = atof(opt.arg);
break;
case DEBUG_ME:
config["meta"][opt.desc->longopt] = atof(opt.arg);
break;
case START_GCODE:
case END_GCODE:
case OUT_FILENAME:
config["gcoder"][opt.desc->longopt] = opt.arg;
break;
case CONFIG:
// handled above before other config values
break;
case HELP:
// not possible, because handled further above and exits the program
default:
break;
}
}
/// handle parameters (not options!)
if ( parse.nonOptionsCount() == 0) {
usage();
}
else if ( parse.nonOptionsCount() != 1) {
Log::severe() << "too many parameters" << endl;
for (int i = 0; i < parse.nonOptionsCount(); ++i)
Log::severe() << "Parameter #" << i << ": " << parse.nonOption(i) << "\n";
exit(-10);
}
else {
//handle the unnamed parameter separately
modelFile = parse.nonOption(0);
Log::finer() << "filename " << modelFile << endl;
ifstream testmodel(modelFile.c_str(), ifstream::in);
if (testmodel.fail()) {
usage();
throw mgl::Exception(("Invalid model file [" + modelFile + "]").c_str());
exit(-10);
}
}
firstSliceIdx = -1;
lastSliceIdx = -1;
// [programName] and [versionStr] are always hard-code overwritten
config["programName"] = GRUE_PROGRAM_NAME;
config["versionStr"] = GRUE_VERSION;
config["firmware"] = "unknown";
/// convert debug data to a module/level specific setting
g_debugVerbosity = log_verbosity_unset;
if ( config["meta"].isMember("debug") ) {
try {
uint32_t debugLvl = config["meta"]["debug"].asUInt();
if ( debugLvl < 90 ) g_debugVerbosity = log_finest;
else if ( debugLvl < 80 ) g_debugVerbosity = log_finer;
else if ( debugLvl < 70 ) g_debugVerbosity = log_fine;
else if ( debugLvl < 60 ) g_debugVerbosity = log_info;
else if ( debugLvl < 10 ) g_debugVerbosity = log_severe;
else g_debugVerbosity = log_verbosity_unset;
}
catch (...){
cout << "fail sauce on debug level" << endl;
// passed -d sans option. Assume default dbg level
g_debugVerbosity = log_default_level;
}
}
return 0;
}
int main(int argc, char *argv[], char *[]) // envp
{
string modelFile;
Configuration config;
try
{
int firstSliceIdx, lastSliceIdx;
int ret = newParseArgs(config, argc, argv, modelFile, firstSliceIdx, lastSliceIdx);
if(ret != 0){
usage();
exit(ret);
}
// cout << config.asJson() << endl;
Log::finer() << "Tube spacing: " << config["slicer"]["tubeSpacing"] << endl;
MyComputer computer;
Log::fine() << endl << endl;
Log::fine() << "behold!" << endl;
Log::fine() << "Materialization of \"" << modelFile << "\" has begun at " << computer.clock.now() << endl;
std::string scadFile = "."; // outDir
scadFile += computer.fileSystem.getPathSeparatorCharacter();
scadFile = computer.fileSystem.ChangeExtension(computer.fileSystem.ExtractFilename(modelFile.c_str()).c_str(), ".scad" );
std::string gcodeFile = config["gcoder"]["outFilename"].asString();
if (gcodeFile.empty()) {
gcodeFile = ".";
gcodeFile += computer.fileSystem.getPathSeparatorCharacter();
gcodeFile = computer.fileSystem.ChangeExtension(computer.fileSystem.ExtractFilename(modelFile.c_str()).c_str(), ".gcode" );
}
Log::fine() << endl << endl;
Log::fine() << modelFile << " to \"" << gcodeFile << "\" and \"" << scadFile << "\"" << endl;
GCoderConfig gcoderCfg;
loadGCoderConfigFromFile(config, gcoderCfg);
SlicerConfig slicerCfg;
loadSlicerConfigFromFile(config, slicerCfg);
const char* scad = NULL;
if (scadFile.size() > 0 )
scad = scadFile.c_str();
Tomograph tomograph;
Regions regions;
std::vector<mgl::SliceData> slices;
ProgressLog log;
miracleGrue(gcoderCfg, slicerCfg, modelFile.c_str(),
scad,
gcodeFile.c_str(),
firstSliceIdx,
lastSliceIdx,
tomograph,
regions,
slices,
&log);
}
catch(mgl::Exception &mixup)
{
Log::severe() << "ERROR: "<< mixup.error << endl;
return -1;
}
}
<commit_msg>updated arg parsing a bit to make it cleaner, and remove an unneeded loop<commit_after>/**
MiracleGrue - Model Generator for toolpathing. <http://www.grue.makerbot.com>
Copyright (C) 2011 Far McKon <Far@makerbot.com>, Hugo Boyer (hugo@makerbot.com)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
*/
#include <iostream>
#include <string>
#include <stdlib.h>
#include <stdint.h>
#include "mgl/abstractable.h"
#include "mgl/configuration.h"
#include "mgl/miracle.h"
#include "libthing/Vector2.h"
#include "optionparser.h"
#include "mgl/log.h"
using namespace std;
using namespace mgl;
/// Extends options::Arg to specifiy limitations on arguments
struct Arg: public option::Arg
{
static void printError(const char* msg1, const option::Option& opt, const char* msg2)
{
fprintf(stderr, "%s", msg1);
fwrite(opt.name, opt.namelen, 1, stderr);
fprintf(stderr, "%s", msg2);
}
static option::ArgStatus Unknown(const option::Option& option, bool msg)
{
if (msg) printError("Unknown option '", option, "'\n");
return option::ARG_ILLEGAL;
}
static option::ArgStatus Required(const option::Option& option, bool msg)
{
if (option.arg != 0)
return option::ARG_OK;
if (msg) printError("Option '", option, "' requires an argument\n");
return option::ARG_ILLEGAL;
}
static option::ArgStatus NonEmpty(const option::Option& option, bool msg)
{
if (option.arg != 0 && option.arg[0] != 0)
return option::ARG_OK;
if (msg) printError("Option '", option, "' requires a non-empty argument\n");
return option::ARG_ILLEGAL;
}
static option::ArgStatus Numeric(const option::Option& option, bool msg)
{
char* endptr = 0;
if (option.arg != 0 && strtod(option.arg, &endptr)){};
if (endptr != option.arg && *endptr == 0)
return option::ARG_OK;
if (msg) printError("Option '", option, "' requires a numeric argument\n");
return option::ARG_ILLEGAL;
}
};
// all ID's of the options we expect
enum optionIndex {UNKNOWN, HELP, CONFIG, FIRST_Z,LAYER_H,LAYER_W, FILL_ANGLE, FILL_DENSITY,
N_SHELLS, BOTTOM_SLICE_IDX, TOP_SLICE_IDX, DEBUG_ME, START_GCODE,
END_GCODE, OUT_FILENAME};
// options descriptor table
const option::Descriptor usageDescriptor[] =
{
{UNKNOWN, 0, "", "",Arg::None, "miracle-grue [OPTIONS] FILE.STL \n\n"
"Options:" },
{HELP, 0,"", "help",Arg::None, " --help \tPrint usage and exit." },
{CONFIG, 1,"c", "config", Arg::NonEmpty, "-c \tconfig data in a config.json file."
"(default is local miracle.config)" },
{FIRST_Z, 2,"f", "firstLayerZ", Arg::Numeric,
"-f \tfirst layer height (mm)" },
{LAYER_H, 3,"h", "layerH", Arg::Numeric,
" -h \tgeneral layer height(mm)" },
{LAYER_W, 4,"w", "layerW", Arg::Numeric,
" -w \tlayer width(mm)" },
{ FILL_ANGLE, 5, "a","angle", Arg::Numeric,
" -a \tinfill grid inter slice angle(radians)" },
{ FILL_DENSITY, 6, "p", "density", Arg::Numeric,
" -p \tapprox infill density(percent), aka rho aka p" },
{ N_SHELLS, 7, "n", "nShells", Arg::Numeric,
" -n \tnumber of shells per layer" },
{ BOTTOM_SLICE_IDX, 8, "b", "bottomIdx", Arg::Numeric,
" -b \tbottom slice index" },
{ TOP_SLICE_IDX, 9, "t", "topIdx", Arg::Numeric,
" -t \ttop slice index" },
{ DEBUG_ME, 10, "d", "debug", Arg::Numeric,
" -d \tdebug level, 0 to 99. 60 is 'info'" },
{ START_GCODE, 11, "s", "header", Arg::NonEmpty,
" -s \tstart gcode file" },
{ END_GCODE, 12, "e", "footer", Arg::NonEmpty,
" -e \tend gcode file" },
{ OUT_FILENAME, 13, "o", "outFilename", Arg::NonEmpty,
" -o \twrite gcode to specific filename (defaults to <model>.gcode" },
{0,0,0,0,0,0},
};
void usage() {
cout << endl;
cout << "It is pitch black. You are likely to be eaten by a grue." << endl;
cout << "You are using " << GRUE_PROGRAM_NAME << " version " << GRUE_VERSION << endl;
cout << endl;
cout << "This program translates a 3d model file in STL format to GCODE toolpath for a " << endl;
cout << "3D printer." << " Another fine MakerBot Industries product!"<< endl;
cout << endl;
option::printUsage(std::cout, usageDescriptor);
Log::severe() <<" Log level::severe ";
Log::info()<<"::info";
Log::fine() <<"::fine";
Log::finer() <<"::finer";
Log::finest() <<"::finest";
cout << endl;
}
int newParseArgs( Configuration &config,
int argc, char *argv[],
string &modelFile,
int &firstSliceIdx,
int &lastSliceIdx) {
string configFilename = "";
argc-=(argc>0); argv+=(argc>0); // skip program name argv[0] if present
option::Stats stats(usageDescriptor, argc, argv);
option::Option* options = new option::Option[stats.options_max];
option::Option* buffer = new option::Option[stats.buffer_max];
option::Parser parse(usageDescriptor, argc, argv, options, buffer);
if (parse.error())
return -20;
if (options[HELP] || argc == 0) {
usage();
exit(0);
}
///read config file and/or help option first
if ( options[CONFIG]) {
configFilename = string(options[CONFIG].arg);
}
// fallback to default config
if (configFilename.compare(string("")) == 0)
configFilename = "miracle.config";
config.readFromFile(configFilename);
for (int i = 0; i < parse.optionsCount(); ++i)
{
option::Option& opt = buffer[i];
fprintf(stdout, "Argument #%d name %s is #%s\n", i, opt.desc->longopt, opt.arg );
switch (opt.index())
{
case LAYER_H:
case LAYER_W:
case FILL_ANGLE:
case FILL_DENSITY:
case N_SHELLS:
case BOTTOM_SLICE_IDX:
case TOP_SLICE_IDX:
case FIRST_Z:
config["slicer"][opt.desc->longopt] = atof(opt.arg);
break;
case DEBUG_ME:
config["meta"][opt.desc->longopt] = atof(opt.arg);
break;
case START_GCODE:
case END_GCODE:
case OUT_FILENAME:
config["gcoder"][opt.desc->longopt] = opt.arg;
break;
case CONFIG:
// handled above before other config values
break;
case HELP:
// not possible, because handled further above and exits the program
default:
break;
}
}
/// handle parameters (not options!)
if ( parse.nonOptionsCount() == 0) {
usage();
}
else if ( parse.nonOptionsCount() != 1) {
Log::severe() << "too many parameters" << endl;
for (int i = 0; i < parse.nonOptionsCount(); ++i)
Log::severe() << "Parameter #" << i << ": " << parse.nonOption(i) << "\n";
exit(-10);
}
else {
//handle the unnamed parameter separately
modelFile = parse.nonOption(0);
Log::finer() << "filename " << modelFile << endl;
ifstream testmodel(modelFile.c_str(), ifstream::in);
if (testmodel.fail()) {
usage();
throw mgl::Exception(("Invalid model file [" + modelFile + "]").c_str());
exit(-10);
}
}
firstSliceIdx = -1;
lastSliceIdx = -1;
// [programName] and [versionStr] are always hard-code overwritten
config["programName"] = GRUE_PROGRAM_NAME;
config["versionStr"] = GRUE_VERSION;
config["firmware"] = "unknown";
/// convert debug data to a module/level specific setting
g_debugVerbosity = log_verbosity_unset;
if ( config["meta"].isMember("debug") ) {
try {
uint32_t debugLvl = config["meta"]["debug"].asUInt();
if ( debugLvl < 90 ) g_debugVerbosity = log_finest;
else if ( debugLvl < 80 ) g_debugVerbosity = log_finer;
else if ( debugLvl < 70 ) g_debugVerbosity = log_fine;
else if ( debugLvl < 60 ) g_debugVerbosity = log_info;
else if ( debugLvl < 10 ) g_debugVerbosity = log_severe;
else g_debugVerbosity = log_verbosity_unset;
}
catch (...){
cout << "fail sauce on debug level" << endl;
// passed -d sans option. Assume default dbg level
g_debugVerbosity = log_default_level;
}
}
return 0;
}
int main(int argc, char *argv[], char *[]) // envp
{
string modelFile;
Configuration config;
try
{
int firstSliceIdx, lastSliceIdx;
int ret = newParseArgs(config, argc, argv, modelFile, firstSliceIdx, lastSliceIdx);
if(ret != 0){
usage();
exit(ret);
}
// cout << config.asJson() << endl;
Log::finer() << "Tube spacing: " << config["slicer"]["tubeSpacing"] << endl;
MyComputer computer;
Log::fine() << endl << endl;
Log::fine() << "behold!" << endl;
Log::fine() << "Materialization of \"" << modelFile << "\" has begun at " << computer.clock.now() << endl;
std::string scadFile = "."; // outDir
scadFile += computer.fileSystem.getPathSeparatorCharacter();
scadFile = computer.fileSystem.ChangeExtension(computer.fileSystem.ExtractFilename(modelFile.c_str()).c_str(), ".scad" );
std::string gcodeFile = config["gcoder"]["outFilename"].asString();
if (gcodeFile.empty()) {
gcodeFile = ".";
gcodeFile += computer.fileSystem.getPathSeparatorCharacter();
gcodeFile = computer.fileSystem.ChangeExtension(computer.fileSystem.ExtractFilename(modelFile.c_str()).c_str(), ".gcode" );
}
Log::fine() << endl << endl;
Log::fine() << modelFile << " to \"" << gcodeFile << "\" and \"" << scadFile << "\"" << endl;
GCoderConfig gcoderCfg;
loadGCoderConfigFromFile(config, gcoderCfg);
SlicerConfig slicerCfg;
loadSlicerConfigFromFile(config, slicerCfg);
const char* scad = NULL;
if (scadFile.size() > 0 )
scad = scadFile.c_str();
Tomograph tomograph;
Regions regions;
std::vector<mgl::SliceData> slices;
ProgressLog log;
miracleGrue(gcoderCfg, slicerCfg, modelFile.c_str(),
scad,
gcodeFile.c_str(),
firstSliceIdx,
lastSliceIdx,
tomograph,
regions,
slices,
&log);
}
catch(mgl::Exception &mixup)
{
Log::severe() << "ERROR: "<< mixup.error << endl;
return -1;
}
}
<|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 file.
#include "chrome/browser/gtk/infobar_gtk.h"
#include <gtk/gtk.h>
#include "app/gfx/gtk_util.h"
#include "base/string_util.h"
#include "chrome/browser/gtk/custom_button.h"
#include "chrome/browser/gtk/gtk_chrome_link_button.h"
#include "chrome/browser/gtk/gtk_theme_provider.h"
#include "chrome/browser/gtk/infobar_container_gtk.h"
#include "chrome/browser/tab_contents/infobar_delegate.h"
#include "chrome/common/gtk_util.h"
#include "chrome/common/notification_service.h"
namespace {
const double kBackgroundColorTop[3] =
{255.0 / 255.0, 242.0 / 255.0, 183.0 / 255.0};
const double kBackgroundColorBottom[3] =
{250.0 / 255.0, 230.0 / 255.0, 145.0 / 255.0};
// The total height of the info bar.
const int kInfoBarHeight = 37;
// Pixels between infobar elements.
const int kElementPadding = 5;
// Extra padding on either end of info bar.
const int kLeftPadding = 5;
const int kRightPadding = 5;
static gboolean OnBackgroundExpose(GtkWidget* widget, GdkEventExpose* event,
gpointer unused) {
const int height = widget->allocation.height;
cairo_t* cr = gdk_cairo_create(GDK_DRAWABLE(widget->window));
cairo_rectangle(cr, event->area.x, event->area.y,
event->area.width, event->area.height);
cairo_clip(cr);
cairo_pattern_t* pattern = cairo_pattern_create_linear(0, 0, 0, height);
cairo_pattern_add_color_stop_rgb(
pattern, 0.0,
kBackgroundColorTop[0], kBackgroundColorTop[1], kBackgroundColorTop[2]);
cairo_pattern_add_color_stop_rgb(
pattern, 1.0,
kBackgroundColorBottom[0], kBackgroundColorBottom[1],
kBackgroundColorBottom[2]);
cairo_set_source(cr, pattern);
cairo_paint(cr);
cairo_pattern_destroy(pattern);
cairo_destroy(cr);
return FALSE;
}
} // namespace
InfoBar::InfoBar(InfoBarDelegate* delegate)
: container_(NULL),
delegate_(delegate),
theme_provider_(NULL) {
// Create |hbox_| and pad the sides.
hbox_ = gtk_hbox_new(FALSE, kElementPadding);
GtkWidget* padding = gtk_alignment_new(0, 0, 1, 1);
gtk_alignment_set_padding(GTK_ALIGNMENT(padding),
0, 0, kLeftPadding, kRightPadding);
GtkWidget* bg_box = gtk_event_box_new();
gtk_widget_set_app_paintable(bg_box, TRUE);
g_signal_connect(bg_box, "expose-event",
G_CALLBACK(OnBackgroundExpose), NULL);
gtk_container_add(GTK_CONTAINER(padding), hbox_);
gtk_container_add(GTK_CONTAINER(bg_box), padding);
// The -1 on the kInfoBarHeight is to account for the border.
gtk_widget_set_size_request(bg_box, -1, kInfoBarHeight - 1);
border_bin_.Own(gtk_util::CreateGtkBorderBin(bg_box, NULL,
0, 1, 0, 0));
// Add the icon on the left, if any.
SkBitmap* icon = delegate->GetIcon();
if (icon) {
GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(icon);
GtkWidget* image = gtk_image_new_from_pixbuf(pixbuf);
g_object_unref(pixbuf);
gtk_box_pack_start(GTK_BOX(hbox_), image, FALSE, FALSE, 0);
}
// TODO(erg): GTK theme the info bar.
close_button_.reset(CustomDrawButton::CloseButton(NULL));
gtk_util::CenterWidgetInHBox(hbox_, close_button_->widget(), true, 0);
g_signal_connect(close_button_->widget(), "clicked",
G_CALLBACK(OnCloseButton), this);
slide_widget_.reset(new SlideAnimatorGtk(border_bin_.get(),
SlideAnimatorGtk::DOWN,
0, true, true, this));
// We store a pointer back to |this| so we can refer to it from the infobar
// container.
g_object_set_data(G_OBJECT(slide_widget_->widget()), "info-bar", this);
}
InfoBar::~InfoBar() {
border_bin_.Destroy();
}
GtkWidget* InfoBar::widget() {
return slide_widget_->widget();
}
void InfoBar::AnimateOpen() {
slide_widget_->Open();
gdk_window_lower(border_bin_->window);
}
void InfoBar::Open() {
slide_widget_->OpenWithoutAnimation();
gdk_window_lower(border_bin_->window);
}
void InfoBar::AnimateClose() {
slide_widget_->Close();
}
void InfoBar::Close() {
if (delegate_) {
delegate_->InfoBarClosed();
delegate_ = NULL;
}
delete this;
}
bool InfoBar::IsAnimating() {
return slide_widget_->IsAnimating();
}
void InfoBar::RemoveInfoBar() const {
container_->RemoveDelegate(delegate_);
}
void InfoBar::Closed() {
Close();
}
void InfoBar::SetThemeProvider(GtkThemeProvider* theme_provider) {
if (theme_provider_) {
NOTREACHED();
return;
}
theme_provider_ = theme_provider;
registrar_.Add(this, NotificationType::BROWSER_THEME_CHANGED,
NotificationService::AllSources());
UpdateBorderColor();
}
void InfoBar::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
UpdateBorderColor();
}
void InfoBar::UpdateBorderColor() {
GdkColor border_color = theme_provider_->GetBorderColor();
gtk_widget_modify_bg(border_bin_.get(), GTK_STATE_NORMAL, &border_color);
}
// static
void InfoBar::OnCloseButton(GtkWidget* button, InfoBar* info_bar) {
if (info_bar->delegate_)
info_bar->delegate_->InfoBarDismissed();
info_bar->RemoveInfoBar();
}
// AlertInfoBar ----------------------------------------------------------------
class AlertInfoBar : public InfoBar {
public:
explicit AlertInfoBar(AlertInfoBarDelegate* delegate)
: InfoBar(delegate) {
std::wstring text = delegate->GetMessageText();
GtkWidget* label = gtk_label_new(WideToUTF8(text).c_str());
gtk_widget_modify_fg(label, GTK_STATE_NORMAL, &gfx::kGdkBlack);
gtk_box_pack_start(GTK_BOX(hbox_), label, FALSE, FALSE, 0);
gtk_widget_show_all(border_bin_.get());
}
};
// LinkInfoBar -----------------------------------------------------------------
class LinkInfoBar : public InfoBar {
public:
explicit LinkInfoBar(LinkInfoBarDelegate* delegate)
: InfoBar(delegate) {
size_t link_offset;
std::wstring display_text =
delegate->GetMessageTextWithOffset(&link_offset);
std::wstring link_text = delegate->GetLinkText();
// Create the link button.
GtkWidget* link_button =
gtk_chrome_link_button_new(WideToUTF8(link_text).c_str());
gtk_chrome_link_button_set_use_gtk_theme(
GTK_CHROME_LINK_BUTTON(link_button), FALSE);
g_signal_connect(link_button, "clicked",
G_CALLBACK(OnLinkClick), this);
gtk_util::SetButtonTriggersNavigation(link_button);
// If link_offset is npos, we right-align the link instead of embedding it
// in the text.
if (link_offset == std::wstring::npos) {
gtk_box_pack_end(GTK_BOX(hbox_), link_button, FALSE, FALSE, 0);
GtkWidget* label = gtk_label_new(WideToUTF8(display_text).c_str());
gtk_widget_modify_fg(label, GTK_STATE_NORMAL, &gfx::kGdkBlack);
gtk_box_pack_start(GTK_BOX(hbox_), label, FALSE, FALSE, 0);
} else {
GtkWidget* initial_label = gtk_label_new(
WideToUTF8(display_text.substr(0, link_offset)).c_str());
GtkWidget* trailing_label = gtk_label_new(
WideToUTF8(display_text.substr(link_offset)).c_str());
gtk_widget_modify_fg(initial_label, GTK_STATE_NORMAL, &gfx::kGdkBlack);
gtk_widget_modify_fg(trailing_label, GTK_STATE_NORMAL, &gfx::kGdkBlack);
// We don't want any spacing between the elements, so we pack them into
// this hbox that doesn't use kElementPadding.
GtkWidget* hbox = gtk_hbox_new(FALSE, 0);
gtk_box_pack_start(GTK_BOX(hbox), initial_label, FALSE, FALSE, 0);
gtk_util::CenterWidgetInHBox(hbox, link_button, false, 0);
gtk_box_pack_start(GTK_BOX(hbox), trailing_label, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(hbox_), hbox, FALSE, FALSE, 0);
}
gtk_widget_show_all(border_bin_.get());
}
private:
static void OnLinkClick(GtkWidget* button, LinkInfoBar* link_info_bar) {
const GdkEventButton* button_click_event =
reinterpret_cast<GdkEventButton*>(gtk_get_current_event());
WindowOpenDisposition disposition = CURRENT_TAB;
if (button_click_event) {
disposition = event_utils::DispositionFromEventFlags(
button_click_event->state);
}
if (link_info_bar->delegate_->AsLinkInfoBarDelegate()->
LinkClicked(disposition)) {
link_info_bar->RemoveInfoBar();
}
}
};
// ConfirmInfoBar --------------------------------------------------------------
class ConfirmInfoBar : public AlertInfoBar {
public:
explicit ConfirmInfoBar(ConfirmInfoBarDelegate* delegate)
: AlertInfoBar(delegate) {
AddConfirmButton(ConfirmInfoBarDelegate::BUTTON_CANCEL);
AddConfirmButton(ConfirmInfoBarDelegate::BUTTON_OK);
gtk_widget_show_all(border_bin_.get());
}
private:
// Adds a button to the info bar by type. It will do nothing if the delegate
// doesn't specify a button of the given type.
void AddConfirmButton(ConfirmInfoBarDelegate::InfoBarButton type) {
if (delegate_->AsConfirmInfoBarDelegate()->GetButtons() & type) {
GtkWidget* button = gtk_button_new_with_label(WideToUTF8(
delegate_->AsConfirmInfoBarDelegate()->GetButtonLabel(type)).c_str());
gtk_util::CenterWidgetInHBox(hbox_, button, true, 0);
g_signal_connect(button, "clicked",
G_CALLBACK(type == ConfirmInfoBarDelegate::BUTTON_OK ?
OnOkButton : OnCancelButton),
this);
}
}
static void OnCancelButton(GtkWidget* button, ConfirmInfoBar* info_bar) {
if (info_bar->delegate_->AsConfirmInfoBarDelegate()->Cancel())
info_bar->RemoveInfoBar();
}
static void OnOkButton(GtkWidget* button, ConfirmInfoBar* info_bar) {
if (info_bar->delegate_->AsConfirmInfoBarDelegate()->Accept())
info_bar->RemoveInfoBar();
}
};
// AlertInfoBarDelegate, InfoBarDelegate overrides: ----------------------------
InfoBar* AlertInfoBarDelegate::CreateInfoBar() {
return new AlertInfoBar(this);
}
// LinkInfoBarDelegate, InfoBarDelegate overrides: -----------------------------
InfoBar* LinkInfoBarDelegate::CreateInfoBar() {
return new LinkInfoBar(this);
}
// ConfirmInfoBarDelegate, InfoBarDelegate overrides: --------------------------
InfoBar* ConfirmInfoBarDelegate::CreateInfoBar() {
return new ConfirmInfoBar(this);
}
<commit_msg>GTK: Don't fail on startup with debug build.<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 file.
#include "chrome/browser/gtk/infobar_gtk.h"
#include <gtk/gtk.h>
#include "app/gfx/gtk_util.h"
#include "base/string_util.h"
#include "chrome/browser/gtk/custom_button.h"
#include "chrome/browser/gtk/gtk_chrome_link_button.h"
#include "chrome/browser/gtk/gtk_theme_provider.h"
#include "chrome/browser/gtk/infobar_container_gtk.h"
#include "chrome/browser/tab_contents/infobar_delegate.h"
#include "chrome/common/gtk_util.h"
#include "chrome/common/notification_service.h"
namespace {
const double kBackgroundColorTop[3] =
{255.0 / 255.0, 242.0 / 255.0, 183.0 / 255.0};
const double kBackgroundColorBottom[3] =
{250.0 / 255.0, 230.0 / 255.0, 145.0 / 255.0};
// The total height of the info bar.
const int kInfoBarHeight = 37;
// Pixels between infobar elements.
const int kElementPadding = 5;
// Extra padding on either end of info bar.
const int kLeftPadding = 5;
const int kRightPadding = 5;
static gboolean OnBackgroundExpose(GtkWidget* widget, GdkEventExpose* event,
gpointer unused) {
const int height = widget->allocation.height;
cairo_t* cr = gdk_cairo_create(GDK_DRAWABLE(widget->window));
cairo_rectangle(cr, event->area.x, event->area.y,
event->area.width, event->area.height);
cairo_clip(cr);
cairo_pattern_t* pattern = cairo_pattern_create_linear(0, 0, 0, height);
cairo_pattern_add_color_stop_rgb(
pattern, 0.0,
kBackgroundColorTop[0], kBackgroundColorTop[1], kBackgroundColorTop[2]);
cairo_pattern_add_color_stop_rgb(
pattern, 1.0,
kBackgroundColorBottom[0], kBackgroundColorBottom[1],
kBackgroundColorBottom[2]);
cairo_set_source(cr, pattern);
cairo_paint(cr);
cairo_pattern_destroy(pattern);
cairo_destroy(cr);
return FALSE;
}
} // namespace
InfoBar::InfoBar(InfoBarDelegate* delegate)
: container_(NULL),
delegate_(delegate),
theme_provider_(NULL) {
// Create |hbox_| and pad the sides.
hbox_ = gtk_hbox_new(FALSE, kElementPadding);
GtkWidget* padding = gtk_alignment_new(0, 0, 1, 1);
gtk_alignment_set_padding(GTK_ALIGNMENT(padding),
0, 0, kLeftPadding, kRightPadding);
GtkWidget* bg_box = gtk_event_box_new();
gtk_widget_set_app_paintable(bg_box, TRUE);
g_signal_connect(bg_box, "expose-event",
G_CALLBACK(OnBackgroundExpose), NULL);
gtk_container_add(GTK_CONTAINER(padding), hbox_);
gtk_container_add(GTK_CONTAINER(bg_box), padding);
// The -1 on the kInfoBarHeight is to account for the border.
gtk_widget_set_size_request(bg_box, -1, kInfoBarHeight - 1);
border_bin_.Own(gtk_util::CreateGtkBorderBin(bg_box, NULL,
0, 1, 0, 0));
// Add the icon on the left, if any.
SkBitmap* icon = delegate->GetIcon();
if (icon) {
GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(icon);
GtkWidget* image = gtk_image_new_from_pixbuf(pixbuf);
g_object_unref(pixbuf);
gtk_box_pack_start(GTK_BOX(hbox_), image, FALSE, FALSE, 0);
}
// TODO(erg): GTK theme the info bar.
close_button_.reset(CustomDrawButton::CloseButton(NULL));
gtk_util::CenterWidgetInHBox(hbox_, close_button_->widget(), true, 0);
g_signal_connect(close_button_->widget(), "clicked",
G_CALLBACK(OnCloseButton), this);
slide_widget_.reset(new SlideAnimatorGtk(border_bin_.get(),
SlideAnimatorGtk::DOWN,
0, true, true, this));
// We store a pointer back to |this| so we can refer to it from the infobar
// container.
g_object_set_data(G_OBJECT(slide_widget_->widget()), "info-bar", this);
}
InfoBar::~InfoBar() {
border_bin_.Destroy();
}
GtkWidget* InfoBar::widget() {
return slide_widget_->widget();
}
void InfoBar::AnimateOpen() {
slide_widget_->Open();
if (border_bin_->window)
gdk_window_lower(border_bin_->window);
}
void InfoBar::Open() {
slide_widget_->OpenWithoutAnimation();
if (border_bin_->window)
gdk_window_lower(border_bin_->window);
}
void InfoBar::AnimateClose() {
slide_widget_->Close();
}
void InfoBar::Close() {
if (delegate_) {
delegate_->InfoBarClosed();
delegate_ = NULL;
}
delete this;
}
bool InfoBar::IsAnimating() {
return slide_widget_->IsAnimating();
}
void InfoBar::RemoveInfoBar() const {
container_->RemoveDelegate(delegate_);
}
void InfoBar::Closed() {
Close();
}
void InfoBar::SetThemeProvider(GtkThemeProvider* theme_provider) {
if (theme_provider_) {
NOTREACHED();
return;
}
theme_provider_ = theme_provider;
registrar_.Add(this, NotificationType::BROWSER_THEME_CHANGED,
NotificationService::AllSources());
UpdateBorderColor();
}
void InfoBar::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
UpdateBorderColor();
}
void InfoBar::UpdateBorderColor() {
GdkColor border_color = theme_provider_->GetBorderColor();
gtk_widget_modify_bg(border_bin_.get(), GTK_STATE_NORMAL, &border_color);
}
// static
void InfoBar::OnCloseButton(GtkWidget* button, InfoBar* info_bar) {
if (info_bar->delegate_)
info_bar->delegate_->InfoBarDismissed();
info_bar->RemoveInfoBar();
}
// AlertInfoBar ----------------------------------------------------------------
class AlertInfoBar : public InfoBar {
public:
explicit AlertInfoBar(AlertInfoBarDelegate* delegate)
: InfoBar(delegate) {
std::wstring text = delegate->GetMessageText();
GtkWidget* label = gtk_label_new(WideToUTF8(text).c_str());
gtk_widget_modify_fg(label, GTK_STATE_NORMAL, &gfx::kGdkBlack);
gtk_box_pack_start(GTK_BOX(hbox_), label, FALSE, FALSE, 0);
gtk_widget_show_all(border_bin_.get());
}
};
// LinkInfoBar -----------------------------------------------------------------
class LinkInfoBar : public InfoBar {
public:
explicit LinkInfoBar(LinkInfoBarDelegate* delegate)
: InfoBar(delegate) {
size_t link_offset;
std::wstring display_text =
delegate->GetMessageTextWithOffset(&link_offset);
std::wstring link_text = delegate->GetLinkText();
// Create the link button.
GtkWidget* link_button =
gtk_chrome_link_button_new(WideToUTF8(link_text).c_str());
gtk_chrome_link_button_set_use_gtk_theme(
GTK_CHROME_LINK_BUTTON(link_button), FALSE);
g_signal_connect(link_button, "clicked",
G_CALLBACK(OnLinkClick), this);
gtk_util::SetButtonTriggersNavigation(link_button);
// If link_offset is npos, we right-align the link instead of embedding it
// in the text.
if (link_offset == std::wstring::npos) {
gtk_box_pack_end(GTK_BOX(hbox_), link_button, FALSE, FALSE, 0);
GtkWidget* label = gtk_label_new(WideToUTF8(display_text).c_str());
gtk_widget_modify_fg(label, GTK_STATE_NORMAL, &gfx::kGdkBlack);
gtk_box_pack_start(GTK_BOX(hbox_), label, FALSE, FALSE, 0);
} else {
GtkWidget* initial_label = gtk_label_new(
WideToUTF8(display_text.substr(0, link_offset)).c_str());
GtkWidget* trailing_label = gtk_label_new(
WideToUTF8(display_text.substr(link_offset)).c_str());
gtk_widget_modify_fg(initial_label, GTK_STATE_NORMAL, &gfx::kGdkBlack);
gtk_widget_modify_fg(trailing_label, GTK_STATE_NORMAL, &gfx::kGdkBlack);
// We don't want any spacing between the elements, so we pack them into
// this hbox that doesn't use kElementPadding.
GtkWidget* hbox = gtk_hbox_new(FALSE, 0);
gtk_box_pack_start(GTK_BOX(hbox), initial_label, FALSE, FALSE, 0);
gtk_util::CenterWidgetInHBox(hbox, link_button, false, 0);
gtk_box_pack_start(GTK_BOX(hbox), trailing_label, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(hbox_), hbox, FALSE, FALSE, 0);
}
gtk_widget_show_all(border_bin_.get());
}
private:
static void OnLinkClick(GtkWidget* button, LinkInfoBar* link_info_bar) {
const GdkEventButton* button_click_event =
reinterpret_cast<GdkEventButton*>(gtk_get_current_event());
WindowOpenDisposition disposition = CURRENT_TAB;
if (button_click_event) {
disposition = event_utils::DispositionFromEventFlags(
button_click_event->state);
}
if (link_info_bar->delegate_->AsLinkInfoBarDelegate()->
LinkClicked(disposition)) {
link_info_bar->RemoveInfoBar();
}
}
};
// ConfirmInfoBar --------------------------------------------------------------
class ConfirmInfoBar : public AlertInfoBar {
public:
explicit ConfirmInfoBar(ConfirmInfoBarDelegate* delegate)
: AlertInfoBar(delegate) {
AddConfirmButton(ConfirmInfoBarDelegate::BUTTON_CANCEL);
AddConfirmButton(ConfirmInfoBarDelegate::BUTTON_OK);
gtk_widget_show_all(border_bin_.get());
}
private:
// Adds a button to the info bar by type. It will do nothing if the delegate
// doesn't specify a button of the given type.
void AddConfirmButton(ConfirmInfoBarDelegate::InfoBarButton type) {
if (delegate_->AsConfirmInfoBarDelegate()->GetButtons() & type) {
GtkWidget* button = gtk_button_new_with_label(WideToUTF8(
delegate_->AsConfirmInfoBarDelegate()->GetButtonLabel(type)).c_str());
gtk_util::CenterWidgetInHBox(hbox_, button, true, 0);
g_signal_connect(button, "clicked",
G_CALLBACK(type == ConfirmInfoBarDelegate::BUTTON_OK ?
OnOkButton : OnCancelButton),
this);
}
}
static void OnCancelButton(GtkWidget* button, ConfirmInfoBar* info_bar) {
if (info_bar->delegate_->AsConfirmInfoBarDelegate()->Cancel())
info_bar->RemoveInfoBar();
}
static void OnOkButton(GtkWidget* button, ConfirmInfoBar* info_bar) {
if (info_bar->delegate_->AsConfirmInfoBarDelegate()->Accept())
info_bar->RemoveInfoBar();
}
};
// AlertInfoBarDelegate, InfoBarDelegate overrides: ----------------------------
InfoBar* AlertInfoBarDelegate::CreateInfoBar() {
return new AlertInfoBar(this);
}
// LinkInfoBarDelegate, InfoBarDelegate overrides: -----------------------------
InfoBar* LinkInfoBarDelegate::CreateInfoBar() {
return new LinkInfoBar(this);
}
// ConfirmInfoBarDelegate, InfoBarDelegate overrides: --------------------------
InfoBar* ConfirmInfoBarDelegate::CreateInfoBar() {
return new ConfirmInfoBar(this);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: FrameOASISTContext.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-09-09 15:45:50 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _XMLOFF_FRAMEOASISTCONTEXT_HXX
#include "FrameOASISTContext.hxx"
#endif
#ifndef _XMLOFF_IGNORETCONTEXT_HXX
#include "IgnoreTContext.hxx"
#endif
#ifndef _XMLOFF_MUTABLEATTRLIST_HXX
#include "MutableAttrList.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_ACTIONMAPTYPESOASIS_HXX
#include "ActionMapTypesOASIS.hxx"
#endif
#ifndef _XMLOFF_ELEMTRANSFORMERACTION_HXX
#include "ElemTransformerAction.hxx"
#endif
#ifndef _XMLOFF_TRANSFORMERACTIONS_HXX
#include "TransformerActions.hxx"
#endif
#ifndef _XMLOFF_TRANSFORMERBASE_HXX
#include "TransformerBase.hxx"
#endif
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::xml::sax;
using namespace ::xmloff::token;
TYPEINIT1( XMLFrameOASISTransformerContext, XMLTransformerContext );
sal_Bool XMLFrameOASISTransformerContext::IsLinkedEmbeddedObject(
const OUString& rLocalName,
const Reference< XAttributeList >& rAttrList )
{
if( !(IsXMLToken( rLocalName, XML_OBJECT ) ||
IsXMLToken( rLocalName, XML_OBJECT_OLE) ) )
return sal_False;
sal_Int16 nAttrCount = rAttrList.is() ? rAttrList->getLength() : 0;
for( sal_Int16 i=0; i < nAttrCount; i++ )
{
OUString aAttrName( rAttrList->getNameByIndex( i ) );
OUString aLocalName;
sal_uInt16 nPrefix =
GetTransformer().GetNamespaceMap().GetKeyByAttrName( aAttrName,
&aLocalName );
if( XML_NAMESPACE_XLINK == nPrefix &&
IsXMLToken( aLocalName, XML_HREF ) )
{
OUString sHRef( rAttrList->getValueByIndex( i ) );
GetTransformer().ConvertURIToOOo( sHRef, sal_True );
return !(sHRef.getLength() && '#'==sHRef[0]);
}
}
return sal_False;
}
XMLFrameOASISTransformerContext::XMLFrameOASISTransformerContext(
XMLTransformerBase& rImp,
const OUString& rQName ) :
XMLTransformerContext( rImp, rQName ),
m_bIgnoreElement( false )
{
}
XMLFrameOASISTransformerContext::~XMLFrameOASISTransformerContext()
{
}
void XMLFrameOASISTransformerContext::StartElement(
const Reference< XAttributeList >& rAttrList )
{
m_xAttrList = new XMLMutableAttributeList( rAttrList, sal_True );
sal_Int16 nAttrCount = rAttrList.is() ? rAttrList->getLength() : 0;
for( sal_Int16 i=0; i < nAttrCount; i++ )
{
const OUString& rAttrName = rAttrList->getNameByIndex( i );
OUString aLocalName;
sal_uInt16 nPrefix =
GetTransformer().GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName );
if( (nPrefix == XML_NAMESPACE_PRESENTATION) && IsXMLToken( aLocalName, XML_CLASS ) )
{
const OUString& rAttrValue = rAttrList->getValueByIndex( i );
if( IsXMLToken( rAttrValue, XML_HEADER ) || IsXMLToken( rAttrValue, XML_FOOTER ) ||
IsXMLToken( rAttrValue, XML_PAGE_NUMBER ) || IsXMLToken( rAttrValue, XML_DATE_TIME ) )
{
m_bIgnoreElement = true;
break;
}
}
}
}
XMLTransformerContext *XMLFrameOASISTransformerContext::CreateChildContext(
sal_uInt16 nPrefix,
const OUString& rLocalName,
const OUString& rQName,
const Reference< XAttributeList >& rAttrList )
{
XMLTransformerContext *pContext = 0;
if( m_bIgnoreElement )
{
// do not export the frame element and all of its children
pContext = new XMLIgnoreTransformerContext( GetTransformer(),
rQName,
sal_True, sal_True );
}
else
{
XMLTransformerActions *pActions =
GetTransformer().GetUserDefinedActions( OASIS_FRAME_ELEM_ACTIONS );
OSL_ENSURE( pActions, "go no actions" );
XMLTransformerActions::key_type aKey( nPrefix, rLocalName );
XMLTransformerActions::const_iterator aIter = pActions->find( aKey );
if( !(aIter == pActions->end()) )
{
switch( (*aIter).second.m_nActionType )
{
case XML_ETACTION_COPY:
if( !m_aElemQName.getLength() &&
!IsLinkedEmbeddedObject( rLocalName, rAttrList ) )
{
pContext = new XMLIgnoreTransformerContext( GetTransformer(),
rQName,
sal_False, sal_False );
m_aElemQName = rQName;
static_cast< XMLMutableAttributeList * >( m_xAttrList.get() )
->AppendAttributeList( rAttrList );
GetTransformer().ProcessAttrList( m_xAttrList,
OASIS_SHAPE_ACTIONS,
sal_False );
GetTransformer().GetDocHandler()->startElement( m_aElemQName,
m_xAttrList );
}
else
{
pContext = new XMLIgnoreTransformerContext( GetTransformer(),
rQName,
sal_True, sal_True );
}
break;
default:
OSL_ENSURE( !this, "unknown action" );
break;
}
}
}
// default is copying
if( !pContext )
pContext = XMLTransformerContext::CreateChildContext( nPrefix,
rLocalName,
rQName,
rAttrList );
return pContext;
}
void XMLFrameOASISTransformerContext::EndElement()
{
if( !m_bIgnoreElement )
GetTransformer().GetDocHandler()->endElement( m_aElemQName );
}
void XMLFrameOASISTransformerContext::Characters( const OUString& rChars )
{
// ignore
if( m_aElemQName.getLength() && !m_bIgnoreElement )
XMLTransformerContext::Characters( rChars );
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.6.158); FILE MERGED 2006/09/01 18:00:16 kaib 1.6.158.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: FrameOASISTContext.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: obo $ $Date: 2006-09-17 11:24:31 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"
#ifndef _XMLOFF_FRAMEOASISTCONTEXT_HXX
#include "FrameOASISTContext.hxx"
#endif
#ifndef _XMLOFF_IGNORETCONTEXT_HXX
#include "IgnoreTContext.hxx"
#endif
#ifndef _XMLOFF_MUTABLEATTRLIST_HXX
#include "MutableAttrList.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_ACTIONMAPTYPESOASIS_HXX
#include "ActionMapTypesOASIS.hxx"
#endif
#ifndef _XMLOFF_ELEMTRANSFORMERACTION_HXX
#include "ElemTransformerAction.hxx"
#endif
#ifndef _XMLOFF_TRANSFORMERACTIONS_HXX
#include "TransformerActions.hxx"
#endif
#ifndef _XMLOFF_TRANSFORMERBASE_HXX
#include "TransformerBase.hxx"
#endif
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::xml::sax;
using namespace ::xmloff::token;
TYPEINIT1( XMLFrameOASISTransformerContext, XMLTransformerContext );
sal_Bool XMLFrameOASISTransformerContext::IsLinkedEmbeddedObject(
const OUString& rLocalName,
const Reference< XAttributeList >& rAttrList )
{
if( !(IsXMLToken( rLocalName, XML_OBJECT ) ||
IsXMLToken( rLocalName, XML_OBJECT_OLE) ) )
return sal_False;
sal_Int16 nAttrCount = rAttrList.is() ? rAttrList->getLength() : 0;
for( sal_Int16 i=0; i < nAttrCount; i++ )
{
OUString aAttrName( rAttrList->getNameByIndex( i ) );
OUString aLocalName;
sal_uInt16 nPrefix =
GetTransformer().GetNamespaceMap().GetKeyByAttrName( aAttrName,
&aLocalName );
if( XML_NAMESPACE_XLINK == nPrefix &&
IsXMLToken( aLocalName, XML_HREF ) )
{
OUString sHRef( rAttrList->getValueByIndex( i ) );
GetTransformer().ConvertURIToOOo( sHRef, sal_True );
return !(sHRef.getLength() && '#'==sHRef[0]);
}
}
return sal_False;
}
XMLFrameOASISTransformerContext::XMLFrameOASISTransformerContext(
XMLTransformerBase& rImp,
const OUString& rQName ) :
XMLTransformerContext( rImp, rQName ),
m_bIgnoreElement( false )
{
}
XMLFrameOASISTransformerContext::~XMLFrameOASISTransformerContext()
{
}
void XMLFrameOASISTransformerContext::StartElement(
const Reference< XAttributeList >& rAttrList )
{
m_xAttrList = new XMLMutableAttributeList( rAttrList, sal_True );
sal_Int16 nAttrCount = rAttrList.is() ? rAttrList->getLength() : 0;
for( sal_Int16 i=0; i < nAttrCount; i++ )
{
const OUString& rAttrName = rAttrList->getNameByIndex( i );
OUString aLocalName;
sal_uInt16 nPrefix =
GetTransformer().GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName );
if( (nPrefix == XML_NAMESPACE_PRESENTATION) && IsXMLToken( aLocalName, XML_CLASS ) )
{
const OUString& rAttrValue = rAttrList->getValueByIndex( i );
if( IsXMLToken( rAttrValue, XML_HEADER ) || IsXMLToken( rAttrValue, XML_FOOTER ) ||
IsXMLToken( rAttrValue, XML_PAGE_NUMBER ) || IsXMLToken( rAttrValue, XML_DATE_TIME ) )
{
m_bIgnoreElement = true;
break;
}
}
}
}
XMLTransformerContext *XMLFrameOASISTransformerContext::CreateChildContext(
sal_uInt16 nPrefix,
const OUString& rLocalName,
const OUString& rQName,
const Reference< XAttributeList >& rAttrList )
{
XMLTransformerContext *pContext = 0;
if( m_bIgnoreElement )
{
// do not export the frame element and all of its children
pContext = new XMLIgnoreTransformerContext( GetTransformer(),
rQName,
sal_True, sal_True );
}
else
{
XMLTransformerActions *pActions =
GetTransformer().GetUserDefinedActions( OASIS_FRAME_ELEM_ACTIONS );
OSL_ENSURE( pActions, "go no actions" );
XMLTransformerActions::key_type aKey( nPrefix, rLocalName );
XMLTransformerActions::const_iterator aIter = pActions->find( aKey );
if( !(aIter == pActions->end()) )
{
switch( (*aIter).second.m_nActionType )
{
case XML_ETACTION_COPY:
if( !m_aElemQName.getLength() &&
!IsLinkedEmbeddedObject( rLocalName, rAttrList ) )
{
pContext = new XMLIgnoreTransformerContext( GetTransformer(),
rQName,
sal_False, sal_False );
m_aElemQName = rQName;
static_cast< XMLMutableAttributeList * >( m_xAttrList.get() )
->AppendAttributeList( rAttrList );
GetTransformer().ProcessAttrList( m_xAttrList,
OASIS_SHAPE_ACTIONS,
sal_False );
GetTransformer().GetDocHandler()->startElement( m_aElemQName,
m_xAttrList );
}
else
{
pContext = new XMLIgnoreTransformerContext( GetTransformer(),
rQName,
sal_True, sal_True );
}
break;
default:
OSL_ENSURE( !this, "unknown action" );
break;
}
}
}
// default is copying
if( !pContext )
pContext = XMLTransformerContext::CreateChildContext( nPrefix,
rLocalName,
rQName,
rAttrList );
return pContext;
}
void XMLFrameOASISTransformerContext::EndElement()
{
if( !m_bIgnoreElement )
GetTransformer().GetDocHandler()->endElement( m_aElemQName );
}
void XMLFrameOASISTransformerContext::Characters( const OUString& rChars )
{
// ignore
if( m_aElemQName.getLength() && !m_bIgnoreElement )
XMLTransformerContext::Characters( rChars );
}
<|endoftext|> |
<commit_before>//
// Copyright Antoine Leblanc 2010 - 2015
// Distributed under the MIT license.
//
// http://nauths.fr
// http://github.com/nicuveo
// mailto://antoine.jp.leblanc@gmail.com
//
#ifndef SAW_FOREACH_HH_
# define SAW_FOREACH_HH_
//HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
// Includes
# include <boost/foreach.hpp>
//HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
// Macros
# define saw_foreach BOOST_FOREACH
# define saw_reverse_foreach BOOST_REVERSE_FOREACH
#endif /* !SAW_FOREACH_HH_ */
<commit_msg>Removed obsolete file.<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/page_info_model.h"
#include <string>
#include "app/l10n_util.h"
#include "base/callback.h"
#include "base/i18n/time_formatting.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/cert_store.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/ssl/ssl_manager.h"
#include "chrome/common/pref_names.h"
#include "grit/generated_resources.h"
#include "net/base/cert_status_flags.h"
#include "net/base/x509_certificate.h"
namespace {
// Returns a name that can be used to represent the issuer. It tries in this
// order CN, O and OU and returns the first non-empty one found.
std::string GetIssuerName(const net::X509Certificate::Principal& issuer) {
if (!issuer.common_name.empty())
return issuer.common_name;
if (!issuer.organization_names.empty())
return issuer.organization_names[0];
if (!issuer.organization_unit_names.empty())
return issuer.organization_unit_names[0];
return std::string();
}
}
PageInfoModel::PageInfoModel(Profile* profile,
const GURL& url,
const NavigationEntry::SSLStatus& ssl,
bool show_history,
PageInfoModelObserver* observer)
: observer_(observer) {
bool state = true;
string16 head_line;
string16 description;
scoped_refptr<net::X509Certificate> cert;
// Identity section.
string16 subject_name(UTF8ToUTF16(url.host()));
bool empty_subject_name = false;
if (subject_name.empty()) {
subject_name.assign(
l10n_util::GetStringUTF16(IDS_PAGE_INFO_SECURITY_TAB_UNKNOWN_PARTY));
empty_subject_name = true;
}
if (ssl.cert_id() &&
CertStore::GetSharedInstance()->RetrieveCert(ssl.cert_id(), &cert) &&
!net::IsCertStatusError(ssl.cert_status())) {
// OK HTTPS page.
if ((ssl.cert_status() & net::CERT_STATUS_IS_EV) != 0) {
DCHECK(!cert->subject().organization_names.empty());
head_line =
l10n_util::GetStringFUTF16(IDS_PAGE_INFO_EV_IDENTITY_TITLE,
UTF8ToUTF16(cert->subject().organization_names[0]),
UTF8ToUTF16(url.host()));
// An EV Cert is required to have a city (localityName) and country but
// state is "if any".
DCHECK(!cert->subject().locality_name.empty());
DCHECK(!cert->subject().country_name.empty());
string16 locality;
if (!cert->subject().state_or_province_name.empty()) {
locality = l10n_util::GetStringFUTF16(
IDS_PAGEINFO_ADDRESS,
UTF8ToUTF16(cert->subject().locality_name),
UTF8ToUTF16(cert->subject().state_or_province_name),
UTF8ToUTF16(cert->subject().country_name));
} else {
locality = l10n_util::GetStringFUTF16(
IDS_PAGEINFO_PARTIAL_ADDRESS,
UTF8ToUTF16(cert->subject().locality_name),
UTF8ToUTF16(cert->subject().country_name));
}
DCHECK(!cert->subject().organization_names.empty());
description.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_EV,
UTF8ToUTF16(cert->subject().organization_names[0]),
locality,
UTF8ToUTF16(GetIssuerName(cert->issuer()))));
} else {
// Non EV OK HTTPS.
if (empty_subject_name)
head_line.clear(); // Don't display any title.
else
head_line.assign(subject_name);
string16 issuer_name(UTF8ToUTF16(GetIssuerName(cert->issuer())));
if (issuer_name.empty()) {
issuer_name.assign(l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_UNKNOWN_PARTY));
} else {
description.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY, issuer_name));
}
}
} else {
// Bad HTTPS.
description.assign(l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_INSECURE_IDENTITY));
state = false;
}
sections_.push_back(SectionInfo(
state,
l10n_util::GetStringUTF16(IDS_PAGE_INFO_SECURITY_TAB_IDENTITY_TITLE),
head_line,
description));
// Connection section.
// We consider anything less than 80 bits encryption to be weak encryption.
// TODO(wtc): Bug 1198735: report mixed/unsafe content for unencrypted and
// weakly encrypted connections.
state = true;
head_line.clear();
description.clear();
if (ssl.security_bits() <= 0) {
state = false;
description.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_NOT_ENCRYPTED_CONNECTION_TEXT,
subject_name));
} else if (ssl.security_bits() < 80) {
state = false;
description.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_WEAK_ENCRYPTION_CONNECTION_TEXT,
subject_name));
} else {
description.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_CONNECTION_TEXT,
subject_name,
IntToString16(ssl.security_bits())));
if (ssl.displayed_insecure_content() || ssl.ran_insecure_content()) {
state = false;
description.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_SENTENCE_LINK,
description,
l10n_util::GetStringUTF16(ssl.ran_insecure_content() ?
IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_INSECURE_CONTENT_ERROR :
IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_INSECURE_CONTENT_WARNING)));
}
}
sections_.push_back(SectionInfo(
state,
l10n_util::GetStringUTF16(IDS_PAGE_INFO_SECURITY_TAB_CONNECTION_TITLE),
head_line,
description));
// Request the number of visits.
HistoryService* history = profile->GetHistoryService(
Profile::EXPLICIT_ACCESS);
if (show_history && history) {
history->GetVisitCountToHost(
url,
&request_consumer_,
NewCallback(this, &PageInfoModel::OnGotVisitCountToHost));
}
}
int PageInfoModel::GetSectionCount() {
return sections_.size();
}
PageInfoModel::SectionInfo PageInfoModel::GetSectionInfo(int index) {
DCHECK(index < static_cast<int>(sections_.size()));
return sections_[index];
}
void PageInfoModel::OnGotVisitCountToHost(HistoryService::Handle handle,
bool found_visits,
int count,
base::Time first_visit) {
if (!found_visits) {
// This indicates an error, such as the page wasn't http/https; do nothing.
return;
}
bool visited_before_today = false;
if (count) {
base::Time today = base::Time::Now().LocalMidnight();
base::Time first_visit_midnight = first_visit.LocalMidnight();
visited_before_today = (first_visit_midnight < today);
}
if (!visited_before_today) {
sections_.push_back(SectionInfo(
false,
l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_PERSONAL_HISTORY_TITLE),
string16(),
l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_FIRST_VISITED_TODAY)));
} else {
sections_.push_back(SectionInfo(
true,
l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_PERSONAL_HISTORY_TITLE),
string16(),
l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_VISITED_BEFORE_TODAY,
WideToUTF16(base::TimeFormatShortDate(first_visit)))));
}
observer_->ModelChanged();
}
// static
void PageInfoModel::RegisterPrefs(PrefService* prefs) {
prefs->RegisterDictionaryPref(prefs::kPageInfoWindowPlacement);
}
<commit_msg>Trivial change: update a comment.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/page_info_model.h"
#include <string>
#include "app/l10n_util.h"
#include "base/callback.h"
#include "base/i18n/time_formatting.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/cert_store.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/ssl/ssl_manager.h"
#include "chrome/common/pref_names.h"
#include "grit/generated_resources.h"
#include "net/base/cert_status_flags.h"
#include "net/base/x509_certificate.h"
namespace {
// Returns a name that can be used to represent the issuer. It tries in this
// order CN, O and OU and returns the first non-empty one found.
std::string GetIssuerName(const net::X509Certificate::Principal& issuer) {
if (!issuer.common_name.empty())
return issuer.common_name;
if (!issuer.organization_names.empty())
return issuer.organization_names[0];
if (!issuer.organization_unit_names.empty())
return issuer.organization_unit_names[0];
return std::string();
}
}
PageInfoModel::PageInfoModel(Profile* profile,
const GURL& url,
const NavigationEntry::SSLStatus& ssl,
bool show_history,
PageInfoModelObserver* observer)
: observer_(observer) {
bool state = true;
string16 head_line;
string16 description;
scoped_refptr<net::X509Certificate> cert;
// Identity section.
string16 subject_name(UTF8ToUTF16(url.host()));
bool empty_subject_name = false;
if (subject_name.empty()) {
subject_name.assign(
l10n_util::GetStringUTF16(IDS_PAGE_INFO_SECURITY_TAB_UNKNOWN_PARTY));
empty_subject_name = true;
}
if (ssl.cert_id() &&
CertStore::GetSharedInstance()->RetrieveCert(ssl.cert_id(), &cert) &&
!net::IsCertStatusError(ssl.cert_status())) {
// OK HTTPS page.
if ((ssl.cert_status() & net::CERT_STATUS_IS_EV) != 0) {
DCHECK(!cert->subject().organization_names.empty());
head_line =
l10n_util::GetStringFUTF16(IDS_PAGE_INFO_EV_IDENTITY_TITLE,
UTF8ToUTF16(cert->subject().organization_names[0]),
UTF8ToUTF16(url.host()));
// An EV Cert is required to have a city (localityName) and country but
// state is "if any".
DCHECK(!cert->subject().locality_name.empty());
DCHECK(!cert->subject().country_name.empty());
string16 locality;
if (!cert->subject().state_or_province_name.empty()) {
locality = l10n_util::GetStringFUTF16(
IDS_PAGEINFO_ADDRESS,
UTF8ToUTF16(cert->subject().locality_name),
UTF8ToUTF16(cert->subject().state_or_province_name),
UTF8ToUTF16(cert->subject().country_name));
} else {
locality = l10n_util::GetStringFUTF16(
IDS_PAGEINFO_PARTIAL_ADDRESS,
UTF8ToUTF16(cert->subject().locality_name),
UTF8ToUTF16(cert->subject().country_name));
}
DCHECK(!cert->subject().organization_names.empty());
description.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_EV,
UTF8ToUTF16(cert->subject().organization_names[0]),
locality,
UTF8ToUTF16(GetIssuerName(cert->issuer()))));
} else {
// Non EV OK HTTPS.
if (empty_subject_name)
head_line.clear(); // Don't display any title.
else
head_line.assign(subject_name);
string16 issuer_name(UTF8ToUTF16(GetIssuerName(cert->issuer())));
if (issuer_name.empty()) {
issuer_name.assign(l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_UNKNOWN_PARTY));
} else {
description.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY, issuer_name));
}
}
} else {
// HTTP or bad HTTPS.
description.assign(l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_INSECURE_IDENTITY));
state = false;
}
sections_.push_back(SectionInfo(
state,
l10n_util::GetStringUTF16(IDS_PAGE_INFO_SECURITY_TAB_IDENTITY_TITLE),
head_line,
description));
// Connection section.
// We consider anything less than 80 bits encryption to be weak encryption.
// TODO(wtc): Bug 1198735: report mixed/unsafe content for unencrypted and
// weakly encrypted connections.
state = true;
head_line.clear();
description.clear();
if (ssl.security_bits() <= 0) {
state = false;
description.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_NOT_ENCRYPTED_CONNECTION_TEXT,
subject_name));
} else if (ssl.security_bits() < 80) {
state = false;
description.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_WEAK_ENCRYPTION_CONNECTION_TEXT,
subject_name));
} else {
description.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_CONNECTION_TEXT,
subject_name,
IntToString16(ssl.security_bits())));
if (ssl.displayed_insecure_content() || ssl.ran_insecure_content()) {
state = false;
description.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_SENTENCE_LINK,
description,
l10n_util::GetStringUTF16(ssl.ran_insecure_content() ?
IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_INSECURE_CONTENT_ERROR :
IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_INSECURE_CONTENT_WARNING)));
}
}
sections_.push_back(SectionInfo(
state,
l10n_util::GetStringUTF16(IDS_PAGE_INFO_SECURITY_TAB_CONNECTION_TITLE),
head_line,
description));
// Request the number of visits.
HistoryService* history = profile->GetHistoryService(
Profile::EXPLICIT_ACCESS);
if (show_history && history) {
history->GetVisitCountToHost(
url,
&request_consumer_,
NewCallback(this, &PageInfoModel::OnGotVisitCountToHost));
}
}
int PageInfoModel::GetSectionCount() {
return sections_.size();
}
PageInfoModel::SectionInfo PageInfoModel::GetSectionInfo(int index) {
DCHECK(index < static_cast<int>(sections_.size()));
return sections_[index];
}
void PageInfoModel::OnGotVisitCountToHost(HistoryService::Handle handle,
bool found_visits,
int count,
base::Time first_visit) {
if (!found_visits) {
// This indicates an error, such as the page wasn't http/https; do nothing.
return;
}
bool visited_before_today = false;
if (count) {
base::Time today = base::Time::Now().LocalMidnight();
base::Time first_visit_midnight = first_visit.LocalMidnight();
visited_before_today = (first_visit_midnight < today);
}
if (!visited_before_today) {
sections_.push_back(SectionInfo(
false,
l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_PERSONAL_HISTORY_TITLE),
string16(),
l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_FIRST_VISITED_TODAY)));
} else {
sections_.push_back(SectionInfo(
true,
l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_PERSONAL_HISTORY_TITLE),
string16(),
l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_VISITED_BEFORE_TODAY,
WideToUTF16(base::TimeFormatShortDate(first_visit)))));
}
observer_->ModelChanged();
}
// static
void PageInfoModel::RegisterPrefs(PrefService* prefs) {
prefs->RegisterDictionaryPref(prefs::kPageInfoWindowPlacement);
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2018 Nagisa Sekiguchi
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef YDSH_RESULT_HPP
#define YDSH_RESULT_HPP
#include <type_traits>
#include "noncopyable.h"
namespace ydsh {
template <typename T>
struct TypeHolder {
using type = T;
};
namespace __detail {
constexpr bool andAll(bool b) {
return b;
}
template <typename ...T>
constexpr bool andAll(bool b, T && ...t) {
return b && andAll(std::forward<T>(t)...);
}
template <typename T>
constexpr int toTypeIndex(int) {
return -1;
}
template <typename T, typename F, typename ...R>
constexpr int toTypeIndex(int index) {
return std::is_same<T, F>::value ? index : toTypeIndex<T, R...>(index + 1);
}
template <std::size_t I, std::size_t N, typename F, typename ...R>
struct TypeByIndex : TypeByIndex<I + 1, N, R...> {};
template <std::size_t N, typename F, typename ...R>
struct TypeByIndex<N, N, F, R...> {
using type = F;
};
template <typename ...T>
struct OverloadResolver;
template <typename F, typename ...T>
struct OverloadResolver<F, T...> : OverloadResolver<T...> {
using OverloadResolver<T...>::operator();
TypeHolder<F> operator()(F) const;
};
template <>
struct OverloadResolver<> {
void operator()() const;
};
template <typename T>
using result_of_t = typename std::result_of<T>::type;
template <typename F, typename ...T>
using resolvedType = typename result_of_t<OverloadResolver<T...>(F)>::type;
} // namespace __detail
template <typename U, typename ...T>
struct TypeTag {
static constexpr int value = __detail::toTypeIndex<U, T...>(0);
};
template <std::size_t N, typename T0, typename ...T>
struct TypeByIndex {
static_assert(N < sizeof...(T) + 1, "out of range");
using type = typename __detail::TypeByIndex<0, N, T0, T...>::type;
};
// #####################
// ## Storage ##
// #####################
template <typename ...T>
struct Storage {
static_assert(sizeof...(T) > 0, "at least 1 type");
std::aligned_union_t<1, T...> data;
template <typename U, typename F = __detail::resolvedType<U, T...>>
void obtain(U &&value) {
static_assert(TypeTag<F, T...>::value > -1, "invalid type");
using Decayed = typename std::decay<F>::type;
new (&this->data) Decayed(std::forward<U>(value));
}
};
template <typename T, typename ...R>
inline T &get(Storage<R...> &storage) {
static_assert(TypeTag<T, R...>::value > -1, "invalid type");
return *reinterpret_cast<T *>(&storage.data);
}
template <typename T, typename ...R>
inline const T &get(const Storage<R...> &storage) {
static_assert(TypeTag<T, R...>::value > -1, "invalid type");
return *reinterpret_cast<const T *>(&storage.data);
}
template <typename T, typename ...R>
inline void destroy(Storage<R...> &storage) {
get<T>(storage).~T();
}
/**
*
* @tparam T
* @tparam R
* @param src
* @param dest
* must be uninitialized
*/
template <typename T, typename ...R>
inline void move(Storage<R...> &src, Storage<R...> &dest) {
dest.obtain(std::move(get<T>(src)));
destroy<T>(src);
}
template <typename T, typename ...R>
inline void copy(const Storage<R...> &src, Storage<R...> &dest) {
dest.obtain(get<T>(src));
}
namespace __detail_union {
template <int N, typename ...R>
struct Destroyer {
void operator()(Storage<R...> &storage, int tag) const {
if(tag == N) {
using T = typename TypeByIndex<N, R...>::type;
destroy<T>(storage);
} else {
Destroyer<N - 1, R...>()(storage, tag);
}
}
};
template <typename ...R>
struct Destroyer<-1, R...> {
void operator()(Storage<R...> &, int) const {}
};
template <int N, typename ...R>
struct Mover {
void operator()(Storage<R...> &src, int srcTag, Storage<R...> &dest) const {
if(srcTag == N) {
using T = typename TypeByIndex<N, R...>::type;
move<T>(src, dest);
} else {
Mover<N - 1, R...>()(src, srcTag, dest);
}
}
};
template <typename ...R>
struct Mover<-1, R...> {
void operator()(Storage<R...> &, int, Storage<R...> &) const {}
};
template <int N, typename ...R>
struct Copier {
void operator()(const Storage<R...> &src, int srcTag, Storage<R...> &dest) const {
if(srcTag == N) {
using T = typename TypeByIndex<N, R...>::type;
copy<T>(src, dest);
} else {
Copier<N - 1, R...>()(src, srcTag, dest);
}
}
};
template <typename ...R>
struct Copier<-1, R...> {
void operator()(const Storage<R...> &, int, Storage<R...> &) const {}
};
} // namespace __detail_union
template <typename ...R>
inline void polyDestroy(Storage<R...> &storage, int tag) {
__detail_union::Destroyer<sizeof...(R) - 1, R...>()(storage, tag);
}
/**
*
* @tparam N
* @tparam R
* @param src
* @param srcTag
* @param dest
* must be uninitialized
*/
template <typename ...R>
inline void polyMove(Storage<R...> &src, int srcTag, Storage<R...> &dest) {
__detail_union::Mover<sizeof...(R) - 1, R...>()(src, srcTag, dest);
}
template <typename ...R>
inline void polyCopy(const Storage<R...> &src, int srcTag, Storage<R...> &dest) {
__detail_union::Copier<sizeof...(R) - 1, R...>()(src, srcTag, dest);
}
// ###################
// ## Union ##
// ###################
template <typename ...T>
class Union {
private:
static_assert(__detail::andAll(std::is_move_constructible<T>::value...), "must be move-constructible");
using StorageType = Storage<T...>;
StorageType value_;
int tag_;
public:
template <typename R>
static constexpr auto TAG = TypeTag<R, T...>::value;
Union() noexcept : tag_(-1) {}
template <typename U, typename F = __detail::resolvedType<U, T...>>
Union(U &&value) noexcept : tag_(TAG<F>) { //NOLINT
this->value_.obtain(std::forward<U>(value));
}
Union(Union &&value) noexcept : tag_(value.tag()) {
polyMove(value.value(), this->tag(), this->value());
value.tag_ = -1;
}
Union(const Union &value) : tag_(value.tag()) {
polyCopy(value.value(), this->tag(), this->value());
}
~Union() {
polyDestroy(this->value(), this->tag());
}
Union &operator=(Union && value) noexcept {
this->moveAssign(value);
return *this;
}
Union &operator=(const Union &value) {
this->copyAssign(value);
return *this;
}
StorageType &value() {
return this->value_;
}
const StorageType &value() const {
return this->value_;
}
int tag() const {
return this->tag_;
}
bool hasValue() const {
return this->tag() > -1;
}
private:
void moveAssign(Union &value) noexcept {
polyDestroy(this->value(), this->tag());
polyMove(value.value(), value.tag(), this->value());
this->tag_ = value.tag();
value.tag_ = -1;
}
void copyAssign(const Union &value) {
polyDestroy(this->value(), this->tag());
polyCopy(value.value(), value.tag(), this->value());
this->tag_ = value.tag();
}
};
template <typename T, typename ...R>
inline bool is(const Union<R...> &value) {
return value.tag() == TypeTag<T, R...>::value;
}
template <typename T, typename ...R>
inline T &get(Union<R...> &value) {
return get<T>(value.value());
}
template <typename T, typename ...R>
inline const T &get(const Union<R...> &value) {
return get<T>(value.value());
}
// ######################
// ## Optional ##
// ######################
template <typename T>
class OptionalBase : public Union<T> {
public:
OptionalBase() noexcept : Union<T>() {}
OptionalBase(T &&value) noexcept : Union<T>(std::forward<T>(value)) {}
T &unwrap() noexcept {
return get<T>(*this);
}
const T &unwrap() const noexcept {
return get<T>(*this);
}
};
template <typename ...T>
class OptionalBase<Union<T...>> : public Union<T...> {
public:
OptionalBase() noexcept : Union<T...>() {}
template <typename U>
OptionalBase(U &&value) noexcept : Union<T...>(std::forward<U>(value)) {}
};
template <typename T>
struct OptFlattener {
using type = T;
};
template <typename T>
struct OptFlattener<OptionalBase<T>> : OptFlattener<T> {};
template <typename T>
using Optional = OptionalBase<typename OptFlattener<T>::type>;
// ####################
// ## Result ##
// ####################
template <typename T>
struct OkHolder {
T value;
explicit OkHolder(T &&value) : value(std::move(value)) {}
explicit OkHolder(const T &value) : value(value) {}
};
template <typename E>
struct ErrHolder {
E value;
explicit ErrHolder(E &&value) : value(std::move(value)) {}
explicit ErrHolder(const E &value) : value(value) {}
};
template <typename T, typename Decayed = typename std::decay<T>::type>
OkHolder<Decayed> Ok(T &&value) {
return OkHolder<Decayed>(std::forward<T>(value));
}
template <typename E, typename Decayed = typename std::decay<E>::type>
ErrHolder<Decayed> Err(E &&value) {
return ErrHolder<Decayed>(std::forward<E>(value));
}
template <typename T, typename E>
class Result : public Union<T, E> {
public:
NON_COPYABLE(Result);
Result() = delete;
template <typename T0>
Result(OkHolder<T0> &&okHolder) noexcept : Union<T, E>(std::move(okHolder.value)) {} //NOLINT
Result(ErrHolder<E> &&errHolder) noexcept : Union<T, E>(std::move(errHolder.value)) {} //NOLINT
Result(Result &&result) noexcept = default;
~Result() = default;
Result &operator=(Result &&result) noexcept = default;
explicit operator bool() const {
return is<T>(*this);
}
T &asOk() {
return get<T>(*this);
}
E &asErr() {
return get<E>(*this);
}
T &&take() {
return std::move(this->asOk());
}
E &&takeError() {
return std::move(this->asErr());
}
};
} // namespace ydsh
#endif //YDSH_RESULT_HPP
<commit_msg>fix clang tildy warning<commit_after>/*
* Copyright (C) 2018 Nagisa Sekiguchi
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef YDSH_RESULT_HPP
#define YDSH_RESULT_HPP
#include <type_traits>
#include "noncopyable.h"
namespace ydsh {
template <typename T>
struct TypeHolder {
using type = T;
};
namespace __detail {
constexpr bool andAll(bool b) {
return b;
}
template <typename ...T>
constexpr bool andAll(bool b, T && ...t) {
return b && andAll(std::forward<T>(t)...);
}
template <typename T>
constexpr int toTypeIndex(int) {
return -1;
}
template <typename T, typename F, typename ...R>
constexpr int toTypeIndex(int index) {
return std::is_same<T, F>::value ? index : toTypeIndex<T, R...>(index + 1);
}
template <std::size_t I, std::size_t N, typename F, typename ...R>
struct TypeByIndex : TypeByIndex<I + 1, N, R...> {};
template <std::size_t N, typename F, typename ...R>
struct TypeByIndex<N, N, F, R...> {
using type = F;
};
template <typename ...T>
struct OverloadResolver;
template <typename F, typename ...T>
struct OverloadResolver<F, T...> : OverloadResolver<T...> {
using OverloadResolver<T...>::operator();
TypeHolder<F> operator()(F) const;
};
template <>
struct OverloadResolver<> {
void operator()() const;
};
template <typename T>
using result_of_t = typename std::result_of<T>::type;
template <typename F, typename ...T>
using resolvedType = typename result_of_t<OverloadResolver<T...>(F)>::type;
} // namespace __detail
template <typename U, typename ...T>
struct TypeTag {
static constexpr int value = __detail::toTypeIndex<U, T...>(0);
};
template <std::size_t N, typename T0, typename ...T>
struct TypeByIndex {
static_assert(N < sizeof...(T) + 1, "out of range");
using type = typename __detail::TypeByIndex<0, N, T0, T...>::type;
};
// #####################
// ## Storage ##
// #####################
template <typename ...T>
struct Storage {
static_assert(sizeof...(T) > 0, "at least 1 type");
std::aligned_union_t<1, T...> data;
template <typename U, typename F = __detail::resolvedType<U, T...>>
void obtain(U &&value) {
static_assert(TypeTag<F, T...>::value > -1, "invalid type");
using Decayed = typename std::decay<F>::type;
new (&this->data) Decayed(std::forward<U>(value));
}
};
template <typename T, typename ...R>
inline T &get(Storage<R...> &storage) {
static_assert(TypeTag<T, R...>::value > -1, "invalid type");
return *reinterpret_cast<T *>(&storage.data);
}
template <typename T, typename ...R>
inline const T &get(const Storage<R...> &storage) {
static_assert(TypeTag<T, R...>::value > -1, "invalid type");
return *reinterpret_cast<const T *>(&storage.data);
}
template <typename T, typename ...R>
inline void destroy(Storage<R...> &storage) {
get<T>(storage).~T();
}
/**
*
* @tparam T
* @tparam R
* @param src
* @param dest
* must be uninitialized
*/
template <typename T, typename ...R>
inline void move(Storage<R...> &src, Storage<R...> &dest) {
dest.obtain(std::move(get<T>(src)));
destroy<T>(src);
}
template <typename T, typename ...R>
inline void copy(const Storage<R...> &src, Storage<R...> &dest) {
dest.obtain(get<T>(src));
}
namespace __detail_union {
template <int N, typename ...R>
struct Destroyer {
void operator()(Storage<R...> &storage, int tag) const {
if(tag == N) {
using T = typename TypeByIndex<N, R...>::type;
destroy<T>(storage);
} else {
Destroyer<N - 1, R...>()(storage, tag);
}
}
};
template <typename ...R>
struct Destroyer<-1, R...> {
void operator()(Storage<R...> &, int) const {}
};
template <int N, typename ...R>
struct Mover {
void operator()(Storage<R...> &src, int srcTag, Storage<R...> &dest) const {
if(srcTag == N) {
using T = typename TypeByIndex<N, R...>::type;
move<T>(src, dest);
} else {
Mover<N - 1, R...>()(src, srcTag, dest);
}
}
};
template <typename ...R>
struct Mover<-1, R...> {
void operator()(Storage<R...> &, int, Storage<R...> &) const {}
};
template <int N, typename ...R>
struct Copier {
void operator()(const Storage<R...> &src, int srcTag, Storage<R...> &dest) const {
if(srcTag == N) {
using T = typename TypeByIndex<N, R...>::type;
copy<T>(src, dest);
} else {
Copier<N - 1, R...>()(src, srcTag, dest);
}
}
};
template <typename ...R>
struct Copier<-1, R...> {
void operator()(const Storage<R...> &, int, Storage<R...> &) const {}
};
} // namespace __detail_union
template <typename ...R>
inline void polyDestroy(Storage<R...> &storage, int tag) {
__detail_union::Destroyer<sizeof...(R) - 1, R...>()(storage, tag);
}
/**
*
* @tparam N
* @tparam R
* @param src
* @param srcTag
* @param dest
* must be uninitialized
*/
template <typename ...R>
inline void polyMove(Storage<R...> &src, int srcTag, Storage<R...> &dest) {
__detail_union::Mover<sizeof...(R) - 1, R...>()(src, srcTag, dest);
}
template <typename ...R>
inline void polyCopy(const Storage<R...> &src, int srcTag, Storage<R...> &dest) {
__detail_union::Copier<sizeof...(R) - 1, R...>()(src, srcTag, dest);
}
// ###################
// ## Union ##
// ###################
template <typename ...T>
class Union {
private:
static_assert(__detail::andAll(std::is_move_constructible<T>::value...), "must be move-constructible");
using StorageType = Storage<T...>;
StorageType value_;
int tag_;
public:
template <typename R>
static constexpr auto TAG = TypeTag<R, T...>::value;
Union() noexcept : tag_(-1) {}
template <typename U, typename F = __detail::resolvedType<U, T...>>
Union(U &&value) noexcept : tag_(TAG<F>) { //NOLINT
this->value_.obtain(std::forward<U>(value));
}
Union(Union &&value) noexcept : tag_(value.tag()) {
polyMove(value.value(), this->tag(), this->value());
value.tag_ = -1;
}
Union(const Union &value) : tag_(value.tag()) {
polyCopy(value.value(), this->tag(), this->value());
}
~Union() {
polyDestroy(this->value(), this->tag());
}
Union &operator=(Union && value) noexcept {
this->moveAssign(value);
return *this;
}
Union &operator=(const Union &value) {
this->copyAssign(value);
return *this;
}
StorageType &value() {
return this->value_;
}
const StorageType &value() const {
return this->value_;
}
int tag() const {
return this->tag_;
}
bool hasValue() const {
return this->tag() > -1;
}
private:
void moveAssign(Union &value) noexcept {
polyDestroy(this->value(), this->tag());
polyMove(value.value(), value.tag(), this->value());
this->tag_ = value.tag();
value.tag_ = -1;
}
void copyAssign(const Union &value) {
polyDestroy(this->value(), this->tag());
polyCopy(value.value(), value.tag(), this->value());
this->tag_ = value.tag();
}
};
template <typename T, typename ...R>
inline bool is(const Union<R...> &value) {
return value.tag() == TypeTag<T, R...>::value;
}
template <typename T, typename ...R>
inline T &get(Union<R...> &value) {
return get<T>(value.value());
}
template <typename T, typename ...R>
inline const T &get(const Union<R...> &value) {
return get<T>(value.value());
}
// ######################
// ## Optional ##
// ######################
template <typename T>
class OptionalBase : public Union<T> {
public:
OptionalBase() noexcept : Union<T>() {}
OptionalBase(T &&value) noexcept : Union<T>(std::forward<T>(value)) {} //NOLINT
T &unwrap() noexcept {
return get<T>(*this);
}
const T &unwrap() const noexcept {
return get<T>(*this);
}
};
template <typename ...T>
class OptionalBase<Union<T...>> : public Union<T...> {
public:
OptionalBase() noexcept : Union<T...>() {}
template <typename U>
OptionalBase(U &&value) noexcept : Union<T...>(std::forward<U>(value)) {} //NOLINT
};
template <typename T>
struct OptFlattener {
using type = T;
};
template <typename T>
struct OptFlattener<OptionalBase<T>> : OptFlattener<T> {};
template <typename T>
using Optional = OptionalBase<typename OptFlattener<T>::type>;
// ####################
// ## Result ##
// ####################
template <typename T>
struct OkHolder {
T value;
explicit OkHolder(T &&value) : value(std::move(value)) {}
explicit OkHolder(const T &value) : value(value) {}
};
template <typename E>
struct ErrHolder {
E value;
explicit ErrHolder(E &&value) : value(std::move(value)) {}
explicit ErrHolder(const E &value) : value(value) {}
};
template <typename T, typename Decayed = typename std::decay<T>::type>
OkHolder<Decayed> Ok(T &&value) {
return OkHolder<Decayed>(std::forward<T>(value));
}
template <typename E, typename Decayed = typename std::decay<E>::type>
ErrHolder<Decayed> Err(E &&value) {
return ErrHolder<Decayed>(std::forward<E>(value));
}
template <typename T, typename E>
class Result : public Union<T, E> {
public:
NON_COPYABLE(Result);
Result() = delete;
template <typename T0>
Result(OkHolder<T0> &&okHolder) noexcept : Union<T, E>(std::move(okHolder.value)) {} //NOLINT
Result(ErrHolder<E> &&errHolder) noexcept : Union<T, E>(std::move(errHolder.value)) {} //NOLINT
Result(Result &&result) noexcept = default;
~Result() = default;
Result &operator=(Result &&result) noexcept = default;
explicit operator bool() const {
return is<T>(*this);
}
T &asOk() {
return get<T>(*this);
}
E &asErr() {
return get<E>(*this);
}
T &&take() {
return std::move(this->asOk());
}
E &&takeError() {
return std::move(this->asErr());
}
};
} // namespace ydsh
#endif //YDSH_RESULT_HPP
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkImageMagnify.cxx
Language: C++
Date: $Date$
Version: $Revision$
Thanks: Thanks to C. Charles Law who developed this class.
Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include "vtkImageMagnify.h"
#include "vtkImageCache.h"
//----------------------------------------------------------------------------
// Constructor: Sets default filter to be identity.
vtkImageMagnify::vtkImageMagnify()
{
int idx;
this->Interpolate = 0;
for (idx = 0; idx < 3; ++idx)
{
this->MagnificationFactors[idx] = 1;
}
}
//----------------------------------------------------------------------------
// Computes any global image information associated with regions.
void vtkImageMagnify::ExecuteImageInformation()
{
float *spacing;
int idx;
int *inExt;
float outSpacing[3];
int outExt[6];
inExt = this->Input->GetWholeExtent();
spacing = this->Input->GetSpacing();
for (idx = 0; idx < 3; idx++)
{
// Scale the output extent
outExt[idx*2] = inExt[idx*2] * this->MagnificationFactors[idx];
outExt[idx*2+1] = outExt[idx*2] +
(inExt[idx*2+1] - inExt[idx*2] + 1)*this->MagnificationFactors[idx] - 1;
// Change the data spacing
outSpacing[idx] = spacing[idx] / (float)(this->MagnificationFactors[idx]);
}
this->Output->SetWholeExtent(outExt);
this->Output->SetSpacing(outSpacing);
}
//----------------------------------------------------------------------------
// This method computes the Region of input necessary to generate outRegion.
// It assumes offset and size are multiples of Magnify Factors.
void vtkImageMagnify::ComputeRequiredInputUpdateExtent(int inExt[6],
int outExt[6])
{
int idx;
for (idx = 0; idx < 3; idx++)
{
// For Min. Round Down
inExt[idx*2] = (int)(floor((float)(outExt[idx*2]) /
(float)(this->MagnificationFactors[idx])));
inExt[idx*2+1] = (int)(floor((float)(outExt[idx*2+1]) /
(float)(this->MagnificationFactors[idx])));
}
}
//----------------------------------------------------------------------------
// The templated execute function handles all the data types.
// 2d even though operation is 1d.
// Note: Slight misalignment (pixel replication is not nearest neighbor).
template <class T>
static void vtkImageMagnifyExecute(vtkImageMagnify *self,
vtkImageData *inData, T *inPtr,
vtkImageData *outData, T *outPtr,
int outExt[6], int id)
{
int idxC, idxX, idxY, idxZ;
int inIdxX, inIdxY, inIdxZ;
int inMinX, inMinY, inMinZ, inMaxX, inMaxY, inMaxZ;
int maxC, maxX, maxY, maxZ;
int inIncX, inIncY, inIncZ;
int outIncX, outIncY, outIncZ;
unsigned long count = 0;
unsigned long target;
int interpolate;
int magXIdx, magX;
int magYIdx, magY;
int magZIdx, magZ;
T *inPtrZ, *inPtrY, *inPtrX, *outPtrC;
float iMag, iMagP, iMagPY, iMagPZ, iMagPYZ;
T dataP, dataPX, dataPY, dataPZ;
T dataPXY, dataPXZ, dataPYZ, dataPXYZ;
int interpSetup;
interpolate = self->GetInterpolate();
magX = self->GetMagnificationFactors()[0];
magY = self->GetMagnificationFactors()[1];
magZ = self->GetMagnificationFactors()[2];
iMag = 1.0/(magX*magY*magZ);
// find the region to loop over
maxC = outData->GetNumberOfScalarComponents();
maxX = outExt[1] - outExt[0];
maxY = outExt[3] - outExt[2];
maxZ = outExt[5] - outExt[4];
target = (unsigned long)(maxC*(maxZ+1)*(maxY+1)/50.0);
target++;
// Get increments to march through data
inData->GetIncrements(inIncX, inIncY, inIncZ);
outData->GetContinuousIncrements(outExt, outIncX, outIncY, outIncZ);
// Now I am putting in my own boundary check because of ABRs and FMRs
// And I do not understand (nor do I care to figure out) what
// Ken is doing with his checks. (Charles)
inData->GetExtent(inMinX, inMaxX, inMinY, inMaxY, inMinZ, inMaxZ);
// Loop through ouput pixels
for (idxC = 0; idxC < maxC; idxC++)
{
inPtrZ = inPtr + idxC;
inIdxZ = inMinZ;
outPtrC = outPtr + idxC;
magZIdx = magZ - outExt[4]%magZ - 1;
for (idxZ = 0; idxZ <= maxZ; idxZ++, magZIdx--)
{
inPtrY = inPtrZ;
inIdxY = inMinY;
magYIdx = magY - outExt[2]%magY - 1;
for (idxY = 0; !self->AbortExecute && idxY <= maxY; idxY++, magYIdx--)
{
if (!id)
{
if (!(count%target))
{
self->UpdateProgress(count/(50.0*target));
}
count++;
}
if (interpolate)
{
// precompute some values for interpolation
iMagP = (magYIdx + 1)*(magZIdx + 1)*iMag;
iMagPY = (magY - magYIdx - 1)*(magZIdx + 1)*iMag;
iMagPZ = (magYIdx + 1)*(magZ - magZIdx - 1)*iMag;
iMagPYZ = (magY - magYIdx - 1)*(magZ - magZIdx - 1)*iMag;
}
magXIdx = magX - outExt[0]%magX - 1;
inPtrX = inPtrY;
inIdxX = inMinX;
interpSetup = 0;
for (idxX = 0; idxX <= maxX; idxX++, magXIdx--)
{
// Pixel operation
if (!interpolate)
{
*outPtrC = *inPtrX;
}
else
{
// setup data values for interp, overload dataP as an
// indicator of if this has been done yet
if (!interpSetup)
{
int tiX, tiY, tiZ;
dataP = *inPtrX;
// Now I am putting in my own boundary check because of
// ABRs and FMRs
// And I do not understand (nor do I care to figure out) what
// Ken was doing with his checks. (Charles)
if (inIdxX < inMaxX)
{
tiX = inIncX;
}
else
{
tiX = 0;
}
if (inIdxY < inMaxY)
{
tiY = inIncY;
}
else
{
tiY = 0;
}
if (inIdxZ < inMaxZ)
{
tiZ = inIncZ;
}
else
{
tiZ = 0;
}
dataPX = *(inPtrX + tiX);
dataPY = *(inPtrX + tiY);
dataPZ = *(inPtrX + tiZ);
dataPXY = *(inPtrX + tiX + tiY);
dataPXZ = *(inPtrX + tiX + tiZ);
dataPYZ = *(inPtrX + tiY + tiZ);
dataPXYZ = *(inPtrX + tiX + tiY + tiZ);
interpSetup = 1;
}
*outPtrC = (T)
(dataP*(magXIdx + 1)*iMagP +
dataPX*(magX - magXIdx - 1)*iMagP +
dataPY*(magXIdx + 1)*iMagPY +
dataPXY*(magX - magXIdx - 1)*iMagPY +
dataPZ*(magXIdx + 1)*iMagPZ +
dataPXZ*(magX - magXIdx - 1)*iMagPZ +
dataPYZ*(magXIdx + 1)*iMagPYZ +
dataPXYZ*(magX - magXIdx - 1)*iMagPYZ);
}
outPtrC += maxC;
if (!magXIdx)
{
inPtrX += inIncX;
++inIdxX;
magXIdx = magX;
interpSetup = 0;
}
}
outPtrC += outIncY;
if (!magYIdx)
{
inPtrY += inIncY;
++inIdxY;
magYIdx = magY;
}
}
outPtrC += outIncZ;
if (!magZIdx)
{
inPtrZ += inIncZ;
++inIdxZ;
magZIdx = magZ;
}
}
}
}
void vtkImageMagnify::ThreadedExecute(vtkImageData *inData,
vtkImageData *outData,
int outExt[6], int id)
{
int inExt[6];
this->ComputeRequiredInputUpdateExtent(inExt,outExt);
void *inPtr = inData->GetScalarPointerForExtent(inExt);
void *outPtr = outData->GetScalarPointerForExtent(outExt);
vtkDebugMacro(<< "Execute: inData = " << inData
<< ", outData = " << outData);
// this filter expects that input is the same type as output.
if (inData->GetScalarType() != outData->GetScalarType())
{
vtkErrorMacro(<< "Execute: input ScalarType, " << inData->GetScalarType()
<< ", must match out ScalarType " << outData->GetScalarType());
return;
}
switch (inData->GetScalarType())
{
case VTK_FLOAT:
vtkImageMagnifyExecute(this,
inData, (float *)(inPtr),
outData, (float *)(outPtr), outExt, id);
break;
case VTK_INT:
vtkImageMagnifyExecute(this,
inData, (int *)(inPtr),
outData, (int *)(outPtr), outExt, id);
break;
case VTK_SHORT:
vtkImageMagnifyExecute(this,
inData, (short *)(inPtr),
outData, (short *)(outPtr), outExt, id);
break;
case VTK_UNSIGNED_SHORT:
vtkImageMagnifyExecute(this,
inData, (unsigned short *)(inPtr),
outData, (unsigned short *)(outPtr), outExt, id);
break;
case VTK_UNSIGNED_CHAR:
vtkImageMagnifyExecute(this,
inData, (unsigned char *)(inPtr),
outData, (unsigned char *)(outPtr), outExt, id);
break;
default:
vtkErrorMacro(<< "Execute: Unknown ScalarType");
return;
}
}
void vtkImageMagnify::PrintSelf(ostream& os, vtkIndent indent)
{
vtkImageFilter::PrintSelf(os,indent);
os << indent << "MagnificationFactors: ( "
<< this->MagnificationFactors[0] << ", "
<< this->MagnificationFactors[1] << ", "
<< this->MagnificationFactors[2] << " )\n";
os << indent << "Interpolate: " << (this->Interpolate ? "On\n" : "Off\n");
}
<commit_msg>Fixed streaming bug (it should work now!)<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkImageMagnify.cxx
Language: C++
Date: $Date$
Version: $Revision$
Thanks: Thanks to C. Charles Law who developed this class.
Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include "vtkImageMagnify.h"
#include "vtkImageCache.h"
//----------------------------------------------------------------------------
// Constructor: Sets default filter to be identity.
vtkImageMagnify::vtkImageMagnify()
{
int idx;
this->Interpolate = 0;
for (idx = 0; idx < 3; ++idx)
{
this->MagnificationFactors[idx] = 1;
}
}
//----------------------------------------------------------------------------
// Computes any global image information associated with regions.
void vtkImageMagnify::ExecuteImageInformation()
{
float *spacing;
int idx;
int *inExt;
float outSpacing[3];
int outExt[6];
inExt = this->Input->GetWholeExtent();
spacing = this->Input->GetSpacing();
for (idx = 0; idx < 3; idx++)
{
// Scale the output extent
outExt[idx*2] = inExt[idx*2] * this->MagnificationFactors[idx];
outExt[idx*2+1] = outExt[idx*2] +
(inExt[idx*2+1] - inExt[idx*2] + 1)*this->MagnificationFactors[idx] - 1;
// Change the data spacing
outSpacing[idx] = spacing[idx] / (float)(this->MagnificationFactors[idx]);
}
this->Output->SetWholeExtent(outExt);
this->Output->SetSpacing(outSpacing);
}
//----------------------------------------------------------------------------
// This method computes the Region of input necessary to generate outRegion.
// It assumes offset and size are multiples of Magnify Factors.
void vtkImageMagnify::ComputeRequiredInputUpdateExtent(int inExt[6],
int outExt[6])
{
int idx;
for (idx = 0; idx < 3; idx++)
{
// For Min. Round Down
inExt[idx*2] = (int)(floor((float)(outExt[idx*2]) /
(float)(this->MagnificationFactors[idx])));
inExt[idx*2+1] = (int)(floor((float)(outExt[idx*2+1]) /
(float)(this->MagnificationFactors[idx])));
}
}
//----------------------------------------------------------------------------
// The templated execute function handles all the data types.
// 2d even though operation is 1d.
// Note: Slight misalignment (pixel replication is not nearest neighbor).
template <class T>
static void vtkImageMagnifyExecute(vtkImageMagnify *self,
vtkImageData *inData, T *inPtr, int inExt[6],
vtkImageData *outData, T *outPtr,
int outExt[6], int id)
{
int idxC, idxX, idxY, idxZ;
int inIdxX, inIdxY, inIdxZ;
int inMaxX, inMaxY, inMaxZ;
int maxC, maxX, maxY, maxZ;
int inIncX, inIncY, inIncZ;
int outIncX, outIncY, outIncZ;
unsigned long count = 0;
unsigned long target;
int interpolate;
int magXIdx, magX;
int magYIdx, magY;
int magZIdx, magZ;
T *inPtrZ, *inPtrY, *inPtrX, *outPtrC;
float iMag, iMagP, iMagPY, iMagPZ, iMagPYZ;
T dataP, dataPX, dataPY, dataPZ;
T dataPXY, dataPXZ, dataPYZ, dataPXYZ;
int interpSetup;
interpolate = self->GetInterpolate();
magX = self->GetMagnificationFactors()[0];
magY = self->GetMagnificationFactors()[1];
magZ = self->GetMagnificationFactors()[2];
iMag = 1.0/(magX*magY*magZ);
// find the region to loop over
maxC = outData->GetNumberOfScalarComponents();
maxX = outExt[1] - outExt[0];
maxY = outExt[3] - outExt[2];
maxZ = outExt[5] - outExt[4];
target = (unsigned long)(maxC*(maxZ+1)*(maxY+1)/50.0);
target++;
// Get increments to march through data
inData->GetIncrements(inIncX, inIncY, inIncZ);
outData->GetContinuousIncrements(outExt, outIncX, outIncY, outIncZ);
// Now I am putting in my own boundary check because of ABRs and FMRs
// And I do not understand (nor do I care to figure out) what
// Ken is doing with his checks. (Charles)
inMaxX = inExt[1];
inMaxY = inExt[3];
inMaxZ = inExt[5];
// Loop through ouput pixels
for (idxC = 0; idxC < maxC; idxC++)
{
inPtrZ = inPtr + idxC;
inIdxZ = inExt[4];
outPtrC = outPtr + idxC;
magZIdx = magZ - outExt[4]%magZ - 1;
for (idxZ = 0; idxZ <= maxZ; idxZ++, magZIdx--)
{
inPtrY = inPtrZ;
inIdxY = inExt[2];
magYIdx = magY - outExt[2]%magY - 1;
for (idxY = 0; !self->AbortExecute && idxY <= maxY; idxY++, magYIdx--)
{
if (!id)
{
if (!(count%target))
{
self->UpdateProgress(count/(50.0*target));
}
count++;
}
if (interpolate)
{
// precompute some values for interpolation
iMagP = (magYIdx + 1)*(magZIdx + 1)*iMag;
iMagPY = (magY - magYIdx - 1)*(magZIdx + 1)*iMag;
iMagPZ = (magYIdx + 1)*(magZ - magZIdx - 1)*iMag;
iMagPYZ = (magY - magYIdx - 1)*(magZ - magZIdx - 1)*iMag;
}
magXIdx = magX - outExt[0]%magX - 1;
inPtrX = inPtrY;
inIdxX = inExt[0];
interpSetup = 0;
for (idxX = 0; idxX <= maxX; idxX++, magXIdx--)
{
// Pixel operation
if (!interpolate)
{
*outPtrC = *inPtrX;
}
else
{
// setup data values for interp, overload dataP as an
// indicator of if this has been done yet
if (!interpSetup)
{
int tiX, tiY, tiZ;
dataP = *inPtrX;
// Now I am putting in my own boundary check because of
// ABRs and FMRs
// And I do not understand (nor do I care to figure out) what
// Ken was doing with his checks. (Charles)
if (inIdxX < inMaxX)
{
tiX = inIncX;
}
else
{
tiX = 0;
}
if (inIdxY < inMaxY)
{
tiY = inIncY;
}
else
{
tiY = 0;
}
if (inIdxZ < inMaxZ)
{
tiZ = inIncZ;
}
else
{
tiZ = 0;
}
dataPX = *(inPtrX + tiX);
dataPY = *(inPtrX + tiY);
dataPZ = *(inPtrX + tiZ);
dataPXY = *(inPtrX + tiX + tiY);
dataPXZ = *(inPtrX + tiX + tiZ);
dataPYZ = *(inPtrX + tiY + tiZ);
dataPXYZ = *(inPtrX + tiX + tiY + tiZ);
interpSetup = 1;
}
*outPtrC = (T)
(dataP*(magXIdx + 1)*iMagP +
dataPX*(magX - magXIdx - 1)*iMagP +
dataPY*(magXIdx + 1)*iMagPY +
dataPXY*(magX - magXIdx - 1)*iMagPY +
dataPZ*(magXIdx + 1)*iMagPZ +
dataPXZ*(magX - magXIdx - 1)*iMagPZ +
dataPYZ*(magXIdx + 1)*iMagPYZ +
dataPXYZ*(magX - magXIdx - 1)*iMagPYZ);
}
outPtrC += maxC;
if (!magXIdx)
{
inPtrX += inIncX;
++inIdxX;
magXIdx = magX;
interpSetup = 0;
}
}
outPtrC += outIncY;
if (!magYIdx)
{
inPtrY += inIncY;
++inIdxY;
magYIdx = magY;
}
}
outPtrC += outIncZ;
if (!magZIdx)
{
inPtrZ += inIncZ;
++inIdxZ;
magZIdx = magZ;
}
}
}
}
void vtkImageMagnify::ThreadedExecute(vtkImageData *inData,
vtkImageData *outData,
int outExt[6], int id)
{
int inExt[6];
this->ComputeRequiredInputUpdateExtent(inExt,outExt);
void *inPtr = inData->GetScalarPointerForExtent(inExt);
void *outPtr = outData->GetScalarPointerForExtent(outExt);
vtkDebugMacro(<< "Execute: inData = " << inData
<< ", outData = " << outData);
// this filter expects that input is the same type as output.
if (inData->GetScalarType() != outData->GetScalarType())
{
vtkErrorMacro(<< "Execute: input ScalarType, " << inData->GetScalarType()
<< ", must match out ScalarType " << outData->GetScalarType());
return;
}
switch (inData->GetScalarType())
{
case VTK_FLOAT:
vtkImageMagnifyExecute(this,
inData, (float *)(inPtr), inExt,
outData, (float *)(outPtr), outExt, id);
break;
case VTK_INT:
vtkImageMagnifyExecute(this,
inData, (int *)(inPtr), inExt,
outData, (int *)(outPtr), outExt, id);
break;
case VTK_SHORT:
vtkImageMagnifyExecute(this,
inData, (short *)(inPtr), inExt,
outData, (short *)(outPtr), outExt, id);
break;
case VTK_UNSIGNED_SHORT:
vtkImageMagnifyExecute(this,
inData, (unsigned short *)(inPtr), inExt,
outData, (unsigned short *)(outPtr), outExt, id);
break;
case VTK_UNSIGNED_CHAR:
vtkImageMagnifyExecute(this,
inData, (unsigned char *)(inPtr), inExt,
outData, (unsigned char *)(outPtr), outExt, id);
break;
default:
vtkErrorMacro(<< "Execute: Unknown ScalarType");
return;
}
}
void vtkImageMagnify::PrintSelf(ostream& os, vtkIndent indent)
{
vtkImageFilter::PrintSelf(os,indent);
os << indent << "MagnificationFactors: ( "
<< this->MagnificationFactors[0] << ", "
<< this->MagnificationFactors[1] << ", "
<< this->MagnificationFactors[2] << " )\n";
os << indent << "Interpolate: " << (this->Interpolate ? "On\n" : "Off\n");
}
<|endoftext|> |
<commit_before>// -*- Mode:C++ -*-
/**************************************************************************************************/
/* */
/* Copyright (C) 2014 University of Hull */
/* */
/**************************************************************************************************/
/* */
/* module : field/adapter_multi.inl */
/* project : */
/* description: */
/* */
/**************************************************************************************************/
#if !defined(UKACHULLDCS_08961_FIELD_ADAPTER_MULTI_INL)
#define UKACHULLDCS_08961_FIELD_ADAPTER_MULTI_INL
// includes, system
#include <ostream> // std::ostream
// includes, project
#include <support/io_utils.hpp>
#define UKACHULLDCS_USE_TRACE
#undef UKACHULLDCS_USE_TRACE
#include <support/trace.hpp>
#if defined(UKACHULLDCS_USE_TRACE) || defined(UKACHULLDCS_ALL_TRACE)
# include <typeinfo>
# include <support/type_info.hpp>
#endif
namespace field {
namespace adapter {
// functions, inlined (inline)
template <typename T, typename C>
inline /* explicit */
multi<T,C>::multi(container_type& a, std::string const& b,
get_callback_type c, set_callback_type d,
add_callback_type e, sub_callback_type f,
value_container_type const& g)
: base(a, b), get_value_(c), set_value_(d), add_value_(e), sub_value_(f)
{
TRACE("field::adapter::multi<" + support::demangle(typeid(T)) + "," +
support::demangle(typeid(C)) + ">::multi(value_container_type)");
set_value_(g);
}
template <typename T, typename C>
inline /* explicit */
multi<T,C>::multi(container_type& a, std::string const& b,
get_callback_type c, set_callback_type d,
add_callback_type e, sub_callback_type f,
std::initializer_list<value_type> g)
: base(a, b), get_value_(c), set_value_(d), add_value_(e), sub_value_(f)
{
TRACE("field::adapter::multi<" + support::demangle(typeid(T)) + "," +
support::demangle(typeid(C)) + ">::multi(std::initializer_list<" +
support::demangle(typeid(T)) + ">)");
set_value_(g);
}
template <typename T, typename C>
inline /* virtual */
multi<T,C>::~multi()
{
TRACE("field::adapter::multi<" + support::demangle(typeid(T)) + "," +
support::demangle(typeid(C)) + ">::~multi");
}
template <typename T, typename C>
inline /* virtual */ void
multi<T,C>::print_on(std::ostream& os) const
{
TRACE("field::adapter::multi<" + support::demangle(typeid(T)) + "," +
support::demangle(typeid(C)) + ">::print_on");
os << '[';
base::print_on(os);
using support::ostream::operator<<;
os << ',' << get_value_() << "]";
}
template <typename T, typename C>
inline typename multi<T,C>::value_container_type const&
multi<T,C>::get() const
{
TRACE("field::adapter::multi<" + support::demangle(typeid(T)) + "," +
support::demangle(typeid(C)) + ">::get");
return get_value_();
}
template <typename T, typename C>
inline typename multi<T,C>::value_container_type
multi<T,C>::set(value_container_type const& a)
{
TRACE("field::adapter::multi<" + support::demangle(typeid(T)) + "," +
support::demangle(typeid(C)) + ">::set(value_container_type)");
value_container_type const result(set_value_(a));
changed();
return result;
}
template <typename T, typename C>
inline typename multi<T,C>::value_container_type
multi<T,C>::set(std::initializer_list<value_type> a)
{
TRACE("field::adapter::multi<" + support::demangle(typeid(T)) + "," +
support::demangle(typeid(C)) + ">::set(std::initializer_list<" +
support::demangle(typeid(T)) + ">)");
value_container_type const result(set_value_(a));
changed();
return result;
}
template <typename T, typename C>
inline bool
multi<T,C>::add(value_type const& a)
{
TRACE("field::adapter::multi<" + support::demangle(typeid(T)) + "," +
support::demangle(typeid(C)) + ">::add");
bool const result(add_value_(a));
if (result) {
changed();
}
return result;
}
template <typename T, typename C>
inline bool
multi<T,C>::sub(value_type const& a)
{
TRACE("field::adapter::multi<" + support::demangle(typeid(T)) + "," +
support::demangle(typeid(C)) + ">::sub");
bool const result(sub_value_(a));
if (result) {
changed();
}
return result;
}
template <typename T, typename C>
inline multi<T,C>::operator multi<T,C>::value_container_type const& () const
{
TRACE("field::adapter::multi<" + support::demangle(typeid(T)) + "," +
support::demangle(typeid(C)) + ">::operator " +
"value_container_type const&");
return get();
}
template <typename T, typename C>
inline multi<T,C>&
multi<T,C>::operator=(value_container_type const& a)
{
TRACE("field::adapter::multi<" + support::demangle(typeid(T)) + "," +
support::demangle(typeid(C)) + ">::operator=" +
"(value_container_type const&)");
set(a);
return *this;
}
template <typename T, typename C>
inline multi<T,C>&
multi<T,C>::operator=(std::initializer_list<value_type> a)
{
TRACE("field::adapter::multi<" + support::demangle(typeid(T)) + "," +
support::demangle(typeid(C)) + ">::operator=" +
"(std::initializer_list<value_type>)");
set(a);
return *this;
}
template <typename T, typename C>
inline multi<T,C>&
multi<T,C>::operator+=(value_type const& a)
{
TRACE("field::adapter::multi<" + support::demangle(typeid(T)) + "," +
support::demangle(typeid(C)) + ">::operator+=");
add(a);
return *this;
}
template <typename T, typename C>
inline multi<T,C>&
multi<T,C>::operator-=(value_type const& a)
{
TRACE("field::adapter::multi<" + support::demangle(typeid(T)) + "," +
support::demangle(typeid(C)) + ">::operator-=");
sub(a);
return *this;
}
} // namespace adapter {
} // namespace field {
#if defined(UKACHULLDCS_USE_TRACE)
# undef UKACHULLDCS_USE_TRACE
#endif
#endif // #if !defined(UKACHULLDCS_08961_FIELD_ADAPTER_MULTI_INL)
<commit_msg>fixed: trace usage<commit_after>// -*- Mode:C++ -*-
/**************************************************************************************************/
/* */
/* Copyright (C) 2014 University of Hull */
/* */
/**************************************************************************************************/
/* */
/* module : field/adapter_multi.inl */
/* project : */
/* description: */
/* */
/**************************************************************************************************/
#if !defined(UKACHULLDCS_08961_FIELD_ADAPTER_MULTI_INL)
#define UKACHULLDCS_08961_FIELD_ADAPTER_MULTI_INL
// includes, system
#include <ostream> // std::ostream
// includes, project
#include <support/io_utils.hpp>
#define UKACHULLDCS_USE_TRACE
#undef UKACHULLDCS_USE_TRACE
#include <support/trace.hpp>
#if defined(UKACHULLDCS_USE_TRACE) || defined(UKACHULLDCS_ALL_TRACE)
# include <typeinfo>
# include <support/type_info.hpp>
#endif
namespace field {
namespace adapter {
// functions, inlined (inline)
template <typename T, typename C>
inline /* explicit */
multi<T,C>::multi(container_type& a, std::string const& b,
get_callback_type c, set_callback_type d,
add_callback_type e, sub_callback_type f,
value_container_type const& g)
: base(a, b), get_value_(c), set_value_(d), add_value_(e), sub_value_(f)
{
TRACE("field::adapter::multi<" + support::demangle(typeid(T)) + "," +
support::demangle(typeid(C)) + ">::multi(value_container_type)");
set_value_(g);
}
template <typename T, typename C>
inline /* explicit */
multi<T,C>::multi(container_type& a, std::string const& b,
get_callback_type c, set_callback_type d,
add_callback_type e, sub_callback_type f,
std::initializer_list<value_type> g)
: base(a, b), get_value_(c), set_value_(d), add_value_(e), sub_value_(f)
{
TRACE("field::adapter::multi<" + support::demangle(typeid(T)) + "," +
support::demangle(typeid(C)) + ">::multi(std::initializer_list<" +
support::demangle(typeid(T)) + ">)");
set_value_(g);
}
template <typename T, typename C>
inline /* virtual */
multi<T,C>::~multi()
{
TRACE("field::adapter::multi<" + support::demangle(typeid(T)) + "," +
support::demangle(typeid(C)) + ">::~multi");
}
template <typename T, typename C>
inline /* virtual */ void
multi<T,C>::print_on(std::ostream& os) const
{
TRACE_NEVER("field::adapter::multi<" + support::demangle(typeid(T)) + "," +
support::demangle(typeid(C)) + ">::print_on");
os << '[';
base::print_on(os);
using support::ostream::operator<<;
os << ',' << get_value_() << "]";
}
template <typename T, typename C>
inline typename multi<T,C>::value_container_type const&
multi<T,C>::get() const
{
TRACE("field::adapter::multi<" + support::demangle(typeid(T)) + "," +
support::demangle(typeid(C)) + ">::get");
return get_value_();
}
template <typename T, typename C>
inline typename multi<T,C>::value_container_type
multi<T,C>::set(value_container_type const& a)
{
TRACE("field::adapter::multi<" + support::demangle(typeid(T)) + "," +
support::demangle(typeid(C)) + ">::set(value_container_type)");
value_container_type const result(set_value_(a));
changed();
return result;
}
template <typename T, typename C>
inline typename multi<T,C>::value_container_type
multi<T,C>::set(std::initializer_list<value_type> a)
{
TRACE("field::adapter::multi<" + support::demangle(typeid(T)) + "," +
support::demangle(typeid(C)) + ">::set(std::initializer_list<" +
support::demangle(typeid(T)) + ">)");
value_container_type const result(set_value_(a));
changed();
return result;
}
template <typename T, typename C>
inline bool
multi<T,C>::add(value_type const& a)
{
TRACE("field::adapter::multi<" + support::demangle(typeid(T)) + "," +
support::demangle(typeid(C)) + ">::add");
bool const result(add_value_(a));
if (result) {
changed();
}
return result;
}
template <typename T, typename C>
inline bool
multi<T,C>::sub(value_type const& a)
{
TRACE("field::adapter::multi<" + support::demangle(typeid(T)) + "," +
support::demangle(typeid(C)) + ">::sub");
bool const result(sub_value_(a));
if (result) {
changed();
}
return result;
}
template <typename T, typename C>
inline multi<T,C>::operator multi<T,C>::value_container_type const& () const
{
TRACE("field::adapter::multi<" + support::demangle(typeid(T)) + "," +
support::demangle(typeid(C)) + ">::operator " +
"value_container_type const&");
return get();
}
template <typename T, typename C>
inline multi<T,C>&
multi<T,C>::operator=(value_container_type const& a)
{
TRACE("field::adapter::multi<" + support::demangle(typeid(T)) + "," +
support::demangle(typeid(C)) + ">::operator=" +
"(value_container_type const&)");
set(a);
return *this;
}
template <typename T, typename C>
inline multi<T,C>&
multi<T,C>::operator=(std::initializer_list<value_type> a)
{
TRACE("field::adapter::multi<" + support::demangle(typeid(T)) + "," +
support::demangle(typeid(C)) + ">::operator=" +
"(std::initializer_list<value_type>)");
set(a);
return *this;
}
template <typename T, typename C>
inline multi<T,C>&
multi<T,C>::operator+=(value_type const& a)
{
TRACE("field::adapter::multi<" + support::demangle(typeid(T)) + "," +
support::demangle(typeid(C)) + ">::operator+=");
add(a);
return *this;
}
template <typename T, typename C>
inline multi<T,C>&
multi<T,C>::operator-=(value_type const& a)
{
TRACE("field::adapter::multi<" + support::demangle(typeid(T)) + "," +
support::demangle(typeid(C)) + ">::operator-=");
sub(a);
return *this;
}
} // namespace adapter {
} // namespace field {
#if defined(UKACHULLDCS_USE_TRACE)
# undef UKACHULLDCS_USE_TRACE
#endif
#endif // #if !defined(UKACHULLDCS_08961_FIELD_ADAPTER_MULTI_INL)
<|endoftext|> |
<commit_before>#include <math.h>
#include <stdlib.h>
#include <string>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/legacy/compat.hpp>
#include "dlib/opencv.h"
#include "dlib/image_processing/frontal_face_detector.h"
#include "dlib/image_processing/render_face_detections.h"
#include "dlib/gui_widgets.h"
void compute_eye_gaze (FacePose* face_pose, dlib::full_object_detection shape, cv::Point pupil, double mag_CP, double mag_LR) {
std::vector<double> vec_LR_u(3), vec_RP(3), vec_CR_u(3), vec_CM_u(3), vec_UD_u(3);
cv::Point p1, p2;
double Y1, Y2, H;
//mode : 0 for left eye, 1 for right eye
if(mode == 0) {
p1 = cv::Point(shape.part(42).x(), shape.part(42).y());
p2 = cv::Point(shape.part(45).x(), shape.part(45).y());
}
else if(mode == 1) {
p1 = cv::Point(shape.part(36).x(), shape.part(36).y());
p2 = cv::Point(shape.part(39).x(), shape.part(39).y());
}
compute_vec_LR(p1, p2, vec_LR_u);
make_unit_vector(vec_LR_u, vec_LR_u);
vec_CM_u[0] = face_pose->normal[0];
vec_CM_u[1] = face_pose->normal[1];
vec_CM_u[2] = face_pose->normal[2];
cross_product(vec_CM_u, vec_LR_u, vec_UD_u);
make_unit_vector(vec_UD_u, vec_UD_u);
solve_CR(vec_UD_u, vec_CM_u, vec_CR_u);
make_unit_vector(vec_CR_u, vec_CR_u);
get_section(p1, p2, pupil, Y1, Y2);
//Vector RP is in real world coordinates
compute_vec_RP(vec_LR_u, mag_LR, vec_RP, Y1, Y2, H);
}
void compute_vec_LR (cv::Point p1, cv::Point p2, FacePose* face_pose, std::vector<double>& LR) {
LR[0] = p1.x - p2.x;
LR[1] = p1.y - p2.y;
LR[2] = -(LR[0]*face_pose->normal[0] + LR[1]*face_pose->normal[1])/face_pose->normal[3];
}
void cross_product(std::vector<double> vec1, std::vector<double> vec2, std::vector<double> product) {
product[0] = vec1[1]*vec2[2] - vec1[2]*vec2[1];
product[1] = vec1[2]*vec2[0] - vec1[0]*vec2[2];
product[2] = vec1[0]*vec2[1] - vec1[1]*vec2[0];
}
void solve_CR(std::vector<double> coeff_1, double const_1, std::vector<double> coeff_2, double const_2, std::vector<double> vec_CR_u) {
vec_CR_u[0] =
}
void get_section(cv::Point p1, cv::Point p2, cv::Point pupil, double& Y1, double& Y2, double& h) {
}
void compute_vec_RP(std::vector<double> vec_LR_u, double mag_LR, std::vector<double> vec_RP, double Y1, double Y2) {
}<commit_msg>minor change<commit_after>#include <math.h>
#include <stdlib.h>
#include <string>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/legacy/compat.hpp>
#include "dlib/opencv.h"
#include "dlib/image_processing/frontal_face_detector.h"
#include "dlib/image_processing/render_face_detections.h"
#include "dlib/gui_widgets.h"
void compute_eye_gaze (FacePose* face_pose, dlib::full_object_detection shape, cv::Point pupil, double mag_CP, double mag_LR) {
std::vector<double> vec_LR_u(3), vec_RP(3), vec_CR_u(3), vec_CM_u(3), vec_UD_u(3);
cv::Point p1, p2;
double Y1, Y2, H;
//mode : 0 for left eye, 1 for right eye
if(mode == 0) {
p1 = cv::Point(shape.part(42).x(), shape.part(42).y());
p2 = cv::Point(shape.part(45).x(), shape.part(45).y());
}
else if(mode == 1) {
p1 = cv::Point(shape.part(36).x(), shape.part(36).y());
p2 = cv::Point(shape.part(39).x(), shape.part(39).y());
}
compute_vec_LR(p1, p2, vec_LR_u);
make_unit_vector(vec_LR_u, vec_LR_u);
vec_CM_u[0] = face_pose->normal[0];
vec_CM_u[1] = face_pose->normal[1];
vec_CM_u[2] = face_pose->normal[2];
cross_product(vec_CM_u, vec_LR_u, vec_UD_u);
make_unit_vector(vec_UD_u, vec_UD_u);
solve_CR(vec_UD_u, vec_CM_u, vec_CR_u);
make_unit_vector(vec_CR_u, vec_CR_u);
get_section(p1, p2, pupil, Y1, Y2, H);
//Vector RP is in real world coordinates
compute_vec_RP(vec_LR_u, mag_LR, vec_RP, Y1, Y2, H);
}
void compute_vec_LR (cv::Point p1, cv::Point p2, FacePose* face_pose, std::vector<double>& LR) {
LR[0] = p1.x - p2.x;
LR[1] = p1.y - p2.y;
LR[2] = -(LR[0]*face_pose->normal[0] + LR[1]*face_pose->normal[1])/face_pose->normal[3];
}
void cross_product(std::vector<double> vec1, std::vector<double> vec2, std::vector<double> product) {
product[0] = vec1[1]*vec2[2] - vec1[2]*vec2[1];
product[1] = vec1[2]*vec2[0] - vec1[0]*vec2[2];
product[2] = vec1[0]*vec2[1] - vec1[1]*vec2[0];
}
void solve_CR(std::vector<double> coeff_1, double const_1, std::vector<double> coeff_2, double const_2, std::vector<double> vec_CR_u) {
vec_CR_u[0] =
}
void get_section(cv::Point p1, cv::Point p2, cv::Point pupil, double& Y1, double& Y2, double& h) {
}
void compute_vec_RP(std::vector<double> vec_LR_u, double mag_LR, std::vector<double> vec_RP, double Y1, double Y2, double H) {
}<|endoftext|> |
<commit_before>/*
* This file is part of the SSH Library
*
* Copyright (c) 2010 by Aris Adamantiadis
*
* The SSH 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.
*
* The SSH 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 the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
#ifndef LIBSSHPP_HPP_
#define LIBSSHPP_HPP_
/** @defgroup ssh_cpp libssh C++ wrapper
* @addtogroup ssh_cpp
* @{
*/
#include <libssh/libssh.h>
namespace ssh {
class Session {
public:
Session(){
session=ssh_new();
}
~Session(){
ssh_free(session);
session=NULL;
}
void setOption(enum ssh_options_e type, const char *option){
ssh_options_set(session,type,option);
}
void setOption(enum ssh_options_e type, long int option){
ssh_options_set(session,type,&option);
}
void setOption(enum ssh_options_e type, void *option){
ssh_options_set(session,type,option);
}
int connect(){
return ssh_connect(session);
}
int userauthAutopubkey(){
return ssh_userauth_autopubkey(session,NULL);
}
private:
ssh_session session;
};
}
/** @}
*/
#endif /* LIBSSHPP_HPP_ */
<commit_msg>Update c++ prototypes<commit_after>/*
* This file is part of the SSH Library
*
* Copyright (c) 2010 by Aris Adamantiadis
*
* The SSH 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.
*
* The SSH 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 the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
#ifndef LIBSSHPP_HPP_
#define LIBSSHPP_HPP_
/** @defgroup ssh_cpp libssh C++ wrapper
* @addtogroup ssh_cpp
* @{
*/
#include <libssh/libssh.h>
namespace ssh {
class Session {
public:
Session(){
session=ssh_new();
}
~Session(){
ssh_free(session);
session=NULL;
}
void setOption(enum ssh_options_e type, const char *option){
ssh_options_set(session,type,option);
}
void setOption(enum ssh_options_e type, long int option){
ssh_options_set(session,type,&option);
}
void setOption(enum ssh_options_e type, void *option){
ssh_options_set(session,type,option);
}
int connect(){
return ssh_connect(session);
}
int userauthAutopubkey(){
return ssh_userauth_autopubkey(session,NULL);
}
int getAuthList();
int disconnect();
const char *getDisconnectMessage();
const char *getError();
int getErrorCode();
socket_t getSocket();
const char *getIssueBanner();
int getOpensshVersion();
int getVersion();
int isServerKnown();
private:
ssh_session session;
};
}
/** @}
*/
#endif /* LIBSSHPP_HPP_ */
<|endoftext|> |
<commit_before>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_TIME_HPP_INCLUDED
#define TORRENT_TIME_HPP_INCLUDED
#include <ctime>
#ifndef _WIN32
#include <unistd.h>
#endif
namespace libtorrent
{
inline char const* time_now_string()
{
time_t t = std::time(0);
return std::ctime(&t);
}
}
#if (!defined (__MACH__) && !defined (_WIN32) && !defined(_POSIX_MONOTONIC_CLOCK) || _POSIX_MONOTONIC_CLOCK < 0) || defined (TORRENT_USE_BOOST_DATE_TIME)
#include <boost/date_time/posix_time/posix_time_types.hpp>
namespace libtorrent
{
typedef boost::posix_time::ptime ptime;
typedef boost::posix_time::time_duration time_duration;
inline ptime time_now()
{ return boost::posix_time::microsec_clock::universal_time(); }
inline ptime min_time()
{ return boost::posix_time::ptime(boost::posix_time::min_date_time); }
inline ptime max_time()
{ return boost::posix_time::ptime(boost::posix_time::max_date_time); }
inline time_duration seconds(int s) { return boost::posix_time::seconds(s); }
inline time_duration milliseconds(int s) { return boost::posix_time::milliseconds(s); }
inline time_duration microsec(int s) { return boost::posix_time::microsec(s); }
inline time_duration minutes(int s) { return boost::posix_time::minutes(s); }
inline time_duration hours(int s) { return boost::posix_time::hours(s); }
inline int total_seconds(time_duration td)
{ return td.total_seconds(); }
inline int total_milliseconds(time_duration td)
{ return td.total_milliseconds(); }
inline boost::int64_t total_microseconds(time_duration td)
{ return td.total_microseconds(); }
}
#else
#include <asio/time_traits.hpp>
#include <boost/cstdint.hpp>
namespace libtorrent
{
// libtorrent time_duration type
struct time_duration
{
time_duration() {}
explicit time_duration(boost::int64_t d) : diff(d) {}
boost::int64_t diff;
};
inline bool is_negative(time_duration dt) { return dt.diff < 0; }
inline bool operator<(time_duration lhs, time_duration rhs)
{ return lhs.diff < rhs.diff; }
inline bool operator>(time_duration lhs, time_duration rhs)
{ return lhs.diff > rhs.diff; }
// libtorrent time type
struct ptime
{
ptime() {}
explicit ptime(boost::int64_t t): time(t) {}
boost::int64_t time;
};
inline bool operator>(ptime lhs, ptime rhs)
{ return lhs.time > rhs.time; }
inline bool operator>=(ptime lhs, ptime rhs)
{ return lhs.time >= rhs.time; }
inline bool operator<=(ptime lhs, ptime rhs)
{ return lhs.time <= rhs.time; }
inline bool operator<(ptime lhs, ptime rhs)
{ return lhs.time < rhs.time; }
inline bool operator!=(ptime lhs, ptime rhs)
{ return lhs.time != rhs.time;}
inline bool operator==(ptime lhs, ptime rhs)
{ return lhs.time == rhs.time;}
inline time_duration operator-(ptime lhs, ptime rhs)
{ return time_duration(lhs.time - rhs.time); }
inline ptime operator+(ptime lhs, time_duration rhs)
{ return ptime(lhs.time + rhs.diff); }
inline ptime operator+(time_duration lhs, ptime rhs)
{ return ptime(rhs.time + lhs.diff); }
inline ptime operator-(ptime lhs, time_duration rhs)
{ return ptime(lhs.time - rhs.diff); }
ptime time_now();
inline ptime min_time() { return ptime(0); }
inline ptime max_time() { return ptime((std::numeric_limits<boost::int64_t>::max)()); }
int total_seconds(time_duration td);
int total_milliseconds(time_duration td);
boost::int64_t total_microseconds(time_duration td);
}
// asio time_traits
namespace asio
{
template<>
struct time_traits<libtorrent::ptime>
{
typedef libtorrent::ptime time_type;
typedef libtorrent::time_duration duration_type;
static time_type now()
{ return time_type(libtorrent::time_now()); }
static time_type add(time_type t, duration_type d)
{ return time_type(t.time + d.diff);}
static duration_type subtract(time_type t1, time_type t2)
{ return duration_type(t1 - t2); }
static bool less_than(time_type t1, time_type t2)
{ return t1 < t2; }
static boost::posix_time::time_duration to_posix_duration(
duration_type d)
{ return boost::posix_time::microseconds(libtorrent::total_microseconds(d)); }
};
}
#if defined(__MACH__)
#include <mach/mach_time.h>
#include <boost/cstdint.hpp>
// high precision timer for darwin intel and ppc
namespace libtorrent
{
namespace aux
{
inline boost::int64_t absolutetime_to_microseconds(boost::int64_t at)
{
static mach_timebase_info_data_t timebase_info = {0,0};
if (timebase_info.denom == 0)
mach_timebase_info(&timebase_info);
// make sure we don't overflow
assert((at >= 0 && at >= at / 1000 * timebase_info.numer / timebase_info.denom)
|| (at < 0 && at < at / 1000 * timebase_info.numer / timebase_info.denom));
return at / 1000 * timebase_info.numer / timebase_info.denom;
}
inline boost::int64_t microseconds_to_absolutetime(boost::int64_t ms)
{
static mach_timebase_info_data_t timebase_info = {0,0};
if (timebase_info.denom == 0)
{
mach_timebase_info(&timebase_info);
assert(timebase_info.numer > 0);
assert(timebase_info.denom > 0);
}
// make sure we don't overflow
assert((ms >= 0 && ms <= ms * timebase_info.denom / timebase_info.numer * 1000)
|| (ms < 0 && ms > ms * timebase_info.denom / timebase_info.numer * 1000));
return ms * timebase_info.denom / timebase_info.numer * 1000;
}
}
inline int total_seconds(time_duration td)
{
return aux::absolutetime_to_microseconds(td.diff)
/ 1000000;
}
inline int total_milliseconds(time_duration td)
{
return aux::absolutetime_to_microseconds(td.diff)
/ 1000;
}
inline boost::int64_t total_microseconds(time_duration td)
{
return aux::absolutetime_to_microseconds(td.diff);
}
inline ptime time_now() { return ptime(mach_absolute_time()); }
inline time_duration microsec(boost::int64_t s)
{
return time_duration(aux::microseconds_to_absolutetime(s));
}
inline time_duration milliseconds(boost::int64_t s)
{
return time_duration(aux::microseconds_to_absolutetime(s * 1000));
}
inline time_duration seconds(boost::int64_t s)
{
return time_duration(aux::microseconds_to_absolutetime(s * 1000000));
}
inline time_duration minutes(boost::int64_t s)
{
return time_duration(aux::microseconds_to_absolutetime(s * 1000000 * 60));
}
inline time_duration hours(boost::int64_t s)
{
return time_duration(aux::microseconds_to_absolutetime(s * 1000000 * 60 * 60));
}
}
#elif defined(_WIN32)
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <Windows.h>
namespace libtorrent
{
namespace aux
{
inline boost::int64_t performance_counter_to_microseconds(boost::int64_t pc)
{
static LARGE_INTEGER performace_counter_frequency = {0,0};
if (performace_counter_frequency.QuadPart == 0)
QueryPerformanceFrequency(&performace_counter_frequency);
return pc * 1000000 / performace_counter_frequency.QuadPart;
}
inline boost::int64_t microseconds_to_performance_counter(boost::int64_t ms)
{
static LARGE_INTEGER performace_counter_frequency = {0,0};
if (performace_counter_frequency.QuadPart == 0)
QueryPerformanceFrequency(&performace_counter_frequency);
return ms * performace_counter_frequency.QuadPart / 1000000;
}
}
inline int total_seconds(time_duration td)
{
return aux::performance_counter_to_microseconds(td.diff)
/ 1000000;
}
inline int total_milliseconds(time_duration td)
{
return aux::performance_counter_to_microseconds(td.diff)
/ 1000;
}
inline boost::int64_t total_microseconds(time_duration td)
{
return aux::performance_counter_to_microseconds(td.diff);
}
inline ptime time_now()
{
LARGE_INTEGER now;
QueryPerformanceCounter(&now);
return ptime(now.QuadPart);
}
inline time_duration microsec(boost::int64_t s)
{
return time_duration(aux::microseconds_to_performance_counter(s));
}
inline time_duration milliseconds(boost::int64_t s)
{
return time_duration(aux::microseconds_to_performance_counter(
s * 1000));
}
inline time_duration seconds(boost::int64_t s)
{
return time_duration(aux::microseconds_to_performance_counter(
s * 1000000));
}
inline time_duration minutes(boost::int64_t s)
{
return time_duration(aux::microseconds_to_performance_counter(
s * 1000000 * 60));
}
inline time_duration hours(boost::int64_t s)
{
return time_duration(aux::microseconds_to_performance_counter(
s * 1000000 * 60 * 60));
}
}
#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0
#include <time.h>
namespace libtorrent
{
inline int total_seconds(time_duration td)
{
return td.diff / 1000000;
}
inline int total_milliseconds(time_duration td)
{
return td.diff / 1000;
}
inline boost::int64_t total_microseconds(time_duration td)
{
return td.diff;
}
inline ptime time_now()
{
timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return ptime(boost::int64_t(ts.tv_sec) * 1000000 + ts.tv_nsec / 1000);
}
inline time_duration microsec(boost::int64_t s)
{
return time_duration(s);
}
inline time_duration milliseconds(boost::int64_t s)
{
return time_duration(s * 1000);
}
inline time_duration seconds(boost::int64_t s)
{
return time_duration(s * 1000000);
}
inline time_duration minutes(boost::int64_t s)
{
return time_duration(s * 1000000 * 60);
}
inline time_duration hours(boost::int64_t s)
{
return time_duration(s * 1000000 * 60 * 60);
}
}
#endif
#endif
#endif
<commit_msg>fixed time_now_string() to not include a line feed at the end<commit_after>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_TIME_HPP_INCLUDED
#define TORRENT_TIME_HPP_INCLUDED
#include <ctime>
#ifndef _WIN32
#include <unistd.h>
#endif
namespace libtorrent
{
inline char const* time_now_string()
{
time_t t = std::time(0);
tm* timeinfo = std::localtime(&t);
static char str[200];
std::strftime(str, 200, "%b %d %X", timeinfo);
return str;
}
}
#if (!defined (__MACH__) && !defined (_WIN32) && !defined(_POSIX_MONOTONIC_CLOCK) || _POSIX_MONOTONIC_CLOCK < 0) || defined (TORRENT_USE_BOOST_DATE_TIME)
#include <boost/date_time/posix_time/posix_time_types.hpp>
namespace libtorrent
{
typedef boost::posix_time::ptime ptime;
typedef boost::posix_time::time_duration time_duration;
inline ptime time_now()
{ return boost::posix_time::microsec_clock::universal_time(); }
inline ptime min_time()
{ return boost::posix_time::ptime(boost::posix_time::min_date_time); }
inline ptime max_time()
{ return boost::posix_time::ptime(boost::posix_time::max_date_time); }
inline time_duration seconds(int s) { return boost::posix_time::seconds(s); }
inline time_duration milliseconds(int s) { return boost::posix_time::milliseconds(s); }
inline time_duration microsec(int s) { return boost::posix_time::microsec(s); }
inline time_duration minutes(int s) { return boost::posix_time::minutes(s); }
inline time_duration hours(int s) { return boost::posix_time::hours(s); }
inline int total_seconds(time_duration td)
{ return td.total_seconds(); }
inline int total_milliseconds(time_duration td)
{ return td.total_milliseconds(); }
inline boost::int64_t total_microseconds(time_duration td)
{ return td.total_microseconds(); }
}
#else
#include <asio/time_traits.hpp>
#include <boost/cstdint.hpp>
namespace libtorrent
{
// libtorrent time_duration type
struct time_duration
{
time_duration() {}
explicit time_duration(boost::int64_t d) : diff(d) {}
boost::int64_t diff;
};
inline bool is_negative(time_duration dt) { return dt.diff < 0; }
inline bool operator<(time_duration lhs, time_duration rhs)
{ return lhs.diff < rhs.diff; }
inline bool operator>(time_duration lhs, time_duration rhs)
{ return lhs.diff > rhs.diff; }
// libtorrent time type
struct ptime
{
ptime() {}
explicit ptime(boost::int64_t t): time(t) {}
boost::int64_t time;
};
inline bool operator>(ptime lhs, ptime rhs)
{ return lhs.time > rhs.time; }
inline bool operator>=(ptime lhs, ptime rhs)
{ return lhs.time >= rhs.time; }
inline bool operator<=(ptime lhs, ptime rhs)
{ return lhs.time <= rhs.time; }
inline bool operator<(ptime lhs, ptime rhs)
{ return lhs.time < rhs.time; }
inline bool operator!=(ptime lhs, ptime rhs)
{ return lhs.time != rhs.time;}
inline bool operator==(ptime lhs, ptime rhs)
{ return lhs.time == rhs.time;}
inline time_duration operator-(ptime lhs, ptime rhs)
{ return time_duration(lhs.time - rhs.time); }
inline ptime operator+(ptime lhs, time_duration rhs)
{ return ptime(lhs.time + rhs.diff); }
inline ptime operator+(time_duration lhs, ptime rhs)
{ return ptime(rhs.time + lhs.diff); }
inline ptime operator-(ptime lhs, time_duration rhs)
{ return ptime(lhs.time - rhs.diff); }
ptime time_now();
inline ptime min_time() { return ptime(0); }
inline ptime max_time() { return ptime((std::numeric_limits<boost::int64_t>::max)()); }
int total_seconds(time_duration td);
int total_milliseconds(time_duration td);
boost::int64_t total_microseconds(time_duration td);
}
// asio time_traits
namespace asio
{
template<>
struct time_traits<libtorrent::ptime>
{
typedef libtorrent::ptime time_type;
typedef libtorrent::time_duration duration_type;
static time_type now()
{ return time_type(libtorrent::time_now()); }
static time_type add(time_type t, duration_type d)
{ return time_type(t.time + d.diff);}
static duration_type subtract(time_type t1, time_type t2)
{ return duration_type(t1 - t2); }
static bool less_than(time_type t1, time_type t2)
{ return t1 < t2; }
static boost::posix_time::time_duration to_posix_duration(
duration_type d)
{ return boost::posix_time::microseconds(libtorrent::total_microseconds(d)); }
};
}
#if defined(__MACH__)
#include <mach/mach_time.h>
#include <boost/cstdint.hpp>
// high precision timer for darwin intel and ppc
namespace libtorrent
{
namespace aux
{
inline boost::int64_t absolutetime_to_microseconds(boost::int64_t at)
{
static mach_timebase_info_data_t timebase_info = {0,0};
if (timebase_info.denom == 0)
mach_timebase_info(&timebase_info);
// make sure we don't overflow
assert((at >= 0 && at >= at / 1000 * timebase_info.numer / timebase_info.denom)
|| (at < 0 && at < at / 1000 * timebase_info.numer / timebase_info.denom));
return at / 1000 * timebase_info.numer / timebase_info.denom;
}
inline boost::int64_t microseconds_to_absolutetime(boost::int64_t ms)
{
static mach_timebase_info_data_t timebase_info = {0,0};
if (timebase_info.denom == 0)
{
mach_timebase_info(&timebase_info);
assert(timebase_info.numer > 0);
assert(timebase_info.denom > 0);
}
// make sure we don't overflow
assert((ms >= 0 && ms <= ms * timebase_info.denom / timebase_info.numer * 1000)
|| (ms < 0 && ms > ms * timebase_info.denom / timebase_info.numer * 1000));
return ms * timebase_info.denom / timebase_info.numer * 1000;
}
}
inline int total_seconds(time_duration td)
{
return aux::absolutetime_to_microseconds(td.diff)
/ 1000000;
}
inline int total_milliseconds(time_duration td)
{
return aux::absolutetime_to_microseconds(td.diff)
/ 1000;
}
inline boost::int64_t total_microseconds(time_duration td)
{
return aux::absolutetime_to_microseconds(td.diff);
}
inline ptime time_now() { return ptime(mach_absolute_time()); }
inline time_duration microsec(boost::int64_t s)
{
return time_duration(aux::microseconds_to_absolutetime(s));
}
inline time_duration milliseconds(boost::int64_t s)
{
return time_duration(aux::microseconds_to_absolutetime(s * 1000));
}
inline time_duration seconds(boost::int64_t s)
{
return time_duration(aux::microseconds_to_absolutetime(s * 1000000));
}
inline time_duration minutes(boost::int64_t s)
{
return time_duration(aux::microseconds_to_absolutetime(s * 1000000 * 60));
}
inline time_duration hours(boost::int64_t s)
{
return time_duration(aux::microseconds_to_absolutetime(s * 1000000 * 60 * 60));
}
}
#elif defined(_WIN32)
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <Windows.h>
namespace libtorrent
{
namespace aux
{
inline boost::int64_t performance_counter_to_microseconds(boost::int64_t pc)
{
static LARGE_INTEGER performace_counter_frequency = {0,0};
if (performace_counter_frequency.QuadPart == 0)
QueryPerformanceFrequency(&performace_counter_frequency);
return pc * 1000000 / performace_counter_frequency.QuadPart;
}
inline boost::int64_t microseconds_to_performance_counter(boost::int64_t ms)
{
static LARGE_INTEGER performace_counter_frequency = {0,0};
if (performace_counter_frequency.QuadPart == 0)
QueryPerformanceFrequency(&performace_counter_frequency);
return ms * performace_counter_frequency.QuadPart / 1000000;
}
}
inline int total_seconds(time_duration td)
{
return aux::performance_counter_to_microseconds(td.diff)
/ 1000000;
}
inline int total_milliseconds(time_duration td)
{
return aux::performance_counter_to_microseconds(td.diff)
/ 1000;
}
inline boost::int64_t total_microseconds(time_duration td)
{
return aux::performance_counter_to_microseconds(td.diff);
}
inline ptime time_now()
{
LARGE_INTEGER now;
QueryPerformanceCounter(&now);
return ptime(now.QuadPart);
}
inline time_duration microsec(boost::int64_t s)
{
return time_duration(aux::microseconds_to_performance_counter(s));
}
inline time_duration milliseconds(boost::int64_t s)
{
return time_duration(aux::microseconds_to_performance_counter(
s * 1000));
}
inline time_duration seconds(boost::int64_t s)
{
return time_duration(aux::microseconds_to_performance_counter(
s * 1000000));
}
inline time_duration minutes(boost::int64_t s)
{
return time_duration(aux::microseconds_to_performance_counter(
s * 1000000 * 60));
}
inline time_duration hours(boost::int64_t s)
{
return time_duration(aux::microseconds_to_performance_counter(
s * 1000000 * 60 * 60));
}
}
#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0
#include <time.h>
namespace libtorrent
{
inline int total_seconds(time_duration td)
{
return td.diff / 1000000;
}
inline int total_milliseconds(time_duration td)
{
return td.diff / 1000;
}
inline boost::int64_t total_microseconds(time_duration td)
{
return td.diff;
}
inline ptime time_now()
{
timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return ptime(boost::int64_t(ts.tv_sec) * 1000000 + ts.tv_nsec / 1000);
}
inline time_duration microsec(boost::int64_t s)
{
return time_duration(s);
}
inline time_duration milliseconds(boost::int64_t s)
{
return time_duration(s * 1000);
}
inline time_duration seconds(boost::int64_t s)
{
return time_duration(s * 1000000);
}
inline time_duration minutes(boost::int64_t s)
{
return time_duration(s * 1000000 * 60);
}
inline time_duration hours(boost::int64_t s)
{
return time_duration(s * 1000000 * 60 * 60);
}
}
#endif
#endif
#endif
<|endoftext|> |
<commit_before>/*
Copyright (C) 2004-2005 Cory Nelson
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
// namespaces added by Arvid Norberg
#ifndef __UTF8_H__
#define __UTF8_H__
#include <string>
#include <iterator>
#include <stdexcept>
namespace libtorrent {
namespace detail {
template<typename InputIterator>
wchar_t decode_utf8_mb(InputIterator &iter, InputIterator last)
{
if(iter==last) throw std::runtime_error("incomplete UTF-8 sequence");
if(((*iter)&0xC0)!=0x80) throw std::runtime_error("invalid UTF-8 sequence");
return (wchar_t)((*iter++)&0x3F);
}
template<typename InputIterator>
wchar_t decode_utf8(InputIterator &iter, InputIterator last)
{
wchar_t ret;
if(((*iter)&0x80) == 0) {
ret=*iter++;
}
else if(((*iter)&0x20) == 0) {
ret=(
(((wchar_t)((*iter++)&0x1F)) << 6) |
decode_utf8_mb(iter, last)
);
}
else if(((*iter)&0x10) == 0) {
ret=(
(((wchar_t)((*iter++)&0x0F)) << 12) |
(decode_utf8_mb(iter, last) << 6) |
decode_utf8_mb(iter, last)
);
}
else throw std::runtime_error("UTF-8 not convertable to UTF-16");
return ret;
}
template<typename InputIterator, typename OutputIterator>
OutputIterator utf8_wchar(InputIterator first, InputIterator last, OutputIterator dest)
{
for(; first!=last; ++dest)
*dest=decode_utf8(first, last);
return dest;
}
template<typename InputIterator, typename OutputIterator>
void encode_wchar(InputIterator iter, OutputIterator &dest)
{
if(*iter <= 0x007F)
{
*dest=(char)*iter;
++dest;
}
else if(*iter <= 0x07FF)
{
*dest = (char)(
0xC0 |
((*iter & 0x07C0) >> 6)
);
++dest;
*dest = (char)(
0x80 |
(*iter & 0x003F)
);
++dest;
}
else if(*iter <= 0xFFFF)
{
*dest = (char)(
0xE0 |
((*iter & 0xF000) >> 12)
);
++dest;
*dest = (char)(
0x80 |
((*iter & 0x0FC0) >> 6)
);
++dest;
*dest = (char)(
0x80 |
(*iter & 0x003F)
);
++dest;
}
}
template<typename InputIterator, typename OutputIterator>
OutputIterator wchar_utf8(InputIterator first, InputIterator last, OutputIterator dest)
{
for(; first!=last; ++first)
encode_wchar(first, dest);
return dest;
}
}
void utf8_wchar(const std::string &utf8, std::wstring &wide)
{
wide.clear();
detail::utf8_wchar(utf8.begin(), utf8.end(), std::insert_iterator<std::wstring>(wide, wide.end()));
}
std::wstring utf8_wchar(const std::string &str)
{
std::wstring ret;
utf8_wchar(str, ret);
return ret;
}
void wchar_utf8(const std::wstring &wide, std::string &utf8)
{
utf8.clear();
detail::wchar_utf8(wide.begin(), wide.end(), std::insert_iterator<std::string>(utf8, utf8.end()));
}
std::string wchar_utf8(const std::wstring &str)
{
std::string ret;
wchar_utf8(str, ret);
return ret;
}
}
#endif
<commit_msg>fixed non-inlined functions<commit_after>/*
Copyright (C) 2004-2005 Cory Nelson
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
// namespaces added by Arvid Norberg
#ifndef __UTF8_H__
#define __UTF8_H__
#include <string>
#include <iterator>
#include <stdexcept>
namespace libtorrent {
namespace detail {
template<typename InputIterator>
wchar_t decode_utf8_mb(InputIterator &iter, InputIterator last)
{
if(iter==last) throw std::runtime_error("incomplete UTF-8 sequence");
if(((*iter)&0xC0)!=0x80) throw std::runtime_error("invalid UTF-8 sequence");
return (wchar_t)((*iter++)&0x3F);
}
template<typename InputIterator>
wchar_t decode_utf8(InputIterator &iter, InputIterator last)
{
wchar_t ret;
if(((*iter)&0x80) == 0) {
ret=*iter++;
}
else if(((*iter)&0x20) == 0) {
ret=(
(((wchar_t)((*iter++)&0x1F)) << 6) |
decode_utf8_mb(iter, last)
);
}
else if(((*iter)&0x10) == 0) {
ret=(
(((wchar_t)((*iter++)&0x0F)) << 12) |
(decode_utf8_mb(iter, last) << 6) |
decode_utf8_mb(iter, last)
);
}
else throw std::runtime_error("UTF-8 not convertable to UTF-16");
return ret;
}
template<typename InputIterator, typename OutputIterator>
OutputIterator utf8_wchar(InputIterator first, InputIterator last, OutputIterator dest)
{
for(; first!=last; ++dest)
*dest=decode_utf8(first, last);
return dest;
}
template<typename InputIterator, typename OutputIterator>
void encode_wchar(InputIterator iter, OutputIterator &dest)
{
if(*iter <= 0x007F)
{
*dest=(char)*iter;
++dest;
}
else if(*iter <= 0x07FF)
{
*dest = (char)(
0xC0 |
((*iter & 0x07C0) >> 6)
);
++dest;
*dest = (char)(
0x80 |
(*iter & 0x003F)
);
++dest;
}
else if(*iter <= 0xFFFF)
{
*dest = (char)(
0xE0 |
((*iter & 0xF000) >> 12)
);
++dest;
*dest = (char)(
0x80 |
((*iter & 0x0FC0) >> 6)
);
++dest;
*dest = (char)(
0x80 |
(*iter & 0x003F)
);
++dest;
}
}
template<typename InputIterator, typename OutputIterator>
OutputIterator wchar_utf8(InputIterator first, InputIterator last, OutputIterator dest)
{
for(; first!=last; ++first)
encode_wchar(first, dest);
return dest;
}
}
inline void utf8_wchar(const std::string &utf8, std::wstring &wide)
{
wide.clear();
detail::utf8_wchar(utf8.begin(), utf8.end(), std::insert_iterator<std::wstring>(wide, wide.end()));
}
inline std::wstring utf8_wchar(const std::string &str)
{
std::wstring ret;
utf8_wchar(str, ret);
return ret;
}
inline void wchar_utf8(const std::wstring &wide, std::string &utf8)
{
utf8.clear();
detail::wchar_utf8(wide.begin(), wide.end(), std::insert_iterator<std::string>(utf8, utf8.end()));
}
inline std::string wchar_utf8(const std::wstring &str)
{
std::string ret;
wchar_utf8(str, ret);
return ret;
}
}
#endif
<|endoftext|> |
<commit_before>/*
===========================================================================
Daemon GPL Source Code
Copyright (C) 2012 Unvanquished Developers
This file is part of the Daemon GPL Source Code (Daemon Source Code).
Daemon Source Code 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.
Daemon Source Code 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 Daemon Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Daemon Source Code is also subject to certain additional terms.
You should have received a copy of these additional terms immediately following the
terms and conditions of the GNU General Public License which accompanied the Daemon
Source Code. If not, please request a copy in writing from id Software at the address
below.
If you have questions concerning this license or the applicable additional terms, you
may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville,
Maryland 20850 USA.
===========================================================================
*/
#include <Rocket/Core/Core.h>
extern "C"
{
#include "client.h"
}
struct HudUnit
{
HudUnit( Rocket::Core::ElementDocument *doc ) : unit( doc )
{
load = true;
}
Rocket::Core::ElementDocument *unit; // Element document that holds the unit
bool load; // Whether to load or not
};
typedef Rocket::Core::Container::list<HudUnit>::Type RocketHud;
RocketHud *activeHud = NULL;
Rocket::Core::Container::vector<RocketHud>::Type huds;
// Initialized to WP_NUM_WEAPONS, which may be different based on different mods
void Rocket_InitializeHuds( int size )
{
huds.clear();
for ( int i = 0; i < size; ++i )
{
huds.push_back( RocketHud() );
}
}
void Rocket_LoadUnit( const char *path )
{
Rocket::Core::ElementDocument *document = hudContext->LoadDocument( path );
Rocket::Core::ElementDocument* other;
if ( document )
{
document->Hide();
document->RemoveReference();
hudContext->PushDocumentToBack( document );
// Close any other documents which may have the same ID
other = menuContext->GetDocument( document->GetId() );
if ( other && other != document )
{
other->Close();
}
}
}
void Rocket_AddUnitToHud( int weapon, const char *id )
{
if ( id && *id )
{
Rocket::Core::ElementDocument *doc = hudContext->GetDocument( id );
if ( doc )
{
huds[ weapon ].push_back( HudUnit( doc ) );
}
}
}
// See if unit exists in a hud
static HudUnit *findUnit( RocketHud *in, HudUnit &find )
{
for ( RocketHud::iterator it = in->begin(); it != in->end(); ++it )
{
if ( it->unit == find.unit )
{
return &*it;
}
}
return NULL;
}
void Rocket_ShowHud( int weapon )
{
RocketHud *currentHud = &huds[ weapon ];
if ( activeHud )
{
for ( RocketHud::iterator it = activeHud->begin(); it != activeHud->end(); ++it )
{
HudUnit *unit;
// Check if the new HUD needs this unit
if ( ( unit = findUnit( currentHud, *it ) ) )
{
unit->load = false;
continue;
}
// Nope. Doesn't need it
it->unit->Hide();
}
}
for ( RocketHud::iterator it = currentHud->begin(); it != currentHud->end(); ++it )
{
if ( it->load )
{
it->unit->Show();
}
// No matter what, reset load status
it->load = true;
}
activeHud = currentHud;
}
void Rocket_ClearHud( int weapon )
{
if ( weapon < huds.size() )
{
huds[ weapon ].clear();
}
}
<commit_msg>Fix duplicate hud id loading and reloadhud.<commit_after>/*
===========================================================================
Daemon GPL Source Code
Copyright (C) 2012 Unvanquished Developers
This file is part of the Daemon GPL Source Code (Daemon Source Code).
Daemon Source Code 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.
Daemon Source Code 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 Daemon Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Daemon Source Code is also subject to certain additional terms.
You should have received a copy of these additional terms immediately following the
terms and conditions of the GNU General Public License which accompanied the Daemon
Source Code. If not, please request a copy in writing from id Software at the address
below.
If you have questions concerning this license or the applicable additional terms, you
may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville,
Maryland 20850 USA.
===========================================================================
*/
#include <Rocket/Core/Core.h>
extern "C"
{
#include "client.h"
}
struct HudUnit
{
HudUnit( Rocket::Core::ElementDocument *doc ) : unit( doc )
{
load = true;
}
Rocket::Core::ElementDocument *unit; // Element document that holds the unit
bool load; // Whether to load or not
};
typedef Rocket::Core::Container::list<HudUnit>::Type RocketHud;
RocketHud *activeHud = NULL;
Rocket::Core::Container::vector<RocketHud>::Type huds;
// Initialized to WP_NUM_WEAPONS, which may be different based on different mods
void Rocket_InitializeHuds( int size )
{
huds.clear();
for ( int i = 0; i < size; ++i )
{
huds.push_back( RocketHud() );
}
activeHud = NULL;
}
void Rocket_LoadUnit( const char *path )
{
Rocket::Core::ElementDocument *document = hudContext->LoadDocument( path );
Rocket::Core::ElementDocument* other;
if ( document )
{
document->Hide();
document->RemoveReference();
hudContext->PullDocumentToFront( document );
// Close any other documents which may have the same ID
other = hudContext->GetDocument( document->GetId() );
if ( other && other != document )
{
other->Close();
}
}
}
void Rocket_AddUnitToHud( int weapon, const char *id )
{
if ( id && *id )
{
Rocket::Core::ElementDocument *doc = hudContext->GetDocument( id );
if ( doc )
{
huds[ weapon ].push_back( HudUnit( doc ) );
}
}
}
// See if unit exists in a hud
static HudUnit *findUnit( RocketHud *in, HudUnit &find )
{
for ( RocketHud::iterator it = in->begin(); it != in->end(); ++it )
{
if ( it->unit == find.unit )
{
return &*it;
}
}
return NULL;
}
void Rocket_ShowHud( int weapon )
{
RocketHud *currentHud = &huds[ weapon ];
if ( activeHud )
{
for ( RocketHud::iterator it = activeHud->begin(); it != activeHud->end(); ++it )
{
HudUnit *unit;
// Check if the new HUD needs this unit
if ( ( unit = findUnit( currentHud, *it ) ) )
{
unit->load = false;
continue;
}
// Nope. Doesn't need it
it->unit->Hide();
}
}
for ( RocketHud::iterator it = currentHud->begin(); it != currentHud->end(); ++it )
{
if ( it->load )
{
it->unit->Show();
}
// No matter what, reset load status
it->load = true;
}
activeHud = currentHud;
}
void Rocket_ClearHud( int weapon )
{
if ( weapon < huds.size() )
{
huds[ weapon ].clear();
}
}
<|endoftext|> |
<commit_before><commit_msg>fixed linux build<commit_after><|endoftext|> |
<commit_before>#include "common.h"
#include "eventdispatcher_libevent.h"
#include "eventdispatcher_libevent_p.h"
EventDispatcherLibEvent::EventDispatcherLibEvent(QObject* parent)
: QAbstractEventDispatcher(parent), d_ptr(new EventDispatcherLibEventPrivate(this))
{
}
EventDispatcherLibEvent::EventDispatcherLibEvent(const EventDispatcherLibEventConfig& config, QObject* parent)
: QAbstractEventDispatcher(parent), d_ptr(new EventDispatcherLibEventPrivate(this, config))
{
}
EventDispatcherLibEvent::~EventDispatcherLibEvent(void)
{
#if QT_VERSION < 0x040600
delete this->d_ptr;
this->d_ptr = 0;
#endif
}
bool EventDispatcherLibEvent::processEvents(QEventLoop::ProcessEventsFlags flags)
{
Q_D(EventDispatcherLibEvent);
return d->processEvents(flags);
}
bool EventDispatcherLibEvent::hasPendingEvents(void)
{
extern uint qGlobalPostedEventsCount();
return qGlobalPostedEventsCount() > 0;
}
void EventDispatcherLibEvent::registerSocketNotifier(QSocketNotifier* notifier)
{
#ifndef QT_NO_DEBUG
if (notifier->socket() < 0) {
qWarning("QSocketNotifier: Internal error: sockfd < 0");
return;
}
if (notifier->thread() != thread() || thread() != QThread::currentThread()) {
qWarning("QSocketNotifier: socket notifiers cannot be enabled from another thread");
return;
}
#endif
if (notifier->type() == QSocketNotifier::Exception) {
return;
}
Q_D(EventDispatcherLibEvent);
d->registerSocketNotifier(notifier);
}
void EventDispatcherLibEvent::unregisterSocketNotifier(QSocketNotifier* notifier)
{
#ifndef QT_NO_DEBUG
if (notifier->socket() < 0) {
qWarning("QSocketNotifier: Internal error: sockfd < 0");
return;
}
if (notifier->thread() != thread() || thread() != QThread::currentThread()) {
qWarning("QSocketNotifier: socket notifiers cannot be disabled from another thread");
return;
}
#endif
// Short circuit, we do not support QSocketNotifier::Exception
if (notifier->type() == QSocketNotifier::Exception) {
return;
}
Q_D(EventDispatcherLibEvent);
d->unregisterSocketNotifier(notifier);
}
void EventDispatcherLibEvent::registerTimer(
int timerId,
int interval,
#if QT_VERSION >= 0x050000
Qt::TimerType timerType,
#endif
QObject* object
)
{
#ifndef QT_NO_DEBUG
if (timerId < 1 || interval < 0 || !object) {
qWarning("%s: invalid arguments", Q_FUNC_INFO);
return;
}
if (object->thread() != this->thread() && this->thread() != QThread::currentThread()) {
qWarning("%s: timers cannot be started from another thread", Q_FUNC_INFO);
return;
}
#endif
Qt::TimerType type;
#if QT_VERSION >= 0x050000
type = timerType;
#else
type = Qt::CoarseTimer;
#endif
Q_D(EventDispatcherLibEvent);
d->registerTimer(timerId, interval, type, object);
}
bool EventDispatcherLibEvent::unregisterTimer(int timerId)
{
#ifndef QT_NO_DEBUG
if (timerId < 1) {
qWarning("%s: invalid arguments", Q_FUNC_INFO);
return false;
}
if (this->thread() != QThread::currentThread()) {
qWarning("%s: timers cannot be stopped from another thread", Q_FUNC_INFO);
return false;
}
#endif
Q_D(EventDispatcherLibEvent);
return d->unregisterTimer(timerId);
}
bool EventDispatcherLibEvent::unregisterTimers(QObject* object)
{
#ifndef QT_NO_DEBUG
if (!object) {
qWarning("%s: invalid arguments", Q_FUNC_INFO);
return false;
}
if (object->thread() != this->thread() && this->thread() != QThread::currentThread()) {
qWarning("%s: timers cannot be stopped from another thread", Q_FUNC_INFO);
return false;
}
#endif
Q_D(EventDispatcherLibEvent);
return d->unregisterTimers(object);
}
QList<QAbstractEventDispatcher::TimerInfo> EventDispatcherLibEvent::registeredTimers(QObject* object) const
{
if (!object) {
qWarning("%s: invalid argument", Q_FUNC_INFO);
return QList<QAbstractEventDispatcher::TimerInfo>();
}
Q_D(const EventDispatcherLibEvent);
return d->registeredTimers(object);
}
#if QT_VERSION >= 0x050000
int EventDispatcherLibEvent::remainingTime(int timerId)
{
Q_D(const EventDispatcherLibEvent);
return d->remainingTime(timerId);
}
#endif
#if defined(Q_OS_WIN) && QT_VERSION >= 0x050000
bool EventDispatcherLibEvent::registerEventNotifier(QWinEventNotifier* notifier)
{
Q_UNUSED(notifier)
Q_UNIMPLEMENTED();
return false;
}
void EventDispatcherLibEvent::unregisterEventNotifier(QWinEventNotifier* notifier)
{
Q_UNUSED(notifier)
Q_UNIMPLEMENTED();
}
#endif
void EventDispatcherLibEvent::wakeUp(void)
{
Q_D(EventDispatcherLibEvent);
d->m_tco->wakeUp();
}
void EventDispatcherLibEvent::interrupt(void)
{
Q_D(EventDispatcherLibEvent);
d->m_interrupt = true;
this->wakeUp();
}
void EventDispatcherLibEvent::flush(void)
{
}
EventDispatcherLibEvent::EventDispatcherLibEvent(EventDispatcherLibEventPrivate& dd, QObject* parent)
: QAbstractEventDispatcher(parent), d_ptr(&dd)
{
}
void EventDispatcherLibEvent::reinitialize(void)
{
Q_D(EventDispatcherLibEvent);
event_reinit(d->m_base);
}
<commit_msg>Added comments<commit_after>#include "common.h"
#include "eventdispatcher_libevent.h"
#include "eventdispatcher_libevent_p.h"
/**
* @class EventDispatcherLibEvent
* @brief The EventDispatcherLibEvent class provides an interface to manage Qt's event queue.
*
* An event dispatcher receives events from the window system and other
* sources. It then sends them to the QCoreApplication or QApplication
* instance for processing and delivery. EventDispatcherLibEvent provides
* fine-grained control over event delivery.
*
* For simple control of event processing use
* QCoreApplication::processEvents().
*
* For finer control of the application's event loop, call
* instance() and call functions on the QAbstractEventDispatcher
* object that is returned.
*
* To use EventDispatcherLibEvent, you must install it with
* QCoreApplication::setEventDispatcher() or QThread::setEventDispatcher()
* before a default event dispatcher has been installed.
* The main event loop is started by calling
* QCoreApplication::exec(), and stopped by calling
* QCoreApplication::exit(). Local event loops can be created using
* QEventLoop.
*
* Programs that perform long operations can call processEvents()
* with a bitwise OR combination of various QEventLoop::ProcessEventsFlag
* values to control which events should be delivered.
*/
/**
* Constructs a new event dispatcher with the given @a parent
*
* @param parent Parent
*/
EventDispatcherLibEvent::EventDispatcherLibEvent(QObject* parent)
: QAbstractEventDispatcher(parent), d_ptr(new EventDispatcherLibEventPrivate(this))
{
}
/**
* Constructs a new event dispatcher with the given configuration @a config and @a parent
*
* @param config Event dispatcher configuration
* @param parent Parent
* @see EventDispatcherLibEventConfig
*/
EventDispatcherLibEvent::EventDispatcherLibEvent(const EventDispatcherLibEventConfig& config, QObject* parent)
: QAbstractEventDispatcher(parent), d_ptr(new EventDispatcherLibEventPrivate(this, config))
{
}
/**
* Destroys the event dispatcher
*/
EventDispatcherLibEvent::~EventDispatcherLibEvent(void)
{
#if QT_VERSION < 0x040600
delete this->d_ptr;
this->d_ptr = 0;
#endif
}
/**
* @brief Processes pending events that match @a flags until there are no more events to process
* @param flags
* @return Whether an event has been processed
* @retval true If an event has been processed;
* @retval false If no events have been processed
*
* Processes pending events that match @a flags until there are no
* more events to process. Returns true if an event was processed;
* otherwise returns false.
*
* This function is especially useful if you have a long running
* operation and want to show its progress without allowing user
* input; i.e. by using the QEventLoop::ExcludeUserInputEvents flag.
*
* If the QEventLoop::WaitForMoreEvents flag is set in @a flags, the
* behavior of this function is as follows:
*
* @list
* @li If events are available, this function returns after processing them.
* @li If no events are available, this function will wait until more
* are available and return after processing newly available events.
* @endlist
*
* If the QEventLoop::WaitForMoreEvents flag is not set in @a flags,
* and no events are available, this function will return
* immediately.
*
* @b Note: This function does not process events continuously; it
* returns after all available events are processed.
*
* @see hasPendingEvents()
*/
bool EventDispatcherLibEvent::processEvents(QEventLoop::ProcessEventsFlags flags)
{
Q_D(EventDispatcherLibEvent);
return d->processEvents(flags);
}
/**
* Returns @c true if there is an event waiting; otherwise returns @c false
*
* @return Whether there is an event waiting
*/
bool EventDispatcherLibEvent::hasPendingEvents(void)
{
extern uint qGlobalPostedEventsCount();
return qGlobalPostedEventsCount() > 0;
}
/**
* Registers @a notifier with the event loop
*
* @param notifier Socket notifier to register
* @warning @a notifier must belong to the same thread as the event dispatcher
* @warning Socket notifiers can only be enabled from the thread they belong to
*/
void EventDispatcherLibEvent::registerSocketNotifier(QSocketNotifier* notifier)
{
#ifndef QT_NO_DEBUG
if (notifier->socket() < 0) {
qWarning("QSocketNotifier: Internal error: sockfd < 0");
return;
}
if (notifier->thread() != this->thread() || this->thread() != QThread::currentThread()) {
qWarning("QSocketNotifier: socket notifiers cannot be enabled from another thread");
return;
}
#endif
if (notifier->type() == QSocketNotifier::Exception) {
return;
}
Q_D(EventDispatcherLibEvent);
d->registerSocketNotifier(notifier);
}
/**
* Unregisters @a notifier from the event dispatcher.
*
* @param notifier Socket notifier to unregister
* @warning @a notifier must belong to the same thread as the event dispatcher
* @warning Socket notifiers can only be disabled from the thread they belong to
*/
void EventDispatcherLibEvent::unregisterSocketNotifier(QSocketNotifier* notifier)
{
#ifndef QT_NO_DEBUG
if (notifier->socket() < 0) {
qWarning("QSocketNotifier: Internal error: sockfd < 0");
return;
}
if (notifier->thread() != this->thread() || this->thread() != QThread::currentThread()) {
qWarning("QSocketNotifier: socket notifiers cannot be disabled from another thread");
return;
}
#endif
// Short circuit, we do not support QSocketNotifier::Exception
if (notifier->type() == QSocketNotifier::Exception) {
return;
}
Q_D(EventDispatcherLibEvent);
d->unregisterSocketNotifier(notifier);
}
/**
* Register a timer with the specified @a timerId, @a interval, and @a timerType
* for the given @a object.
*
* @param timerId Timer ID
* @param interval Timer interval (msec); must be greater than 0
* @param timerType Timer type (not available in Qt 4)
* @param object Object for which the timer is registered
* @warning @a object must belong to the same thread as the event dispatcher
* @warning Timers can only be started from the thread the event dispatcher lives in
*/
void EventDispatcherLibEvent::registerTimer(
int timerId,
int interval,
#if QT_VERSION >= 0x050000
Qt::TimerType timerType,
#endif
QObject* object
)
{
#ifndef QT_NO_DEBUG
if (timerId < 1 || interval < 0 || !object) {
qWarning("%s: invalid arguments", Q_FUNC_INFO);
return;
}
if (object->thread() != this->thread() && this->thread() != QThread::currentThread()) {
qWarning("%s: timers cannot be started from another thread", Q_FUNC_INFO);
return;
}
#endif
Qt::TimerType type;
#if QT_VERSION >= 0x050000
type = timerType;
#else
type = Qt::CoarseTimer;
#endif
Q_D(EventDispatcherLibEvent);
d->registerTimer(timerId, interval, type, object);
}
/**
* Unregisters the timer
*
* @param timerId ID of the timer
* @return Whether the timer has been unregistered
* @warning Timers can only be stopped from the same thread as the event dispatcher lives in
*/
bool EventDispatcherLibEvent::unregisterTimer(int timerId)
{
#ifndef QT_NO_DEBUG
if (timerId < 1) {
qWarning("%s: invalid arguments", Q_FUNC_INFO);
return false;
}
if (this->thread() != QThread::currentThread()) {
qWarning("%s: timers cannot be stopped from another thread", Q_FUNC_INFO);
return false;
}
#endif
Q_D(EventDispatcherLibEvent);
return d->unregisterTimer(timerId);
}
/**
* Unregisters all timers for the given @a object
*
* @param object Object
* @return Whether timers have been unregistered
* @warning @a object must belong to the same thread as the event dispatcher
* @warning Timers can only be started from the thread the event dispatcher lives in
*/
bool EventDispatcherLibEvent::unregisterTimers(QObject* object)
{
#ifndef QT_NO_DEBUG
if (!object) {
qWarning("%s: invalid arguments", Q_FUNC_INFO);
return false;
}
if (object->thread() != this->thread() && this->thread() != QThread::currentThread()) {
qWarning("%s: timers cannot be stopped from another thread", Q_FUNC_INFO);
return false;
}
#endif
Q_D(EventDispatcherLibEvent);
return d->unregisterTimers(object);
}
/**
* @brief Returns a list of registered timers for the given @a object.
* @param object Object
* @return List of registered timers
*/
QList<QAbstractEventDispatcher::TimerInfo> EventDispatcherLibEvent::registeredTimers(QObject* object) const
{
if (!object) {
qWarning("%s: invalid argument", Q_FUNC_INFO);
return QList<QAbstractEventDispatcher::TimerInfo>();
}
Q_D(const EventDispatcherLibEvent);
return d->registeredTimers(object);
}
#if QT_VERSION >= 0x050000
/**
* Returns the remaining time in milliseconds with the given @a timerId.
*
* @param timerId Timer ID
* @return The remaining time
* @retval -1 If the timer is inactive
* @retval 0 If the timer is overdue
*/
int EventDispatcherLibEvent::remainingTime(int timerId)
{
Q_D(const EventDispatcherLibEvent);
return d->remainingTime(timerId);
}
#endif
#if defined(Q_OS_WIN) && QT_VERSION >= 0x050000
bool EventDispatcherLibEvent::registerEventNotifier(QWinEventNotifier* notifier)
{
Q_UNUSED(notifier)
Q_UNIMPLEMENTED();
return false;
}
void EventDispatcherLibEvent::unregisterEventNotifier(QWinEventNotifier* notifier)
{
Q_UNUSED(notifier)
Q_UNIMPLEMENTED();
}
#endif
/**
* Wakes up the event loop. Thread-safe
*/
void EventDispatcherLibEvent::wakeUp(void)
{
Q_D(EventDispatcherLibEvent);
d->m_tco->wakeUp();
}
/**
* Interrupts event dispatching. The event dispatcher will return from @c processEvents()
* as soon as possible.
*/
void EventDispatcherLibEvent::interrupt(void)
{
Q_D(EventDispatcherLibEvent);
d->m_interrupt = true;
this->wakeUp();
}
/**
* @brief Does nothing
*/
void EventDispatcherLibEvent::flush(void)
{
}
/**
* @brief EventDispatcherLibEvent::EventDispatcherLibEvent
* @param dd
* @param parent
* @internal
*/
EventDispatcherLibEvent::EventDispatcherLibEvent(EventDispatcherLibEventPrivate& dd, QObject* parent)
: QAbstractEventDispatcher(parent), d_ptr(&dd)
{
}
void EventDispatcherLibEvent::reinitialize(void)
{
Q_D(EventDispatcherLibEvent);
event_reinit(d->m_base);
}
/**
* @fn void EventDispatcherLibEvent::awake()
*
* This signal is emitted after the event loop returns from a function that could block.
*
* @see wakeUp()
* @see aboutToBlock()
*/
/**
* @fn void EventDispatcherLibEvent::aboutToBlock()
*
* This signal is emitted before the event loop calls a function that could block.
*
* @see awake()
*/
<|endoftext|> |
<commit_before>/*
* Copyright © 2010 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
/**
* \file opt_redundant_jumps.cpp
* Remove certain types of redundant jumps
*/
#include "ir.h"
class redundant_jumps_visitor : public ir_hierarchical_visitor {
public:
redundant_jumps_visitor()
{
this->progress = false;
}
virtual ir_visitor_status visit_leave(ir_if *);
virtual ir_visitor_status visit_leave(ir_loop *);
bool progress;
};
ir_visitor_status
redundant_jumps_visitor::visit_leave(ir_if *ir)
{
/* If the last instruction in both branches is a 'break' or a 'continue',
* pull it out of the branches and insert it after the if-statment. Note
* that both must be the same type (either 'break' or 'continue').
*/
ir_instruction *const last_then =
(ir_instruction *) ir->then_instructions.get_tail();
ir_instruction *const last_else =
(ir_instruction *) ir->else_instructions.get_tail();
if ((last_then == NULL) || (last_else == NULL))
return visit_continue;
if ((last_then->ir_type != ir_type_loop_jump)
|| (last_else->ir_type != ir_type_loop_jump))
return visit_continue;
ir_loop_jump *const then_jump = (ir_loop_jump *) last_then;
ir_loop_jump *const else_jump = (ir_loop_jump *) last_else;
if (then_jump->mode != else_jump->mode)
return visit_continue;
then_jump->remove();
else_jump->remove();
this->progress = true;
ir->insert_after(then_jump);
/* If both branchs of the if-statement are now empty, remove the
* if-statement.
*/
if (ir->then_instructions.is_empty() && ir->else_instructions.is_empty())
ir->remove();
return visit_continue;
}
ir_visitor_status
redundant_jumps_visitor::visit_leave(ir_loop *ir)
{
/* If the last instruction of a loop body is a 'continue', remove it.
*/
ir_instruction *const last =
(ir_instruction *) ir->body_instructions.get_tail();
if (last && (last->ir_type == ir_type_loop_jump)
&& (((ir_loop_jump *) last)->mode == ir_loop_jump::jump_continue)) {
last->remove();
this->progress = true;
}
return visit_continue;
}
bool
optimize_redundant_jumps(exec_list *instructions)
{
redundant_jumps_visitor v;
v.run(instructions);
return v.progress;
}
<commit_msg>glsl: Skip processing expression trees in optimize_redundant_jumps()<commit_after>/*
* Copyright © 2010 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
/**
* \file opt_redundant_jumps.cpp
* Remove certain types of redundant jumps
*/
#include "ir.h"
class redundant_jumps_visitor : public ir_hierarchical_visitor {
public:
redundant_jumps_visitor()
{
this->progress = false;
}
virtual ir_visitor_status visit_leave(ir_if *);
virtual ir_visitor_status visit_leave(ir_loop *);
virtual ir_visitor_status visit_enter(ir_assignment *);
bool progress;
};
/* We only care about the top level instructions, so don't descend
* into expressions.
*/
ir_visitor_status
redundant_jumps_visitor::visit_enter(ir_assignment *ir)
{
return visit_continue_with_parent;
}
ir_visitor_status
redundant_jumps_visitor::visit_leave(ir_if *ir)
{
/* If the last instruction in both branches is a 'break' or a 'continue',
* pull it out of the branches and insert it after the if-statment. Note
* that both must be the same type (either 'break' or 'continue').
*/
ir_instruction *const last_then =
(ir_instruction *) ir->then_instructions.get_tail();
ir_instruction *const last_else =
(ir_instruction *) ir->else_instructions.get_tail();
if ((last_then == NULL) || (last_else == NULL))
return visit_continue;
if ((last_then->ir_type != ir_type_loop_jump)
|| (last_else->ir_type != ir_type_loop_jump))
return visit_continue;
ir_loop_jump *const then_jump = (ir_loop_jump *) last_then;
ir_loop_jump *const else_jump = (ir_loop_jump *) last_else;
if (then_jump->mode != else_jump->mode)
return visit_continue;
then_jump->remove();
else_jump->remove();
this->progress = true;
ir->insert_after(then_jump);
/* If both branchs of the if-statement are now empty, remove the
* if-statement.
*/
if (ir->then_instructions.is_empty() && ir->else_instructions.is_empty())
ir->remove();
return visit_continue;
}
ir_visitor_status
redundant_jumps_visitor::visit_leave(ir_loop *ir)
{
/* If the last instruction of a loop body is a 'continue', remove it.
*/
ir_instruction *const last =
(ir_instruction *) ir->body_instructions.get_tail();
if (last && (last->ir_type == ir_type_loop_jump)
&& (((ir_loop_jump *) last)->mode == ir_loop_jump::jump_continue)) {
last->remove();
this->progress = true;
}
return visit_continue;
}
bool
optimize_redundant_jumps(exec_list *instructions)
{
redundant_jumps_visitor v;
v.run(instructions);
return v.progress;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2021 Google LLC
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "src/gpu/ganesh/vk/GrVkBuffer.h"
#include "include/gpu/GrDirectContext.h"
#include "src/gpu/ganesh/GrDirectContextPriv.h"
#include "src/gpu/ganesh/GrResourceProvider.h"
#include "src/gpu/ganesh/vk/GrVkDescriptorSet.h"
#include "src/gpu/ganesh/vk/GrVkGpu.h"
#include "src/gpu/ganesh/vk/GrVkMemory.h"
#include "src/gpu/ganesh/vk/GrVkUtil.h"
#define VK_CALL(GPU, X) GR_VK_CALL(GPU->vkInterface(), X)
GrVkBuffer::GrVkBuffer(GrVkGpu* gpu,
size_t sizeInBytes,
GrGpuBufferType bufferType,
GrAccessPattern accessPattern,
VkBuffer buffer,
const GrVkAlloc& alloc,
const GrVkDescriptorSet* uniformDescriptorSet,
std::string_view label)
: GrGpuBuffer(gpu, sizeInBytes, bufferType, accessPattern, label)
, fBuffer(buffer)
, fAlloc(alloc)
, fUniformDescriptorSet(uniformDescriptorSet) {
// We always require dynamic buffers to be mappable
SkASSERT(accessPattern != kDynamic_GrAccessPattern || this->isVkMappable());
SkASSERT(bufferType != GrGpuBufferType::kUniform || uniformDescriptorSet);
this->registerWithCache(SkBudgeted::kYes);
}
static const GrVkDescriptorSet* make_uniform_desc_set(GrVkGpu* gpu, VkBuffer buffer, size_t size) {
const GrVkDescriptorSet* descriptorSet = gpu->resourceProvider().getUniformDescriptorSet();
if (!descriptorSet) {
return nullptr;
}
VkDescriptorBufferInfo bufferInfo;
memset(&bufferInfo, 0, sizeof(VkDescriptorBufferInfo));
bufferInfo.buffer = buffer;
bufferInfo.offset = 0;
bufferInfo.range = size;
VkWriteDescriptorSet descriptorWrite;
memset(&descriptorWrite, 0, sizeof(VkWriteDescriptorSet));
descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrite.pNext = nullptr;
descriptorWrite.dstSet = *descriptorSet->descriptorSet();
descriptorWrite.dstBinding = GrVkUniformHandler::kUniformBinding;
descriptorWrite.dstArrayElement = 0;
descriptorWrite.descriptorCount = 1;
descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrite.pImageInfo = nullptr;
descriptorWrite.pBufferInfo = &bufferInfo;
descriptorWrite.pTexelBufferView = nullptr;
GR_VK_CALL(gpu->vkInterface(),
UpdateDescriptorSets(gpu->device(), 1, &descriptorWrite, 0, nullptr));
return descriptorSet;
}
sk_sp<GrVkBuffer> GrVkBuffer::Make(GrVkGpu* gpu,
size_t size,
GrGpuBufferType bufferType,
GrAccessPattern accessPattern) {
VkBuffer buffer;
GrVkAlloc alloc;
// The only time we don't require mappable buffers is when we have a static access pattern and
// we're on a device where gpu only memory has faster reads on the gpu than memory that is also
// mappable on the cpu. Protected memory always uses mappable buffers.
bool requiresMappable = gpu->protectedContext() ||
accessPattern == kDynamic_GrAccessPattern ||
accessPattern == kStream_GrAccessPattern ||
!gpu->vkCaps().gpuOnlyBuffersMorePerformant();
using BufferUsage = GrVkMemoryAllocator::BufferUsage;
BufferUsage allocUsage;
// create the buffer object
VkBufferCreateInfo bufInfo;
memset(&bufInfo, 0, sizeof(VkBufferCreateInfo));
bufInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
bufInfo.flags = 0;
bufInfo.size = size;
switch (bufferType) {
case GrGpuBufferType::kVertex:
bufInfo.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
allocUsage = requiresMappable ? BufferUsage::kCpuWritesGpuReads : BufferUsage::kGpuOnly;
break;
case GrGpuBufferType::kIndex:
bufInfo.usage = VK_BUFFER_USAGE_INDEX_BUFFER_BIT;
allocUsage = requiresMappable ? BufferUsage::kCpuWritesGpuReads : BufferUsage::kGpuOnly;
break;
case GrGpuBufferType::kDrawIndirect:
bufInfo.usage = VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT;
allocUsage = requiresMappable ? BufferUsage::kCpuWritesGpuReads : BufferUsage::kGpuOnly;
break;
case GrGpuBufferType::kUniform:
bufInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
allocUsage = BufferUsage::kCpuWritesGpuReads;
break;
case GrGpuBufferType::kXferCpuToGpu:
bufInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
allocUsage = BufferUsage::kTransfersFromCpuToGpu;
break;
case GrGpuBufferType::kXferGpuToCpu:
bufInfo.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
allocUsage = BufferUsage::kTransfersFromGpuToCpu;
break;
}
// We may not always get a mappable buffer for non dynamic access buffers. Thus we set the
// transfer dst usage bit in case we need to do a copy to write data.
// TODO: It doesn't really hurt setting this extra usage flag, but maybe we can narrow the scope
// of buffers we set it on more than just not dynamic.
if (!requiresMappable) {
bufInfo.usage |= VK_BUFFER_USAGE_TRANSFER_DST_BIT;
}
bufInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
bufInfo.queueFamilyIndexCount = 0;
bufInfo.pQueueFamilyIndices = nullptr;
VkResult err;
err = VK_CALL(gpu, CreateBuffer(gpu->device(), &bufInfo, nullptr, &buffer));
if (err) {
return nullptr;
}
if (!GrVkMemory::AllocAndBindBufferMemory(gpu, buffer, allocUsage, &alloc)) {
VK_CALL(gpu, DestroyBuffer(gpu->device(), buffer, nullptr));
return nullptr;
}
// If this is a uniform buffer we must setup a descriptor set
const GrVkDescriptorSet* uniformDescSet = nullptr;
if (bufferType == GrGpuBufferType::kUniform) {
uniformDescSet = make_uniform_desc_set(gpu, buffer, size);
if (!uniformDescSet) {
VK_CALL(gpu, DestroyBuffer(gpu->device(), buffer, nullptr));
GrVkMemory::FreeBufferMemory(gpu, alloc);
return nullptr;
}
}
return sk_sp<GrVkBuffer>(new GrVkBuffer(
gpu, size, bufferType, accessPattern, buffer, alloc, uniformDescSet,
/*label=*/"MakeVkBuffer"));
}
void GrVkBuffer::vkMap(size_t size) {
SkASSERT(!fMapPtr);
if (this->isVkMappable()) {
// Not every buffer will use command buffer usage refs and instead the command buffer just
// holds normal refs. Systems higher up in Ganesh should be making sure not to reuse a
// buffer that currently has a ref held by something else. However, we do need to make sure
// there isn't a buffer with just a command buffer usage that is trying to be mapped.
SkASSERT(this->internalHasNoCommandBufferUsages());
SkASSERT(fAlloc.fSize > 0);
SkASSERT(fAlloc.fSize >= size);
fMapPtr = GrVkMemory::MapAlloc(this->getVkGpu(), fAlloc);
if (fMapPtr && this->intendedType() == GrGpuBufferType::kXferGpuToCpu) {
GrVkMemory::InvalidateMappedAlloc(this->getVkGpu(), fAlloc, 0, size);
}
}
}
void GrVkBuffer::vkUnmap(size_t size) {
SkASSERT(fMapPtr && this->isVkMappable());
SkASSERT(fAlloc.fSize > 0);
SkASSERT(fAlloc.fSize >= size);
GrVkGpu* gpu = this->getVkGpu();
GrVkMemory::FlushMappedAlloc(gpu, fAlloc, 0, size);
GrVkMemory::UnmapAlloc(gpu, fAlloc);
}
static VkAccessFlags buffer_type_to_access_flags(GrGpuBufferType type) {
switch (type) {
case GrGpuBufferType::kIndex:
return VK_ACCESS_INDEX_READ_BIT;
case GrGpuBufferType::kVertex:
return VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT;
default:
// This helper is only called for static buffers so we should only ever see index or
// vertex buffers types
SkUNREACHABLE;
}
}
void GrVkBuffer::copyCpuDataToGpuBuffer(const void* src, size_t size) {
SkASSERT(src);
GrVkGpu* gpu = this->getVkGpu();
// We should never call this method in protected contexts.
SkASSERT(!gpu->protectedContext());
// The vulkan api restricts the use of vkCmdUpdateBuffer to updates that are less than or equal
// to 65536 bytes and a size the is 4 byte aligned.
if ((size <= 65536) && (0 == (size & 0x3)) && !gpu->vkCaps().avoidUpdateBuffers()) {
gpu->updateBuffer(sk_ref_sp(this), src, /*offset=*/0, size);
} else {
GrResourceProvider* resourceProvider = gpu->getContext()->priv().resourceProvider();
sk_sp<GrGpuBuffer> transferBuffer = resourceProvider->createBuffer(
src,
size,
GrGpuBufferType::kXferCpuToGpu,
kDynamic_GrAccessPattern);
if (!transferBuffer) {
return;
}
gpu->copyBuffer(std::move(transferBuffer), sk_ref_sp(this), /*srcOffset=*/0,
/*dstOffset=*/0, size);
}
this->addMemoryBarrier(VK_ACCESS_TRANSFER_WRITE_BIT,
buffer_type_to_access_flags(this->intendedType()),
VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_PIPELINE_STAGE_VERTEX_INPUT_BIT,
/*byRegion=*/false);
}
void GrVkBuffer::addMemoryBarrier(VkAccessFlags srcAccessMask,
VkAccessFlags dstAccesMask,
VkPipelineStageFlags srcStageMask,
VkPipelineStageFlags dstStageMask,
bool byRegion) const {
VkBufferMemoryBarrier bufferMemoryBarrier = {
VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, // sType
nullptr, // pNext
srcAccessMask, // srcAccessMask
dstAccesMask, // dstAccessMask
VK_QUEUE_FAMILY_IGNORED, // srcQueueFamilyIndex
VK_QUEUE_FAMILY_IGNORED, // dstQueueFamilyIndex
fBuffer, // buffer
0, // offset
this->size(), // size
};
// TODO: restrict to area of buffer we're interested in
this->getVkGpu()->addBufferMemoryBarrier(srcStageMask, dstStageMask, byRegion,
&bufferMemoryBarrier);
}
void GrVkBuffer::vkRelease() {
if (this->wasDestroyed()) {
return;
}
if (fMapPtr) {
this->vkUnmap(this->size());
fMapPtr = nullptr;
}
if (fUniformDescriptorSet) {
fUniformDescriptorSet->recycle();
fUniformDescriptorSet = nullptr;
}
SkASSERT(fBuffer);
SkASSERT(fAlloc.fMemory && fAlloc.fBackendMemory);
VK_CALL(this->getVkGpu(), DestroyBuffer(this->getVkGpu()->device(), fBuffer, nullptr));
fBuffer = VK_NULL_HANDLE;
GrVkMemory::FreeBufferMemory(this->getVkGpu(), fAlloc);
fAlloc.fMemory = VK_NULL_HANDLE;
fAlloc.fBackendMemory = 0;
}
void GrVkBuffer::onRelease() {
this->vkRelease();
this->GrGpuBuffer::onRelease();
}
void GrVkBuffer::onAbandon() {
this->vkRelease();
this->GrGpuBuffer::onAbandon();
}
void GrVkBuffer::onMap() {
if (!this->wasDestroyed()) {
this->vkMap(this->size());
}
}
void GrVkBuffer::onUnmap() {
if (!this->wasDestroyed()) {
this->vkUnmap(this->size());
}
}
bool GrVkBuffer::onUpdateData(const void* src, size_t srcSizeInBytes) {
if (this->isVkMappable()) {
this->vkMap(srcSizeInBytes);
if (!fMapPtr) {
return false;
}
memcpy(fMapPtr, src, srcSizeInBytes);
this->vkUnmap(srcSizeInBytes);
fMapPtr = nullptr;
} else {
this->copyCpuDataToGpuBuffer(src, srcSizeInBytes);
}
return true;
}
GrVkGpu* GrVkBuffer::getVkGpu() const {
SkASSERT(!this->wasDestroyed());
return static_cast<GrVkGpu*>(this->getGpu());
}
const VkDescriptorSet* GrVkBuffer::uniformDescriptorSet() const {
SkASSERT(fUniformDescriptorSet);
return fUniformDescriptorSet->descriptorSet();
}
<commit_msg>Make Vulkan vertex and index buffers support transfer dst<commit_after>/*
* Copyright 2021 Google LLC
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "src/gpu/ganesh/vk/GrVkBuffer.h"
#include "include/gpu/GrDirectContext.h"
#include "src/gpu/ganesh/GrDirectContextPriv.h"
#include "src/gpu/ganesh/GrResourceProvider.h"
#include "src/gpu/ganesh/vk/GrVkDescriptorSet.h"
#include "src/gpu/ganesh/vk/GrVkGpu.h"
#include "src/gpu/ganesh/vk/GrVkMemory.h"
#include "src/gpu/ganesh/vk/GrVkUtil.h"
#define VK_CALL(GPU, X) GR_VK_CALL(GPU->vkInterface(), X)
GrVkBuffer::GrVkBuffer(GrVkGpu* gpu,
size_t sizeInBytes,
GrGpuBufferType bufferType,
GrAccessPattern accessPattern,
VkBuffer buffer,
const GrVkAlloc& alloc,
const GrVkDescriptorSet* uniformDescriptorSet,
std::string_view label)
: GrGpuBuffer(gpu, sizeInBytes, bufferType, accessPattern, label)
, fBuffer(buffer)
, fAlloc(alloc)
, fUniformDescriptorSet(uniformDescriptorSet) {
// We always require dynamic buffers to be mappable
SkASSERT(accessPattern != kDynamic_GrAccessPattern || this->isVkMappable());
SkASSERT(bufferType != GrGpuBufferType::kUniform || uniformDescriptorSet);
this->registerWithCache(SkBudgeted::kYes);
}
static const GrVkDescriptorSet* make_uniform_desc_set(GrVkGpu* gpu, VkBuffer buffer, size_t size) {
const GrVkDescriptorSet* descriptorSet = gpu->resourceProvider().getUniformDescriptorSet();
if (!descriptorSet) {
return nullptr;
}
VkDescriptorBufferInfo bufferInfo;
memset(&bufferInfo, 0, sizeof(VkDescriptorBufferInfo));
bufferInfo.buffer = buffer;
bufferInfo.offset = 0;
bufferInfo.range = size;
VkWriteDescriptorSet descriptorWrite;
memset(&descriptorWrite, 0, sizeof(VkWriteDescriptorSet));
descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrite.pNext = nullptr;
descriptorWrite.dstSet = *descriptorSet->descriptorSet();
descriptorWrite.dstBinding = GrVkUniformHandler::kUniformBinding;
descriptorWrite.dstArrayElement = 0;
descriptorWrite.descriptorCount = 1;
descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrite.pImageInfo = nullptr;
descriptorWrite.pBufferInfo = &bufferInfo;
descriptorWrite.pTexelBufferView = nullptr;
GR_VK_CALL(gpu->vkInterface(),
UpdateDescriptorSets(gpu->device(), 1, &descriptorWrite, 0, nullptr));
return descriptorSet;
}
sk_sp<GrVkBuffer> GrVkBuffer::Make(GrVkGpu* gpu,
size_t size,
GrGpuBufferType bufferType,
GrAccessPattern accessPattern) {
VkBuffer buffer;
GrVkAlloc alloc;
// The only time we don't require mappable buffers is when we have a static access pattern and
// we're on a device where gpu only memory has faster reads on the gpu than memory that is also
// mappable on the cpu. Protected memory always uses mappable buffers.
bool requiresMappable = gpu->protectedContext() ||
accessPattern == kDynamic_GrAccessPattern ||
accessPattern == kStream_GrAccessPattern ||
!gpu->vkCaps().gpuOnlyBuffersMorePerformant();
using BufferUsage = GrVkMemoryAllocator::BufferUsage;
BufferUsage allocUsage;
// create the buffer object
VkBufferCreateInfo bufInfo;
memset(&bufInfo, 0, sizeof(VkBufferCreateInfo));
bufInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
bufInfo.flags = 0;
bufInfo.size = size;
// To support SkMesh buffer updates we make Vertex and Index buffers capable of being transfer
// dsts.
switch (bufferType) {
case GrGpuBufferType::kVertex:
bufInfo.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
allocUsage = requiresMappable ? BufferUsage::kCpuWritesGpuReads : BufferUsage::kGpuOnly;
break;
case GrGpuBufferType::kIndex:
bufInfo.usage = VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
allocUsage = requiresMappable ? BufferUsage::kCpuWritesGpuReads : BufferUsage::kGpuOnly;
break;
case GrGpuBufferType::kDrawIndirect:
bufInfo.usage = VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT;
allocUsage = requiresMappable ? BufferUsage::kCpuWritesGpuReads : BufferUsage::kGpuOnly;
break;
case GrGpuBufferType::kUniform:
bufInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
allocUsage = BufferUsage::kCpuWritesGpuReads;
break;
case GrGpuBufferType::kXferCpuToGpu:
bufInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
allocUsage = BufferUsage::kTransfersFromCpuToGpu;
break;
case GrGpuBufferType::kXferGpuToCpu:
bufInfo.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
allocUsage = BufferUsage::kTransfersFromGpuToCpu;
break;
}
// We may not always get a mappable buffer for non dynamic access buffers. Thus we set the
// transfer dst usage bit in case we need to do a copy to write data.
// TODO: It doesn't really hurt setting this extra usage flag, but maybe we can narrow the scope
// of buffers we set it on more than just not dynamic.
if (!requiresMappable) {
bufInfo.usage |= VK_BUFFER_USAGE_TRANSFER_DST_BIT;
}
bufInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
bufInfo.queueFamilyIndexCount = 0;
bufInfo.pQueueFamilyIndices = nullptr;
VkResult err;
err = VK_CALL(gpu, CreateBuffer(gpu->device(), &bufInfo, nullptr, &buffer));
if (err) {
return nullptr;
}
if (!GrVkMemory::AllocAndBindBufferMemory(gpu, buffer, allocUsage, &alloc)) {
VK_CALL(gpu, DestroyBuffer(gpu->device(), buffer, nullptr));
return nullptr;
}
// If this is a uniform buffer we must setup a descriptor set
const GrVkDescriptorSet* uniformDescSet = nullptr;
if (bufferType == GrGpuBufferType::kUniform) {
uniformDescSet = make_uniform_desc_set(gpu, buffer, size);
if (!uniformDescSet) {
VK_CALL(gpu, DestroyBuffer(gpu->device(), buffer, nullptr));
GrVkMemory::FreeBufferMemory(gpu, alloc);
return nullptr;
}
}
return sk_sp<GrVkBuffer>(new GrVkBuffer(
gpu, size, bufferType, accessPattern, buffer, alloc, uniformDescSet,
/*label=*/"MakeVkBuffer"));
}
void GrVkBuffer::vkMap(size_t size) {
SkASSERT(!fMapPtr);
if (this->isVkMappable()) {
// Not every buffer will use command buffer usage refs and instead the command buffer just
// holds normal refs. Systems higher up in Ganesh should be making sure not to reuse a
// buffer that currently has a ref held by something else. However, we do need to make sure
// there isn't a buffer with just a command buffer usage that is trying to be mapped.
SkASSERT(this->internalHasNoCommandBufferUsages());
SkASSERT(fAlloc.fSize > 0);
SkASSERT(fAlloc.fSize >= size);
fMapPtr = GrVkMemory::MapAlloc(this->getVkGpu(), fAlloc);
if (fMapPtr && this->intendedType() == GrGpuBufferType::kXferGpuToCpu) {
GrVkMemory::InvalidateMappedAlloc(this->getVkGpu(), fAlloc, 0, size);
}
}
}
void GrVkBuffer::vkUnmap(size_t size) {
SkASSERT(fMapPtr && this->isVkMappable());
SkASSERT(fAlloc.fSize > 0);
SkASSERT(fAlloc.fSize >= size);
GrVkGpu* gpu = this->getVkGpu();
GrVkMemory::FlushMappedAlloc(gpu, fAlloc, 0, size);
GrVkMemory::UnmapAlloc(gpu, fAlloc);
}
static VkAccessFlags buffer_type_to_access_flags(GrGpuBufferType type) {
switch (type) {
case GrGpuBufferType::kIndex:
return VK_ACCESS_INDEX_READ_BIT;
case GrGpuBufferType::kVertex:
return VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT;
default:
// This helper is only called for static buffers so we should only ever see index or
// vertex buffers types
SkUNREACHABLE;
}
}
void GrVkBuffer::copyCpuDataToGpuBuffer(const void* src, size_t size) {
SkASSERT(src);
GrVkGpu* gpu = this->getVkGpu();
// We should never call this method in protected contexts.
SkASSERT(!gpu->protectedContext());
// The vulkan api restricts the use of vkCmdUpdateBuffer to updates that are less than or equal
// to 65536 bytes and a size the is 4 byte aligned.
if ((size <= 65536) && (0 == (size & 0x3)) && !gpu->vkCaps().avoidUpdateBuffers()) {
gpu->updateBuffer(sk_ref_sp(this), src, /*offset=*/0, size);
} else {
GrResourceProvider* resourceProvider = gpu->getContext()->priv().resourceProvider();
sk_sp<GrGpuBuffer> transferBuffer = resourceProvider->createBuffer(
src,
size,
GrGpuBufferType::kXferCpuToGpu,
kDynamic_GrAccessPattern);
if (!transferBuffer) {
return;
}
gpu->copyBuffer(std::move(transferBuffer), sk_ref_sp(this), /*srcOffset=*/0,
/*dstOffset=*/0, size);
}
this->addMemoryBarrier(VK_ACCESS_TRANSFER_WRITE_BIT,
buffer_type_to_access_flags(this->intendedType()),
VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_PIPELINE_STAGE_VERTEX_INPUT_BIT,
/*byRegion=*/false);
}
void GrVkBuffer::addMemoryBarrier(VkAccessFlags srcAccessMask,
VkAccessFlags dstAccesMask,
VkPipelineStageFlags srcStageMask,
VkPipelineStageFlags dstStageMask,
bool byRegion) const {
VkBufferMemoryBarrier bufferMemoryBarrier = {
VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, // sType
nullptr, // pNext
srcAccessMask, // srcAccessMask
dstAccesMask, // dstAccessMask
VK_QUEUE_FAMILY_IGNORED, // srcQueueFamilyIndex
VK_QUEUE_FAMILY_IGNORED, // dstQueueFamilyIndex
fBuffer, // buffer
0, // offset
this->size(), // size
};
// TODO: restrict to area of buffer we're interested in
this->getVkGpu()->addBufferMemoryBarrier(srcStageMask, dstStageMask, byRegion,
&bufferMemoryBarrier);
}
void GrVkBuffer::vkRelease() {
if (this->wasDestroyed()) {
return;
}
if (fMapPtr) {
this->vkUnmap(this->size());
fMapPtr = nullptr;
}
if (fUniformDescriptorSet) {
fUniformDescriptorSet->recycle();
fUniformDescriptorSet = nullptr;
}
SkASSERT(fBuffer);
SkASSERT(fAlloc.fMemory && fAlloc.fBackendMemory);
VK_CALL(this->getVkGpu(), DestroyBuffer(this->getVkGpu()->device(), fBuffer, nullptr));
fBuffer = VK_NULL_HANDLE;
GrVkMemory::FreeBufferMemory(this->getVkGpu(), fAlloc);
fAlloc.fMemory = VK_NULL_HANDLE;
fAlloc.fBackendMemory = 0;
}
void GrVkBuffer::onRelease() {
this->vkRelease();
this->GrGpuBuffer::onRelease();
}
void GrVkBuffer::onAbandon() {
this->vkRelease();
this->GrGpuBuffer::onAbandon();
}
void GrVkBuffer::onMap() {
if (!this->wasDestroyed()) {
this->vkMap(this->size());
}
}
void GrVkBuffer::onUnmap() {
if (!this->wasDestroyed()) {
this->vkUnmap(this->size());
}
}
bool GrVkBuffer::onUpdateData(const void* src, size_t srcSizeInBytes) {
if (this->isVkMappable()) {
this->vkMap(srcSizeInBytes);
if (!fMapPtr) {
return false;
}
memcpy(fMapPtr, src, srcSizeInBytes);
this->vkUnmap(srcSizeInBytes);
fMapPtr = nullptr;
} else {
this->copyCpuDataToGpuBuffer(src, srcSizeInBytes);
}
return true;
}
GrVkGpu* GrVkBuffer::getVkGpu() const {
SkASSERT(!this->wasDestroyed());
return static_cast<GrVkGpu*>(this->getGpu());
}
const VkDescriptorSet* GrVkBuffer::uniformDescriptorSet() const {
SkASSERT(fUniformDescriptorSet);
return fUniformDescriptorSet->descriptorSet();
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2008-2016 the MRtrix3 contributors
*
* 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/
*
* MRtrix 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.
*
* For more details, see www.mrtrix.org
*
*/
#include "gui/mrview/mode/lightbox.h"
namespace MR
{
namespace GUI
{
namespace MRView
{
namespace Mode
{
bool LightBox::show_grid_lines(true);
size_t LightBox::n_rows(3);
size_t LightBox::n_cols(5);
float LightBox::slice_focus_increment(1.f);
float LightBox::slice_focus_inc_adjust_rate(0.2f);
std::string LightBox::prev_image_name;
LightBox::LightBox () :
layout_is_dirty(true),
current_slice_index((n_rows*n_cols) / 2),
slices_proj_focusdelta(n_rows*n_cols, proj_focusdelta(projection, 0.f))
{
Image* img = image();
if(!img || prev_image_name != img->header().name())
image_changed_event();
else
set_slice_increment(slice_focus_increment);
}
void LightBox::set_rows(size_t rows)
{
n_rows = rows;
layout_is_dirty = true;
updateGL();
}
void LightBox::set_cols(size_t cols)
{
n_cols = cols;
layout_is_dirty = true;
updateGL();
}
void LightBox::set_slice_increment(float inc)
{
slice_focus_increment = inc;
update_slices_focusdelta();
updateGL();
}
void LightBox::set_show_grid(bool show_grid)
{
show_grid_lines = show_grid;
updateGL();
}
inline void LightBox::update_layout()
{
// Can't use std::vector resize() because Projection needs to be assignable
slices_proj_focusdelta = std::vector<proj_focusdelta>(
n_cols * n_rows,
proj_focusdelta(projection, 0.f));
set_current_slice_index((n_rows * n_cols) / 2);
update_slices_focusdelta();
frame_VB.clear();
frame_VAO.clear();
}
void LightBox::set_current_slice_index(size_t slice_index)
{
size_t prev_index = current_slice_index;
current_slice_index = slice_index;
if(prev_index != current_slice_index)
{
const Projection& slice_proj = slices_proj_focusdelta[current_slice_index].first;
float focus_delta = slices_proj_focusdelta[current_slice_index].second;
const Eigen::Vector3f slice_focus = move_in_out_displacement(focus_delta, slice_proj);
set_focus(focus() + slice_focus);
update_slices_focusdelta();
}
}
void LightBox::update_slices_focusdelta()
{
const int current_slice_index_int = current_slice_index;
for(int i = 0, N = slices_proj_focusdelta.size(); i < N; ++i) {
slices_proj_focusdelta[i].second =
slice_focus_increment * (i - current_slice_index_int);
}
}
void LightBox::draw_plane_primitive (int axis, Displayable::Shader& shader_program, Projection& with_projection)
{
ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT;
if (visible)
image()->render3D (shader_program, with_projection, with_projection.depth_of (focus()));
render_tools (with_projection, false, axis, slice (axis));
ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT;
}
void LightBox::paint(Projection&)
{
ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT;
// Setup OpenGL environment:
gl::Disable (gl::BLEND);
gl::Disable (gl::DEPTH_TEST);
gl::DepthMask (gl::FALSE_);
gl::ColorMask (gl::TRUE_, gl::TRUE_, gl::TRUE_, gl::TRUE_);
GLint x = projection.x_position(), y = projection.y_position();
GLint w = projection.width(), h = projection.height();
GLfloat dw = w / (float)n_cols, dh = h / (float)n_rows;
const Eigen::Vector3f orig_focus = window().focus();
if(layout_is_dirty)
{
update_layout();
layout_is_dirty = false;
}
size_t slice_idx = 0;
for(size_t row = 0; row < n_rows; ++row)
{
for(size_t col = 0; col < n_cols; ++col, ++slice_idx)
{
Projection& slice_proj = slices_proj_focusdelta[slice_idx].first;
// Place the first slice in the top-left corner
slice_proj.set_viewport(window(), x + dw * col, y + h - (dh * (row+1)), dw, dh);
// We need to setup the modelview/proj matrices before we set the new focus
// because move_in_out_displacement is reliant on MVP
setup_projection (plane(), slice_proj);
float focus_delta = slices_proj_focusdelta[slice_idx].second;
Eigen::Vector3f slice_focus = move_in_out_displacement(focus_delta, slice_proj);
set_focus(orig_focus + slice_focus);
draw_plane_primitive(plane(), slice_shader, slice_proj);
if(slice_idx == current_slice_index) {
// Drawing plane may alter the depth test state
// so need to ensure that crosshairs/labels will be visible
gl::Disable (gl::DEPTH_TEST);
draw_crosshairs(slice_proj);
draw_orientation_labels(slice_proj);
}
}
}
// Restore view state
set_focus(orig_focus);
projection.set_viewport(window(), x, y, w, h);
// Users may want to screen capture without grid lines
if(show_grid_lines) {
gl::Disable(gl::DEPTH_TEST);
draw_grid();
}
ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT;
}
void LightBox::draw_grid()
{
ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT;
if(n_cols < 1 && n_rows < 1)
return;
size_t num_points = ((n_rows - 1) + (n_cols - 1)) * 4;
GL::mat4 MV = GL::identity();
GL::mat4 P = GL::ortho (0, width(), 0, height(), -1.0, 1.0);
projection.set (MV, P);
if (!frame_VB || !frame_VAO) {
frame_VB.gen();
frame_VAO.gen();
frame_VB.bind (gl::ARRAY_BUFFER);
frame_VAO.bind();
gl::EnableVertexAttribArray (0);
gl::VertexAttribPointer (0, 2, gl::FLOAT, gl::FALSE_, 0, (void*)0);
GLfloat data[num_points];
// Grid line stride
float x_inc = 2.f / n_cols;
float y_inc = 2.f / n_rows;
size_t pt_idx = 0;
// Row grid lines
for(size_t row = 1; row < n_rows; ++row, pt_idx += 4)
{
float y_pos = (y_inc * row) - 1.f;
data[pt_idx] = -1.f;
data[pt_idx+1] = y_pos;
data[pt_idx+2] = 1.f;
data[pt_idx+3] = y_pos;
}
// Column grid lines
for(size_t col = 1; col < n_cols; ++col, pt_idx += 4)
{
float x_pos = (x_inc * col) - 1.f;
data[pt_idx] = x_pos;
data[pt_idx+1] = -1.f;
data[pt_idx+2] = x_pos;
data[pt_idx+3] = 1.f;
}
gl::BufferData (gl::ARRAY_BUFFER, sizeof(data), data, gl::STATIC_DRAW);
}
else
frame_VAO.bind();
if (!frame_program) {
GL::Shader::Vertex vertex_shader (
"layout(location=0) in vec2 pos;\n"
"void main () {\n"
" gl_Position = vec4 (pos, 0.0, 1.0);\n"
"}\n");
GL::Shader::Fragment fragment_shader (
"out vec3 color;\n"
"void main () {\n"
" color = vec3 (0.1);\n"
"}\n");
frame_program.attach (vertex_shader);
frame_program.attach (fragment_shader);
frame_program.link();
}
frame_program.start();
gl::DrawArrays (gl::LINES, 0, num_points / 2);
frame_program.stop();
ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT;
}
void LightBox::mouse_press_event()
{
GLint x = projection.x_position(), y = projection.y_position();
GLint w = projection.width(), h = projection.height();
GLint dw = w / n_cols, dh = h / n_rows;
const auto& mouse_pos = window().mouse_position();
size_t col = (mouse_pos.x() - x) / dw;
size_t row = n_rows - (mouse_pos.y() - y) / dh - 1;
if(col < n_cols && row < n_rows) {
set_current_slice_index(slice_index(row, col));
}
}
// Called when we get a mouse move event
void LightBox::set_focus_event()
{
Base::set_focus_event();
mouse_press_event();
}
void LightBox::image_changed_event()
{
Base::image_changed_event();
if(image())
{
const auto& header = image()->header();
float slice_inc = std::pow (header.spacing(0)*header.spacing(1)*header.spacing(2), 1.f/3.f);
slice_focus_inc_adjust_rate = slice_inc / 5.f;
set_slice_increment(slice_inc);
emit slice_increment_reset();
prev_image_name = image()->header().name();
}
else
prev_image_name.clear();
}
}
}
}
}
<commit_msg>Fix #651 mrview: switching images resets slice increment in light box<commit_after>/*
* Copyright (c) 2008-2016 the MRtrix3 contributors
*
* 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/
*
* MRtrix 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.
*
* For more details, see www.mrtrix.org
*
*/
#include "gui/mrview/mode/lightbox.h"
namespace MR
{
namespace GUI
{
namespace MRView
{
namespace Mode
{
bool LightBox::show_grid_lines(true);
size_t LightBox::n_rows(3);
size_t LightBox::n_cols(5);
float LightBox::slice_focus_increment(1.f);
float LightBox::slice_focus_inc_adjust_rate(0.2f);
std::string LightBox::prev_image_name;
LightBox::LightBox () :
layout_is_dirty(true),
current_slice_index((n_rows*n_cols) / 2),
slices_proj_focusdelta(n_rows*n_cols, proj_focusdelta(projection, 0.f))
{
Image* img = image();
if(!img || prev_image_name != img->header().name())
image_changed_event();
else
set_slice_increment(slice_focus_increment);
}
void LightBox::set_rows(size_t rows)
{
n_rows = rows;
layout_is_dirty = true;
updateGL();
}
void LightBox::set_cols(size_t cols)
{
n_cols = cols;
layout_is_dirty = true;
updateGL();
}
void LightBox::set_slice_increment(float inc)
{
slice_focus_increment = inc;
update_slices_focusdelta();
updateGL();
}
void LightBox::set_show_grid(bool show_grid)
{
show_grid_lines = show_grid;
updateGL();
}
inline void LightBox::update_layout()
{
// Can't use std::vector resize() because Projection needs to be assignable
slices_proj_focusdelta = std::vector<proj_focusdelta>(
n_cols * n_rows,
proj_focusdelta(projection, 0.f));
set_current_slice_index((n_rows * n_cols) / 2);
update_slices_focusdelta();
frame_VB.clear();
frame_VAO.clear();
}
void LightBox::set_current_slice_index(size_t slice_index)
{
size_t prev_index = current_slice_index;
current_slice_index = slice_index;
if(prev_index != current_slice_index)
{
const Projection& slice_proj = slices_proj_focusdelta[current_slice_index].first;
float focus_delta = slices_proj_focusdelta[current_slice_index].second;
const Eigen::Vector3f slice_focus = move_in_out_displacement(focus_delta, slice_proj);
set_focus(focus() + slice_focus);
update_slices_focusdelta();
}
}
void LightBox::update_slices_focusdelta()
{
const int current_slice_index_int = current_slice_index;
for(int i = 0, N = slices_proj_focusdelta.size(); i < N; ++i) {
slices_proj_focusdelta[i].second =
slice_focus_increment * (i - current_slice_index_int);
}
}
void LightBox::draw_plane_primitive (int axis, Displayable::Shader& shader_program, Projection& with_projection)
{
ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT;
if (visible)
image()->render3D (shader_program, with_projection, with_projection.depth_of (focus()));
render_tools (with_projection, false, axis, slice (axis));
ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT;
}
void LightBox::paint(Projection&)
{
ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT;
// Setup OpenGL environment:
gl::Disable (gl::BLEND);
gl::Disable (gl::DEPTH_TEST);
gl::DepthMask (gl::FALSE_);
gl::ColorMask (gl::TRUE_, gl::TRUE_, gl::TRUE_, gl::TRUE_);
GLint x = projection.x_position(), y = projection.y_position();
GLint w = projection.width(), h = projection.height();
GLfloat dw = w / (float)n_cols, dh = h / (float)n_rows;
const Eigen::Vector3f orig_focus = window().focus();
if(layout_is_dirty)
{
update_layout();
layout_is_dirty = false;
}
size_t slice_idx = 0;
for(size_t row = 0; row < n_rows; ++row)
{
for(size_t col = 0; col < n_cols; ++col, ++slice_idx)
{
Projection& slice_proj = slices_proj_focusdelta[slice_idx].first;
// Place the first slice in the top-left corner
slice_proj.set_viewport(window(), x + dw * col, y + h - (dh * (row+1)), dw, dh);
// We need to setup the modelview/proj matrices before we set the new focus
// because move_in_out_displacement is reliant on MVP
setup_projection (plane(), slice_proj);
float focus_delta = slices_proj_focusdelta[slice_idx].second;
Eigen::Vector3f slice_focus = move_in_out_displacement(focus_delta, slice_proj);
set_focus(orig_focus + slice_focus);
draw_plane_primitive(plane(), slice_shader, slice_proj);
if(slice_idx == current_slice_index) {
// Drawing plane may alter the depth test state
// so need to ensure that crosshairs/labels will be visible
gl::Disable (gl::DEPTH_TEST);
draw_crosshairs(slice_proj);
draw_orientation_labels(slice_proj);
}
}
}
// Restore view state
set_focus(orig_focus);
projection.set_viewport(window(), x, y, w, h);
// Users may want to screen capture without grid lines
if(show_grid_lines) {
gl::Disable(gl::DEPTH_TEST);
draw_grid();
}
ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT;
}
void LightBox::draw_grid()
{
ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT;
if(n_cols < 1 && n_rows < 1)
return;
size_t num_points = ((n_rows - 1) + (n_cols - 1)) * 4;
GL::mat4 MV = GL::identity();
GL::mat4 P = GL::ortho (0, width(), 0, height(), -1.0, 1.0);
projection.set (MV, P);
if (!frame_VB || !frame_VAO) {
frame_VB.gen();
frame_VAO.gen();
frame_VB.bind (gl::ARRAY_BUFFER);
frame_VAO.bind();
gl::EnableVertexAttribArray (0);
gl::VertexAttribPointer (0, 2, gl::FLOAT, gl::FALSE_, 0, (void*)0);
GLfloat data[num_points];
// Grid line stride
float x_inc = 2.f / n_cols;
float y_inc = 2.f / n_rows;
size_t pt_idx = 0;
// Row grid lines
for(size_t row = 1; row < n_rows; ++row, pt_idx += 4)
{
float y_pos = (y_inc * row) - 1.f;
data[pt_idx] = -1.f;
data[pt_idx+1] = y_pos;
data[pt_idx+2] = 1.f;
data[pt_idx+3] = y_pos;
}
// Column grid lines
for(size_t col = 1; col < n_cols; ++col, pt_idx += 4)
{
float x_pos = (x_inc * col) - 1.f;
data[pt_idx] = x_pos;
data[pt_idx+1] = -1.f;
data[pt_idx+2] = x_pos;
data[pt_idx+3] = 1.f;
}
gl::BufferData (gl::ARRAY_BUFFER, sizeof(data), data, gl::STATIC_DRAW);
}
else
frame_VAO.bind();
if (!frame_program) {
GL::Shader::Vertex vertex_shader (
"layout(location=0) in vec2 pos;\n"
"void main () {\n"
" gl_Position = vec4 (pos, 0.0, 1.0);\n"
"}\n");
GL::Shader::Fragment fragment_shader (
"out vec3 color;\n"
"void main () {\n"
" color = vec3 (0.1);\n"
"}\n");
frame_program.attach (vertex_shader);
frame_program.attach (fragment_shader);
frame_program.link();
}
frame_program.start();
gl::DrawArrays (gl::LINES, 0, num_points / 2);
frame_program.stop();
ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT;
}
void LightBox::mouse_press_event()
{
GLint x = projection.x_position(), y = projection.y_position();
GLint w = projection.width(), h = projection.height();
GLint dw = w / n_cols, dh = h / n_rows;
const auto& mouse_pos = window().mouse_position();
size_t col = (mouse_pos.x() - x) / dw;
size_t row = n_rows - (mouse_pos.y() - y) / dh - 1;
if(col < n_cols && row < n_rows) {
set_current_slice_index(slice_index(row, col));
}
}
// Called when we get a mouse move event
void LightBox::set_focus_event()
{
Base::set_focus_event();
mouse_press_event();
}
void LightBox::image_changed_event()
{
Base::image_changed_event();
if(image())
{
const auto& header = image()->header();
if (prev_image_name.empty()) {
float slice_inc = std::pow (header.spacing(0)*header.spacing(1)*header.spacing(2), 1.f/3.f);
slice_focus_inc_adjust_rate = slice_inc / 5.f;
set_slice_increment(slice_inc);
emit slice_increment_reset();
}
prev_image_name = image()->header().name();
}
else
prev_image_name.clear();
}
}
}
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2008-2018 the MRtrix3 contributors.
*
* 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/
*
* MRtrix3 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.
*
* For more details, see http://www.mrtrix.org/
*/
#include "gui/mrview/mode/lightbox.h"
namespace MR
{
namespace GUI
{
namespace MRView
{
namespace Mode
{
bool LightBox::show_grid_lines = true;
bool LightBox::show_volumes = false;
ssize_t LightBox::n_rows = 3;
ssize_t LightBox::n_cols = 5;
ssize_t LightBox::volume_increment = 1;
float LightBox::slice_focus_increment = 1.0f;
float LightBox::slice_focus_inc_adjust_rate = 0.2f;
std::string LightBox::prev_image_name;
ssize_t LightBox::current_slice_index = 0;
LightBox::LightBox ()
{
Image* img = image();
if(!img || prev_image_name != img->header().name())
image_changed_event();
else {
set_volume_increment (volume_increment);
set_slice_increment (slice_focus_increment);
}
}
void LightBox::set_rows (size_t rows)
{
n_rows = rows;
frame_VB.clear();
frame_VAO.clear();
updateGL();
}
void LightBox::set_cols (size_t cols)
{
n_cols = cols;
frame_VB.clear();
frame_VAO.clear();
updateGL();
}
void LightBox::set_volume_increment (size_t vol_inc)
{
volume_increment = vol_inc;
updateGL();
}
void LightBox::set_slice_increment (float inc)
{
slice_focus_increment = inc;
updateGL();
}
void LightBox::set_show_grid (bool show_grid)
{
show_grid_lines = show_grid;
updateGL();
}
void LightBox::set_show_volumes (bool show_vol)
{
show_volumes = show_vol;
updateGL();
}
inline bool LightBox::render_volumes()
{
return show_volumes && image () && image()->image.ndim() == 4;
}
void LightBox::draw_plane_primitive (int axis, Displayable::Shader& shader_program, Projection& with_projection)
{
ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT;
// Setup OpenGL environment:
gl::Disable (gl::BLEND);
gl::Disable (gl::DEPTH_TEST);
gl::DepthMask (gl::FALSE_);
gl::ColorMask (gl::TRUE_, gl::TRUE_, gl::TRUE_, gl::TRUE_);
if (visible)
image()->render3D (shader_program, with_projection, with_projection.depth_of (focus()));
render_tools (with_projection, false, axis, slice (axis));
ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT;
}
void LightBox::paint (Projection&)
{
ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT;
GLint x = projection.x_position(), y = projection.y_position();
GLint w = projection.width(), h = projection.height();
GLfloat dw = w / (float)n_cols, dh = h / (float)n_rows;
const Eigen::Vector3f orig_focus = window().focus();
const ssize_t original_slice_index = image()->image.index(3);
if (render_volumes()) {
if (current_slice_index < 0)
current_slice_index = 0;
if (current_slice_index >= n_rows*n_cols)
current_slice_index = n_rows*n_cols-1;
if (original_slice_index + volume_increment * (n_rows*n_cols-1 - current_slice_index) >= image()->image.size(3))
current_slice_index = n_rows*n_cols-1-(image()->image.size(3)-1-original_slice_index)/volume_increment;
if (original_slice_index < volume_increment * current_slice_index)
current_slice_index = original_slice_index / volume_increment;
}
ssize_t slice_idx = 0;
for (ssize_t row = 0; row < n_rows; ++row) {
for (ssize_t col = 0; col < n_cols; ++col, ++slice_idx) {
bool render_plane = true;
// Place the first slice in the top-left corner
projection.set_viewport (window(), x + dw * col, y + h - (dh * (row+1)), dw, dh);
// We need to setup the modelview/proj matrices before we set the new focus
// because move_in_out_displacement is reliant on MVP
setup_projection (plane(), projection);
if (render_volumes()) {
int vol_index = original_slice_index + volume_increment * (slice_idx - current_slice_index);
if (vol_index >= 0 && vol_index < image()->image.size(3))
image()->image.index(3) = vol_index;
else
render_plane = false;
}
else {
float focus_delta = slice_focus_increment * (slice_idx - current_slice_index);
Eigen::Vector3f slice_focus = move_in_out_displacement(focus_delta, projection);
set_focus (orig_focus + slice_focus);
}
if (render_plane)
draw_plane_primitive (plane(), slice_shader, projection);
if (slice_idx == current_slice_index) {
// Drawing plane may alter the depth test state
// so need to ensure that crosshairs/labels will be visible
gl::Disable (gl::DEPTH_TEST);
draw_crosshairs (projection);
draw_orientation_labels (projection);
}
}
}
// Restore view state
if (render_volumes())
image()->image.index(3) = original_slice_index;
set_focus (orig_focus);
projection.set_viewport (window(), x, y, w, h);
// Users may want to screen capture without grid lines
if (show_grid_lines) {
gl::Disable(gl::DEPTH_TEST);
draw_grid();
}
ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT;
}
void LightBox::draw_grid()
{
ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT;
if(n_cols < 1 && n_rows < 1)
return;
size_t num_points = ((n_rows - 1) + (n_cols - 1)) * 4;
GL::mat4 MV = GL::identity();
GL::mat4 P = GL::ortho (0, width(), 0, height(), -1.0, 1.0);
projection.set (MV, P);
if (!frame_VB || !frame_VAO) {
frame_VB.gen();
frame_VAO.gen();
frame_VB.bind (gl::ARRAY_BUFFER);
frame_VAO.bind();
gl::EnableVertexAttribArray (0);
gl::VertexAttribPointer (0, 2, gl::FLOAT, gl::FALSE_, 0, (void*)0);
GLfloat data[num_points];
// Grid line stride
float x_inc = 2.f / n_cols;
float y_inc = 2.f / n_rows;
size_t pt_idx = 0;
// Row grid lines
for (ssize_t row = 1; row < n_rows; ++row, pt_idx += 4) {
float y_pos = (y_inc * row) - 1.f;
data[pt_idx] = -1.f;
data[pt_idx+1] = y_pos;
data[pt_idx+2] = 1.f;
data[pt_idx+3] = y_pos;
}
// Column grid lines
for (ssize_t col = 1; col < n_cols; ++col, pt_idx += 4) {
float x_pos = (x_inc * col) - 1.f;
data[pt_idx] = x_pos;
data[pt_idx+1] = -1.f;
data[pt_idx+2] = x_pos;
data[pt_idx+3] = 1.f;
}
gl::BufferData (gl::ARRAY_BUFFER, sizeof(data), data, gl::STATIC_DRAW);
}
else
frame_VAO.bind();
if (!frame_program) {
GL::Shader::Vertex vertex_shader (
"layout(location=0) in vec2 pos;\n"
"void main () {\n"
" gl_Position = vec4 (pos, 0.0, 1.0);\n"
"}\n");
GL::Shader::Fragment fragment_shader (
"out vec3 color;\n"
"void main () {\n"
" color = vec3 (0.1);\n"
"}\n");
frame_program.attach (vertex_shader);
frame_program.attach (fragment_shader);
frame_program.link();
}
frame_program.start();
gl::DrawArrays (gl::LINES, 0, num_points / 2);
frame_program.stop();
ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT;
}
ModelViewProjection LightBox::get_projection_at (int row, int col) const
{
GLint x = projection.x_position();
GLint y = projection.y_position();
GLint dw = projection.width() / n_cols;
GLint dh = projection.height() / n_rows;
ModelViewProjection proj;
proj.set_viewport (x + dw * col, y + projection.height() - (dh * (row+1)), dw, dh);
setup_projection (plane(), proj);
return proj;
}
void LightBox::set_focus_event()
{
const auto& mouse_pos = window().mouse_position();
GLint dw = projection.width() / n_cols;
GLint dh = projection.height() / n_rows;
ssize_t col = (mouse_pos.x() - projection.x_position()) / dw;
ssize_t row = n_rows - 1 - (mouse_pos.y() - projection.y_position()) / dh;
ssize_t new_slice_index = col + row*n_cols;
ModelViewProjection proj = get_projection_at (row, col);
Eigen::Vector3f slice_focus = focus();
if (render_volumes()) {
ssize_t vol = image()->image.index(3) - current_slice_index + new_slice_index;
TRACE;
if (vol < 0 || vol >= image()->image.size(3))
return;
TRACE;
window().set_image_volume (3, vol);
emit window().volumeChanged (vol);
}
else {
float focus_delta = slice_focus_increment * (new_slice_index - current_slice_index);
slice_focus += move_in_out_displacement(focus_delta, proj);
}
set_focus (proj.screen_to_model (mouse_pos, slice_focus));
current_slice_index = new_slice_index;
updateGL();
}
void LightBox::slice_move_event (float x)
{
int row = current_slice_index / n_cols;
int col = current_slice_index - row*n_cols;
ModelViewProjection proj = get_projection_at (row, col);
Slice::slice_move_event (proj, x);
}
void LightBox::pan_event ()
{
int row = current_slice_index / n_cols;
int col = current_slice_index - row*n_cols;
ModelViewProjection proj = get_projection_at (row, col);
Slice::pan_event (proj);
}
void LightBox::panthrough_event ()
{
int row = current_slice_index / n_cols;
int col = current_slice_index - row*n_cols;
ModelViewProjection proj = get_projection_at (row, col);
Slice::panthrough_event (proj);
}
void LightBox::tilt_event ()
{
int row = current_slice_index / n_cols;
int col = current_slice_index - row*n_cols;
ModelViewProjection proj = get_projection_at (row, col);
Slice::tilt_event (proj);
}
void LightBox::rotate_event ()
{
int row = current_slice_index / n_cols;
int col = current_slice_index - row*n_cols;
ModelViewProjection proj = get_projection_at (row, col);
Slice::rotate_event (proj);
}
void LightBox::image_changed_event()
{
Base::image_changed_event();
if (image()) {
const auto& header = image()->header();
if (prev_image_name.empty()) {
float slice_inc = std::pow (header.spacing(0)*header.spacing(1)*header.spacing(2), 1.f/3.f);
slice_focus_inc_adjust_rate = slice_inc / 5.f;
set_slice_increment(slice_inc);
emit slice_increment_reset();
}
prev_image_name = image()->header().name();
}
else
prev_image_name.clear();
}
}
}
}
}
<commit_msg>lightbox: remove debug TRACE<commit_after>/*
* Copyright (c) 2008-2018 the MRtrix3 contributors.
*
* 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/
*
* MRtrix3 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.
*
* For more details, see http://www.mrtrix.org/
*/
#include "gui/mrview/mode/lightbox.h"
namespace MR
{
namespace GUI
{
namespace MRView
{
namespace Mode
{
bool LightBox::show_grid_lines = true;
bool LightBox::show_volumes = false;
ssize_t LightBox::n_rows = 3;
ssize_t LightBox::n_cols = 5;
ssize_t LightBox::volume_increment = 1;
float LightBox::slice_focus_increment = 1.0f;
float LightBox::slice_focus_inc_adjust_rate = 0.2f;
std::string LightBox::prev_image_name;
ssize_t LightBox::current_slice_index = 0;
LightBox::LightBox ()
{
Image* img = image();
if(!img || prev_image_name != img->header().name())
image_changed_event();
else {
set_volume_increment (volume_increment);
set_slice_increment (slice_focus_increment);
}
}
void LightBox::set_rows (size_t rows)
{
n_rows = rows;
frame_VB.clear();
frame_VAO.clear();
updateGL();
}
void LightBox::set_cols (size_t cols)
{
n_cols = cols;
frame_VB.clear();
frame_VAO.clear();
updateGL();
}
void LightBox::set_volume_increment (size_t vol_inc)
{
volume_increment = vol_inc;
updateGL();
}
void LightBox::set_slice_increment (float inc)
{
slice_focus_increment = inc;
updateGL();
}
void LightBox::set_show_grid (bool show_grid)
{
show_grid_lines = show_grid;
updateGL();
}
void LightBox::set_show_volumes (bool show_vol)
{
show_volumes = show_vol;
updateGL();
}
inline bool LightBox::render_volumes()
{
return show_volumes && image () && image()->image.ndim() == 4;
}
void LightBox::draw_plane_primitive (int axis, Displayable::Shader& shader_program, Projection& with_projection)
{
ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT;
// Setup OpenGL environment:
gl::Disable (gl::BLEND);
gl::Disable (gl::DEPTH_TEST);
gl::DepthMask (gl::FALSE_);
gl::ColorMask (gl::TRUE_, gl::TRUE_, gl::TRUE_, gl::TRUE_);
if (visible)
image()->render3D (shader_program, with_projection, with_projection.depth_of (focus()));
render_tools (with_projection, false, axis, slice (axis));
ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT;
}
void LightBox::paint (Projection&)
{
ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT;
GLint x = projection.x_position(), y = projection.y_position();
GLint w = projection.width(), h = projection.height();
GLfloat dw = w / (float)n_cols, dh = h / (float)n_rows;
const Eigen::Vector3f orig_focus = window().focus();
const ssize_t original_slice_index = image()->image.index(3);
if (render_volumes()) {
if (current_slice_index < 0)
current_slice_index = 0;
if (current_slice_index >= n_rows*n_cols)
current_slice_index = n_rows*n_cols-1;
if (original_slice_index + volume_increment * (n_rows*n_cols-1 - current_slice_index) >= image()->image.size(3))
current_slice_index = n_rows*n_cols-1-(image()->image.size(3)-1-original_slice_index)/volume_increment;
if (original_slice_index < volume_increment * current_slice_index)
current_slice_index = original_slice_index / volume_increment;
}
ssize_t slice_idx = 0;
for (ssize_t row = 0; row < n_rows; ++row) {
for (ssize_t col = 0; col < n_cols; ++col, ++slice_idx) {
bool render_plane = true;
// Place the first slice in the top-left corner
projection.set_viewport (window(), x + dw * col, y + h - (dh * (row+1)), dw, dh);
// We need to setup the modelview/proj matrices before we set the new focus
// because move_in_out_displacement is reliant on MVP
setup_projection (plane(), projection);
if (render_volumes()) {
int vol_index = original_slice_index + volume_increment * (slice_idx - current_slice_index);
if (vol_index >= 0 && vol_index < image()->image.size(3))
image()->image.index(3) = vol_index;
else
render_plane = false;
}
else {
float focus_delta = slice_focus_increment * (slice_idx - current_slice_index);
Eigen::Vector3f slice_focus = move_in_out_displacement(focus_delta, projection);
set_focus (orig_focus + slice_focus);
}
if (render_plane)
draw_plane_primitive (plane(), slice_shader, projection);
if (slice_idx == current_slice_index) {
// Drawing plane may alter the depth test state
// so need to ensure that crosshairs/labels will be visible
gl::Disable (gl::DEPTH_TEST);
draw_crosshairs (projection);
draw_orientation_labels (projection);
}
}
}
// Restore view state
if (render_volumes())
image()->image.index(3) = original_slice_index;
set_focus (orig_focus);
projection.set_viewport (window(), x, y, w, h);
// Users may want to screen capture without grid lines
if (show_grid_lines) {
gl::Disable(gl::DEPTH_TEST);
draw_grid();
}
ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT;
}
void LightBox::draw_grid()
{
ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT;
if(n_cols < 1 && n_rows < 1)
return;
size_t num_points = ((n_rows - 1) + (n_cols - 1)) * 4;
GL::mat4 MV = GL::identity();
GL::mat4 P = GL::ortho (0, width(), 0, height(), -1.0, 1.0);
projection.set (MV, P);
if (!frame_VB || !frame_VAO) {
frame_VB.gen();
frame_VAO.gen();
frame_VB.bind (gl::ARRAY_BUFFER);
frame_VAO.bind();
gl::EnableVertexAttribArray (0);
gl::VertexAttribPointer (0, 2, gl::FLOAT, gl::FALSE_, 0, (void*)0);
GLfloat data[num_points];
// Grid line stride
float x_inc = 2.f / n_cols;
float y_inc = 2.f / n_rows;
size_t pt_idx = 0;
// Row grid lines
for (ssize_t row = 1; row < n_rows; ++row, pt_idx += 4) {
float y_pos = (y_inc * row) - 1.f;
data[pt_idx] = -1.f;
data[pt_idx+1] = y_pos;
data[pt_idx+2] = 1.f;
data[pt_idx+3] = y_pos;
}
// Column grid lines
for (ssize_t col = 1; col < n_cols; ++col, pt_idx += 4) {
float x_pos = (x_inc * col) - 1.f;
data[pt_idx] = x_pos;
data[pt_idx+1] = -1.f;
data[pt_idx+2] = x_pos;
data[pt_idx+3] = 1.f;
}
gl::BufferData (gl::ARRAY_BUFFER, sizeof(data), data, gl::STATIC_DRAW);
}
else
frame_VAO.bind();
if (!frame_program) {
GL::Shader::Vertex vertex_shader (
"layout(location=0) in vec2 pos;\n"
"void main () {\n"
" gl_Position = vec4 (pos, 0.0, 1.0);\n"
"}\n");
GL::Shader::Fragment fragment_shader (
"out vec3 color;\n"
"void main () {\n"
" color = vec3 (0.1);\n"
"}\n");
frame_program.attach (vertex_shader);
frame_program.attach (fragment_shader);
frame_program.link();
}
frame_program.start();
gl::DrawArrays (gl::LINES, 0, num_points / 2);
frame_program.stop();
ASSERT_GL_MRVIEW_CONTEXT_IS_CURRENT;
}
ModelViewProjection LightBox::get_projection_at (int row, int col) const
{
GLint x = projection.x_position();
GLint y = projection.y_position();
GLint dw = projection.width() / n_cols;
GLint dh = projection.height() / n_rows;
ModelViewProjection proj;
proj.set_viewport (x + dw * col, y + projection.height() - (dh * (row+1)), dw, dh);
setup_projection (plane(), proj);
return proj;
}
void LightBox::set_focus_event()
{
const auto& mouse_pos = window().mouse_position();
GLint dw = projection.width() / n_cols;
GLint dh = projection.height() / n_rows;
ssize_t col = (mouse_pos.x() - projection.x_position()) / dw;
ssize_t row = n_rows - 1 - (mouse_pos.y() - projection.y_position()) / dh;
ssize_t new_slice_index = col + row*n_cols;
ModelViewProjection proj = get_projection_at (row, col);
Eigen::Vector3f slice_focus = focus();
if (render_volumes()) {
ssize_t vol = image()->image.index(3) - current_slice_index + new_slice_index;
if (vol < 0 || vol >= image()->image.size(3))
return;
window().set_image_volume (3, vol);
emit window().volumeChanged (vol);
}
else {
float focus_delta = slice_focus_increment * (new_slice_index - current_slice_index);
slice_focus += move_in_out_displacement(focus_delta, proj);
}
set_focus (proj.screen_to_model (mouse_pos, slice_focus));
current_slice_index = new_slice_index;
updateGL();
}
void LightBox::slice_move_event (float x)
{
int row = current_slice_index / n_cols;
int col = current_slice_index - row*n_cols;
ModelViewProjection proj = get_projection_at (row, col);
Slice::slice_move_event (proj, x);
}
void LightBox::pan_event ()
{
int row = current_slice_index / n_cols;
int col = current_slice_index - row*n_cols;
ModelViewProjection proj = get_projection_at (row, col);
Slice::pan_event (proj);
}
void LightBox::panthrough_event ()
{
int row = current_slice_index / n_cols;
int col = current_slice_index - row*n_cols;
ModelViewProjection proj = get_projection_at (row, col);
Slice::panthrough_event (proj);
}
void LightBox::tilt_event ()
{
int row = current_slice_index / n_cols;
int col = current_slice_index - row*n_cols;
ModelViewProjection proj = get_projection_at (row, col);
Slice::tilt_event (proj);
}
void LightBox::rotate_event ()
{
int row = current_slice_index / n_cols;
int col = current_slice_index - row*n_cols;
ModelViewProjection proj = get_projection_at (row, col);
Slice::rotate_event (proj);
}
void LightBox::image_changed_event()
{
Base::image_changed_event();
if (image()) {
const auto& header = image()->header();
if (prev_image_name.empty()) {
float slice_inc = std::pow (header.spacing(0)*header.spacing(1)*header.spacing(2), 1.f/3.f);
slice_focus_inc_adjust_rate = slice_inc / 5.f;
set_slice_increment(slice_inc);
emit slice_increment_reset();
}
prev_image_name = image()->header().name();
}
else
prev_image_name.clear();
}
}
}
}
}
<|endoftext|> |
<commit_before>#include <Poco/Logger.h>
#include <Poco/JSON/Array.h>
#include "di/Injectable.h"
#include "gwmessage/GWMessageType.h"
#include "gwmessage/GWRequest.h"
#include "gwmessage/GWLastValueResponse.h"
#include "gwmessage/GWDeviceListResponse.h"
#include "gwmessage/GWAck.h"
#include "gws/GWMessageHandlerImpl.h"
#include "model/DeviceDescription.h"
#include "util/Sanitize.h"
BEEEON_OBJECT_BEGIN(BeeeOn, GWMessageHandlerImpl)
BEEEON_OBJECT_CASTABLE(GWMessageHandler)
BEEEON_OBJECT_PROPERTY("gatewayCommunicator", &GWMessageHandlerImpl::setGatewayCommunicator)
BEEEON_OBJECT_PROPERTY("responseExpectedQueue", &GWMessageHandlerImpl::setGWResponseExpectedQueue)
BEEEON_OBJECT_PROPERTY("rpcForwarder", &GWMessageHandlerImpl::setRPCForwarder)
BEEEON_OBJECT_PROPERTY("deviceService", &GWMessageHandlerImpl::setDeviceService)
BEEEON_OBJECT_PROPERTY("gatewayService", &GWMessageHandlerImpl::setGatewayService)
BEEEON_OBJECT_PROPERTY("sensorHistoryService", &GWMessageHandlerImpl::setSensorHistoryService)
BEEEON_OBJECT_PROPERTY("eventsExecutor", &GWMessageHandlerImpl::setEventsExecutor)
BEEEON_OBJECT_PROPERTY("dataListeners", &GWMessageHandlerImpl::registerDataListener)
BEEEON_OBJECT_PROPERTY("deviceListeners", &GWMessageHandlerImpl::registerDeviceListener)
BEEEON_OBJECT_HOOK("cleanup", &GWMessageHandlerImpl::cleanup)
BEEEON_OBJECT_END(BeeeOn, GWMessageHandlerImpl)
using namespace std;
using namespace Poco;
using namespace BeeeOn;
void GWMessageHandlerImpl::handle(const GWMessage::Ptr message,
const GatewayID &gatewayID)
{
if (!message.cast<GWRequest>().isNull())
handleRequest(message.cast<GWRequest>(), gatewayID);
else if (!message.cast<GWResponse>().isNull())
handleResponse(message.cast<GWResponse>(), gatewayID);
else if (!message.cast<GWSensorDataExport>().isNull())
handleSensorData(message.cast<GWSensorDataExport>(), gatewayID);
else
throw InvalidArgumentException("bad message type " + message->type());
}
void GWMessageHandlerImpl::handleRequest(GWRequest::Ptr request,
const GatewayID &gatewayID)
{
GWResponse::Ptr response;
switch(request->type()) {
case GWMessageType::NEW_DEVICE_REQUEST:
response = handleNewDevice(request.cast<GWNewDeviceRequest>(), gatewayID);
break;
case GWMessageType::NEW_DEVICE_GROUP_REQUEST:
response = handleNewDeviceGroup(request.cast<GWNewDeviceGroupRequest>(), gatewayID);
break;
case GWMessageType::LAST_VALUE_REQUEST:
response = handleLastValue(request.cast<GWLastValueRequest>(), gatewayID);
break;
case GWMessageType::DEVICE_LIST_REQUEST:
response = handleDeviceList(request.cast<GWDeviceListRequest>(), gatewayID);
break;
case GWMessageType::NOTICE_REQUEST:
response = handleNotice(request.cast<GWNoticeRequest>(), gatewayID);
break;
default:
throw InvalidArgumentException(
"bad request type " + request->type());
}
try {
m_gatewayCommunicator->sendMessage(gatewayID, response);
}
catch (const NotFoundException &e) {
logger().log(e, __FILE__, __LINE__);
}
}
void GWMessageHandlerImpl::handleResponse(GWResponse::Ptr response,
const GatewayID &gatewayID)
{
const GlobalID &responseID = response->id();
m_responseExpectedQueue->notifyDelivered(gatewayID, responseID);
m_rpcForwarder->forwardResponse(gatewayID, response);
if (!response->ackExpected())
return;
try {
m_gatewayCommunicator->sendMessage(gatewayID, response->ack());
}
catch (const NotFoundException &e) {
logger().log(e, __FILE__, __LINE__);
}
}
void GWMessageHandlerImpl::handleSensorData(GWSensorDataExport::Ptr dataExport,
const GatewayID &gatewayID)
{
GWSensorDataConfirm::Ptr dataConfirm = dataExport->confirm();
vector<SensorData> data = dataExport->data();
for (const auto &it : data) {
Device device = it.deviceID();
device.setGateway(gatewayID);
vector<ModuleValue> moduleValues;
for (const auto &sensorValue : it) {
ModuleValue moduleValue;
moduleValue.setModule(sensorValue.moduleID().value());
if (sensorValue.isValid())
moduleValue.setValue(sensorValue.value());
else
moduleValue.setValue(NAN);
moduleValues.push_back(moduleValue);
}
try {
m_sensorHistoryService->insertMany(
device, it.timestamp(), moduleValues);
if (moduleValues.empty())
continue;
SensorDataEvent e;
e.setGatewayID(gatewayID);
e.setDeviceID(device.id());
e.setStamp(it.timestamp());
e.setData(moduleValues);
m_dataEventSource.fireEvent(e, &SensorDataListener::onReceived);
}
catch (const Exception &e) {
logger().log(e, __FILE__, __LINE__);
}
}
try {
m_gatewayCommunicator->sendMessage(gatewayID, dataConfirm);
}
catch (const NotFoundException &e) {
logger().log(e, __FILE__, __LINE__);
}
}
GWResponse::Ptr GWMessageHandlerImpl::handleNewDevice(
GWNewDeviceRequest::Ptr request, const GatewayID &gatewayID)
{
GWResponse::Ptr response = request->derive();
Device device(request->deviceID());
device.setRefresh(request->deviceDescription().refreshTime());
DeviceEvent event = {gatewayID, device.id()};
try {
if (m_deviceService->registerDevice(device,
sanitizeDeviceDescription(request->deviceDescription()),
gatewayID)) {
response->setStatus(GWResponse::Status::SUCCESS);
event.setName(device.name());
event.setType(*device.type());
m_deviceEventSource.fireEvent(event, &DeviceListener::onNewDevice);
}
else {
response->setStatus(GWResponse::Status::FAILED);
m_deviceEventSource.fireEvent(event, &DeviceListener::onRefusedNewDevice);
}
}
BEEEON_CATCH_CHAIN_ACTION(logger(),
response->setStatus(GWResponse::Status::FAILED);
m_deviceEventSource.fireEvent(event, &DeviceListener::onRefusedNewDevice);
);
return response;
}
GWResponse::Ptr GWMessageHandlerImpl::handleNewDeviceGroup(
GWNewDeviceGroupRequest::Ptr request, const GatewayID &gatewayID)
{
GWResponse::Ptr response = request->derive();
vector<DeviceDescription> descriptions;
vector<DeviceEvent> events;
for (const auto &des : request->deviceDescriptions()) {
descriptions.emplace_back(sanitizeDeviceDescription(des));
const DeviceEvent event = {gatewayID, des.id()};
events.emplace_back(event);
}
try {
m_deviceService->registerDeviceGroup(descriptions, gatewayID);
response->setStatus(GWResponse::Status::SUCCESS);
for (auto &event : events)
m_deviceEventSource.fireEvent(event, &DeviceListener::onNewDevice);
}
BEEEON_CATCH_CHAIN_ACTION(logger(),
response->setStatus(GWResponse::Status::FAILED);
for (auto &event : events)
m_deviceEventSource.fireEvent(event, &DeviceListener::onRefusedNewDevice);
);
return response;
}
GWResponse::Ptr GWMessageHandlerImpl::handleLastValue(
GWLastValueRequest::Ptr request, const GatewayID &gatewayID)
{
GWLastValueResponse::Ptr response =
request->derive().cast<GWLastValueResponse>();
Device device(request->deviceID());
device.setGateway(gatewayID);
ModuleInfo module;
module.setId(request->moduleID().value());
Timestamp timestamp;
double value;
try {
if (m_sensorHistoryService->fetchLast(device, module, timestamp, value)) {
response->setValid(!std::isnan(value));
response->setValue(value);
response->setStatus(GWResponse::Status::SUCCESS);
}
else {
response->setStatus(GWResponse::Status::FAILED);
}
}
BEEEON_CATCH_CHAIN_ACTION(logger(),
response->setStatus(GWResponse::Status::FAILED);
);
return response;
}
GWResponse::Ptr GWMessageHandlerImpl::handleDeviceList(
GWDeviceListRequest::Ptr request, const GatewayID &gatewayID)
{
GWDeviceListResponse::Ptr response(
request->derive().cast<GWDeviceListResponse>()
);
DevicePrefix prefix(request->devicePrefix());
vector<DeviceWithData> devices;
try {
m_deviceService->fetchActiveWithPrefix(devices, gatewayID, prefix);
vector<DeviceID> deviceIDs;
for (const auto &device : devices)
deviceIDs.push_back(device.id());
response->setDevices(deviceIDs);
for (const auto &device : devices) {
size_t id = 0;
map<ModuleID, double> values;
for (const auto &value : device.values()) {
if (value.isValid())
values.emplace(id++, value.value());
}
if (values.empty())
continue;
response->setModulesValues(device.id(), values);
response->setRefreshFor(device.id(), device.refresh());
}
response->setStatus(GWResponse::Status::SUCCESS);
}
BEEEON_CATCH_CHAIN_ACTION(logger(),
response->setStatus(GWResponse::Status::FAILED);
);
return response;
}
GWResponse::Ptr GWMessageHandlerImpl::handleNotice(
GWNoticeRequest::Ptr request,
const GatewayID &gatewayID)
{
GWResponse::Ptr response = request->derive();
GatewayMessage message;
message.setGateway({gatewayID});
message.setAt(request->at());
message.setSeverity(request->severity());
message.setKey("gateway." + Sanitize::token(request->key()));
auto context = request->context();
const auto names = context->getNames();
// sanitize strings
for (const auto &name : names) {
const auto value = context->get(name);
context->remove(name);
if (value.isString()) {
context->set(
Sanitize::token(name),
Sanitize::common(value.extract<string>()));
}
else if (value.isArray()) {
JSON::Array::Ptr a = value.extract<JSON::Array::Ptr>();
for (size_t i = 0; i < a->size(); ++i) {
auto value = a->get(i);
if (value.isString())
a->set(i, Sanitize::common(value.extract<string>()));
}
context->set(Sanitize::token(name), a);
}
else {
context->set(Sanitize::token(name), value);
}
}
message.setContext(context);
m_gatewayService->deliverMessage(message);
return response;
}
DeviceDescription GWMessageHandlerImpl::sanitizeDeviceDescription(
const DeviceDescription& description)
{
DeviceDescription des;
des.setID(description.id());
des.setVendor(Sanitize::common(description.vendor()));
des.setProductName(Sanitize::common(description.productName()));
des.setDataTypes(description.dataTypes());
des.setRefreshTime(description.refreshTime());
return des;
}
void GWMessageHandlerImpl::cleanup()
{
m_gatewayCommunicator = nullptr;
m_responseExpectedQueue = nullptr;
m_rpcForwarder = nullptr;
}
void GWMessageHandlerImpl::setGatewayCommunicator(
GatewayCommunicator::Ptr communicator)
{
m_gatewayCommunicator = communicator;
}
void GWMessageHandlerImpl::setGWResponseExpectedQueue(
GWResponseExpectedQueue::Ptr queue)
{
m_responseExpectedQueue = queue;
}
void GWMessageHandlerImpl::setRPCForwarder(RPCForwarder::Ptr forwarder)
{
m_rpcForwarder = forwarder;
}
void GWMessageHandlerImpl::setDeviceService(GWSDeviceService::Ptr service)
{
m_deviceService = service;
}
void GWMessageHandlerImpl::setGatewayService(GWSGatewayService::Ptr service)
{
m_gatewayService = service;
}
void GWMessageHandlerImpl::setSensorHistoryService(
GWSSensorHistoryService::Ptr service)
{
m_sensorHistoryService = service;
}
void GWMessageHandlerImpl::registerDataListener(SensorDataListener::Ptr listener)
{
m_dataEventSource.addListener(listener);
}
void GWMessageHandlerImpl::registerDeviceListener(DeviceListener::Ptr listener)
{
m_deviceEventSource.addListener(listener);
}
void GWMessageHandlerImpl::setEventsExecutor(AsyncExecutor::Ptr executor)
{
m_dataEventSource.setAsyncExecutor(executor);
m_deviceEventSource.setAsyncExecutor(executor);
}
<commit_msg>GWMessageHandlerImpl: fix Poco before 1.9<commit_after>#include <Poco/Logger.h>
#include <Poco/JSON/Array.h>
#include "di/Injectable.h"
#include "gwmessage/GWMessageType.h"
#include "gwmessage/GWRequest.h"
#include "gwmessage/GWLastValueResponse.h"
#include "gwmessage/GWDeviceListResponse.h"
#include "gwmessage/GWAck.h"
#include "gws/GWMessageHandlerImpl.h"
#include "model/DeviceDescription.h"
#include "util/Sanitize.h"
BEEEON_OBJECT_BEGIN(BeeeOn, GWMessageHandlerImpl)
BEEEON_OBJECT_CASTABLE(GWMessageHandler)
BEEEON_OBJECT_PROPERTY("gatewayCommunicator", &GWMessageHandlerImpl::setGatewayCommunicator)
BEEEON_OBJECT_PROPERTY("responseExpectedQueue", &GWMessageHandlerImpl::setGWResponseExpectedQueue)
BEEEON_OBJECT_PROPERTY("rpcForwarder", &GWMessageHandlerImpl::setRPCForwarder)
BEEEON_OBJECT_PROPERTY("deviceService", &GWMessageHandlerImpl::setDeviceService)
BEEEON_OBJECT_PROPERTY("gatewayService", &GWMessageHandlerImpl::setGatewayService)
BEEEON_OBJECT_PROPERTY("sensorHistoryService", &GWMessageHandlerImpl::setSensorHistoryService)
BEEEON_OBJECT_PROPERTY("eventsExecutor", &GWMessageHandlerImpl::setEventsExecutor)
BEEEON_OBJECT_PROPERTY("dataListeners", &GWMessageHandlerImpl::registerDataListener)
BEEEON_OBJECT_PROPERTY("deviceListeners", &GWMessageHandlerImpl::registerDeviceListener)
BEEEON_OBJECT_HOOK("cleanup", &GWMessageHandlerImpl::cleanup)
BEEEON_OBJECT_END(BeeeOn, GWMessageHandlerImpl)
using namespace std;
using namespace Poco;
using namespace BeeeOn;
void GWMessageHandlerImpl::handle(const GWMessage::Ptr message,
const GatewayID &gatewayID)
{
if (!message.cast<GWRequest>().isNull())
handleRequest(message.cast<GWRequest>(), gatewayID);
else if (!message.cast<GWResponse>().isNull())
handleResponse(message.cast<GWResponse>(), gatewayID);
else if (!message.cast<GWSensorDataExport>().isNull())
handleSensorData(message.cast<GWSensorDataExport>(), gatewayID);
else
throw InvalidArgumentException("bad message type " + message->type());
}
void GWMessageHandlerImpl::handleRequest(GWRequest::Ptr request,
const GatewayID &gatewayID)
{
GWResponse::Ptr response;
switch(request->type()) {
case GWMessageType::NEW_DEVICE_REQUEST:
response = handleNewDevice(request.cast<GWNewDeviceRequest>(), gatewayID);
break;
case GWMessageType::NEW_DEVICE_GROUP_REQUEST:
response = handleNewDeviceGroup(request.cast<GWNewDeviceGroupRequest>(), gatewayID);
break;
case GWMessageType::LAST_VALUE_REQUEST:
response = handleLastValue(request.cast<GWLastValueRequest>(), gatewayID);
break;
case GWMessageType::DEVICE_LIST_REQUEST:
response = handleDeviceList(request.cast<GWDeviceListRequest>(), gatewayID);
break;
case GWMessageType::NOTICE_REQUEST:
response = handleNotice(request.cast<GWNoticeRequest>(), gatewayID);
break;
default:
throw InvalidArgumentException(
"bad request type " + request->type());
}
try {
m_gatewayCommunicator->sendMessage(gatewayID, response);
}
catch (const NotFoundException &e) {
logger().log(e, __FILE__, __LINE__);
}
}
void GWMessageHandlerImpl::handleResponse(GWResponse::Ptr response,
const GatewayID &gatewayID)
{
const GlobalID &responseID = response->id();
m_responseExpectedQueue->notifyDelivered(gatewayID, responseID);
m_rpcForwarder->forwardResponse(gatewayID, response);
if (!response->ackExpected())
return;
try {
m_gatewayCommunicator->sendMessage(gatewayID, response->ack());
}
catch (const NotFoundException &e) {
logger().log(e, __FILE__, __LINE__);
}
}
void GWMessageHandlerImpl::handleSensorData(GWSensorDataExport::Ptr dataExport,
const GatewayID &gatewayID)
{
GWSensorDataConfirm::Ptr dataConfirm = dataExport->confirm();
vector<SensorData> data = dataExport->data();
for (const auto &it : data) {
Device device = it.deviceID();
device.setGateway(gatewayID);
vector<ModuleValue> moduleValues;
for (const auto &sensorValue : it) {
ModuleValue moduleValue;
moduleValue.setModule(sensorValue.moduleID().value());
if (sensorValue.isValid())
moduleValue.setValue(sensorValue.value());
else
moduleValue.setValue(NAN);
moduleValues.push_back(moduleValue);
}
try {
m_sensorHistoryService->insertMany(
device, it.timestamp(), moduleValues);
if (moduleValues.empty())
continue;
SensorDataEvent e;
e.setGatewayID(gatewayID);
e.setDeviceID(device.id());
e.setStamp(it.timestamp());
e.setData(moduleValues);
m_dataEventSource.fireEvent(e, &SensorDataListener::onReceived);
}
catch (const Exception &e) {
logger().log(e, __FILE__, __LINE__);
}
}
try {
m_gatewayCommunicator->sendMessage(gatewayID, dataConfirm);
}
catch (const NotFoundException &e) {
logger().log(e, __FILE__, __LINE__);
}
}
GWResponse::Ptr GWMessageHandlerImpl::handleNewDevice(
GWNewDeviceRequest::Ptr request, const GatewayID &gatewayID)
{
GWResponse::Ptr response = request->derive();
Device device(request->deviceID());
device.setRefresh(request->deviceDescription().refreshTime());
DeviceEvent event = {gatewayID, device.id()};
try {
if (m_deviceService->registerDevice(device,
sanitizeDeviceDescription(request->deviceDescription()),
gatewayID)) {
response->setStatus(GWResponse::Status::SUCCESS);
event.setName(device.name());
event.setType(*device.type());
m_deviceEventSource.fireEvent(event, &DeviceListener::onNewDevice);
}
else {
response->setStatus(GWResponse::Status::FAILED);
m_deviceEventSource.fireEvent(event, &DeviceListener::onRefusedNewDevice);
}
}
BEEEON_CATCH_CHAIN_ACTION(logger(),
response->setStatus(GWResponse::Status::FAILED);
m_deviceEventSource.fireEvent(event, &DeviceListener::onRefusedNewDevice);
);
return response;
}
GWResponse::Ptr GWMessageHandlerImpl::handleNewDeviceGroup(
GWNewDeviceGroupRequest::Ptr request, const GatewayID &gatewayID)
{
GWResponse::Ptr response = request->derive();
vector<DeviceDescription> descriptions;
vector<DeviceEvent> events;
for (const auto &des : request->deviceDescriptions()) {
descriptions.emplace_back(sanitizeDeviceDescription(des));
const DeviceEvent event = {gatewayID, des.id()};
events.emplace_back(event);
}
try {
m_deviceService->registerDeviceGroup(descriptions, gatewayID);
response->setStatus(GWResponse::Status::SUCCESS);
for (auto &event : events)
m_deviceEventSource.fireEvent(event, &DeviceListener::onNewDevice);
}
BEEEON_CATCH_CHAIN_ACTION(logger(),
response->setStatus(GWResponse::Status::FAILED);
for (auto &event : events)
m_deviceEventSource.fireEvent(event, &DeviceListener::onRefusedNewDevice);
);
return response;
}
GWResponse::Ptr GWMessageHandlerImpl::handleLastValue(
GWLastValueRequest::Ptr request, const GatewayID &gatewayID)
{
GWLastValueResponse::Ptr response =
request->derive().cast<GWLastValueResponse>();
Device device(request->deviceID());
device.setGateway(gatewayID);
ModuleInfo module;
module.setId(request->moduleID().value());
Timestamp timestamp;
double value;
try {
if (m_sensorHistoryService->fetchLast(device, module, timestamp, value)) {
response->setValid(!std::isnan(value));
response->setValue(value);
response->setStatus(GWResponse::Status::SUCCESS);
}
else {
response->setStatus(GWResponse::Status::FAILED);
}
}
BEEEON_CATCH_CHAIN_ACTION(logger(),
response->setStatus(GWResponse::Status::FAILED);
);
return response;
}
GWResponse::Ptr GWMessageHandlerImpl::handleDeviceList(
GWDeviceListRequest::Ptr request, const GatewayID &gatewayID)
{
GWDeviceListResponse::Ptr response(
request->derive().cast<GWDeviceListResponse>()
);
DevicePrefix prefix(request->devicePrefix());
vector<DeviceWithData> devices;
try {
m_deviceService->fetchActiveWithPrefix(devices, gatewayID, prefix);
vector<DeviceID> deviceIDs;
for (const auto &device : devices)
deviceIDs.push_back(device.id());
response->setDevices(deviceIDs);
for (const auto &device : devices) {
size_t id = 0;
map<ModuleID, double> values;
for (const auto &value : device.values()) {
if (value.isValid())
values.emplace(id++, value.value());
}
if (values.empty())
continue;
response->setModulesValues(device.id(), values);
response->setRefreshFor(device.id(), device.refresh());
}
response->setStatus(GWResponse::Status::SUCCESS);
}
BEEEON_CATCH_CHAIN_ACTION(logger(),
response->setStatus(GWResponse::Status::FAILED);
);
return response;
}
GWResponse::Ptr GWMessageHandlerImpl::handleNotice(
GWNoticeRequest::Ptr request,
const GatewayID &gatewayID)
{
GWResponse::Ptr response = request->derive();
GatewayMessage message;
message.setGateway({gatewayID});
message.setAt(request->at());
message.setSeverity(request->severity());
message.setKey("gateway." + Sanitize::token(request->key()));
auto context = request->context();
vector<string> names;
for (const auto &pair : *context)
names.emplace_back(pair.first);
// sanitize strings
for (const auto &name : names) {
const auto value = context->get(name);
context->remove(name);
if (value.isString()) {
context->set(
Sanitize::token(name),
Sanitize::common(value.extract<string>()));
}
else if (value.isArray()) {
JSON::Array::Ptr a = value.extract<JSON::Array::Ptr>();
for (size_t i = 0; i < a->size(); ++i) {
auto value = a->get(i);
if (value.isString())
a->set(i, Sanitize::common(value.extract<string>()));
}
context->set(Sanitize::token(name), a);
}
else {
context->set(Sanitize::token(name), value);
}
}
message.setContext(context);
m_gatewayService->deliverMessage(message);
return response;
}
DeviceDescription GWMessageHandlerImpl::sanitizeDeviceDescription(
const DeviceDescription& description)
{
DeviceDescription des;
des.setID(description.id());
des.setVendor(Sanitize::common(description.vendor()));
des.setProductName(Sanitize::common(description.productName()));
des.setDataTypes(description.dataTypes());
des.setRefreshTime(description.refreshTime());
return des;
}
void GWMessageHandlerImpl::cleanup()
{
m_gatewayCommunicator = nullptr;
m_responseExpectedQueue = nullptr;
m_rpcForwarder = nullptr;
}
void GWMessageHandlerImpl::setGatewayCommunicator(
GatewayCommunicator::Ptr communicator)
{
m_gatewayCommunicator = communicator;
}
void GWMessageHandlerImpl::setGWResponseExpectedQueue(
GWResponseExpectedQueue::Ptr queue)
{
m_responseExpectedQueue = queue;
}
void GWMessageHandlerImpl::setRPCForwarder(RPCForwarder::Ptr forwarder)
{
m_rpcForwarder = forwarder;
}
void GWMessageHandlerImpl::setDeviceService(GWSDeviceService::Ptr service)
{
m_deviceService = service;
}
void GWMessageHandlerImpl::setGatewayService(GWSGatewayService::Ptr service)
{
m_gatewayService = service;
}
void GWMessageHandlerImpl::setSensorHistoryService(
GWSSensorHistoryService::Ptr service)
{
m_sensorHistoryService = service;
}
void GWMessageHandlerImpl::registerDataListener(SensorDataListener::Ptr listener)
{
m_dataEventSource.addListener(listener);
}
void GWMessageHandlerImpl::registerDeviceListener(DeviceListener::Ptr listener)
{
m_deviceEventSource.addListener(listener);
}
void GWMessageHandlerImpl::setEventsExecutor(AsyncExecutor::Ptr executor)
{
m_dataEventSource.setAsyncExecutor(executor);
m_deviceEventSource.setAsyncExecutor(executor);
}
<|endoftext|> |
<commit_before>/************************************************************************/
/* */
/* Copyright 1998-2004 by Ullrich Koethe */
/* Cognitive Systems Group, University of Hamburg, Germany */
/* */
/* This file is part of the VIGRA computer vision library. */
/* You may use, modify, and distribute this software according */
/* to the terms stated in the LICENSE file included in */
/* the VIGRA distribution. */
/* */
/* The VIGRA Website is */
/* http://kogs-www.informatik.uni-hamburg.de/~koethe/vigra/ */
/* Please direct questions, bug reports, and contributions to */
/* koethe@informatik.uni-hamburg.de */
/* */
/* THIS SOFTWARE IS PROVIDED AS IS AND WITHOUT ANY EXPRESS OR */
/* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED */
/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */
/* */
/************************************************************************/
#ifndef VIGRA_GAUSSIANS_HXX
#define VIGRA_GAUSSIANS_HXX
#include <cmath>
#include "vigra/config.hxx"
#include "vigra/mathutil.hxx"
#include "vigra/array_vector.hxx"
namespace vigra {
/** \addtogroup MathFunctions Mathematical Functions
*/
//@{
/*!
<b>\#include</b> "<a href="gaussians_8hxx-source.html">vigra/gaussians.hxx</a>"<br>
Namespace: vigra
*/
template <class T = double>
class Gaussian
{
public:
typedef T value_type;
typedef T argument_type;
typedef T result_type;
explicit Gaussian(T sigma = 1.0, unsigned int derivativeOrder = 0)
: sigma_(sigma),
sigma2_(-0.5 / sigma / sigma),
norm_(0.0),
order_(derivativeOrder),
hermitePolynomial_(derivativeOrder / 2 + 1)
{
vigra_precondition(sigma_ > 0.0,
"Gaussian::Gaussian(): sigma > 0 required.");
switch(order_)
{
case 1:
case 2:
norm_ = -1.0 / (VIGRA_CSTD::sqrt(2.0 * M_PI) * sq(sigma) * sigma);
break;
case 3:
norm_ = 1.0 / (VIGRA_CSTD::sqrt(2.0 * M_PI) * sq(sigma) * sq(sigma) * sigma);
break;
default:
norm_ = 1.0 / VIGRA_CSTD::sqrt(2.0 * M_PI) / sigma;
}
calculateHermitePolynomial();
}
result_type operator()(argument_type x) const;
value_type sigma() const
{ return sigma_; }
unsigned int derivativeOrder() const
{ return order_; }
double radius(double sigmaMultiple = 3.0) const
{ return sigmaMultiple * sigma_ + 0.5 * derivativeOrder(); }
private:
void calculateHermitePolynomial();
T horner(T x) const;
T sigma_, sigma2_, norm_;
unsigned int order_;
ArrayVector<T> hermitePolynomial_;
};
template <class T>
typename Gaussian<T>::result_type
Gaussian<T>::operator()(argument_type x) const
{
T x2 = x * x;
T g = norm_ * VIGRA_CSTD::exp(x2 * sigma2_);
switch(order_)
{
case 0:
return g;
case 1:
return x * g;
case 2:
return (1.0 - sq(x / sigma_)) * g;
case 3:
return (3.0 - sq(x / sigma_)) * x * g;
default:
return order_ % 2 == 0 ?
g * horner(x2)
: x * g * horner(x2);
}
}
template <class T>
T Gaussian<T>::horner(T x) const
{
int i = order_ / 2;
T res = hermitePolynomial_[i];
for(--i; i >= 0; --i)
res = x * res + hermitePolynomial_[i];
return res;
}
template <class T>
void Gaussian<T>::calculateHermitePolynomial()
{
if(order_ == 0)
{
hermitePolynomial_[0] = 1.0;
}
else if(order_ == 1)
{
hermitePolynomial_[0] = 2.0 * sigma2_;
}
else
{
T s2 = 2.0 * sigma2_;
ArrayVector<T> hn(3*order_+3, 0.0);
typename ArrayVector<T>::iterator hn0 = hn.begin(),
hn1 = hn0 + order_+1,
hn2 = hn1 + order_+1,
ht;
hn2[0] = 1.0;
hn1[1] = s2;
for(unsigned int i = 2; i <= order_; ++i)
{
hn0[0] = s2 * (i-1) * hn2[0];
for(unsigned int j = 1; j <= i; ++j)
hn0[j] = s2 * (hn1[j-1] + (i-1) * hn2[j]);
ht = hn2;
hn2 = hn1;
hn1 = hn0;
hn0 = ht;
}
for(unsigned int i = 0; i < hermitePolynomial_.size(); ++i)
hermitePolynomial_[i] = order_ % 2 == 0 ?
hn1[2*i]
: hn1[2*i+1];
}
}
//@}
} // namespace vigra
#endif /* VIGRA_GAUSSIANS_HXX */
<commit_msg>added comments<commit_after>/************************************************************************/
/* */
/* Copyright 1998-2004 by Ullrich Koethe */
/* Cognitive Systems Group, University of Hamburg, Germany */
/* */
/* This file is part of the VIGRA computer vision library. */
/* You may use, modify, and distribute this software according */
/* to the terms stated in the LICENSE file included in */
/* the VIGRA distribution. */
/* */
/* The VIGRA Website is */
/* http://kogs-www.informatik.uni-hamburg.de/~koethe/vigra/ */
/* Please direct questions, bug reports, and contributions to */
/* koethe@informatik.uni-hamburg.de */
/* */
/* THIS SOFTWARE IS PROVIDED AS IS AND WITHOUT ANY EXPRESS OR */
/* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED */
/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */
/* */
/************************************************************************/
#ifndef VIGRA_GAUSSIANS_HXX
#define VIGRA_GAUSSIANS_HXX
#include <cmath>
#include "vigra/config.hxx"
#include "vigra/mathutil.hxx"
#include "vigra/array_vector.hxx"
namespace vigra {
/** \addtogroup MathFunctions Mathematical Functions
*/
//@{
/*!
<b>\#include</b> "<a href="gaussians_8hxx-source.html">vigra/gaussians.hxx</a>"<br>
Namespace: vigra
*/
template <class T = double>
class Gaussian
{
public:
typedef T value_type;
typedef T argument_type;
typedef T result_type;
explicit Gaussian(T sigma = 1.0, unsigned int derivativeOrder = 0)
: sigma_(sigma),
sigma2_(-0.5 / sigma / sigma),
norm_(0.0),
order_(derivativeOrder),
hermitePolynomial_(derivativeOrder / 2 + 1)
{
vigra_precondition(sigma_ > 0.0,
"Gaussian::Gaussian(): sigma > 0 required.");
switch(order_)
{
case 1:
case 2:
norm_ = -1.0 / (VIGRA_CSTD::sqrt(2.0 * M_PI) * sq(sigma) * sigma);
break;
case 3:
norm_ = 1.0 / (VIGRA_CSTD::sqrt(2.0 * M_PI) * sq(sigma) * sq(sigma) * sigma);
break;
default:
norm_ = 1.0 / VIGRA_CSTD::sqrt(2.0 * M_PI) / sigma;
}
calculateHermitePolynomial();
}
result_type operator()(argument_type x) const;
value_type sigma() const
{ return sigma_; }
unsigned int derivativeOrder() const
{ return order_; }
double radius(double sigmaMultiple = 3.0) const
{ return sigmaMultiple * sigma_ + 0.5 * derivativeOrder(); }
private:
void calculateHermitePolynomial();
T horner(T x) const;
T sigma_, sigma2_, norm_;
unsigned int order_;
ArrayVector<T> hermitePolynomial_;
};
template <class T>
typename Gaussian<T>::result_type
Gaussian<T>::operator()(argument_type x) const
{
T x2 = x * x;
T g = norm_ * VIGRA_CSTD::exp(x2 * sigma2_);
switch(order_)
{
case 0:
return g;
case 1:
return x * g;
case 2:
return (1.0 - sq(x / sigma_)) * g;
case 3:
return (3.0 - sq(x / sigma_)) * x * g;
default:
return order_ % 2 == 0 ?
g * horner(x2)
: x * g * horner(x2);
}
}
template <class T>
T Gaussian<T>::horner(T x) const
{
int i = order_ / 2;
T res = hermitePolynomial_[i];
for(--i; i >= 0; --i)
res = x * res + hermitePolynomial_[i];
return res;
}
template <class T>
void Gaussian<T>::calculateHermitePolynomial()
{
if(order_ == 0)
{
hermitePolynomial_[0] = 1.0;
}
else if(order_ == 1)
{
hermitePolynomial_[0] = -1.0 / sigma_ / sigma_;
}
else
{
// calculate Hermite polynomial for requested derivative
// recursively according to
// (0)
// h (x) = 1
//
// (1)
// h (x) = -x / s^2
//
// (n+1) (n) (n-1)
// h (x) = -1 / s^2 * [ x * h (x) + n * h (x) ]
//
T s2 = -1.0 / sigma_ / sigma_;
ArrayVector<T> hn(3*order_+3, 0.0);
typename ArrayVector<T>::iterator hn0 = hn.begin(),
hn1 = hn0 + order_+1,
hn2 = hn1 + order_+1,
ht;
hn2[0] = 1.0;
hn1[1] = s2;
for(unsigned int i = 2; i <= order_; ++i)
{
hn0[0] = s2 * (i-1) * hn2[0];
for(unsigned int j = 1; j <= i; ++j)
hn0[j] = s2 * (hn1[j-1] + (i-1) * hn2[j]);
ht = hn2;
hn2 = hn1;
hn1 = hn0;
hn0 = ht;
}
// keep only non-zero coefficients of the polynomial
for(unsigned int i = 0; i < hermitePolynomial_.size(); ++i)
hermitePolynomial_[i] = order_ % 2 == 0 ?
hn1[2*i]
: hn1[2*i+1];
}
}
//@}
} // namespace vigra
#endif /* VIGRA_GAUSSIANS_HXX */
<|endoftext|> |
<commit_before>#include "qhexedithighlighter.h"
QHexEditHighlighter::QHexEditHighlighter(QHexEditData *hexeditdata, QColor backdefault, QColor foredefault, QObject *parent): QObject(parent), _hexeditdata(hexeditdata), _backdefault(backdefault), _foredefault(foredefault)
{
}
void QHexEditHighlighter::colors(qint64 pos, QColor &bc, QColor &fc) const
{
bc = this->backColor(pos);
fc = this->foreColor(pos);
}
QColor QHexEditHighlighter::defaultBackColor() const
{
return this->_backdefault;
}
QColor QHexEditHighlighter::defaultForeColor() const
{
return this->_foredefault;
}
QColor QHexEditHighlighter::backColor(qint64 pos) const
{
if(!this->_backgroundmap.contains(pos))
return this->_backdefault;
return this->_backgroundmap[pos];
}
QColor QHexEditHighlighter::foreColor(qint64 pos) const
{
if(!this->_foregroundmap.contains(pos))
return this->_foredefault;
return this->_foregroundmap.contains(pos);
}
void QHexEditHighlighter::highlightForeground(qint64 start, qint64 end, const QColor& color)
{
if(start < 0)
start = 0;
if(end > this->_hexeditdata->length())
end = this->_hexeditdata->length() - 1;
this->internalHighlight(this->_foregroundmap, start, end, color);
}
void QHexEditHighlighter::highlightBackground(qint64 start, qint64 end, const QColor& color)
{
if(start < 0)
start = 0;
if(end > this->_hexeditdata->length())
end = this->_hexeditdata->length() - 1;
this->internalHighlight(this->_backgroundmap, start, end, color);
}
void QHexEditHighlighter::clearHighlight(qint64 start, qint64 end)
{
if(start < 0)
start = 0;
if(end > this->_hexeditdata->length())
end = this->_hexeditdata->length() - 1;
this->internalClear(this->_foregroundmap, start, end);
this->internalClear(this->_backgroundmap, start, end);
}
void QHexEditHighlighter::internalClear(QHexEditHighlighter::ColorMap& rangelist, qint64 start, qint64 end)
{
for(qint64 k = start; k <= end; k++)
{
if(rangelist.contains(k))
rangelist.remove(k);
}
}
void QHexEditHighlighter::internalHighlight(QHexEditHighlighter::ColorMap &rangelist, qint64 start, qint64 end, const QColor& color)
{
for(qint64 k = start; k <= end; k++)
rangelist[k] = color;
}
<commit_msg>Fixed copy/paste typo in QHexEditHighlighter<commit_after>#include "qhexedithighlighter.h"
QHexEditHighlighter::QHexEditHighlighter(QHexEditData *hexeditdata, QColor backdefault, QColor foredefault, QObject *parent): QObject(parent), _hexeditdata(hexeditdata), _backdefault(backdefault), _foredefault(foredefault)
{
}
void QHexEditHighlighter::colors(qint64 pos, QColor &bc, QColor &fc) const
{
bc = this->backColor(pos);
fc = this->foreColor(pos);
}
QColor QHexEditHighlighter::defaultBackColor() const
{
return this->_backdefault;
}
QColor QHexEditHighlighter::defaultForeColor() const
{
return this->_foredefault;
}
QColor QHexEditHighlighter::backColor(qint64 pos) const
{
if(!this->_backgroundmap.contains(pos))
return this->_backdefault;
return this->_backgroundmap[pos];
}
QColor QHexEditHighlighter::foreColor(qint64 pos) const
{
if(!this->_foregroundmap.contains(pos))
return this->_foredefault;
return this->_foregroundmap[pos];
}
void QHexEditHighlighter::highlightForeground(qint64 start, qint64 end, const QColor& color)
{
if(start < 0)
start = 0;
if(end > this->_hexeditdata->length())
end = this->_hexeditdata->length() - 1;
this->internalHighlight(this->_foregroundmap, start, end, color);
}
void QHexEditHighlighter::highlightBackground(qint64 start, qint64 end, const QColor& color)
{
if(start < 0)
start = 0;
if(end > this->_hexeditdata->length())
end = this->_hexeditdata->length() - 1;
this->internalHighlight(this->_backgroundmap, start, end, color);
}
void QHexEditHighlighter::clearHighlight(qint64 start, qint64 end)
{
if(start < 0)
start = 0;
if(end > this->_hexeditdata->length())
end = this->_hexeditdata->length() - 1;
this->internalClear(this->_foregroundmap, start, end);
this->internalClear(this->_backgroundmap, start, end);
}
void QHexEditHighlighter::internalClear(QHexEditHighlighter::ColorMap& rangelist, qint64 start, qint64 end)
{
for(qint64 k = start; k <= end; k++)
{
if(rangelist.contains(k))
rangelist.remove(k);
}
}
void QHexEditHighlighter::internalHighlight(QHexEditHighlighter::ColorMap &rangelist, qint64 start, qint64 end, const QColor& color)
{
for(qint64 k = start; k <= end; k++)
rangelist[k] = color;
}
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (c) 2016, Johan Mabille and Sylvain Corlay *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
/**
* @brief functions to obtain xgenerators generating random numbers with given shape
*/
#ifndef XRANDOM_HPP
#define XRANDOM_HPP
#include <utility>
#include <random>
#include <memory>
#include <sstream>
#include "xgenerator.hpp"
namespace xt
{
namespace detail
{
template <class T>
struct random_impl
{
using value_type = T;
random_impl(std::function<value_type()>&& generator) :
m_generator(std::move(generator))
{
}
template <class... Args>
inline value_type operator()(Args... /*args*/) const
{
return m_generator();
}
inline value_type operator[](const xindex& /*idx*/) const
{
return m_generator();
}
template <class It>
inline value_type element(It /*first*/, It /*last*/) const
{
return m_generator();
}
private:
std::function<value_type()> m_generator;
};
}
namespace random
{
using default_engine_type = std::mt19937;
using seed_type = default_engine_type::result_type;
inline default_engine_type& get_default_random_engine()
{
static default_engine_type mt;
return mt;
}
inline void set_seed(seed_type seed)
{
get_default_random_engine().seed(seed);
}
}
/**
* @function rand
* @brief xexpression with specified @p shape containing uniformly distributed random numbers
* in the interval from @p lower to @p upper, excluding upper.
*
* Numbers are drawn from @c std::uniform_real_distribution.
*
* @param shape shape of resulting xexpression
* @param lower lower bound
* @param upper upper bound
* @param engine random number engine
*
* @tparam T number type to use
*/
template <class T, class E = random::default_engine_type>
inline auto rand(std::vector<std::size_t> shape, T lower = 0, T upper = 1,
E& engine = random::get_default_random_engine())
{
std::uniform_real_distribution<T> dist(lower, upper);
return detail::make_xgenerator(detail::random_impl<T>(std::bind(dist, std::ref(engine))), shape);
}
/**
* @function randint
* @brief xexpression with specified @p shape containing uniformly distributed
* random integers in the interval from @p lower to @p upper, excluding upper.
*
* Numbers are drawn from @c std::uniform_int_distribution.
*
* @param shape shape of resulting xexpression
* @param lower lower bound
* @param upper upper bound
* @param engine random number engine
*
* @tparam T number type to use
*/
template <class T, class E = random::default_engine_type>
inline auto randint(std::vector<std::size_t> shape,
T lower = 0, T upper = std::numeric_limits<T>::max(),
E& engine = random::get_default_random_engine())
{
std::uniform_int_distribution<T> dist(lower, upper - 1);
return detail::make_xgenerator(detail::random_impl<T>(std::bind(dist, std::ref(engine))), shape);
}
/**
* @function randn
* @brief xexpression with specified @p shape containing numbers sampled from
* the Normal (Gaussian) random number distribution with mean @p mean and
* standard deviation @p std_dev.
*
* Numbers are drawn from @c std::normal_distribution.
*
* @param shape shape of resulting xexpression
* @param mean mean of normal distribution
* @param std_dev standard deviation of normal distribution
* @param engine random number engine
*
* @tparam T number type to use
*/
template <class T, class E = random::default_engine_type>
inline auto randn(std::vector<std::size_t> shape,
T mean = 0, T std_dev = 1,
E& engine = random::get_default_random_engine())
{
std::normal_distribution<T> dist(mean, std_dev);
return detail::make_xgenerator(detail::random_impl<T>(std::bind(dist, std::ref(engine))), shape);
}
}
#endif
<commit_msg>clean headers in xrandom<commit_after>/***************************************************************************
* Copyright (c) 2016, Johan Mabille and Sylvain Corlay *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
/**
* @brief functions to obtain xgenerators generating random numbers with given shape
*/
#ifndef XRANDOM_HPP
#define XRANDOM_HPP
#include <utility>
#include <random>
#include <functional>
#include "xgenerator.hpp"
namespace xt
{
namespace detail
{
template <class T>
struct random_impl
{
using value_type = T;
random_impl(std::function<value_type()>&& generator) :
m_generator(std::move(generator))
{
}
template <class... Args>
inline value_type operator()(Args... /*args*/) const
{
return m_generator();
}
inline value_type operator[](const xindex& /*idx*/) const
{
return m_generator();
}
template <class It>
inline value_type element(It /*first*/, It /*last*/) const
{
return m_generator();
}
private:
std::function<value_type()> m_generator;
};
}
namespace random
{
using default_engine_type = std::mt19937;
using seed_type = default_engine_type::result_type;
inline default_engine_type& get_default_random_engine()
{
static default_engine_type mt;
return mt;
}
inline void set_seed(seed_type seed)
{
get_default_random_engine().seed(seed);
}
}
/**
* @function rand
* @brief xexpression with specified @p shape containing uniformly distributed random numbers
* in the interval from @p lower to @p upper, excluding upper.
*
* Numbers are drawn from @c std::uniform_real_distribution.
*
* @param shape shape of resulting xexpression
* @param lower lower bound
* @param upper upper bound
* @param engine random number engine
*
* @tparam T number type to use
*/
template <class T, class E = random::default_engine_type>
inline auto rand(std::vector<std::size_t> shape, T lower = 0, T upper = 1,
E& engine = random::get_default_random_engine())
{
std::uniform_real_distribution<T> dist(lower, upper);
return detail::make_xgenerator(detail::random_impl<T>(std::bind(dist, std::ref(engine))), shape);
}
/**
* @function randint
* @brief xexpression with specified @p shape containing uniformly distributed
* random integers in the interval from @p lower to @p upper, excluding upper.
*
* Numbers are drawn from @c std::uniform_int_distribution.
*
* @param shape shape of resulting xexpression
* @param lower lower bound
* @param upper upper bound
* @param engine random number engine
*
* @tparam T number type to use
*/
template <class T, class E = random::default_engine_type>
inline auto randint(std::vector<std::size_t> shape,
T lower = 0, T upper = std::numeric_limits<T>::max(),
E& engine = random::get_default_random_engine())
{
std::uniform_int_distribution<T> dist(lower, upper - 1);
return detail::make_xgenerator(detail::random_impl<T>(std::bind(dist, std::ref(engine))), shape);
}
/**
* @function randn
* @brief xexpression with specified @p shape containing numbers sampled from
* the Normal (Gaussian) random number distribution with mean @p mean and
* standard deviation @p std_dev.
*
* Numbers are drawn from @c std::normal_distribution.
*
* @param shape shape of resulting xexpression
* @param mean mean of normal distribution
* @param std_dev standard deviation of normal distribution
* @param engine random number engine
*
* @tparam T number type to use
*/
template <class T, class E = random::default_engine_type>
inline auto randn(std::vector<std::size_t> shape,
T mean = 0, T std_dev = 1,
E& engine = random::get_default_random_engine())
{
std::normal_distribution<T> dist(mean, std_dev);
return detail::make_xgenerator(detail::random_impl<T>(std::bind(dist, std::ref(engine))), shape);
}
}
#endif
<|endoftext|> |
<commit_before><commit_msg>Related: fdo#37691 \shptxt ... \jpegblip<commit_after><|endoftext|> |
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 <mutex>
#include <vector>
#include <openssl/err.h>
#include <openssl/rand.h>
#include <openssl/ssl.h>
#include <openssl/x509v3.h>
#include "kudu/util/debug/leakcheck_disabler.h"
#include "kudu/util/mutex.h"
#include "kudu/util/thread.h"
#include "kudu/util/net/ssl_factory.h"
#include "kudu/util/net/ssl_socket.h"
namespace kudu {
// These non-POD elements will be alive for the lifetime of the process, so don't allocate in
// static storage.
static std::vector<Mutex*> ssl_mutexes;
// Lock/Unlock the nth lock. Only to be used by OpenSSL.
static void CryptoLockingCallback(int mode, int n, const char* /*unused*/, int /*unused*/) {
if (mode & CRYPTO_LOCK) {
ssl_mutexes[n]->Acquire();
} else {
ssl_mutexes[n]->Release();
}
}
// Return the current pthread's tid. Only to be used by OpenSSL.
static void CryptoThreadIDCallback(CRYPTO_THREADID* id) {
return CRYPTO_THREADID_set_numeric(id, Thread::UniqueThreadId());
}
void DoSSLInit() {
SSL_library_init();
SSL_load_error_strings();
OpenSSL_add_all_algorithms();
RAND_poll();
for (int i = 0; i < CRYPTO_num_locks(); ++i) {
debug::ScopedLeakCheckDisabler d;
ssl_mutexes.push_back(new Mutex());
}
// Callbacks used by OpenSSL required in a multi-threaded setting.
CRYPTO_set_locking_callback(CryptoLockingCallback);
CRYPTO_THREADID_set_callback(CryptoThreadIDCallback);
}
SSLFactory::SSLFactory() : ctx_(nullptr, SSL_CTX_free) {
static std::once_flag ssl_once;
std::call_once(ssl_once, DoSSLInit);
}
SSLFactory::~SSLFactory() {
}
Status SSLFactory::Init() {
CHECK(!ctx_.get());
ctx_.reset(SSL_CTX_new(TLSv1_2_method()));
if (ctx_ == nullptr) {
return Status::RuntimeError("Could not create SSL context");
}
SSL_CTX_set_mode(ctx_.get(), SSL_MODE_AUTO_RETRY);
SSL_CTX_set_options(ctx_.get(),
SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1);
SSL_CTX_set_verify(ctx_.get(),
SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_CLIENT_ONCE, nullptr);
return Status::OK();
}
std::string SSLFactory::GetLastError(int errno_copy) {
int error_code = ERR_get_error();
if (error_code == 0) return kudu::ErrnoToString(errno_copy);
const char* error_reason = ERR_reason_error_string(error_code);
if (error_reason != NULL) return error_reason;
return strings::Substitute("SSL error $0", error_code);
}
Status SSLFactory::LoadCertificate(const std::string& certificate_path) {
ERR_clear_error();
errno = 0;
if (SSL_CTX_use_certificate_file(ctx_.get(), certificate_path.c_str(), SSL_FILETYPE_PEM) != 1) {
return Status::NotFound(
"Failed to load certificate file '" + certificate_path + "': " + GetLastError(errno));
}
return Status::OK();
}
Status SSLFactory::LoadPrivateKey(const std::string& key_path) {
ERR_clear_error();
errno = 0;
if (SSL_CTX_use_PrivateKey_file(ctx_.get(), key_path.c_str(), SSL_FILETYPE_PEM) != 1) {
return Status::NotFound(
"Failed to load private key file '" + key_path + "': " + GetLastError(errno));
}
return Status::OK();
}
Status SSLFactory::LoadCertificateAuthority(const std::string& certificate_path) {
ERR_clear_error();
errno = 0;
if (SSL_CTX_load_verify_locations(ctx_.get(), certificate_path.c_str(), nullptr) != 1) {
return Status::NotFound(
"Failed to load certificate authority file '" + certificate_path + "': " +
GetLastError(errno));
}
return Status::OK();
}
std::unique_ptr<SSLSocket> SSLFactory::CreateSocket(int socket_fd, bool is_server) {
CHECK(ctx_);
// Create SSL object and transfer ownership to the SSLSocket object created.
SSL* ssl = SSL_new(ctx_.get());
if (ssl == nullptr) {
return nullptr;
}
std::unique_ptr<SSLSocket> socket(new SSLSocket(socket_fd, ssl, is_server));
return socket;
//return new SSLSocket(socket_fd, ssl, is_server);
}
} // namespace kudu
<commit_msg>ssl: switch to older APIs for initializing SSL<commit_after>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 <mutex>
#include <vector>
#include <openssl/err.h>
#include <openssl/rand.h>
#include <openssl/ssl.h>
#include <openssl/x509v3.h>
#include "kudu/util/debug/leakcheck_disabler.h"
#include "kudu/util/mutex.h"
#include "kudu/util/thread.h"
#include "kudu/util/net/ssl_factory.h"
#include "kudu/util/net/ssl_socket.h"
namespace kudu {
// These non-POD elements will be alive for the lifetime of the process, so don't allocate in
// static storage.
static std::vector<Mutex*> ssl_mutexes;
// Lock/Unlock the nth lock. Only to be used by OpenSSL.
static void CryptoLockingCallback(int mode, int n, const char* /*unused*/, int /*unused*/) {
if (mode & CRYPTO_LOCK) {
ssl_mutexes[n]->Acquire();
} else {
ssl_mutexes[n]->Release();
}
}
// Return the current pthread's tid. Only to be used by OpenSSL.
static void CryptoThreadIDCallback(CRYPTO_THREADID* id) {
return CRYPTO_THREADID_set_numeric(id, Thread::UniqueThreadId());
}
void DoSSLInit() {
SSL_library_init();
SSL_load_error_strings();
OpenSSL_add_all_algorithms();
RAND_poll();
for (int i = 0; i < CRYPTO_num_locks(); ++i) {
debug::ScopedLeakCheckDisabler d;
ssl_mutexes.push_back(new Mutex());
}
// Callbacks used by OpenSSL required in a multi-threaded setting.
CRYPTO_set_locking_callback(CryptoLockingCallback);
CRYPTO_THREADID_set_callback(CryptoThreadIDCallback);
}
SSLFactory::SSLFactory() : ctx_(nullptr, SSL_CTX_free) {
static std::once_flag ssl_once;
std::call_once(ssl_once, DoSSLInit);
}
SSLFactory::~SSLFactory() {
}
Status SSLFactory::Init() {
CHECK(!ctx_.get());
// NOTE: 'SSLv23 method' sounds like it would enable only SSLv2 and SSLv3, but in fact
// this is a sort of wildcard which enables all methods (including TLSv1 and later).
// We explicitly disable SSLv2 and SSLv3 below so that only TLS methods remain.
// See the discussion on https://trac.torproject.org/projects/tor/ticket/11598 for more
// info.
ctx_.reset(SSL_CTX_new(SSLv23_method()));
if (!ctx_) {
return Status::RuntimeError("Could not create SSL context");
}
SSL_CTX_set_mode(ctx_.get(), SSL_MODE_AUTO_RETRY);
// Disable SSLv2 and SSLv3 which are vulnerable to various issues such as POODLE.
// We support versions back to TLSv1.0 since OpenSSL on RHEL 6.4 and earlier does not
// not support TLSv1.1 or later.
SSL_CTX_set_options(ctx_.get(), SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
SSL_CTX_set_verify(ctx_.get(),
SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_CLIENT_ONCE, nullptr);
return Status::OK();
}
std::string SSLFactory::GetLastError(int errno_copy) {
int error_code = ERR_get_error();
if (error_code == 0) return kudu::ErrnoToString(errno_copy);
const char* error_reason = ERR_reason_error_string(error_code);
if (error_reason != NULL) return error_reason;
return strings::Substitute("SSL error $0", error_code);
}
Status SSLFactory::LoadCertificate(const std::string& certificate_path) {
ERR_clear_error();
errno = 0;
if (SSL_CTX_use_certificate_file(ctx_.get(), certificate_path.c_str(), SSL_FILETYPE_PEM) != 1) {
return Status::NotFound(
"Failed to load certificate file '" + certificate_path + "': " + GetLastError(errno));
}
return Status::OK();
}
Status SSLFactory::LoadPrivateKey(const std::string& key_path) {
ERR_clear_error();
errno = 0;
if (SSL_CTX_use_PrivateKey_file(ctx_.get(), key_path.c_str(), SSL_FILETYPE_PEM) != 1) {
return Status::NotFound(
"Failed to load private key file '" + key_path + "': " + GetLastError(errno));
}
return Status::OK();
}
Status SSLFactory::LoadCertificateAuthority(const std::string& certificate_path) {
ERR_clear_error();
errno = 0;
if (SSL_CTX_load_verify_locations(ctx_.get(), certificate_path.c_str(), nullptr) != 1) {
return Status::NotFound(
"Failed to load certificate authority file '" + certificate_path + "': " +
GetLastError(errno));
}
return Status::OK();
}
std::unique_ptr<SSLSocket> SSLFactory::CreateSocket(int socket_fd, bool is_server) {
CHECK(ctx_);
// Create SSL object and transfer ownership to the SSLSocket object created.
SSL* ssl = SSL_new(ctx_.get());
if (ssl == nullptr) {
return nullptr;
}
std::unique_ptr<SSLSocket> socket(new SSLSocket(socket_fd, ssl, is_server));
return socket;
//return new SSLSocket(socket_fd, ssl, is_server);
}
} // namespace kudu
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
// Software Guide : BeginLatex
//
// This example illustrates the use of the
// \doxygen{SpatialObjectToImageFilter}. This filter expect a
// \doxygen{SpatialObject} as input, and rasterize it in order to generate an
// output image. This is particularly useful for generating synthetic images,
// in particular binary images containing a mask.
//
// \index{itk::SpatialObjectToImageFilter|textbf}
//
// Software Guide : EndLatex
// Software Guide : BeginLatex
//
// The first step required for using this filter is to include its header file
//
// \index{itk::SpatialObjectToImageFilter!header}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "itkSpatialObjectToImageFilter.h"
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// This filter takes as input a SpatialObject. However, SpatialObject can be
// grouped together in a hierarchical structure in order to produce more
// complex shapes. In this case, we illustrate how to aggregate multiple basic
// shapes. We should, therefore, include the headers of the individual elementary
// SpatialObjects.
//
// \index{itk::EllipseSpatialObject!header}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "itkEllipseSpatialObject.h"
#include "itkTubeSpatialObject.h"
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Then we include the header of the \doxygen{GroupSpatialObject} that will
// group together these instances of SpatialObjects.
//
// \index{itk::GroupSpatialObject!header}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "itkGroupSpatialObject.h"
// Software Guide : EndCodeSnippet
#include "itkImageFileWriter.h"
int main( int argc, char *argv[] )
{
if( argc != 2 )
{
std::cerr << "Usage: " << argv[0] << " outputimagefile " << std::endl;
return EXIT_FAILURE;
}
// Software Guide : BeginLatex
//
// We declare the pixel type and dimension of the image to be produced as
// output.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
using PixelType = signed short;
constexpr unsigned int Dimension = 3;
using ImageType = itk::Image< PixelType, Dimension >;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Using the same dimension, we instantiate the types of the elementary
// SpatialObjects that we plan to group, and we instantiate as well the type
// of the SpatialObject that will hold the group together.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
using EllipseType = itk::EllipseSpatialObject< Dimension >;
using TubeType = itk::TubeSpatialObject< Dimension >;
using GroupType = itk::GroupSpatialObject< Dimension >;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We instantiate the SpatialObjectToImageFilter type by using as template
// arguments the input SpatialObject and the output image types.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
using SpatialObjectToImageFilterType = itk::SpatialObjectToImageFilter<
GroupType, ImageType >;
SpatialObjectToImageFilterType::Pointer imageFilter =
SpatialObjectToImageFilterType::New();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The SpatialObjectToImageFilter requires that the user defines the grid
// parameters of the output image. This includes the number of pixels along
// each dimension, the pixel spacing, image direction and
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
ImageType::SizeType size;
size[ 0 ] = 50;
size[ 1 ] = 50;
size[ 2 ] = 150;
imageFilter->SetSize( size );
// Software Guide : EndCodeSnippet
// Software Guide : BeginCodeSnippet
ImageType::SpacingType spacing;
spacing[0] = 100.0 / size[0];
spacing[1] = 100.0 / size[1];
spacing[2] = 300.0 / size[2];
imageFilter->SetSpacing( spacing );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We create the elementary shapes that are going to be composed into the
// group spatial objects.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
EllipseType::Pointer ellipse = EllipseType::New();
TubeType::Pointer tube1 = TubeType::New();
TubeType::Pointer tube2 = TubeType::New();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The Elementary shapes have internal parameters of their own. These
// parameters define the geometrical characteristics of the basic shapes.
// For example, a tube is defined by its radius and height.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
ellipse->SetRadiusInObjectSpace( size[0] * 0.2 * spacing[0] );
typename TubeType::PointType point;
typename TubeType::TubePointType tubePoint;
typename TubeType::TubePointListType tubePointList;
point[0] = size[0] * 0.2 * spacing[0];
point[1] = size[1] * 0.2 * spacing[1];
tubePoint.SetPositionInObjectSpace( point );
tubePoint.SetRadiusInObjectSpace( size[0] * 0.05 * spacing[0] );
tubePointList.push_back( tubePoint );
point[0] = size[0] * 0.8 * spacing[0];
point[1] = size[1] * 0.2 * spacing[1];
tubePoint.SetPositionInObjectSpace( point );
tubePoint.SetRadiusInObjectSpace( size[0] * 0.05 * spacing[0] );
tubePointList.push_back( tubePoint );
tube1->SetPoints( tubePointList );
tubePointList.clear();
point[0] = size[0] * 0.2 * spacing[0];
point[1] = size[1] * 0.8 * spacing[1];
tubePoint.SetPositionInObjectSpace( point );
tubePoint.SetRadiusInObjectSpace( size[0] * 0.05 * spacing[0] );
tubePointList.push_back( tubePoint );
point[0] = size[0] * 0.8 * spacing[0];
point[1] = size[1] * 0.8 * spacing[1];
tubePoint.SetPositionInObjectSpace( point );
tubePoint.SetRadiusInObjectSpace( size[0] * 0.05 * spacing[0] );
tubePointList.push_back( tubePoint );
tube2->SetPoints( tubePointList );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Each one of these components will be placed in a different position and
// orientation. We define transforms in order to specify those relative
// positions and orientations.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
using TransformType = GroupType::TransformType;
TransformType::Pointer transform1 = TransformType::New();
TransformType::Pointer transform2 = TransformType::New();
TransformType::Pointer transform3 = TransformType::New();
transform1->SetIdentity();
transform2->SetIdentity();
transform3->SetIdentity();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Then we set the specific values of the transform parameters, and we
// assign the transforms to the elementary shapes.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
TransformType::OutputVectorType translation;
translation[ 0 ] = size[0] * spacing[0] / 2.0;
translation[ 1 ] = size[1] * spacing[1] / 4.0;
translation[ 2 ] = size[2] * spacing[2] / 2.0;
transform1->Translate( translation, false );
translation[ 1 ] = size[1] * spacing[1] / 2.0;
translation[ 2 ] = size[2] * spacing[2] * 0.22;
transform2->Rotate( 1, 2, itk::Math::pi / 2.0 );
transform2->Translate( translation, false );
translation[ 2 ] = size[2] * spacing[2] * 0.78;
transform3->Rotate( 1, 2, itk::Math::pi / 2.0 );
transform3->Translate( translation, false );
ellipse->SetObjectToParentTransform( transform1 );
tube1->SetObjectToParentTransform( transform2 );
tube2->SetObjectToParentTransform( transform3 );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The elementary shapes are aggregated in a parent group, that in turn is
// passed as input to the filter.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
GroupType::Pointer group = GroupType::New();
group->AddChild( ellipse );
group->AddChild( tube1 );
group->AddChild( tube2 );
ellipse->Update();
tube1->Update();
tube2->Update();
imageFilter->SetInput( group );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// By default, the filter will rasterize the aggregation of elementary
// shapes and will assign a pixel value to locations that fall inside of any
// of the elementary shapes, and a different pixel value to locations that
// fall outside of all of the elementary shapes. It is possible, however, to
// generate richer images if we allow the filter to use the values that the
// elementary spatial objects return via their \code{ValueAt} methods. This
// is what we choose to do in this example, by using the following code.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
const PixelType airHounsfieldUnits = -1000;
constexpr PixelType boneHounsfieldUnits = 800;
ellipse->SetDefaultInsideValue( boneHounsfieldUnits );
tube1->SetDefaultInsideValue( boneHounsfieldUnits );
tube2->SetDefaultInsideValue( boneHounsfieldUnits );
ellipse->SetDefaultOutsideValue( airHounsfieldUnits );
tube1->SetDefaultOutsideValue( airHounsfieldUnits );
tube2->SetDefaultOutsideValue( airHounsfieldUnits );
imageFilter->SetUseObjectValue( true );
imageFilter->SetOutsideValue( airHounsfieldUnits );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Finally we are ready to run the filter. We use the typical invocation of
// the \code{Update} method, and we instantiate an \code{ImageFileWriter} in
// order to save the generated image into a file.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
using WriterType = itk::ImageFileWriter< ImageType >;
WriterType::Pointer writer = WriterType::New();
writer->SetFileName( argv[1] );
writer->SetInput( imageFilter->GetOutput() );
try
{
imageFilter->Update();
writer->Update();
}
catch( itk::ExceptionObject & excp )
{
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
// Software Guide : EndCodeSnippet
return EXIT_SUCCESS;
}
<commit_msg>BUG: Set all component of 3D points<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
// Software Guide : BeginLatex
//
// This example illustrates the use of the
// \doxygen{SpatialObjectToImageFilter}. This filter expect a
// \doxygen{SpatialObject} as input, and rasterize it in order to generate an
// output image. This is particularly useful for generating synthetic images,
// in particular binary images containing a mask.
//
// \index{itk::SpatialObjectToImageFilter|textbf}
//
// Software Guide : EndLatex
// Software Guide : BeginLatex
//
// The first step required for using this filter is to include its header file
//
// \index{itk::SpatialObjectToImageFilter!header}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "itkSpatialObjectToImageFilter.h"
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// This filter takes as input a SpatialObject. However, SpatialObject can be
// grouped together in a hierarchical structure in order to produce more
// complex shapes. In this case, we illustrate how to aggregate multiple basic
// shapes. We should, therefore, include the headers of the individual elementary
// SpatialObjects.
//
// \index{itk::EllipseSpatialObject!header}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "itkEllipseSpatialObject.h"
#include "itkTubeSpatialObject.h"
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Then we include the header of the \doxygen{GroupSpatialObject} that will
// group together these instances of SpatialObjects.
//
// \index{itk::GroupSpatialObject!header}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "itkGroupSpatialObject.h"
// Software Guide : EndCodeSnippet
#include "itkImageFileWriter.h"
int main( int argc, char *argv[] )
{
if( argc != 2 )
{
std::cerr << "Usage: " << argv[0] << " outputimagefile " << std::endl;
return EXIT_FAILURE;
}
// Software Guide : BeginLatex
//
// We declare the pixel type and dimension of the image to be produced as
// output.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
using PixelType = signed short;
constexpr unsigned int Dimension = 3;
using ImageType = itk::Image< PixelType, Dimension >;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Using the same dimension, we instantiate the types of the elementary
// SpatialObjects that we plan to group, and we instantiate as well the type
// of the SpatialObject that will hold the group together.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
using EllipseType = itk::EllipseSpatialObject< Dimension >;
using TubeType = itk::TubeSpatialObject< Dimension >;
using GroupType = itk::GroupSpatialObject< Dimension >;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We instantiate the SpatialObjectToImageFilter type by using as template
// arguments the input SpatialObject and the output image types.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
using SpatialObjectToImageFilterType = itk::SpatialObjectToImageFilter<
GroupType, ImageType >;
SpatialObjectToImageFilterType::Pointer imageFilter =
SpatialObjectToImageFilterType::New();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The SpatialObjectToImageFilter requires that the user defines the grid
// parameters of the output image. This includes the number of pixels along
// each dimension, the pixel spacing, image direction and
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
ImageType::SizeType size;
size[ 0 ] = 50;
size[ 1 ] = 50;
size[ 2 ] = 150;
imageFilter->SetSize( size );
// Software Guide : EndCodeSnippet
// Software Guide : BeginCodeSnippet
ImageType::SpacingType spacing;
spacing[0] = 100.0 / size[0];
spacing[1] = 100.0 / size[1];
spacing[2] = 300.0 / size[2];
imageFilter->SetSpacing( spacing );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We create the elementary shapes that are going to be composed into the
// group spatial objects.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
EllipseType::Pointer ellipse = EllipseType::New();
TubeType::Pointer tube1 = TubeType::New();
TubeType::Pointer tube2 = TubeType::New();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The Elementary shapes have internal parameters of their own. These
// parameters define the geometrical characteristics of the basic shapes.
// For example, a tube is defined by its radius and height.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
ellipse->SetRadiusInObjectSpace( size[0] * 0.2 * spacing[0] );
typename TubeType::PointType point;
typename TubeType::TubePointType tubePoint;
typename TubeType::TubePointListType tubePointList;
point[0] = size[0] * 0.2 * spacing[0];
point[1] = size[1] * 0.2 * spacing[1];
point[2] = size[2] * 0.2 * spacing[2];
tubePoint.SetPositionInObjectSpace( point );
tubePoint.SetRadiusInObjectSpace( size[0] * 0.05 * spacing[0] );
tubePointList.push_back( tubePoint );
point[0] = size[0] * 0.8 * spacing[0];
point[1] = size[1] * 0.2 * spacing[1];
point[2] = size[2] * 0.2 * spacing[2];
tubePoint.SetPositionInObjectSpace( point );
tubePoint.SetRadiusInObjectSpace( size[0] * 0.05 * spacing[0] );
tubePointList.push_back( tubePoint );
tube1->SetPoints( tubePointList );
tubePointList.clear();
point[0] = size[0] * 0.2 * spacing[0];
point[1] = size[1] * 0.8 * spacing[1];
point[2] = size[2] * 0.2 * spacing[2];
tubePoint.SetPositionInObjectSpace( point );
tubePoint.SetRadiusInObjectSpace( size[0] * 0.05 * spacing[0] );
tubePointList.push_back( tubePoint );
point[0] = size[0] * 0.8 * spacing[0];
point[1] = size[1] * 0.8 * spacing[1];
point[2] = size[2] * 0.8 * spacing[1];
tubePoint.SetPositionInObjectSpace( point );
tubePoint.SetRadiusInObjectSpace( size[0] * 0.05 * spacing[0] );
tubePointList.push_back( tubePoint );
tube2->SetPoints( tubePointList );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Each one of these components will be placed in a different position and
// orientation. We define transforms in order to specify those relative
// positions and orientations.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
using TransformType = GroupType::TransformType;
TransformType::Pointer transform1 = TransformType::New();
TransformType::Pointer transform2 = TransformType::New();
TransformType::Pointer transform3 = TransformType::New();
transform1->SetIdentity();
transform2->SetIdentity();
transform3->SetIdentity();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Then we set the specific values of the transform parameters, and we
// assign the transforms to the elementary shapes.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
TransformType::OutputVectorType translation;
translation[ 0 ] = size[0] * spacing[0] / 2.0;
translation[ 1 ] = size[1] * spacing[1] / 4.0;
translation[ 2 ] = size[2] * spacing[2] / 2.0;
transform1->Translate( translation, false );
translation[ 1 ] = size[1] * spacing[1] / 2.0;
translation[ 2 ] = size[2] * spacing[2] * 0.22;
transform2->Rotate( 1, 2, itk::Math::pi / 2.0 );
transform2->Translate( translation, false );
translation[ 2 ] = size[2] * spacing[2] * 0.78;
transform3->Rotate( 1, 2, itk::Math::pi / 2.0 );
transform3->Translate( translation, false );
ellipse->SetObjectToParentTransform( transform1 );
tube1->SetObjectToParentTransform( transform2 );
tube2->SetObjectToParentTransform( transform3 );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The elementary shapes are aggregated in a parent group, that in turn is
// passed as input to the filter.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
GroupType::Pointer group = GroupType::New();
group->AddChild( ellipse );
group->AddChild( tube1 );
group->AddChild( tube2 );
ellipse->Update();
tube1->Update();
tube2->Update();
imageFilter->SetInput( group );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// By default, the filter will rasterize the aggregation of elementary
// shapes and will assign a pixel value to locations that fall inside of any
// of the elementary shapes, and a different pixel value to locations that
// fall outside of all of the elementary shapes. It is possible, however, to
// generate richer images if we allow the filter to use the values that the
// elementary spatial objects return via their \code{ValueAt} methods. This
// is what we choose to do in this example, by using the following code.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
const PixelType airHounsfieldUnits = -1000;
constexpr PixelType boneHounsfieldUnits = 800;
ellipse->SetDefaultInsideValue( boneHounsfieldUnits );
tube1->SetDefaultInsideValue( boneHounsfieldUnits );
tube2->SetDefaultInsideValue( boneHounsfieldUnits );
ellipse->SetDefaultOutsideValue( airHounsfieldUnits );
tube1->SetDefaultOutsideValue( airHounsfieldUnits );
tube2->SetDefaultOutsideValue( airHounsfieldUnits );
imageFilter->SetUseObjectValue( true );
imageFilter->SetOutsideValue( airHounsfieldUnits );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Finally we are ready to run the filter. We use the typical invocation of
// the \code{Update} method, and we instantiate an \code{ImageFileWriter} in
// order to save the generated image into a file.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
using WriterType = itk::ImageFileWriter< ImageType >;
WriterType::Pointer writer = WriterType::New();
writer->SetFileName( argv[1] );
writer->SetInput( imageFilter->GetOutput() );
try
{
imageFilter->Update();
writer->Update();
}
catch( itk::ExceptionObject & excp )
{
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
// Software Guide : EndCodeSnippet
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Build Suite.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "process.h"
#include <logging/translator.h>
#include <tools/hostosinfo.h>
#include <QProcess>
#include <QScriptEngine>
#include <QScriptValue>
#include <QTextCodec>
#include <QTextStream>
namespace qbs {
namespace Internal {
void initializeJsExtensionProcess(QScriptValue extensionObject)
{
QScriptEngine *engine = extensionObject.engine();
QScriptValue obj = engine->newQMetaObject(&Process::staticMetaObject, engine->newFunction(&Process::ctor));
extensionObject.setProperty("Process", obj);
}
QScriptValue Process::ctor(QScriptContext *context, QScriptEngine *engine)
{
Process *t;
switch (context->argumentCount()) {
case 0:
t = new Process(context);
break;
default:
return context->throwError("Process()");
}
QScriptValue obj = engine->newQObject(t, QScriptEngine::ScriptOwnership);
// Get environment
QVariant v = engine->property("_qbs_procenv");
if (!v.isNull())
t->m_environment
= QProcessEnvironment(*reinterpret_cast<QProcessEnvironment*>(v.value<void*>()));
return obj;
}
Process::~Process()
{
delete m_textStream;
delete m_qProcess;
}
Process::Process(QScriptContext *context)
{
Q_UNUSED(context);
Q_ASSERT(thisObject().engine() == engine());
m_qProcess = new QProcess;
m_textStream = new QTextStream(m_qProcess);
}
QString Process::getEnv(const QString &name)
{
Q_ASSERT(thisObject().engine() == engine());
return m_environment.value(name);
}
void Process::setEnv(const QString &name, const QString &value)
{
Q_ASSERT(thisObject().engine() == engine());
m_environment.insert(name, value);
}
QString Process::workingDirectory()
{
Q_ASSERT(thisObject().engine() == engine());
return m_workingDirectory;
}
void Process::setWorkingDirectory(const QString &dir)
{
Q_ASSERT(thisObject().engine() == engine());
m_workingDirectory = dir;
}
bool Process::start(const QString &program, const QStringList &arguments)
{
Q_ASSERT(thisObject().engine() == engine());
if (!m_workingDirectory.isEmpty())
m_qProcess->setWorkingDirectory(m_workingDirectory);
m_qProcess->setProcessEnvironment(m_environment);
m_qProcess->start(program, arguments);
return m_qProcess->waitForStarted();
}
int Process::exec(const QString &program, const QStringList &arguments, bool throwOnError)
{
Q_ASSERT(thisObject().engine() == engine());
if (!start(program, arguments)) {
if (throwOnError) {
context()->throwError(Tr::tr("Error running '%1': %2")
.arg(program, m_qProcess->errorString()));
}
return -1;
}
m_qProcess->closeWriteChannel();
m_qProcess->waitForFinished();
if (throwOnError) {
if (m_qProcess->error() != QProcess::UnknownError) {
context()->throwError(Tr::tr("Error running '%1': %2")
.arg(program, m_qProcess->errorString()));
} else if (m_qProcess->exitCode() != 0) {
QString errorMessage = Tr::tr("Process '%1' finished with exit code %2.")
.arg(program).arg(m_qProcess->exitCode());
const QString stdErr = readStdErr();
if (!stdErr.isEmpty())
errorMessage.append(Tr::tr(" The standard error output was:\n")).append(stdErr);
context()->throwError(errorMessage);
}
}
if (m_qProcess->error() != QProcess::UnknownError)
return -1;
return m_qProcess->exitCode();
}
void Process::close()
{
Q_ASSERT(thisObject().engine() == engine());
delete m_qProcess;
m_qProcess = 0;
delete m_textStream;
m_textStream = 0;
}
bool Process::waitForFinished(int msecs)
{
Q_ASSERT(thisObject().engine() == engine());
if (m_qProcess->state() == QProcess::NotRunning)
return true;
return m_qProcess->waitForFinished(msecs);
}
void Process::terminate()
{
m_qProcess->terminate();
}
void Process::kill()
{
m_qProcess->kill();
}
void Process::setCodec(const QString &codec)
{
Q_ASSERT(thisObject().engine() == engine());
m_textStream->setCodec(qPrintable(codec));
}
QString Process::readLine()
{
return m_textStream->readLine();
}
QString Process::readStdOut()
{
return m_textStream->readAll();
}
QString Process::readStdErr()
{
return m_textStream->codec()->toUnicode(m_qProcess->readAllStandardError());
}
int Process::exitCode() const
{
return m_qProcess->exitCode();
}
void Process::write(const QString &str)
{
(*m_textStream) << str;
}
void Process::writeLine(const QString &str)
{
(*m_textStream) << str;
if (HostOsInfo::isWindowsHost())
(*m_textStream) << '\r';
(*m_textStream) << '\n';
}
} // namespace Internal
} // namespace qbs
<commit_msg>Fix Process.exec().<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Build Suite.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "process.h"
#include <logging/translator.h>
#include <tools/hostosinfo.h>
#include <QProcess>
#include <QScriptEngine>
#include <QScriptValue>
#include <QTextCodec>
#include <QTextStream>
namespace qbs {
namespace Internal {
void initializeJsExtensionProcess(QScriptValue extensionObject)
{
QScriptEngine *engine = extensionObject.engine();
QScriptValue obj = engine->newQMetaObject(&Process::staticMetaObject, engine->newFunction(&Process::ctor));
extensionObject.setProperty("Process", obj);
}
QScriptValue Process::ctor(QScriptContext *context, QScriptEngine *engine)
{
Process *t;
switch (context->argumentCount()) {
case 0:
t = new Process(context);
break;
default:
return context->throwError("Process()");
}
QScriptValue obj = engine->newQObject(t, QScriptEngine::ScriptOwnership);
// Get environment
QVariant v = engine->property("_qbs_procenv");
if (!v.isNull())
t->m_environment
= QProcessEnvironment(*reinterpret_cast<QProcessEnvironment*>(v.value<void*>()));
return obj;
}
Process::~Process()
{
delete m_textStream;
delete m_qProcess;
}
Process::Process(QScriptContext *context)
{
Q_UNUSED(context);
Q_ASSERT(thisObject().engine() == engine());
m_qProcess = new QProcess;
m_textStream = new QTextStream(m_qProcess);
}
QString Process::getEnv(const QString &name)
{
Q_ASSERT(thisObject().engine() == engine());
return m_environment.value(name);
}
void Process::setEnv(const QString &name, const QString &value)
{
Q_ASSERT(thisObject().engine() == engine());
m_environment.insert(name, value);
}
QString Process::workingDirectory()
{
Q_ASSERT(thisObject().engine() == engine());
return m_workingDirectory;
}
void Process::setWorkingDirectory(const QString &dir)
{
Q_ASSERT(thisObject().engine() == engine());
m_workingDirectory = dir;
}
bool Process::start(const QString &program, const QStringList &arguments)
{
Q_ASSERT(thisObject().engine() == engine());
if (!m_workingDirectory.isEmpty())
m_qProcess->setWorkingDirectory(m_workingDirectory);
m_qProcess->setProcessEnvironment(m_environment);
m_qProcess->start(program, arguments);
return m_qProcess->waitForStarted();
}
int Process::exec(const QString &program, const QStringList &arguments, bool throwOnError)
{
Q_ASSERT(thisObject().engine() == engine());
if (!start(program, arguments)) {
if (throwOnError) {
context()->throwError(Tr::tr("Error running '%1': %2")
.arg(program, m_qProcess->errorString()));
}
return -1;
}
m_qProcess->closeWriteChannel();
m_qProcess->waitForFinished(-1);
if (throwOnError) {
if (m_qProcess->error() != QProcess::UnknownError) {
context()->throwError(Tr::tr("Error running '%1': %2")
.arg(program, m_qProcess->errorString()));
} else if (m_qProcess->exitCode() != 0) {
QString errorMessage = Tr::tr("Process '%1' finished with exit code %2.")
.arg(program).arg(m_qProcess->exitCode());
const QString stdErr = readStdErr();
if (!stdErr.isEmpty())
errorMessage.append(Tr::tr(" The standard error output was:\n")).append(stdErr);
context()->throwError(errorMessage);
}
}
if (m_qProcess->error() != QProcess::UnknownError)
return -1;
return m_qProcess->exitCode();
}
void Process::close()
{
Q_ASSERT(thisObject().engine() == engine());
delete m_qProcess;
m_qProcess = 0;
delete m_textStream;
m_textStream = 0;
}
bool Process::waitForFinished(int msecs)
{
Q_ASSERT(thisObject().engine() == engine());
if (m_qProcess->state() == QProcess::NotRunning)
return true;
return m_qProcess->waitForFinished(msecs);
}
void Process::terminate()
{
m_qProcess->terminate();
}
void Process::kill()
{
m_qProcess->kill();
}
void Process::setCodec(const QString &codec)
{
Q_ASSERT(thisObject().engine() == engine());
m_textStream->setCodec(qPrintable(codec));
}
QString Process::readLine()
{
return m_textStream->readLine();
}
QString Process::readStdOut()
{
return m_textStream->readAll();
}
QString Process::readStdErr()
{
return m_textStream->codec()->toUnicode(m_qProcess->readAllStandardError());
}
int Process::exitCode() const
{
return m_qProcess->exitCode();
}
void Process::write(const QString &str)
{
(*m_textStream) << str;
}
void Process::writeLine(const QString &str)
{
(*m_textStream) << str;
if (HostOsInfo::isWindowsHost())
(*m_textStream) << '\r';
(*m_textStream) << '\n';
}
} // namespace Internal
} // namespace qbs
<|endoftext|> |
<commit_before>
#include "logger.h"
#include "owtemp.h"
#include "utils.h"
extern "C"
{
#include "ownet.h"
}
using namespace std;
namespace home_system
{
namespace input_output
{
namespace ow
{
temp::temp(int portnum, uint64_t serial_num)
: portnum_(portnum),
serial_num_(serial_num)
{
LOG("Created temperature device (DS1920): " << serial_num_to_string(serial_num_));
}
uint64_t temp::id()
{
return serial_num_;
}
float temp::get_value()
{
LOG(serial_num_to_string(serial_num_) << " " << value_);
return value_;
}
void temp::send_convert()
{
// set the device serial number to the counter device
owSerialNum(portnum_, (uchar*)&serial_num_, FALSE);
// access the device
if (owAccess(portnum_))
{
// send the convert command
if (!owWriteByte(portnum_, 0x44))
{
throw std::runtime_error("Problem writing convert command");
}
}
else
{
throw std::runtime_error("Problem accessing device");
}
}
bool temp::read_temp()
{
owSerialNum(portnum_, (uchar*)&serial_num_, FALSE);
// access the device
if (owAccess(portnum_))
{
// create a block to send that reads the temperature
// read scratchpad command
uchar send_block[30];
size_t send_cnt = 0;
send_block[send_cnt++] = 0xBE;
// now add the read bytes for data bytes and crc8
for (size_t i = 0; i < 9; i++)
send_block[send_cnt++] = 0xFF;
// now send the block
if (owBlock(portnum_, FALSE, send_block, send_cnt))
{
// initialize the CRC8
setcrc8(portnum_, 0);
// perform the CRC8 on the last 8 bytes of packet
uchar lastcrc8;
for (size_t i = send_cnt - 9; i < send_cnt; i++)
lastcrc8 = docrc8(portnum_, send_block[i]);
// verify CRC8 is correct
if (lastcrc8 == 0x00)
{
float tmp,cr,cpc;
// calculate the high-res temperature
int tsht;
tsht = send_block[1]/2;
if (send_block[2] & 0x01)
tsht |= -128;
tmp = (float)(tsht);
cr = send_block[7];
cpc = send_block[8];
if ((cpc - cr) == 1)
{
LOGWARN("Conversion not ready yet");
return false;
}
if (cpc == 0)
{
throw std::runtime_error("CPC == 0");
}
else
tmp = tmp - (float)0.25 + (cpc - cr)/cpc;
LOG(serial_num_to_string(serial_num_) << ": " << tmp);
value_ = tmp;
return true;
}
else
{
throw std::runtime_error("Wrong CRC");
}
}
throw std::runtime_error("Sending block failed");
}
throw std::runtime_error("Accessing device failed");
}
}
}
}
<commit_msg>Removed not needed log<commit_after>
#include "logger.h"
#include "owtemp.h"
#include "utils.h"
extern "C"
{
#include "ownet.h"
}
using namespace std;
namespace home_system
{
namespace input_output
{
namespace ow
{
temp::temp(int portnum, uint64_t serial_num)
: portnum_(portnum),
serial_num_(serial_num)
{
LOG("Created temperature device (DS1920): " << serial_num_to_string(serial_num_));
}
uint64_t temp::id()
{
return serial_num_;
}
float temp::get_value()
{
return value_;
}
void temp::send_convert()
{
// set the device serial number to the counter device
owSerialNum(portnum_, (uchar*)&serial_num_, FALSE);
// access the device
if (owAccess(portnum_))
{
// send the convert command
if (!owWriteByte(portnum_, 0x44))
{
throw std::runtime_error("Problem writing convert command");
}
}
else
{
throw std::runtime_error("Problem accessing device");
}
}
bool temp::read_temp()
{
owSerialNum(portnum_, (uchar*)&serial_num_, FALSE);
// access the device
if (owAccess(portnum_))
{
// create a block to send that reads the temperature
// read scratchpad command
uchar send_block[30];
size_t send_cnt = 0;
send_block[send_cnt++] = 0xBE;
// now add the read bytes for data bytes and crc8
for (size_t i = 0; i < 9; i++)
send_block[send_cnt++] = 0xFF;
// now send the block
if (owBlock(portnum_, FALSE, send_block, send_cnt))
{
// initialize the CRC8
setcrc8(portnum_, 0);
// perform the CRC8 on the last 8 bytes of packet
uchar lastcrc8;
for (size_t i = send_cnt - 9; i < send_cnt; i++)
lastcrc8 = docrc8(portnum_, send_block[i]);
// verify CRC8 is correct
if (lastcrc8 == 0x00)
{
float tmp,cr,cpc;
// calculate the high-res temperature
int tsht;
tsht = send_block[1]/2;
if (send_block[2] & 0x01)
tsht |= -128;
tmp = (float)(tsht);
cr = send_block[7];
cpc = send_block[8];
if ((cpc - cr) == 1)
{
LOGWARN("Conversion not ready yet");
return false;
}
if (cpc == 0)
{
throw std::runtime_error("CPC == 0");
}
else
tmp = tmp - (float)0.25 + (cpc - cr)/cpc;
LOG(serial_num_to_string(serial_num_) << ": " << tmp);
value_ = tmp;
return true;
}
else
{
throw std::runtime_error("Wrong CRC");
}
}
throw std::runtime_error("Sending block failed");
}
throw std::runtime_error("Accessing device failed");
}
}
}
}
<|endoftext|> |
<commit_before>
#include "stm32_spi_arbiter.hpp"
#include "stm32_system.h"
#include "utils.hpp"
#include <cmsis_os.h>
bool equals(const SPI_InitTypeDef& lhs, const SPI_InitTypeDef& rhs) {
return (lhs.Mode == rhs.Mode)
&& (lhs.Direction == rhs.Direction)
&& (lhs.DataSize == rhs.DataSize)
&& (lhs.CLKPolarity == rhs.CLKPolarity)
&& (lhs.CLKPhase == rhs.CLKPhase)
&& (lhs.NSS == rhs.NSS)
&& (lhs.BaudRatePrescaler == rhs.BaudRatePrescaler)
&& (lhs.FirstBit == rhs.FirstBit)
&& (lhs.TIMode == rhs.TIMode)
&& (lhs.CRCCalculation == rhs.CRCCalculation)
&& (lhs.CRCPolynomial == rhs.CRCPolynomial);
}
bool Stm32SpiArbiter::acquire_task(SpiTask* task) {
return !__atomic_exchange_n(&task->is_in_use, true, __ATOMIC_SEQ_CST);
}
void Stm32SpiArbiter::release_task(SpiTask* task) {
task->is_in_use = false;
}
bool Stm32SpiArbiter::start() {
if (!task_list_) {
return false;
}
SpiTask& task = *task_list_;
if (!equals(task.config, hspi_->Init)) {
HAL_SPI_DeInit(hspi_);
hspi_->Init = task.config;
HAL_SPI_Init(hspi_);
}
task.ncs_gpio.write(false);
HAL_StatusTypeDef status = HAL_ERROR;
if (task.tx_buf && task.rx_buf) {
status = HAL_SPI_TransmitReceive_DMA(hspi_, (uint8_t*)task.tx_buf, task.rx_buf, task.length);
} else if (task.tx_buf) {
status = HAL_SPI_Transmit_DMA(hspi_, (uint8_t*)task.tx_buf, task.length);
} else if (task.rx_buf) {
status = HAL_SPI_Receive_DMA(hspi_, task.rx_buf, task.length);
}
if (status != HAL_OK) {
task.ncs_gpio.write(true);
}
return status == HAL_OK;
}
void Stm32SpiArbiter::transfer_async(SpiTask* task) {
task->next = nullptr;
// Append new task to task list.
// We could try to do this lock free but we could also use our time for useful things.
SpiTask** ptr = &task_list_;
CRITICAL_SECTION() {
while (*ptr)
ptr = &(*ptr)->next;
*ptr = task;
}
// If the list was empty before, kick off the SPI arbiter now
if (ptr == &task_list_) {
if (!start()) {
if (task->on_complete) {
(*task->on_complete)(task->on_complete_ctx, false);
}
}
}
}
// TODO: this currently only works when called in a CMSIS thread.
bool Stm32SpiArbiter::transfer(SPI_InitTypeDef config, Stm32Gpio ncs_gpio, const uint8_t* tx_buf, uint8_t* rx_buf, size_t length, uint32_t timeout_ms) {
volatile uint8_t result = 0xff;
SpiTask task = {
.config = config,
.ncs_gpio = ncs_gpio,
.tx_buf = tx_buf,
.rx_buf = rx_buf,
.length = length,
.on_complete = [](void* ctx, bool success) { *(volatile uint8_t*)ctx = success ? 1 : 0; },
.on_complete_ctx = (void*)&result,
.next = nullptr
};
transfer_async(&task);
while (result == 0xff) {
osDelay(1); // TODO: honor timeout
}
return result;
}
void Stm32SpiArbiter::on_complete() {
if (!task_list_) {
return; // this should not happen
}
// Wrap up transfer
task_list_->ncs_gpio.write(true);
if (task_list_->on_complete) {
(*task_list_->on_complete)(task_list_->on_complete_ctx, true);
}
// Start next task if any
SpiTask* next = nullptr;
CRITICAL_SECTION() {
next = task_list_ = task_list_->next;
}
if (next) {
start();
}
}
<commit_msg>fix compilation on GCC <= 7.x<commit_after>
#include "stm32_spi_arbiter.hpp"
#include "stm32_system.h"
#include "utils.hpp"
#include <cmsis_os.h>
bool equals(const SPI_InitTypeDef& lhs, const SPI_InitTypeDef& rhs) {
return (lhs.Mode == rhs.Mode)
&& (lhs.Direction == rhs.Direction)
&& (lhs.DataSize == rhs.DataSize)
&& (lhs.CLKPolarity == rhs.CLKPolarity)
&& (lhs.CLKPhase == rhs.CLKPhase)
&& (lhs.NSS == rhs.NSS)
&& (lhs.BaudRatePrescaler == rhs.BaudRatePrescaler)
&& (lhs.FirstBit == rhs.FirstBit)
&& (lhs.TIMode == rhs.TIMode)
&& (lhs.CRCCalculation == rhs.CRCCalculation)
&& (lhs.CRCPolynomial == rhs.CRCPolynomial);
}
bool Stm32SpiArbiter::acquire_task(SpiTask* task) {
return !__atomic_exchange_n(&task->is_in_use, true, __ATOMIC_SEQ_CST);
}
void Stm32SpiArbiter::release_task(SpiTask* task) {
task->is_in_use = false;
}
bool Stm32SpiArbiter::start() {
if (!task_list_) {
return false;
}
SpiTask& task = *task_list_;
if (!equals(task.config, hspi_->Init)) {
HAL_SPI_DeInit(hspi_);
hspi_->Init = task.config;
HAL_SPI_Init(hspi_);
}
task.ncs_gpio.write(false);
HAL_StatusTypeDef status = HAL_ERROR;
if (task.tx_buf && task.rx_buf) {
status = HAL_SPI_TransmitReceive_DMA(hspi_, (uint8_t*)task.tx_buf, task.rx_buf, task.length);
} else if (task.tx_buf) {
status = HAL_SPI_Transmit_DMA(hspi_, (uint8_t*)task.tx_buf, task.length);
} else if (task.rx_buf) {
status = HAL_SPI_Receive_DMA(hspi_, task.rx_buf, task.length);
}
if (status != HAL_OK) {
task.ncs_gpio.write(true);
}
return status == HAL_OK;
}
void Stm32SpiArbiter::transfer_async(SpiTask* task) {
task->next = nullptr;
// Append new task to task list.
// We could try to do this lock free but we could also use our time for useful things.
SpiTask** ptr = &task_list_;
CRITICAL_SECTION() {
while (*ptr)
ptr = &(*ptr)->next;
*ptr = task;
}
// If the list was empty before, kick off the SPI arbiter now
if (ptr == &task_list_) {
if (!start()) {
if (task->on_complete) {
(*task->on_complete)(task->on_complete_ctx, false);
}
}
}
}
// TODO: this currently only works when called in a CMSIS thread.
bool Stm32SpiArbiter::transfer(SPI_InitTypeDef config, Stm32Gpio ncs_gpio, const uint8_t* tx_buf, uint8_t* rx_buf, size_t length, uint32_t timeout_ms) {
volatile uint8_t result = 0xff;
SpiTask task = {
.config = config,
.ncs_gpio = ncs_gpio,
.tx_buf = tx_buf,
.rx_buf = rx_buf,
.length = length,
.on_complete = [](void* ctx, bool success) { *(volatile uint8_t*)ctx = success ? 1 : 0; },
.on_complete_ctx = (void*)&result,
.is_in_use = false,
.next = nullptr
};
transfer_async(&task);
while (result == 0xff) {
osDelay(1); // TODO: honor timeout
}
return result;
}
void Stm32SpiArbiter::on_complete() {
if (!task_list_) {
return; // this should not happen
}
// Wrap up transfer
task_list_->ncs_gpio.write(true);
if (task_list_->on_complete) {
(*task_list_->on_complete)(task_list_->on_complete_ctx, true);
}
// Start next task if any
SpiTask* next = nullptr;
CRITICAL_SECTION() {
next = task_list_ = task_list_->next;
}
if (next) {
start();
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
Library: TubeTK
Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
#include "tubeARFFParser.h"
#include <fstream>
#include <sstream>
#include <list>
#include <string>
#include <limits>
#include <iostream>
namespace tube
{
ARFFParser
::ARFFParser()
: m_Filename(""),
m_XLabel("x"),
m_YLabel("y"),
m_ClassLabel("class"),
m_XIndex(0),
m_YIndex(0),
m_ClassIndex(0),
m_ClassNames(),
m_MinX(std::numeric_limits<float>::max()),
m_MinY(std::numeric_limits<float>::max()),
m_MaxX(std::numeric_limits<float>::min()),
m_MaxY(std::numeric_limits<float>::min()),
m_ARFFData()
{
}
ARFFParser
::~ARFFParser()
{
std::list<float*>::iterator itr;
for( itr = m_ARFFData.begin(); itr != m_ARFFData.end(); ++itr )
{
delete [] *itr;
}
}
void
ARFFParser
::SetFilename( const std::string& filename )
{
m_Filename = filename;
}
void
ARFFParser
::SetXLabel( const std::string& xLabel )
{
m_XLabel = xLabel;
}
void
ARFFParser
::SetYLabel( const std::string& yLabel )
{
m_YLabel = yLabel;
}
void
ARFFParser
::SetClassLabel( const std::string& classLabel )
{
m_ClassLabel = classLabel;
}
void
ARFFParser
::Parse()
{
std::ifstream file( m_Filename.c_str() );
std::string line;
this->determineHeaderParameters( file );
while( std::getline( file, line ) )
{
float* values = new float[3];
if( line != "" && line.find( "%" ) == std::string::npos )
{
this->getValuesFromDataLine( line, values );
this->adjustMinAndMaxBasedOnNewData( values );
m_ARFFData.push_back( values );
}
delete [] values;
}
}
void
ARFFParser
::determineHeaderParameters( std::ifstream& file )
{
std::string line;
unsigned int index = 0;
while( std::getline( file, line ) )
{
if( line.find( "@DATA" ) != std::string::npos ||
line.find( "@data" ) != std::string::npos )
{
break;
}
else if( line.find( "@ATTRIBUTE" ) != std::string::npos ||
line.find( "@attribute" ) != std::string::npos )
{
std::string name;
this->getAttributeName( line, name );
if( name == this->m_XLabel )
{
m_XIndex = index;
}
else if( name == this->m_YLabel )
{
m_YIndex = index;
}
else if( name == this->m_ClassLabel )
{
this->determineClassificationsFromAttributeLine( line );
m_ClassIndex = index;
}
else
{ // do nothing
}
++index;
}
else
{ // do nothing
}
}
}
void
ARFFParser
::getAttributeName( const std::string& line, std::string& name ) const
{
std::stringstream stringStream( line );
std::getline( stringStream, name, ' ' );
std::getline( stringStream, name, ' ' );
}
void
ARFFParser
::getValuesFromDataLine( const std::string& line, float* values ) const
{
std::stringstream stringStream( line );
std::string cell;
for( unsigned int i = 0;
i <= m_XIndex || i <= m_YIndex || i <= m_ClassIndex;
++i )
{
std::getline( stringStream, cell, ',' );
std::stringstream cellStream( cell );
if( i == m_XIndex )
{
cellStream >> values[0];
}
else if( i == m_YIndex )
{
cellStream >> values[1];
}
else if( i == m_ClassIndex )
{
std::string name;
cellStream >> name;
values[2] = m_ClassNames.find(name)->second;
}
else
{ // do nothing
}
}
}
void
ARFFParser
::determineClassificationsFromAttributeLine( const std::string& line )
{
size_t opening = line.find_first_of( '{' );
++opening;
size_t closing = line.find_first_of( '}' );
std::stringstream stringStream( line.substr( opening, closing-opening ) );
std::string name;
float counter = 0;
while( std::getline( stringStream, name, ',' ) )
{
m_ClassNames[name] = counter;
counter += 1;
}
}
void
ARFFParser
::adjustMinAndMaxBasedOnNewData( float* values )
{
if( values[0] > m_MaxX )
{
m_MaxX = values[0];
}
if( values[0] < m_MinX )
{
m_MinX = values[0];
}
if( values[1] > m_MaxY )
{
m_MaxY = values[1];
}
if( values[1] < m_MinY )
{
m_MinY = values[1];
}
}
const std::list<float*>&
ARFFParser
::GetARFFData() const
{
return m_ARFFData;
}
float
ARFFParser
::GetMinX() const
{
return m_MinX;
}
float
ARFFParser
::GetMinY() const
{
return m_MinY;
}
float
ARFFParser
::GetMaxX() const
{
return m_MaxX;
}
float
ARFFParser
::GetMaxY() const
{
return m_MaxY;
}
} // end namespace tube
<commit_msg>BUG: Only delete the unused array of values if it is not pushed back into the parser's storage vector.<commit_after>/*=========================================================================
Library: TubeTK
Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
#include "tubeARFFParser.h"
#include <fstream>
#include <sstream>
#include <list>
#include <string>
#include <limits>
#include <iostream>
namespace tube
{
ARFFParser
::ARFFParser()
: m_Filename(""),
m_XLabel("x"),
m_YLabel("y"),
m_ClassLabel("class"),
m_XIndex(0),
m_YIndex(0),
m_ClassIndex(0),
m_ClassNames(),
m_MinX(std::numeric_limits<float>::max()),
m_MinY(std::numeric_limits<float>::max()),
m_MaxX(std::numeric_limits<float>::min()),
m_MaxY(std::numeric_limits<float>::min()),
m_ARFFData()
{
}
ARFFParser
::~ARFFParser()
{
std::list<float*>::iterator itr;
for( itr = m_ARFFData.begin(); itr != m_ARFFData.end(); ++itr )
{
delete [] *itr;
}
}
void
ARFFParser
::SetFilename( const std::string& filename )
{
m_Filename = filename;
}
void
ARFFParser
::SetXLabel( const std::string& xLabel )
{
m_XLabel = xLabel;
}
void
ARFFParser
::SetYLabel( const std::string& yLabel )
{
m_YLabel = yLabel;
}
void
ARFFParser
::SetClassLabel( const std::string& classLabel )
{
m_ClassLabel = classLabel;
}
void
ARFFParser
::Parse()
{
std::ifstream file( m_Filename.c_str() );
std::string line;
this->determineHeaderParameters( file );
while( std::getline( file, line ) )
{
float* values = new float[3];
if( line != "" && line.find( "%" ) == std::string::npos )
{
this->getValuesFromDataLine( line, values );
this->adjustMinAndMaxBasedOnNewData( values );
m_ARFFData.push_back( values );
}
else
{
delete [] values;
}
}
}
void
ARFFParser
::determineHeaderParameters( std::ifstream& file )
{
std::string line;
unsigned int index = 0;
while( std::getline( file, line ) )
{
if( line.find( "@DATA" ) != std::string::npos ||
line.find( "@data" ) != std::string::npos )
{
break;
}
else if( line.find( "@ATTRIBUTE" ) != std::string::npos ||
line.find( "@attribute" ) != std::string::npos )
{
std::string name;
this->getAttributeName( line, name );
if( name == this->m_XLabel )
{
m_XIndex = index;
}
else if( name == this->m_YLabel )
{
m_YIndex = index;
}
else if( name == this->m_ClassLabel )
{
this->determineClassificationsFromAttributeLine( line );
m_ClassIndex = index;
}
else
{ // do nothing
}
++index;
}
else
{ // do nothing
}
}
}
void
ARFFParser
::getAttributeName( const std::string& line, std::string& name ) const
{
std::stringstream stringStream( line );
std::getline( stringStream, name, ' ' );
std::getline( stringStream, name, ' ' );
}
void
ARFFParser
::getValuesFromDataLine( const std::string& line, float* values ) const
{
std::stringstream stringStream( line );
std::string cell;
for( unsigned int i = 0;
i <= m_XIndex || i <= m_YIndex || i <= m_ClassIndex;
++i )
{
std::getline( stringStream, cell, ',' );
std::stringstream cellStream( cell );
if( i == m_XIndex )
{
cellStream >> values[0];
}
else if( i == m_YIndex )
{
cellStream >> values[1];
}
else if( i == m_ClassIndex )
{
std::string name;
cellStream >> name;
values[2] = m_ClassNames.find(name)->second;
}
else
{ // do nothing
}
}
}
void
ARFFParser
::determineClassificationsFromAttributeLine( const std::string& line )
{
size_t opening = line.find_first_of( '{' );
++opening;
size_t closing = line.find_first_of( '}' );
std::stringstream stringStream( line.substr( opening, closing-opening ) );
std::string name;
float counter = 0;
while( std::getline( stringStream, name, ',' ) )
{
m_ClassNames[name] = counter;
counter += 1;
}
}
void
ARFFParser
::adjustMinAndMaxBasedOnNewData( float* values )
{
if( values[0] > m_MaxX )
{
m_MaxX = values[0];
}
if( values[0] < m_MinX )
{
m_MinX = values[0];
}
if( values[1] > m_MaxY )
{
m_MaxY = values[1];
}
if( values[1] < m_MinY )
{
m_MinY = values[1];
}
}
const std::list<float*>&
ARFFParser
::GetARFFData() const
{
return m_ARFFData;
}
float
ARFFParser
::GetMinX() const
{
return m_MinX;
}
float
ARFFParser
::GetMinY() const
{
return m_MinY;
}
float
ARFFParser
::GetMaxX() const
{
return m_MaxX;
}
float
ARFFParser
::GetMaxY() const
{
return m_MaxY;
}
} // end namespace tube
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (c) 2013-2014 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file navigator_rtl.cpp
* Helper class to access RTL
* @author Julian Oes <julian@oes.ch>
* @author Anton Babushkin <anton.babushkin@me.com>
*/
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <fcntl.h>
#include <systemlib/mavlink_log.h>
#include <systemlib/err.h>
#include <geo/geo.h>
#include <uORB/uORB.h>
#include <navigator/navigation.h>
#include <uORB/topics/home_position.h>
#include "navigator.h"
#include "rtl.h"
#define DELAY_SIGMA 0.01f
RTL::RTL(Navigator *navigator, const char *name) :
MissionBlock(navigator, name),
_rtl_state(RTL_STATE_NONE),
_rtl_start_lock(false),
_param_return_alt(this, "RTL_RETURN_ALT", false),
_param_descend_alt(this, "RTL_DESCEND_ALT", false),
_param_land_delay(this, "RTL_LAND_DELAY", false)
{
/* load initial params */
updateParams();
/* initial reset */
on_inactive();
}
RTL::~RTL()
{
}
void
RTL::on_inactive()
{
/* reset RTL state only if setpoint moved */
if (!_navigator->get_can_loiter_at_sp()) {
_rtl_state = RTL_STATE_NONE;
}
}
void
RTL::on_activation()
{
/* reset starting point so we override what the triplet contained from the previous navigation state */
_rtl_start_lock = false;
set_current_position_item(&_mission_item);
struct position_setpoint_triplet_s *pos_sp_triplet = _navigator->get_position_setpoint_triplet();
mission_item_to_position_setpoint(&_mission_item, &pos_sp_triplet->current);
/* decide where to enter the RTL procedure when we switch into it */
if (_rtl_state == RTL_STATE_NONE) {
/* for safety reasons don't go into RTL if landed */
if (_navigator->get_land_detected()->landed) {
_rtl_state = RTL_STATE_LANDED;
mavlink_log_critical(_navigator->get_mavlink_log_pub(), "no RTL when landed");
/* if lower than return altitude, climb up first */
} else if (_navigator->get_global_position()->alt < _navigator->get_home_position()->alt
+ _param_return_alt.get()) {
_rtl_state = RTL_STATE_CLIMB;
/* otherwise go straight to return */
} else {
/* set altitude setpoint to current altitude */
_rtl_state = RTL_STATE_RETURN;
_mission_item.altitude_is_relative = false;
_mission_item.altitude = _navigator->get_global_position()->alt;
}
}
set_rtl_item();
}
void
RTL::on_active()
{
if (_rtl_state != RTL_STATE_LANDED && is_mission_item_reached()) {
advance_rtl();
set_rtl_item();
}
}
void
RTL::set_rtl_item()
{
struct position_setpoint_triplet_s *pos_sp_triplet = _navigator->get_position_setpoint_triplet();
/* make sure we have the latest params */
updateParams();
if (!_rtl_start_lock) {
set_previous_pos_setpoint();
}
_navigator->set_can_loiter_at_sp(false);
switch (_rtl_state) {
case RTL_STATE_CLIMB: {
float climb_alt = _navigator->get_home_position()->alt + _param_return_alt.get();
_mission_item.lat = _navigator->get_global_position()->lat;
_mission_item.lon = _navigator->get_global_position()->lon;
_mission_item.altitude_is_relative = false;
_mission_item.altitude = climb_alt;
_mission_item.yaw = NAN;
_mission_item.loiter_radius = _navigator->get_loiter_radius();
_mission_item.loiter_direction = 1;
_mission_item.nav_cmd = NAV_CMD_WAYPOINT;
_mission_item.acceptance_radius = _navigator->get_acceptance_radius();
_mission_item.time_inside = 0.0f;
_mission_item.pitch_min = 0.0f;
_mission_item.autocontinue = true;
_mission_item.origin = ORIGIN_ONBOARD;
mavlink_log_critical(_navigator->get_mavlink_log_pub(), "RTL: climb to %d m (%d m above home)",
(int)(climb_alt),
(int)(climb_alt - _navigator->get_home_position()->alt));
break;
}
case RTL_STATE_RETURN: {
_mission_item.lat = _navigator->get_home_position()->lat;
_mission_item.lon = _navigator->get_home_position()->lon;
// don't change altitude
if (pos_sp_triplet->previous.valid) {
/* if previous setpoint is valid then use it to calculate heading to home */
_mission_item.yaw = get_bearing_to_next_waypoint(
pos_sp_triplet->previous.lat, pos_sp_triplet->previous.lon,
_mission_item.lat, _mission_item.lon);
} else {
/* else use current position */
_mission_item.yaw = get_bearing_to_next_waypoint(
_navigator->get_global_position()->lat, _navigator->get_global_position()->lon,
_mission_item.lat, _mission_item.lon);
}
_mission_item.loiter_radius = _navigator->get_loiter_radius();
_mission_item.loiter_direction = 1;
_mission_item.nav_cmd = NAV_CMD_WAYPOINT;
_mission_item.acceptance_radius = _navigator->get_acceptance_radius();
_mission_item.time_inside = 0.0f;
_mission_item.pitch_min = 0.0f;
_mission_item.autocontinue = true;
_mission_item.origin = ORIGIN_ONBOARD;
mavlink_log_critical(_navigator->get_mavlink_log_pub(), "RTL: return at %d m (%d m above home)",
(int)(_mission_item.altitude),
(int)(_mission_item.altitude - _navigator->get_home_position()->alt));
_rtl_start_lock = true;
break;
}
case RTL_STATE_TRANSITION_TO_MC: {
_mission_item.nav_cmd = NAV_CMD_DO_VTOL_TRANSITION;
_mission_item.params[0] = vehicle_status_s::VEHICLE_VTOL_STATE_MC;
break;
}
case RTL_STATE_DESCEND: {
_mission_item.lat = _navigator->get_home_position()->lat;
_mission_item.lon = _navigator->get_home_position()->lon;
_mission_item.altitude_is_relative = false;
_mission_item.altitude = _navigator->get_home_position()->alt + _param_descend_alt.get();
_mission_item.yaw = NAN; // don't bother with yaw
// except for vtol which might be still off here and should point towards this location
float d_current = get_distance_to_next_waypoint(
_navigator->get_global_position()->lat, _navigator->get_global_position()->lon,
_mission_item.lat, _mission_item.lon);
if (_navigator->get_vstatus()->is_vtol && d_current > _navigator->get_acceptance_radius()) {
_mission_item.yaw = get_bearing_to_next_waypoint(
_navigator->get_global_position()->lat, _navigator->get_global_position()->lon,
_mission_item.lat, _mission_item.lon);
}
_mission_item.loiter_radius = _navigator->get_loiter_radius();
_mission_item.loiter_direction = 1;
_mission_item.nav_cmd = NAV_CMD_LOITER_TIME_LIMIT;
_mission_item.acceptance_radius = _navigator->get_acceptance_radius();
_mission_item.time_inside = 0.0f;
_mission_item.pitch_min = 0.0f;
_mission_item.autocontinue = false;
_mission_item.origin = ORIGIN_ONBOARD;
mavlink_log_critical(_navigator->get_mavlink_log_pub(), "RTL: descend to %d m (%d m above home)",
(int)(_mission_item.altitude),
(int)(_mission_item.altitude - _navigator->get_home_position()->alt));
break;
}
case RTL_STATE_LOITER: {
bool autoland = _param_land_delay.get() > -DELAY_SIGMA;
_mission_item.lat = _navigator->get_home_position()->lat;
_mission_item.lon = _navigator->get_home_position()->lon;
// don't change altitude
_mission_item.yaw = NAN; // don't bother with yaw
_mission_item.loiter_radius = _navigator->get_loiter_radius();
_mission_item.loiter_direction = 1;
_mission_item.nav_cmd = autoland ? NAV_CMD_LOITER_TIME_LIMIT : NAV_CMD_LOITER_UNLIMITED;
_mission_item.acceptance_radius = _navigator->get_acceptance_radius();
_mission_item.time_inside = _param_land_delay.get() < 0.0f ? 0.0f : _param_land_delay.get();
_mission_item.pitch_min = 0.0f;
_mission_item.autocontinue = autoland;
_mission_item.origin = ORIGIN_ONBOARD;
_navigator->set_can_loiter_at_sp(true);
if (autoland) {
mavlink_log_critical(_navigator->get_mavlink_log_pub(), "RTL: loiter %.1fs", (double)_mission_item.time_inside);
} else {
mavlink_log_critical(_navigator->get_mavlink_log_pub(), "RTL: completed, loiter");
}
break;
}
case RTL_STATE_LAND: {
set_land_item(&_mission_item, false);
mavlink_log_critical(_navigator->get_mavlink_log_pub(), "RTL: land at home");
break;
}
case RTL_STATE_LANDED: {
set_idle_item(&_mission_item);
mavlink_log_critical(_navigator->get_mavlink_log_pub(), "RTL: completed, landed");
break;
}
default:
break;
}
reset_mission_item_reached();
/* execute command if set */
if (!item_contains_position(&_mission_item)) {
issue_command(&_mission_item);
}
/* convert mission item to current position setpoint and make it valid */
mission_item_to_position_setpoint(&_mission_item, &pos_sp_triplet->current);
pos_sp_triplet->next.valid = false;
_navigator->set_position_setpoint_triplet_updated();
}
void
RTL::advance_rtl()
{
switch (_rtl_state) {
case RTL_STATE_CLIMB:
_rtl_state = RTL_STATE_RETURN;
break;
case RTL_STATE_RETURN:
_rtl_state = RTL_STATE_DESCEND;
if (_navigator->get_vstatus()->is_vtol && !_navigator->get_vstatus()->is_rotary_wing) {
_rtl_state = RTL_STATE_TRANSITION_TO_MC;
}
break;
case RTL_STATE_TRANSITION_TO_MC:
_rtl_state = RTL_STATE_DESCEND;
break;
case RTL_STATE_DESCEND:
/* only go to land if autoland is enabled */
if (_param_land_delay.get() < -DELAY_SIGMA || _param_land_delay.get() > DELAY_SIGMA) {
_rtl_state = RTL_STATE_LOITER;
} else {
_rtl_state = RTL_STATE_LAND;
}
break;
case RTL_STATE_LOITER:
_rtl_state = RTL_STATE_LAND;
break;
case RTL_STATE_LAND:
_rtl_state = RTL_STATE_LANDED;
break;
default:
break;
}
}
<commit_msg>use waypoint type for RTL descent phase<commit_after>/****************************************************************************
*
* Copyright (c) 2013-2014 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file navigator_rtl.cpp
* Helper class to access RTL
* @author Julian Oes <julian@oes.ch>
* @author Anton Babushkin <anton.babushkin@me.com>
*/
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <fcntl.h>
#include <systemlib/mavlink_log.h>
#include <systemlib/err.h>
#include <geo/geo.h>
#include <uORB/uORB.h>
#include <navigator/navigation.h>
#include <uORB/topics/home_position.h>
#include "navigator.h"
#include "rtl.h"
#define DELAY_SIGMA 0.01f
RTL::RTL(Navigator *navigator, const char *name) :
MissionBlock(navigator, name),
_rtl_state(RTL_STATE_NONE),
_rtl_start_lock(false),
_param_return_alt(this, "RTL_RETURN_ALT", false),
_param_descend_alt(this, "RTL_DESCEND_ALT", false),
_param_land_delay(this, "RTL_LAND_DELAY", false)
{
/* load initial params */
updateParams();
/* initial reset */
on_inactive();
}
RTL::~RTL()
{
}
void
RTL::on_inactive()
{
/* reset RTL state only if setpoint moved */
if (!_navigator->get_can_loiter_at_sp()) {
_rtl_state = RTL_STATE_NONE;
}
}
void
RTL::on_activation()
{
/* reset starting point so we override what the triplet contained from the previous navigation state */
_rtl_start_lock = false;
set_current_position_item(&_mission_item);
struct position_setpoint_triplet_s *pos_sp_triplet = _navigator->get_position_setpoint_triplet();
mission_item_to_position_setpoint(&_mission_item, &pos_sp_triplet->current);
/* decide where to enter the RTL procedure when we switch into it */
if (_rtl_state == RTL_STATE_NONE) {
/* for safety reasons don't go into RTL if landed */
if (_navigator->get_land_detected()->landed) {
_rtl_state = RTL_STATE_LANDED;
mavlink_log_critical(_navigator->get_mavlink_log_pub(), "no RTL when landed");
/* if lower than return altitude, climb up first */
} else if (_navigator->get_global_position()->alt < _navigator->get_home_position()->alt
+ _param_return_alt.get()) {
_rtl_state = RTL_STATE_CLIMB;
/* otherwise go straight to return */
} else {
/* set altitude setpoint to current altitude */
_rtl_state = RTL_STATE_RETURN;
_mission_item.altitude_is_relative = false;
_mission_item.altitude = _navigator->get_global_position()->alt;
}
}
set_rtl_item();
}
void
RTL::on_active()
{
if (_rtl_state != RTL_STATE_LANDED && is_mission_item_reached()) {
advance_rtl();
set_rtl_item();
}
}
void
RTL::set_rtl_item()
{
struct position_setpoint_triplet_s *pos_sp_triplet = _navigator->get_position_setpoint_triplet();
/* make sure we have the latest params */
updateParams();
if (!_rtl_start_lock) {
set_previous_pos_setpoint();
}
_navigator->set_can_loiter_at_sp(false);
switch (_rtl_state) {
case RTL_STATE_CLIMB: {
float climb_alt = _navigator->get_home_position()->alt + _param_return_alt.get();
_mission_item.lat = _navigator->get_global_position()->lat;
_mission_item.lon = _navigator->get_global_position()->lon;
_mission_item.altitude_is_relative = false;
_mission_item.altitude = climb_alt;
_mission_item.yaw = NAN;
_mission_item.loiter_radius = _navigator->get_loiter_radius();
_mission_item.loiter_direction = 1;
_mission_item.nav_cmd = NAV_CMD_WAYPOINT;
_mission_item.acceptance_radius = _navigator->get_acceptance_radius();
_mission_item.time_inside = 0.0f;
_mission_item.pitch_min = 0.0f;
_mission_item.autocontinue = true;
_mission_item.origin = ORIGIN_ONBOARD;
mavlink_log_critical(_navigator->get_mavlink_log_pub(), "RTL: climb to %d m (%d m above home)",
(int)(climb_alt),
(int)(climb_alt - _navigator->get_home_position()->alt));
break;
}
case RTL_STATE_RETURN: {
_mission_item.lat = _navigator->get_home_position()->lat;
_mission_item.lon = _navigator->get_home_position()->lon;
// don't change altitude
if (pos_sp_triplet->previous.valid) {
/* if previous setpoint is valid then use it to calculate heading to home */
_mission_item.yaw = get_bearing_to_next_waypoint(
pos_sp_triplet->previous.lat, pos_sp_triplet->previous.lon,
_mission_item.lat, _mission_item.lon);
} else {
/* else use current position */
_mission_item.yaw = get_bearing_to_next_waypoint(
_navigator->get_global_position()->lat, _navigator->get_global_position()->lon,
_mission_item.lat, _mission_item.lon);
}
_mission_item.loiter_radius = _navigator->get_loiter_radius();
_mission_item.loiter_direction = 1;
_mission_item.nav_cmd = NAV_CMD_WAYPOINT;
_mission_item.acceptance_radius = _navigator->get_acceptance_radius();
_mission_item.time_inside = 0.0f;
_mission_item.pitch_min = 0.0f;
_mission_item.autocontinue = true;
_mission_item.origin = ORIGIN_ONBOARD;
mavlink_log_critical(_navigator->get_mavlink_log_pub(), "RTL: return at %d m (%d m above home)",
(int)(_mission_item.altitude),
(int)(_mission_item.altitude - _navigator->get_home_position()->alt));
_rtl_start_lock = true;
break;
}
case RTL_STATE_TRANSITION_TO_MC: {
_mission_item.nav_cmd = NAV_CMD_DO_VTOL_TRANSITION;
_mission_item.params[0] = vehicle_status_s::VEHICLE_VTOL_STATE_MC;
break;
}
case RTL_STATE_DESCEND: {
_mission_item.lat = _navigator->get_home_position()->lat;
_mission_item.lon = _navigator->get_home_position()->lon;
_mission_item.altitude_is_relative = false;
_mission_item.altitude = _navigator->get_home_position()->alt + _param_descend_alt.get();
_mission_item.yaw = NAN; // don't bother with yaw
// except for vtol which might be still off here and should point towards this location
float d_current = get_distance_to_next_waypoint(
_navigator->get_global_position()->lat, _navigator->get_global_position()->lon,
_mission_item.lat, _mission_item.lon);
if (_navigator->get_vstatus()->is_vtol && d_current > _navigator->get_acceptance_radius()) {
_mission_item.yaw = get_bearing_to_next_waypoint(
_navigator->get_global_position()->lat, _navigator->get_global_position()->lon,
_mission_item.lat, _mission_item.lon);
}
_mission_item.loiter_radius = _navigator->get_loiter_radius();
_mission_item.loiter_direction = 1;
_mission_item.nav_cmd = NAV_CMD_WAYPOINT;
_mission_item.acceptance_radius = _navigator->get_acceptance_radius();
_mission_item.time_inside = 0.0f;
_mission_item.pitch_min = 0.0f;
_mission_item.autocontinue = false;
_mission_item.origin = ORIGIN_ONBOARD;
mavlink_log_critical(_navigator->get_mavlink_log_pub(), "RTL: descend to %d m (%d m above home)",
(int)(_mission_item.altitude),
(int)(_mission_item.altitude - _navigator->get_home_position()->alt));
break;
}
case RTL_STATE_LOITER: {
bool autoland = _param_land_delay.get() > -DELAY_SIGMA;
_mission_item.lat = _navigator->get_home_position()->lat;
_mission_item.lon = _navigator->get_home_position()->lon;
// don't change altitude
_mission_item.yaw = NAN; // don't bother with yaw
_mission_item.loiter_radius = _navigator->get_loiter_radius();
_mission_item.loiter_direction = 1;
_mission_item.nav_cmd = autoland ? NAV_CMD_LOITER_TIME_LIMIT : NAV_CMD_LOITER_UNLIMITED;
_mission_item.acceptance_radius = _navigator->get_acceptance_radius();
_mission_item.time_inside = _param_land_delay.get() < 0.0f ? 0.0f : _param_land_delay.get();
_mission_item.pitch_min = 0.0f;
_mission_item.autocontinue = autoland;
_mission_item.origin = ORIGIN_ONBOARD;
_navigator->set_can_loiter_at_sp(true);
if (autoland) {
mavlink_log_critical(_navigator->get_mavlink_log_pub(), "RTL: loiter %.1fs", (double)_mission_item.time_inside);
} else {
mavlink_log_critical(_navigator->get_mavlink_log_pub(), "RTL: completed, loiter");
}
break;
}
case RTL_STATE_LAND: {
set_land_item(&_mission_item, false);
mavlink_log_critical(_navigator->get_mavlink_log_pub(), "RTL: land at home");
break;
}
case RTL_STATE_LANDED: {
set_idle_item(&_mission_item);
mavlink_log_critical(_navigator->get_mavlink_log_pub(), "RTL: completed, landed");
break;
}
default:
break;
}
reset_mission_item_reached();
/* execute command if set */
if (!item_contains_position(&_mission_item)) {
issue_command(&_mission_item);
}
/* convert mission item to current position setpoint and make it valid */
mission_item_to_position_setpoint(&_mission_item, &pos_sp_triplet->current);
pos_sp_triplet->next.valid = false;
_navigator->set_position_setpoint_triplet_updated();
}
void
RTL::advance_rtl()
{
switch (_rtl_state) {
case RTL_STATE_CLIMB:
_rtl_state = RTL_STATE_RETURN;
break;
case RTL_STATE_RETURN:
_rtl_state = RTL_STATE_DESCEND;
if (_navigator->get_vstatus()->is_vtol && !_navigator->get_vstatus()->is_rotary_wing) {
_rtl_state = RTL_STATE_TRANSITION_TO_MC;
}
break;
case RTL_STATE_TRANSITION_TO_MC:
_rtl_state = RTL_STATE_DESCEND;
break;
case RTL_STATE_DESCEND:
/* only go to land if autoland is enabled */
if (_param_land_delay.get() < -DELAY_SIGMA || _param_land_delay.get() > DELAY_SIGMA) {
_rtl_state = RTL_STATE_LOITER;
} else {
_rtl_state = RTL_STATE_LAND;
}
break;
case RTL_STATE_LOITER:
_rtl_state = RTL_STATE_LAND;
break;
case RTL_STATE_LAND:
_rtl_state = RTL_STATE_LANDED;
break;
default:
break;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2016 - 2021 gary@drinkingtea.net
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <QApplication>
#include <QDebug>
#include <ox/clargs/clargs.hpp>
#include <ox/std/trace.hpp>
#include <qdark/theme.hpp>
#include "mainwindow.hpp"
using namespace nostalgia::studio;
int main(int argc, char **args) {
ox::trace::init();
ox::ClArgs clargs(argc, const_cast<const char**>(args));
QString argProfilePath = clargs.getString("profile", ":/profiles/nostalgia-studio.json").c_str();
QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QApplication app(argc, args);
// load theme
qdark::load(&app);
try {
MainWindow w(argProfilePath);
app.setApplicationName(w.windowTitle());
w.show();
QObject::connect(&app, &QApplication::aboutToQuit, &w, &MainWindow::onExit);
return app.exec();
} catch (const ox::Error &err) {
oxPanic(err, "Unhandled ox::Error");
}
}
<commit_msg>[nostalgia/studio] Disable QDark theme on Mac<commit_after>/*
* Copyright 2016 - 2021 gary@drinkingtea.net
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <QApplication>
#include <QDebug>
#include <ox/clargs/clargs.hpp>
#include <ox/std/trace.hpp>
#include <qdark/theme.hpp>
#include "mainwindow.hpp"
using namespace nostalgia::studio;
int main(int argc, char **args) {
ox::trace::init();
ox::ClArgs clargs(argc, const_cast<const char**>(args));
QString argProfilePath = clargs.getString("profile", ":/profiles/nostalgia-studio.json").c_str();
QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QApplication app(argc, args);
// load theme
if constexpr(ox::defines::OS != ox::defines::OS::Darwin) {
qdark::load(&app);
}
try {
MainWindow w(argProfilePath);
app.setApplicationName(w.windowTitle());
w.show();
QObject::connect(&app, &QApplication::aboutToQuit, &w, &MainWindow::onExit);
return app.exec();
} catch (const ox::Error &err) {
oxPanic(err, "Unhandled ox::Error");
}
}
<|endoftext|> |
<commit_before>/*
Copyright (C) 2014-2018 Sven Willner <sven.willner@pik-potsdam.de>
Christian Otto <christian.otto@pik-potsdam.de>
This file is part of Acclimate.
Acclimate 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.
Acclimate is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Acclimate. If not, see <http://www.gnu.org/licenses/>.
*/
#include "output/ProgressOutput.h"
#include <iostream>
#include <string>
#include <utility>
#include "model/Model.h"
#include "model/Sector.h"
#include "variants/ModelVariants.h"
#ifdef USE_TQDM
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wredundant-decls"
#pragma GCC diagnostic ignored "-Wfloat-equal"
#include "tqdm/tqdm.h"
#pragma GCC diagnostic pop
#endif
namespace acclimate {
template<class ModelVariant>
ProgressOutput<ModelVariant>::ProgressOutput(const settings::SettingsNode& settings_p,
Model<ModelVariant>* model_p,
Scenario<ModelVariant>* scenario_p,
settings::SettingsNode output_node_p)
: Output<ModelVariant>(settings_p, model_p, scenario_p, std::move(output_node_p)) {}
template<class ModelVariant>
void ProgressOutput<ModelVariant>::initialize() {
#ifdef USE_TQDM
tqdm::Params p;
p.ascii = "";
p.f = stdout;
total = output_node["total"].template as<int>();
it.reset(new tqdm::RangeTqdm<int>(tqdm::RangeIterator<int>(total), tqdm::RangeIterator<int>(total, total), p));
#else
error("tqdm not enabled");
#endif
}
template<class ModelVariant>
void ProgressOutput<ModelVariant>::checkpoint_stop() {
#ifdef USE_TQDM
total = it->size_remaining();
it->close();
#endif
}
template<class ModelVariant>
void ProgressOutput<ModelVariant>::checkpoint_resume() {
#ifdef USE_TQDM
tqdm::Params p;
p.ascii = "";
p.f = stdout;
p.miniters = 1;
it.reset(new tqdm::RangeTqdm<int>(tqdm::RangeIterator<int>(total), tqdm::RangeIterator<int>(total, total), p));
#endif
}
template<class ModelVariant>
void ProgressOutput<ModelVariant>::internal_end() {
#ifdef USE_TQDM
it->close();
#endif
}
template<class ModelVariant>
void ProgressOutput<ModelVariant>::internal_iterate_end() {
#ifdef USE_TQDM
if (!it->ended()) {
++(*it);
std::cout << std::flush;
}
#endif
}
INSTANTIATE_BASIC(ProgressOutput);
} // namespace acclimate
<commit_msg>Increase frequency of tqdm progress output<commit_after>/*
Copyright (C) 2014-2018 Sven Willner <sven.willner@pik-potsdam.de>
Christian Otto <christian.otto@pik-potsdam.de>
This file is part of Acclimate.
Acclimate 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.
Acclimate is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Acclimate. If not, see <http://www.gnu.org/licenses/>.
*/
#include "output/ProgressOutput.h"
#include <iostream>
#include <string>
#include <utility>
#include "model/Model.h"
#include "model/Sector.h"
#include "variants/ModelVariants.h"
#ifdef USE_TQDM
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wredundant-decls"
#pragma GCC diagnostic ignored "-Wfloat-equal"
#include "tqdm/tqdm.h"
#pragma GCC diagnostic pop
#endif
namespace acclimate {
template<class ModelVariant>
ProgressOutput<ModelVariant>::ProgressOutput(const settings::SettingsNode& settings_p,
Model<ModelVariant>* model_p,
Scenario<ModelVariant>* scenario_p,
settings::SettingsNode output_node_p)
: Output<ModelVariant>(settings_p, model_p, scenario_p, std::move(output_node_p)) {}
template<class ModelVariant>
void ProgressOutput<ModelVariant>::initialize() {
#ifdef USE_TQDM
tqdm::Params p;
p.ascii = "";
p.f = stdout;
p.miniters = 1;
total = output_node["total"].template as<int>();
it.reset(new tqdm::RangeTqdm<int>(tqdm::RangeIterator<int>(total), tqdm::RangeIterator<int>(total, total), p));
#else
error("tqdm not enabled");
#endif
}
template<class ModelVariant>
void ProgressOutput<ModelVariant>::checkpoint_stop() {
#ifdef USE_TQDM
total = it->size_remaining();
it->close();
#endif
}
template<class ModelVariant>
void ProgressOutput<ModelVariant>::checkpoint_resume() {
#ifdef USE_TQDM
tqdm::Params p;
p.ascii = "";
p.f = stdout;
p.miniters = 1;
it.reset(new tqdm::RangeTqdm<int>(tqdm::RangeIterator<int>(total), tqdm::RangeIterator<int>(total, total), p));
#endif
}
template<class ModelVariant>
void ProgressOutput<ModelVariant>::internal_end() {
#ifdef USE_TQDM
it->close();
#endif
}
template<class ModelVariant>
void ProgressOutput<ModelVariant>::internal_iterate_end() {
#ifdef USE_TQDM
if (!it->ended()) {
++(*it);
std::cout << std::flush;
}
#endif
}
INSTANTIATE_BASIC(ProgressOutput);
} // namespace acclimate
<|endoftext|> |
<commit_before>//
// calcCOVARchunks.cpp
//
//
// Created by Evan McCartney-Melstad on 2/13/15.
//
//
#include "calcCOVARchunks.h"
#include <iostream>
#include <vector>
#include <fstream>
#include <thread>
#include <string>
int calcCOVARfromBinaryFile (std::string binaryFile, unsigned long long int numLoci, const int numIndividuals, std::string outFile, int lociChunkSize, int numThreads) {
std::cout << "Number of threads: " << numThreads << std::endl;
//std::streampos size;
std::ifstream file (binaryFile, std::ios::in|std::ios::binary);
std::cout << "Made it to line 22" << std::endl;
if (file.is_open()) {
unsigned long long int maxLocus = numLoci;
std::cout << "Calculating divergence based on " << maxLocus << " total loci." << std::endl;
// How many bytes to read in at one time (this number of loci will be split amongs numThreads threads, so it should be divisible exactly by numThreads. So the number of loci read in at a time will actually be numLoci*numThreads
unsigned long long int lociChunkByteSize = (unsigned long long)lociChunkSize * numIndividuals * 2 * numThreads;
int numFullChunks = (maxLocus*numIndividuals*2)/lociChunkByteSize; // Truncates answer to an integer
unsigned long long remainingBytesAfterFullChunks = (maxLocus*numIndividuals*2) % lociChunkByteSize;
std::cout << "Total number of chunks to run: " << numFullChunks + 1 << std::endl;
/* We are going to split the loci between numThreads threads. Each thread will modify two multidimensional
vectors that will hold the weightings, the weighted sum of products, and weighted sums of the firsts.
First, we'll generate all of these vectors, which apparently in C++ needs to be constructed of a
vector of two-dimensional vectors...
*/
std::vector<std::vector<std::vector<unsigned long long>>> weightSumProductsThreads(numThreads, std::vector<std::vector<unsigned long long>> (numIndividuals, std::vector<unsigned long long> (numIndividuals,0) ) ); //covarThreads[0] is the first 2D array for the first thread, etc...
std::vector<std::vector<std::vector<unsigned long long>>> weightSumFirstThreads(numThreads, std::vector<std::vector<unsigned long long>> (numIndividuals, std::vector<unsigned long long> (numIndividuals,0) ) ); //covarThreads[0] is the first 2D array for the first thread, etc...
std::vector<std::vector<std::vector<unsigned long long int>>> weightingsThreads(numThreads, std::vector<std::vector<unsigned long long int> > (numIndividuals, std::vector<unsigned long long int> (numIndividuals,0) ) );
std::cout << "Initialized the 3d weighting and covar vectors" << std::endl;
// Read in the data in chunks, and process each chunk using numThreads threads
int chunkCounter = 0;
while (chunkCounter < numFullChunks) {
unsigned long long bytesPerThread = lociChunkByteSize / numThreads;
unsigned long long int lociPerThread = bytesPerThread / (numIndividuals*2);
std::cout << "Running chunk #" << chunkCounter << std::endl;
std::vector<unsigned char> readCounts(lociChunkByteSize);
file.read((char*) &readCounts[0], lociChunkByteSize);
std::cout << "Number of bytes in the chunk vector: " << readCounts.size() << std::endl;
std::vector<std::thread> threadsVec;
for (int threadRunning = 0; threadRunning < numThreads; threadRunning++) {
unsigned long long int firstLocus = (unsigned long long int) threadRunning * lociPerThread;
unsigned long long int finishingLocus = ((unsigned long long int) threadRunning * lociPerThread) + lociPerThread - (unsigned long long)1.0;
std::cout << "Got to the function call in main loop. Running thread # " << threadRunning << std::endl;
//threadsVec.push_back(std::thread(calcCOVARforRange, numIndividuals, lociPerThread, std::ref(readCounts), std::ref(covarThreads[threadRunning]), std::ref(weightingsThreads[threadRunning])));
threadsVec.push_back(std::thread(calcCOVARforRange, firstLocus, finishingLocus, numIndividuals, std::ref(readCounts), std::ref(weightSumProductsThreads[threadRunning]), std::ref(weightSumFirstThreads[threadRunning]), std::ref(weightingsThreads[threadRunning])));
}
// Wait on threads to finish
for (int i = 0; i < numThreads; ++i) {
threadsVec[i].join();
std::cout << "Joined thread " << i << std::endl;
}
std::cout << "All threads completed running for chunk " << chunkCounter << " of " << numFullChunks + 1 << std::endl;
chunkCounter++;
}
// For the last chunk, we'll just run it in a single thread, so we don't have to worry about numRemainingLoci/lociPerThread remainders... Just add everything to the vectors for thread 1
std::vector<unsigned char> readCountsRemaining(remainingBytesAfterFullChunks);
file.read((char*) &readCountsRemaining[0], remainingBytesAfterFullChunks);
unsigned long long int finishingLocus = (readCountsRemaining.size()/(numIndividuals*2)) - 1;
calcCOVARforRange(0, finishingLocus, numIndividuals, std::ref(readCountsRemaining), std::ref(weightSumProductsThreads[0]), std::ref(weightSumFirstThreads[0]), std::ref(weightingsThreads[0]));
// Now aggregate the results of the threads and print final results
std::vector<std::vector<long double>> weightingsSUM(numIndividuals, std::vector<long double>(numIndividuals,0));
std::vector<std::vector<long double>> weightSumProductsSUM(numIndividuals, std::vector<long double>(numIndividuals,0));
std::vector<std::vector<long double>> weightSumFirstSUM(numIndividuals, std::vector<long double>(numIndividuals,0));
for (int tortoise = 0; tortoise < numIndividuals; tortoise++) {
for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) {
for (int threadVector = 0; threadVector < numThreads; threadVector++) {
weightingsSUM[tortoise][comparisonTortoise] += weightingsThreads[threadVector][tortoise][comparisonTortoise];
weightSumProductsSUM[tortoise][comparisonTortoise] += weightSumProductsThreads[threadVector][tortoise][comparisonTortoise];
}
}
}
//weightSumFirstSUM is a full matrix (not half), so run comparison tortoise from 0 to numIndividuals, not 0 to tortoise
for (int tortoise = 0; tortoise < numIndividuals; tortoise++) {
for (int comparisonTortoise = 0; comparisonTortoise < numIndividuals; comparisonTortoise++) {
for (int threadVector = 0; threadVector < numThreads; threadVector++) {
weightSumFirstSUM[tortoise][comparisonTortoise] += weightSumFirstThreads[threadVector][tortoise][comparisonTortoise];
}
}
}
std::cout << "Finished summing the threads vectors" << std::endl;\
file.close(); // This is the binary file that holds all the read count data
// Now print out the final output to the pairwise covariance file:
std::ofstream covarOUT (outFile);
if (!covarOUT) {
std::cerr << "Crap, " << outFile << "didn't open!" << std::endl;
} else {
for (int tortoise=0; tortoise < numIndividuals; tortoise++) {
for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) {
covar = long double(((weightSumProductsSUM[tortoise][comparisonTortoise])/(weightingsSUM[tortoise][comparisonTortoise])) - ((weightSumFirstSUM[tortoise][comparisonTortoise])/(weightingsSUM[tortoise][comparisonTortoise]))*((weightSumFirstSUM[comparisonTortoise][tortoise])/weightingsSUM[tortoise][comparisonTortoise]));
covarOUT << covar << std::endl;
}
}
}
} else std::cout << "Unable to open file";
return 0;
}
/*
D[N] = total coverage
P[N] = major allele counts
W[N,N] = weights
C[N,N] = weighted sum of products
Z[N,N] = weighted sum of first one (note cancelation of D[N])
W[N,M] = weights
C[N,M] = weighted sum of products
Z[N,M] = weighted sum of first one (note cancelation of D[M]) : weightSumFirst
Z[M,N] = weighted sum of second one (IN TRANSPOSE) : weightSumFirst
*/
int calcCOVARforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, std::vector<unsigned char>& mainReadCountVector, std::vector<std::vector<long double>>& weightSumProducts, std::vector<std::vector<unsigned long long int>>& weightSumFirst, std::vector<std::vector<unsigned long long int>>& threadWeightings) {
std::cout << "Calculating COVAR for the following locus range: " << startingLocus << " to " << endingLocus << std::endl;
for( unsigned long long locus = startingLocus; locus < endingLocus; locus++) {
if (locus % 100000 == 0) {
std::cout << locus << " loci processed through calcCOVARfromBinaryFile" << std::endl;
}
unsigned long long coverages[numIndividuals];
unsigned long long int *majorAlleleCounts = new unsigned long long int[numIndividuals]; // This will hold the major allele counts for that locus for each tortoise
for( int tortoise = 0; tortoise < numIndividuals; tortoise++ ) {
unsigned long long majorIndex = locus * (numIndividuals*2) + 2 * tortoise;
unsigned long long minorIndex = locus * (numIndividuals*2) + 2 * tortoise + 1;
coverages[tortoise] = int(mainReadCountVector[majorIndex]) + int(mainReadCountVector[minorIndex]); // Hold the coverages for each locus
if ( coverages[tortoise] > 0 ) {
majorAlleleCounts[tortoise] = (unsigned long long int)mainReadCountVector[majorIndex]; // This will be an integer value
if (coverages[tortoise] > 1) {
unsigned long long int locusWeighting = (unsigned long long int) (coverages[tortoise]*(coverages[tortoise]-1));
threadWeightings[tortoise][tortoise] += (unsigned long long int)locusWeighting; // This is an integer--discrete number of reads
weightSumProducts[tortoise][tortoise] += (majorAlleleCounts[tortoise]) * (majorAlleleCounts[tortoise]) * (coverages[tortoise]-1)/(coverages[tortoise]);
weightSumFirst[tortoise][tortoise] += (majorAlleleCounts[tortoise]) * (coverages[tortoise]-1);
}
for( int comparisonTortoise = 0; comparisonTortoise < tortoise; comparisonTortoise++) {
if (coverages[comparisonTortoise] > 0) {
unsigned long long int locusWeighting = (unsigned long long int)coverages[tortoise] * (unsigned long long int)(coverages[comparisonTortoise]);
threadWeightings[tortoise][comparisonTortoise] += locusWeighting;
weightSumProducts[tortoise][comparisonTortoise] += (majorAlleleCounts[tortoise]) * (majorAlleleCounts[comparisonTortoise]);
weightSumFirst[tortoise][comparisonTortoise] += (majorAlleleCounts[comparisonTortoise]) * coverages[tortoise];
weightSumFirst[comparisonTortoise][tortoise] += (majorAlleleCounts[tortoise]) * coverages[comparisonTortoise];
}
}
}
}
delete[] majorAlleleCounts; // Needed to avoid memory leaks
}
std::cout << "Finished thread ending on locus " << endingLocus << std::endl;
return 0;
}
<commit_msg>Minor change<commit_after>//
// calcCOVARchunks.cpp
//
//
// Created by Evan McCartney-Melstad on 2/13/15.
//
//
#include "calcCOVARchunks.h"
#include <iostream>
#include <vector>
#include <fstream>
#include <thread>
#include <string>
int calcCOVARfromBinaryFile (std::string binaryFile, unsigned long long int numLoci, const int numIndividuals, std::string outFile, int lociChunkSize, int numThreads) {
std::cout << "Number of threads: " << numThreads << std::endl;
//std::streampos size;
std::ifstream file (binaryFile, std::ios::in|std::ios::binary);
std::cout << "Made it to line 22" << std::endl;
if (file.is_open()) {
unsigned long long int maxLocus = numLoci;
std::cout << "Calculating divergence based on " << maxLocus << " total loci." << std::endl;
// How many bytes to read in at one time (this number of loci will be split amongs numThreads threads, so it should be divisible exactly by numThreads. So the number of loci read in at a time will actually be numLoci*numThreads
unsigned long long int lociChunkByteSize = (unsigned long long)lociChunkSize * numIndividuals * 2 * numThreads;
int numFullChunks = (maxLocus*numIndividuals*2)/lociChunkByteSize; // Truncates answer to an integer
unsigned long long remainingBytesAfterFullChunks = (maxLocus*numIndividuals*2) % lociChunkByteSize;
std::cout << "Total number of chunks to run: " << numFullChunks + 1 << std::endl;
/* We are going to split the loci between numThreads threads. Each thread will modify two multidimensional
vectors that will hold the weightings, the weighted sum of products, and weighted sums of the firsts.
First, we'll generate all of these vectors, which apparently in C++ needs to be constructed of a
vector of two-dimensional vectors...
*/
std::vector<std::vector<std::vector<unsigned long long>>> weightSumProductsThreads(numThreads, std::vector<std::vector<unsigned long long>> (numIndividuals, std::vector<unsigned long long> (numIndividuals,0) ) ); //covarThreads[0] is the first 2D array for the first thread, etc...
std::vector<std::vector<std::vector<unsigned long long>>> weightSumFirstThreads(numThreads, std::vector<std::vector<unsigned long long>> (numIndividuals, std::vector<unsigned long long> (numIndividuals,0) ) ); //covarThreads[0] is the first 2D array for the first thread, etc...
std::vector<std::vector<std::vector<unsigned long long int>>> weightingsThreads(numThreads, std::vector<std::vector<unsigned long long int> > (numIndividuals, std::vector<unsigned long long int> (numIndividuals,0) ) );
std::cout << "Initialized the 3d weighting and covar vectors" << std::endl;
// Read in the data in chunks, and process each chunk using numThreads threads
int chunkCounter = 0;
while (chunkCounter < numFullChunks) {
unsigned long long bytesPerThread = lociChunkByteSize / numThreads;
unsigned long long int lociPerThread = bytesPerThread / (numIndividuals*2);
std::cout << "Running chunk #" << chunkCounter << std::endl;
std::vector<unsigned char> readCounts(lociChunkByteSize);
file.read((char*) &readCounts[0], lociChunkByteSize);
std::cout << "Number of bytes in the chunk vector: " << readCounts.size() << std::endl;
std::vector<std::thread> threadsVec;
for (int threadRunning = 0; threadRunning < numThreads; threadRunning++) {
unsigned long long int firstLocus = (unsigned long long int) threadRunning * lociPerThread;
unsigned long long int finishingLocus = ((unsigned long long int) threadRunning * lociPerThread) + lociPerThread - (unsigned long long)1.0;
std::cout << "Got to the function call in main loop. Running thread # " << threadRunning << std::endl;
//threadsVec.push_back(std::thread(calcCOVARforRange, numIndividuals, lociPerThread, std::ref(readCounts), std::ref(covarThreads[threadRunning]), std::ref(weightingsThreads[threadRunning])));
threadsVec.push_back(std::thread(calcCOVARforRange, firstLocus, finishingLocus, numIndividuals, std::ref(readCounts), std::ref(weightSumProductsThreads[threadRunning]), std::ref(weightSumFirstThreads[threadRunning]), std::ref(weightingsThreads[threadRunning])));
}
// Wait on threads to finish
for (int i = 0; i < numThreads; ++i) {
threadsVec[i].join();
std::cout << "Joined thread " << i << std::endl;
}
std::cout << "All threads completed running for chunk " << chunkCounter << " of " << numFullChunks + 1 << std::endl;
chunkCounter++;
}
// For the last chunk, we'll just run it in a single thread, so we don't have to worry about numRemainingLoci/lociPerThread remainders... Just add everything to the vectors for thread 1
std::vector<unsigned char> readCountsRemaining(remainingBytesAfterFullChunks);
file.read((char*) &readCountsRemaining[0], remainingBytesAfterFullChunks);
unsigned long long int finishingLocus = (readCountsRemaining.size()/(numIndividuals*2)) - 1;
calcCOVARforRange(0, finishingLocus, numIndividuals, std::ref(readCountsRemaining), std::ref(weightSumProductsThreads[0]), std::ref(weightSumFirstThreads[0]), std::ref(weightingsThreads[0]));
// Now aggregate the results of the threads and print final results
std::vector<std::vector<long double>> weightingsSUM(numIndividuals, std::vector<long double>(numIndividuals,0));
std::vector<std::vector<long double>> weightSumProductsSUM(numIndividuals, std::vector<long double>(numIndividuals,0));
std::vector<std::vector<long double>> weightSumFirstSUM(numIndividuals, std::vector<long double>(numIndividuals,0));
for (int tortoise = 0; tortoise < numIndividuals; tortoise++) {
for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) {
for (int threadVector = 0; threadVector < numThreads; threadVector++) {
weightingsSUM[tortoise][comparisonTortoise] += weightingsThreads[threadVector][tortoise][comparisonTortoise];
weightSumProductsSUM[tortoise][comparisonTortoise] += weightSumProductsThreads[threadVector][tortoise][comparisonTortoise];
}
}
}
//weightSumFirstSUM is a full matrix (not half), so run comparison tortoise from 0 to numIndividuals, not 0 to tortoise
for (int tortoise = 0; tortoise < numIndividuals; tortoise++) {
for (int comparisonTortoise = 0; comparisonTortoise < numIndividuals; comparisonTortoise++) {
for (int threadVector = 0; threadVector < numThreads; threadVector++) {
weightSumFirstSUM[tortoise][comparisonTortoise] += weightSumFirstThreads[threadVector][tortoise][comparisonTortoise];
}
}
}
std::cout << "Finished summing the threads vectors" << std::endl;\
file.close(); // This is the binary file that holds all the read count data
// Now print out the final output to the pairwise covariance file:
std::ofstream covarOUT (outFile);
if (!covarOUT) {
std::cerr << "Crap, " << outFile << "didn't open!" << std::endl;
} else {
for (int tortoise=0; tortoise < numIndividuals; tortoise++) {
for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) {
covar = long double(((weightSumProductsSUM[tortoise][comparisonTortoise])/(weightingsSUM[tortoise][comparisonTortoise])) - ((weightSumFirstSUM[tortoise][comparisonTortoise])/(weightingsSUM[tortoise][comparisonTortoise]))*((weightSumFirstSUM[comparisonTortoise][tortoise])/weightingsSUM[tortoise][comparisonTortoise]));
covarOUT << covar << std::endl;
}
}
}
} else std::cout << "Unable to open file";
return 0;
}
/*
D[N] = total coverage
P[N] = major allele counts
W[N,N] = weights
C[N,N] = weighted sum of products
Z[N,N] = weighted sum of first one (note cancelation of D[N])
W[N,M] = weights
C[N,M] = weighted sum of products
Z[N,M] = weighted sum of first one (note cancelation of D[M]) : weightSumFirst
Z[M,N] = weighted sum of second one (IN TRANSPOSE) : weightSumFirst
*/
int calcCOVARforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, std::vector<unsigned char>& mainReadCountVector, std::vector<std::vector<unsigned long long int>>& weightSumProducts, std::vector<std::vector<unsigned long long int>>& weightSumFirst, std::vector<std::vector<unsigned long long int>>& threadWeightings) {
std::cout << "Calculating COVAR for the following locus range: " << startingLocus << " to " << endingLocus << std::endl;
for( unsigned long long locus = startingLocus; locus < endingLocus; locus++) {
if (locus % 100000 == 0) {
std::cout << locus << " loci processed through calcCOVARfromBinaryFile" << std::endl;
}
unsigned long long coverages[numIndividuals];
unsigned long long int *majorAlleleCounts = new unsigned long long int[numIndividuals]; // This will hold the major allele counts for that locus for each tortoise
for( int tortoise = 0; tortoise < numIndividuals; tortoise++ ) {
unsigned long long majorIndex = locus * (numIndividuals*2) + 2 * tortoise;
unsigned long long minorIndex = locus * (numIndividuals*2) + 2 * tortoise + 1;
coverages[tortoise] = int(mainReadCountVector[majorIndex]) + int(mainReadCountVector[minorIndex]); // Hold the coverages for each locus
if ( coverages[tortoise] > 0 ) {
majorAlleleCounts[tortoise] = (unsigned long long int)mainReadCountVector[majorIndex]; // This will be an integer value
if (coverages[tortoise] > 1) {
unsigned long long int locusWeighting = (unsigned long long int) (coverages[tortoise]*(coverages[tortoise]-1));
threadWeightings[tortoise][tortoise] += (unsigned long long int)locusWeighting; // This is an integer--discrete number of reads
weightSumProducts[tortoise][tortoise] += (majorAlleleCounts[tortoise]) * (majorAlleleCounts[tortoise]) * (coverages[tortoise]-1)/(coverages[tortoise]);
weightSumFirst[tortoise][tortoise] += (majorAlleleCounts[tortoise]) * (coverages[tortoise]-1);
}
for( int comparisonTortoise = 0; comparisonTortoise < tortoise; comparisonTortoise++) {
if (coverages[comparisonTortoise] > 0) {
unsigned long long int locusWeighting = (unsigned long long int)coverages[tortoise] * (unsigned long long int)(coverages[comparisonTortoise]);
threadWeightings[tortoise][comparisonTortoise] += locusWeighting;
weightSumProducts[tortoise][comparisonTortoise] += (majorAlleleCounts[tortoise]) * (majorAlleleCounts[comparisonTortoise]);
weightSumFirst[tortoise][comparisonTortoise] += (majorAlleleCounts[comparisonTortoise]) * coverages[tortoise];
weightSumFirst[comparisonTortoise][tortoise] += (majorAlleleCounts[tortoise]) * coverages[comparisonTortoise];
}
}
}
}
delete[] majorAlleleCounts; // Needed to avoid memory leaks
}
std::cout << "Finished thread ending on locus " << endingLocus << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993-2013 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "SolarisMedia.h"
#include "TimeKeeper.h"
#define DEBUG_SOLARIS 0 //(1 = debug, 0 = don't!)
#define AUDIO_BUFFER_SIZE 5000
#if defined(HALF_RATE_AUDIO)
static const int defaultAudioRate = 11025;
#else
static const int defaultAudioRate = 22050;
#endif
static const int defaultChannels = 2;
static const int defaultEncoding = AUDIO_ENCODING_LINEAR;
static const int defaultPrecision = 16;
short tmp_buf[512];
//
// SolarisMedia
//
SolarisMedia::SolarisMedia() : BzfMedia(), audio_fd(-1),
queueIn(-1), queueOut(-1),
childProcID(0),
written(0), eof_written(0),
eof_counter(0),audio_ready(0)
{
// do nothing
}
SolarisMedia::~SolarisMedia()
{
// do nothing
}
double SolarisMedia::stopwatch(bool start)
{
struct timeval tv;
gettimeofday(&tv, 0);
if (start)
{
stopwatchTime = (double)tv.tv_sec + 1.0e-6 * (double)tv.tv_usec;
return 0.0;
}
return (double)tv.tv_sec + 1.0e-6 * (double)tv.tv_usec - stopwatchTime;
}
static const int NumChunks = 4;
bool SolarisMedia::openAudio()
{
int fd[2];
if(audio_ready)
return false;
audio_fd = open("/dev/audio", O_WRONLY | O_NDELAY);
if(audio_fd < 0)
return false;
if(DEBUG_SOLARIS)
fprintf(stderr, "Audio device '/dev/audio' opened\n");
audioctl_fd = open("/dev/audioctl", O_RDWR);
if(audioctl_fd < 0)
return false;
if(DEBUG_SOLARIS)
fprintf(stderr, "Opened audio control device '/dev/audioctl'\n");
// removing these avoids a kernel crash on solaris 8 - bzFrank
#ifdef FLUSHDRAIN
// Empty buffers
ioctl(audio_fd, AUDIO_DRAIN, 0);
ioctl(audio_fd, I_FLUSH, FLUSHRW);
ioctl(audioctl_fd, I_FLUSH, FLUSHRW);
#endif
if(ioctl(audio_fd, AUDIO_GETDEV, &a_dev) < 0)
{
if(DEBUG_SOLARIS)
fprintf(stderr, "Cannot get audio information.\n");
close(audio_fd);
close(audioctl_fd);
return false;
}
if(DEBUG_SOLARIS)
fprintf(stderr, "Sound device is a %s %s version %s\n", a_dev.config, a_dev.name, a_dev.version);
// Get audio parameters
if(ioctl(audioctl_fd, AUDIO_GETINFO, &a_info) < 0)
{
if(DEBUG_SOLARIS)
fprintf(stderr, "Cannot get audio information.\n");
close(audio_fd);
close(audioctl_fd);
return false;
}
AUDIO_INITINFO(&a_info);
a_info.play.sample_rate = defaultAudioRate;
a_info.play.channels = defaultChannels;
a_info.play.precision = defaultPrecision;
a_info.play.encoding = defaultEncoding;
a_info.play.buffer_size = NumChunks * AUDIO_BUFFER_SIZE;
audioBufferSize = AUDIO_BUFFER_SIZE;
audioLowWaterMark = 2;
if(ioctl(audio_fd, AUDIO_SETINFO, &a_info) == -1)
{
if(DEBUG_SOLARIS)
fprintf(stderr, "Warning: Cannot set audio parameters.\n");
return false;
}
if(DEBUG_SOLARIS)
fprintf(stderr, "Audio initialised. Setting up queues...\n");
if (pipe(fd)<0) {
closeAudio();
return false;
}
queueIn = fd[1];
queueOut = fd[0];
fcntl(queueOut, F_SETFL, fcntl(queueOut, F_GETFL, 0) | O_NDELAY);
// compute maxFd for use in select() call
maxFd = queueOut;
if (maxFd<audio_fd) maxFd = audio_fd;
maxFd++;
// Set default no thread
childProcID=0;
// ready to go
audio_ready = true;
if(DEBUG_SOLARIS)
fprintf(stderr, "Audio ready.\n");
return true;
}
void SolarisMedia::closeAudio()
{
close(audio_fd);
close(audioctl_fd);
}
bool SolarisMedia::startAudioThread(
void (*proc)(void*), void* data)
{
// if no audio thread then just call proc and return
if (!hasAudioThread()) {
proc(data);
return true;
}
// has an audio thread so fork and call proc
if (childProcID) return true;
if ((childProcID=fork()) > 0) {
close(queueOut);
close(audio_fd);
return true;
}
else if (childProcID < 0) {
return false;
}
close(queueIn);
proc(data);
exit(0);
}
void SolarisMedia::stopAudioThread()
{
if (childProcID != 0) kill(childProcID, SIGTERM);
childProcID=0;
}
bool SolarisMedia::hasAudioThread() const
{
// XXX -- adjust this if the system always uses or never uses a thread
#if defined(NO_AUDIO_THREAD)
return false;
#else
return true;
#endif
}
void SolarisMedia::writeSoundCommand(const void* cmd, int len)
{
if (!audio_ready) return;
write(queueIn, cmd, len);
}
bool SolarisMedia::readSoundCommand(void* cmd, int len)
{
return (read(queueOut, cmd, len)==len);
}
int SolarisMedia::getAudioOutputRate() const
{
return defaultAudioRate;
}
int SolarisMedia::getAudioBufferSize() const
{
return NumChunks * (audioBufferSize >> 1);
}
int SolarisMedia::getAudioBufferChunkSize() const
{
return audioBufferSize>>1;
}
bool SolarisMedia::isAudioTooEmpty() const
{
ioctl(audioctl_fd, AUDIO_GETINFO, &a_info);
return ((int)a_info.play.eof >= eof_written - audioLowWaterMark);
}
void SolarisMedia::writeAudioFrames(
const float* samples, int numFrames)
{
int numSamples = 2 * numFrames;
int limit;
while (numSamples > 0) {
if (numSamples>512) limit=512;
else limit=numSamples;
for (int j = 0; j < limit; j++) {
if (samples[j] < -32767.0) tmp_buf[j] = -32767;
else if (samples[j] > 32767.0) tmp_buf[j] = 32767;
else tmp_buf[j] = short(samples[j]);
}
// fill out the chunk (we never write a partial chunk)
if (limit < 512) {
for (int j = limit; j < 512; ++j)
tmp_buf[j] = 0;
limit = 512;
}
write(audio_fd, tmp_buf, 2*limit);
write(audio_fd, NULL, 0);
samples += limit;
numSamples -= limit;
eof_written++;
}
}
void SolarisMedia::audioSleep(
bool checkLowWater, double endTime)
{
fd_set commandSelectSet;
struct timeval tv;
// To do both these operations at once, we need to poll.
if (checkLowWater) {
// start looping
TimeKeeper start = TimeKeeper::getCurrent();
do {
// break if buffer has drained enough
if (isAudioTooEmpty()) break;
FD_ZERO(&commandSelectSet);
FD_SET((unsigned int)queueOut, &commandSelectSet);
tv.tv_sec=0;
tv.tv_usec=50000;
if (select(maxFd, &commandSelectSet, 0, 0, &tv)) break;
} while (endTime<0.0 || (TimeKeeper::getCurrent()-start)<endTime);
} else {
FD_ZERO(&commandSelectSet);
FD_SET((unsigned int)queueOut, &commandSelectSet);
tv.tv_sec=int(endTime);
tv.tv_usec=int(1.0e6*(endTime-floor(endTime)));
select(maxFd, &commandSelectSet, 0, 0, (endTime>=0.0)?&tv : 0);
}
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>Initialize SolarisMedia private variables in the same order that they are declared.<commit_after>/* bzflag
* Copyright (c) 1993-2013 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "SolarisMedia.h"
#include "TimeKeeper.h"
#define DEBUG_SOLARIS 0 //(1 = debug, 0 = don't!)
#define AUDIO_BUFFER_SIZE 5000
#if defined(HALF_RATE_AUDIO)
static const int defaultAudioRate = 11025;
#else
static const int defaultAudioRate = 22050;
#endif
static const int defaultChannels = 2;
static const int defaultEncoding = AUDIO_ENCODING_LINEAR;
static const int defaultPrecision = 16;
short tmp_buf[512];
//
// SolarisMedia
//
SolarisMedia::SolarisMedia() : BzfMedia(), audio_fd(-1), audio_ready(0),
queueIn(-1), queueOut(-1), written(0),
eof_written(0), eof_counter(0), childProcID(0)
{
// do nothing
}
SolarisMedia::~SolarisMedia()
{
// do nothing
}
double SolarisMedia::stopwatch(bool start)
{
struct timeval tv;
gettimeofday(&tv, 0);
if (start)
{
stopwatchTime = (double)tv.tv_sec + 1.0e-6 * (double)tv.tv_usec;
return 0.0;
}
return (double)tv.tv_sec + 1.0e-6 * (double)tv.tv_usec - stopwatchTime;
}
static const int NumChunks = 4;
bool SolarisMedia::openAudio()
{
int fd[2];
if(audio_ready)
return false;
audio_fd = open("/dev/audio", O_WRONLY | O_NDELAY);
if(audio_fd < 0)
return false;
if(DEBUG_SOLARIS)
fprintf(stderr, "Audio device '/dev/audio' opened\n");
audioctl_fd = open("/dev/audioctl", O_RDWR);
if(audioctl_fd < 0)
return false;
if(DEBUG_SOLARIS)
fprintf(stderr, "Opened audio control device '/dev/audioctl'\n");
// removing these avoids a kernel crash on solaris 8 - bzFrank
#ifdef FLUSHDRAIN
// Empty buffers
ioctl(audio_fd, AUDIO_DRAIN, 0);
ioctl(audio_fd, I_FLUSH, FLUSHRW);
ioctl(audioctl_fd, I_FLUSH, FLUSHRW);
#endif
if(ioctl(audio_fd, AUDIO_GETDEV, &a_dev) < 0)
{
if(DEBUG_SOLARIS)
fprintf(stderr, "Cannot get audio information.\n");
close(audio_fd);
close(audioctl_fd);
return false;
}
if(DEBUG_SOLARIS)
fprintf(stderr, "Sound device is a %s %s version %s\n", a_dev.config, a_dev.name, a_dev.version);
// Get audio parameters
if(ioctl(audioctl_fd, AUDIO_GETINFO, &a_info) < 0)
{
if(DEBUG_SOLARIS)
fprintf(stderr, "Cannot get audio information.\n");
close(audio_fd);
close(audioctl_fd);
return false;
}
AUDIO_INITINFO(&a_info);
a_info.play.sample_rate = defaultAudioRate;
a_info.play.channels = defaultChannels;
a_info.play.precision = defaultPrecision;
a_info.play.encoding = defaultEncoding;
a_info.play.buffer_size = NumChunks * AUDIO_BUFFER_SIZE;
audioBufferSize = AUDIO_BUFFER_SIZE;
audioLowWaterMark = 2;
if(ioctl(audio_fd, AUDIO_SETINFO, &a_info) == -1)
{
if(DEBUG_SOLARIS)
fprintf(stderr, "Warning: Cannot set audio parameters.\n");
return false;
}
if(DEBUG_SOLARIS)
fprintf(stderr, "Audio initialised. Setting up queues...\n");
if (pipe(fd)<0) {
closeAudio();
return false;
}
queueIn = fd[1];
queueOut = fd[0];
fcntl(queueOut, F_SETFL, fcntl(queueOut, F_GETFL, 0) | O_NDELAY);
// compute maxFd for use in select() call
maxFd = queueOut;
if (maxFd<audio_fd) maxFd = audio_fd;
maxFd++;
// Set default no thread
childProcID=0;
// ready to go
audio_ready = true;
if(DEBUG_SOLARIS)
fprintf(stderr, "Audio ready.\n");
return true;
}
void SolarisMedia::closeAudio()
{
close(audio_fd);
close(audioctl_fd);
}
bool SolarisMedia::startAudioThread(
void (*proc)(void*), void* data)
{
// if no audio thread then just call proc and return
if (!hasAudioThread()) {
proc(data);
return true;
}
// has an audio thread so fork and call proc
if (childProcID) return true;
if ((childProcID=fork()) > 0) {
close(queueOut);
close(audio_fd);
return true;
}
else if (childProcID < 0) {
return false;
}
close(queueIn);
proc(data);
exit(0);
}
void SolarisMedia::stopAudioThread()
{
if (childProcID != 0) kill(childProcID, SIGTERM);
childProcID=0;
}
bool SolarisMedia::hasAudioThread() const
{
// XXX -- adjust this if the system always uses or never uses a thread
#if defined(NO_AUDIO_THREAD)
return false;
#else
return true;
#endif
}
void SolarisMedia::writeSoundCommand(const void* cmd, int len)
{
if (!audio_ready) return;
write(queueIn, cmd, len);
}
bool SolarisMedia::readSoundCommand(void* cmd, int len)
{
return (read(queueOut, cmd, len)==len);
}
int SolarisMedia::getAudioOutputRate() const
{
return defaultAudioRate;
}
int SolarisMedia::getAudioBufferSize() const
{
return NumChunks * (audioBufferSize >> 1);
}
int SolarisMedia::getAudioBufferChunkSize() const
{
return audioBufferSize>>1;
}
bool SolarisMedia::isAudioTooEmpty() const
{
ioctl(audioctl_fd, AUDIO_GETINFO, &a_info);
return ((int)a_info.play.eof >= eof_written - audioLowWaterMark);
}
void SolarisMedia::writeAudioFrames(
const float* samples, int numFrames)
{
int numSamples = 2 * numFrames;
int limit;
while (numSamples > 0) {
if (numSamples>512) limit=512;
else limit=numSamples;
for (int j = 0; j < limit; j++) {
if (samples[j] < -32767.0) tmp_buf[j] = -32767;
else if (samples[j] > 32767.0) tmp_buf[j] = 32767;
else tmp_buf[j] = short(samples[j]);
}
// fill out the chunk (we never write a partial chunk)
if (limit < 512) {
for (int j = limit; j < 512; ++j)
tmp_buf[j] = 0;
limit = 512;
}
write(audio_fd, tmp_buf, 2*limit);
write(audio_fd, NULL, 0);
samples += limit;
numSamples -= limit;
eof_written++;
}
}
void SolarisMedia::audioSleep(
bool checkLowWater, double endTime)
{
fd_set commandSelectSet;
struct timeval tv;
// To do both these operations at once, we need to poll.
if (checkLowWater) {
// start looping
TimeKeeper start = TimeKeeper::getCurrent();
do {
// break if buffer has drained enough
if (isAudioTooEmpty()) break;
FD_ZERO(&commandSelectSet);
FD_SET((unsigned int)queueOut, &commandSelectSet);
tv.tv_sec=0;
tv.tv_usec=50000;
if (select(maxFd, &commandSelectSet, 0, 0, &tv)) break;
} while (endTime<0.0 || (TimeKeeper::getCurrent()-start)<endTime);
} else {
FD_ZERO(&commandSelectSet);
FD_SET((unsigned int)queueOut, &commandSelectSet);
tv.tv_sec=int(endTime);
tv.tv_usec=int(1.0e6*(endTime-floor(endTime)));
select(maxFd, &commandSelectSet, 0, 0, (endTime>=0.0)?&tv : 0);
}
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>#include "ex14_26_StrBlob.h"
#include <algorithm>
//==================================================================
//
// StrBlob - operators
//
//==================================================================
bool operator==(const StrBlob& lhs, const StrBlob& rhs)
{
return *lhs.data == *rhs.data;
}
bool operator!=(const StrBlob& lhs, const StrBlob& rhs)
{
return !(lhs == rhs);
}
bool operator<(const StrBlob& lhs, const StrBlob& rhs)
{
return std::lexicographical_compare(lhs.data->begin(), lhs.data->end(),
rhs.data->begin(), rhs.data->end());
}
bool operator>(const StrBlob& lhs, const StrBlob& rhs)
{
return rhs < lhs;
}
bool operator<=(const StrBlob& lhs, const StrBlob& rhs)
{
return !(rhs < lhs);
}
bool operator>=(const StrBlob& lhs, const StrBlob& rhs)
{
return !(lhs < rhs);
}
//================================================================
//
// StrBlobPtr - operators
//
//================================================================
bool operator==(const StrBlobPtr& lhs, const StrBlobPtr& rhs)
{
return lhs.curr == rhs.curr;
}
bool operator!=(const StrBlobPtr& lhs, const StrBlobPtr& rhs)
{
return !(lhs == rhs);
}
bool operator<(const StrBlobPtr& x, const StrBlobPtr& y)
{
return x.curr < y.curr;
}
bool operator>(const StrBlobPtr& x, const StrBlobPtr& y)
{
return x.curr > y.curr;
}
bool operator<=(const StrBlobPtr& x, const StrBlobPtr& y)
{
return x.curr <= y.curr;
}
bool operator>=(const StrBlobPtr& x, const StrBlobPtr& y)
{
return x.curr >= y.curr;
}
//================================================================
//
// ConstStrBlobPtr - operators
//
//================================================================
bool operator==(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs)
{
return lhs.curr == rhs.curr;
}
bool operator!=(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs)
{
return !(lhs == rhs);
}
bool operator<(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs)
{
return lhs.curr < rhs.curr;
}
bool operator>(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs)
{
return lhs.curr > rhs.curr;
}
bool operator<=(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs)
{
return lhs.curr <= rhs.curr;
}
bool operator>=(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs)
{
return lhs.curr >= rhs.curr;
}
//==================================================================
//
// copy assignment operator and move assignment operator.
//
//==================================================================
StrBlob& StrBlob::operator=(const StrBlob& lhs)
{
data = make_shared<vector<string>>(*lhs.data);
return *this;
}
StrBlob& StrBlob::operator=(StrBlob&& rhs) NOEXCEPT
{
if (this != &rhs) {
data = std::move(rhs.data);
rhs.data = nullptr;
}
return *this;
}
//==================================================================
//
// members
//
//==================================================================
StrBlobPtr StrBlob::begin()
{
return StrBlobPtr(*this);
}
StrBlobPtr StrBlob::end()
{
return StrBlobPtr(*this, data->size());
}
ConstStrBlobPtr StrBlob::cbegin() const
{
return ConstStrBlobPtr(*this);
}
ConstStrBlobPtr StrBlob::cend() const
{
return ConstStrBlobPtr(*this, data->size());
}
<commit_msg>Update ex14_26_StrBlob.cpp<commit_after>#include <algorithm>
#include "ex14_26_StrBlob.h"
//==================================================================
//
// StrBlob - operators
//
//==================================================================
bool operator==(const StrBlob& lhs, const StrBlob& rhs)
{
return *lhs.data == *rhs.data;
}
bool operator!=(const StrBlob& lhs, const StrBlob& rhs)
{
return !(lhs == rhs);
}
bool operator<(const StrBlob& lhs, const StrBlob& rhs)
{
return lexicographical_compare(lhs.data->begin(), lhs.data->end(), rhs.data->begin(), rhs.data->end());
}
bool operator>(const StrBlob& lhs, const StrBlob& rhs)
{
return rhs < lhs;
}
bool operator<=(const StrBlob& lhs, const StrBlob& rhs)
{
return !(rhs < lhs);
}
bool operator>=(const StrBlob& lhs, const StrBlob& rhs)
{
return !(lhs < rhs);
}
//================================================================
//
// StrBlobPtr - operators
//
//================================================================
bool operator==(const StrBlobPtr& lhs, const StrBlobPtr& rhs)
{
return lhs.curr == rhs.curr;
}
bool operator!=(const StrBlobPtr& lhs, const StrBlobPtr& rhs)
{
return !(lhs == rhs);
}
bool operator<(const StrBlobPtr& lhs, const StrBlobPtr& rhs)
{
return lhs.curr < rhs.curr;
}
bool operator>(const StrBlobPtr& lhs, const StrBlobPtr& rhs)
{
return lhs.curr > rhs.curr;
}
bool operator<=(const StrBlobPtr& lhs, const StrBlobPtr& rhs)
{
return lhs.curr <= rhs.curr;
}
bool operator>=(const StrBlobPtr& lhs, const StrBlobPtr& rhs)
{
return lhs.curr >= rhs.curr;
}
//================================================================
//
// ConstStrBlobPtr - operators
//
//================================================================
bool operator==(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs)
{
return lhs.curr == rhs.curr;
}
bool operator!=(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs)
{
return !(lhs == rhs);
}
bool operator<(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs)
{
return lhs.curr < rhs.curr;
}
bool operator>(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs)
{
return lhs.curr > rhs.curr;
}
bool operator<=(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs)
{
return lhs.curr <= rhs.curr;
}
bool operator>=(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs)
{
return lhs.curr >= rhs.curr;
}
//==================================================================
//
// copy assignment operator and move assignment operator
//
//==================================================================
StrBlob& StrBlob::operator=(const StrBlob& lhs)
{
data = make_shared<vector<string>>(*lhs.data);
return *this;
}
StrBlob& StrBlob::operator=(StrBlob&& rhs) noexcept
{
if (this != &rhs)
{
data = move(rhs.data);
rhs.data = nullptr;
}
return *this;
}
//==================================================================
//
// members
//
//==================================================================
StrBlobPtr StrBlob::begin()
{
return StrBlobPtr(*this);
}
StrBlobPtr StrBlob::end()
{
return StrBlobPtr(*this, data->size());
}
ConstStrBlobPtr StrBlob::cbegin() const
{
return ConstStrBlobPtr(*this);
}
ConstStrBlobPtr StrBlob::cend() const
{
return ConstStrBlobPtr(*this, data->size());
}
<|endoftext|> |
<commit_before>#include "contracttablemodel.h"
#include "guiutil.h"
#include "walletmodel.h"
#include "wallet/wallet.h"
#include <boost/foreach.hpp>
#include <QFont>
#include <QDebug>
struct ContractTableEntry
{
QString label;
QString address;
QString abi;
ContractTableEntry() {}
ContractTableEntry(const QString &_label, const QString &_address, const QString &_abi):
label(_label), address(_address), abi(_abi) {}
};
struct ContractTableEntryLessThan
{
bool operator()(const ContractTableEntry &a, const ContractTableEntry &b) const
{
return a.address < b.address;
}
bool operator()(const ContractTableEntry &a, const QString &b) const
{
return a.address < b;
}
bool operator()(const QString &a, const ContractTableEntry &b) const
{
return a < b.address;
}
};
// Private implementation
class ContractTablePriv
{
public:
CWallet *wallet;
QList<ContractTableEntry> cachedContractTable;
ContractTableModel *parent;
ContractTablePriv(CWallet *_wallet, ContractTableModel *_parent):
wallet(_wallet), parent(_parent) {}
void refreshContractTable()
{
cachedContractTable.clear();
{
LOCK(wallet->cs_wallet);
BOOST_FOREACH(const PAIRTYPE(std::string, CContractBookData)& item, wallet->mapContractBook)
{
const std::string& address = item.first;
const std::string& strName = item.second.name;
const std::string& strAbi = item.second.abi;
cachedContractTable.append(ContractTableEntry(
QString::fromStdString(strName),
QString::fromStdString(address),
QString::fromStdString(strAbi)));
}
}
// qLowerBound() and qUpperBound() require our cachedContractTable list to be sorted in asc order
qSort(cachedContractTable.begin(), cachedContractTable.end(), ContractTableEntryLessThan());
}
void updateEntry(const QString &address, const QString &label, const QString &abi, int status)
{
// Find address / label in model
QList<ContractTableEntry>::iterator lower = qLowerBound(
cachedContractTable.begin(), cachedContractTable.end(), address, ContractTableEntryLessThan());
QList<ContractTableEntry>::iterator upper = qUpperBound(
cachedContractTable.begin(), cachedContractTable.end(), address, ContractTableEntryLessThan());
int lowerIndex = (lower - cachedContractTable.begin());
int upperIndex = (upper - cachedContractTable.begin());
bool inModel = (lower != upper);
switch(status)
{
case CT_NEW:
if(inModel)
{
qWarning() << "ContractTablePriv::updateEntry: Warning: Got CT_NEW, but entry is already in model";
break;
}
parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex);
cachedContractTable.insert(lowerIndex, ContractTableEntry(label, address, abi));
parent->endInsertRows();
break;
case CT_UPDATED:
if(!inModel)
{
qWarning() << "ContractTablePriv::updateEntry: Warning: Got CT_UPDATED, but entry is not in model";
break;
}
lower->label = label;
lower->abi = abi;
parent->emitDataChanged(lowerIndex);
break;
case CT_DELETED:
if(!inModel)
{
qWarning() << "ContractTablePriv::updateEntry: Warning: Got CT_DELETED, but entry is not in model";
break;
}
parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1);
cachedContractTable.erase(lower, upper);
parent->endRemoveRows();
break;
}
}
int size()
{
return cachedContractTable.size();
}
ContractTableEntry *index(int idx)
{
if(idx >= 0 && idx < cachedContractTable.size())
{
return &cachedContractTable[idx];
}
else
{
return 0;
}
}
};
ContractTableModel::ContractTableModel(CWallet *_wallet, WalletModel *parent) :
QAbstractTableModel(parent),walletModel(parent),wallet(_wallet),priv(0)
{
columns << tr("Label") << tr("Contract Address") << tr("Interface (ABI)");
priv = new ContractTablePriv(wallet, this);
priv->refreshContractTable();
}
ContractTableModel::~ContractTableModel()
{
delete priv;
}
int ContractTableModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return priv->size();
}
int ContractTableModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return columns.length();
}
QVariant ContractTableModel::data(const QModelIndex &index, int role) const
{
if(!index.isValid())
return QVariant();
ContractTableEntry *rec = static_cast<ContractTableEntry*>(index.internalPointer());
if(role == Qt::DisplayRole || role == Qt::EditRole)
{
switch(index.column())
{
case Label:
if(rec->label.isEmpty() && role == Qt::DisplayRole)
{
return tr("(no label)");
}
else
{
return rec->label;
}
case Address:
return rec->address;
case ABI:
return rec->abi;
}
}
else if (role == Qt::FontRole)
{
QFont font;
if(index.column() == Address)
{
font = GUIUtil::fixedPitchFont();
}
return font;
}
return QVariant();
}
bool ContractTableModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if(!index.isValid())
return false;
ContractTableEntry *rec = static_cast<ContractTableEntry*>(index.internalPointer());
if(role == Qt::EditRole)
{
LOCK(wallet->cs_wallet); /* For SetContractBook / DelContractBook */
std::string curAddress = rec->address.toStdString();
std::string curLabel = rec->label.toStdString();
std::string curAbi = rec->abi.toStdString();
if(index.column() == Label)
{
// Do nothing, if old label == new label
if(rec->label == value.toString())
{
updateEditStatus(NO_CHANGES);
return false;
}
wallet->SetContractBook(curAddress, value.toString().toStdString(), curAbi);
} else if(index.column() == Address) {
std::string newAddress = value.toString().toStdString();
// Do nothing, if old address == new address
if(newAddress == curAddress)
{
updateEditStatus(NO_CHANGES);
return false;
}
// Check for duplicate addresses to prevent accidental deletion of addresses, if you try
// to paste an existing address over another address (with a different label)
else if(wallet->mapContractBook.count(newAddress))
{
updateEditStatus(DUPLICATE_ADDRESS);
return false;
}
else
{
// Remove old entry
wallet->DelContractBook(curAddress);
// Add new entry with new address
wallet->SetContractBook(newAddress, curLabel, curAbi);
}
}
else if(index.column() == ABI) {
// Do nothing, if old abi == new abi
if(rec->abi == value.toString())
{
updateEditStatus(NO_CHANGES);
return false;
}
wallet->SetContractBook(curAddress, curLabel, value.toString().toStdString());
}
return true;
}
return false;
}
QVariant ContractTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if(orientation == Qt::Horizontal)
{
if(role == Qt::DisplayRole && section < columns.size())
{
return columns[section];
}
}
return QVariant();
}
QModelIndex ContractTableModel::index(int row, int column, const QModelIndex &parent) const
{
Q_UNUSED(parent);
ContractTableEntry *data = priv->index(row);
if(data)
{
return createIndex(row, column, priv->index(row));
}
else
{
return QModelIndex();
}
}
void ContractTableModel::updateEntry(const QString &address,
const QString &label, const QString &abi, int status)
{
// Update contract book model from Qtum core
priv->updateEntry(address, label, abi, status);
}
QString ContractTableModel::addRow(const QString &label, const QString &address, const QString &abi)
{
std::string strLabel = label.toStdString();
std::string strAddress = address.toStdString();
std::string strAbi = abi.toStdString();
editStatus = OK;
// Add entry
{
LOCK(wallet->cs_wallet);
wallet->SetContractBook(strAddress, strLabel, strAbi);
}
return QString::fromStdString(strAddress);
}
bool ContractTableModel::removeRows(int row, int count, const QModelIndex &parent)
{
Q_UNUSED(parent);
ContractTableEntry *rec = priv->index(row);
if(count != 1 || !rec )
{
// Can only remove one row at a time, and cannot remove rows not in model.
return false;
}
{
LOCK(wallet->cs_wallet);
wallet->DelContractBook(rec->address.toStdString());
}
return true;
}
/* Label for address in contract book, if not found return empty string.
*/
QString ContractTableModel::labelForAddress(const QString &address) const
{
{
LOCK(wallet->cs_wallet);
std::string address_parsed(address.toStdString());
std::map<std::string, CContractBookData>::iterator mi = wallet->mapContractBook.find(address_parsed);
if (mi != wallet->mapContractBook.end())
{
return QString::fromStdString(mi->second.name);
}
}
return QString();
}
/* ABI for address in contract book, if not found return empty string.
*/
QString ContractTableModel::abiForAddress(const QString &address) const
{
{
LOCK(wallet->cs_wallet);
std::string address_parsed(address.toStdString());
std::map<std::string, CContractBookData>::iterator mi = wallet->mapContractBook.find(address_parsed);
if (mi != wallet->mapContractBook.end())
{
return QString::fromStdString(mi->second.abi);
}
}
return QString();
}
int ContractTableModel::lookupAddress(const QString &address) const
{
QModelIndexList lst = match(index(0, Address, QModelIndex()),
Qt::EditRole, address, 1, Qt::MatchExactly);
if(lst.isEmpty())
{
return -1;
}
else
{
return lst.at(0).row();
}
}
void ContractTableModel::resetEditStatus()
{
editStatus = OK;
}
void ContractTableModel::emitDataChanged(int idx)
{
Q_EMIT dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length()-1, QModelIndex()));
}
void ContractTableModel::updateEditStatus(ContractTableModel::EditStatus status)
{
if(status > editStatus)
{
editStatus = status;
}
}
<commit_msg>Add duplicate contract address check in new row<commit_after>#include "contracttablemodel.h"
#include "guiutil.h"
#include "walletmodel.h"
#include "wallet/wallet.h"
#include <boost/foreach.hpp>
#include <QFont>
#include <QDebug>
struct ContractTableEntry
{
QString label;
QString address;
QString abi;
ContractTableEntry() {}
ContractTableEntry(const QString &_label, const QString &_address, const QString &_abi):
label(_label), address(_address), abi(_abi) {}
};
struct ContractTableEntryLessThan
{
bool operator()(const ContractTableEntry &a, const ContractTableEntry &b) const
{
return a.address < b.address;
}
bool operator()(const ContractTableEntry &a, const QString &b) const
{
return a.address < b;
}
bool operator()(const QString &a, const ContractTableEntry &b) const
{
return a < b.address;
}
};
// Private implementation
class ContractTablePriv
{
public:
CWallet *wallet;
QList<ContractTableEntry> cachedContractTable;
ContractTableModel *parent;
ContractTablePriv(CWallet *_wallet, ContractTableModel *_parent):
wallet(_wallet), parent(_parent) {}
void refreshContractTable()
{
cachedContractTable.clear();
{
LOCK(wallet->cs_wallet);
BOOST_FOREACH(const PAIRTYPE(std::string, CContractBookData)& item, wallet->mapContractBook)
{
const std::string& address = item.first;
const std::string& strName = item.second.name;
const std::string& strAbi = item.second.abi;
cachedContractTable.append(ContractTableEntry(
QString::fromStdString(strName),
QString::fromStdString(address),
QString::fromStdString(strAbi)));
}
}
// qLowerBound() and qUpperBound() require our cachedContractTable list to be sorted in asc order
qSort(cachedContractTable.begin(), cachedContractTable.end(), ContractTableEntryLessThan());
}
void updateEntry(const QString &address, const QString &label, const QString &abi, int status)
{
// Find address / label in model
QList<ContractTableEntry>::iterator lower = qLowerBound(
cachedContractTable.begin(), cachedContractTable.end(), address, ContractTableEntryLessThan());
QList<ContractTableEntry>::iterator upper = qUpperBound(
cachedContractTable.begin(), cachedContractTable.end(), address, ContractTableEntryLessThan());
int lowerIndex = (lower - cachedContractTable.begin());
int upperIndex = (upper - cachedContractTable.begin());
bool inModel = (lower != upper);
switch(status)
{
case CT_NEW:
if(inModel)
{
qWarning() << "ContractTablePriv::updateEntry: Warning: Got CT_NEW, but entry is already in model";
break;
}
parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex);
cachedContractTable.insert(lowerIndex, ContractTableEntry(label, address, abi));
parent->endInsertRows();
break;
case CT_UPDATED:
if(!inModel)
{
qWarning() << "ContractTablePriv::updateEntry: Warning: Got CT_UPDATED, but entry is not in model";
break;
}
lower->label = label;
lower->abi = abi;
parent->emitDataChanged(lowerIndex);
break;
case CT_DELETED:
if(!inModel)
{
qWarning() << "ContractTablePriv::updateEntry: Warning: Got CT_DELETED, but entry is not in model";
break;
}
parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1);
cachedContractTable.erase(lower, upper);
parent->endRemoveRows();
break;
}
}
int size()
{
return cachedContractTable.size();
}
ContractTableEntry *index(int idx)
{
if(idx >= 0 && idx < cachedContractTable.size())
{
return &cachedContractTable[idx];
}
else
{
return 0;
}
}
};
ContractTableModel::ContractTableModel(CWallet *_wallet, WalletModel *parent) :
QAbstractTableModel(parent),walletModel(parent),wallet(_wallet),priv(0)
{
columns << tr("Label") << tr("Contract Address") << tr("Interface (ABI)");
priv = new ContractTablePriv(wallet, this);
priv->refreshContractTable();
}
ContractTableModel::~ContractTableModel()
{
delete priv;
}
int ContractTableModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return priv->size();
}
int ContractTableModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return columns.length();
}
QVariant ContractTableModel::data(const QModelIndex &index, int role) const
{
if(!index.isValid())
return QVariant();
ContractTableEntry *rec = static_cast<ContractTableEntry*>(index.internalPointer());
if(role == Qt::DisplayRole || role == Qt::EditRole)
{
switch(index.column())
{
case Label:
if(rec->label.isEmpty() && role == Qt::DisplayRole)
{
return tr("(no label)");
}
else
{
return rec->label;
}
case Address:
return rec->address;
case ABI:
return rec->abi;
}
}
else if (role == Qt::FontRole)
{
QFont font;
if(index.column() == Address)
{
font = GUIUtil::fixedPitchFont();
}
return font;
}
return QVariant();
}
bool ContractTableModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if(!index.isValid())
return false;
ContractTableEntry *rec = static_cast<ContractTableEntry*>(index.internalPointer());
if(role == Qt::EditRole)
{
LOCK(wallet->cs_wallet); /* For SetContractBook / DelContractBook */
std::string curAddress = rec->address.toStdString();
std::string curLabel = rec->label.toStdString();
std::string curAbi = rec->abi.toStdString();
if(index.column() == Label)
{
// Do nothing, if old label == new label
if(rec->label == value.toString())
{
updateEditStatus(NO_CHANGES);
return false;
}
wallet->SetContractBook(curAddress, value.toString().toStdString(), curAbi);
} else if(index.column() == Address) {
std::string newAddress = value.toString().toStdString();
// Do nothing, if old address == new address
if(newAddress == curAddress)
{
updateEditStatus(NO_CHANGES);
return false;
}
// Check for duplicate addresses to prevent accidental deletion of addresses, if you try
// to paste an existing address over another address (with a different label)
else if(wallet->mapContractBook.count(newAddress))
{
updateEditStatus(DUPLICATE_ADDRESS);
return false;
}
else
{
// Remove old entry
wallet->DelContractBook(curAddress);
// Add new entry with new address
wallet->SetContractBook(newAddress, curLabel, curAbi);
}
}
else if(index.column() == ABI) {
// Do nothing, if old abi == new abi
if(rec->abi == value.toString())
{
updateEditStatus(NO_CHANGES);
return false;
}
wallet->SetContractBook(curAddress, curLabel, value.toString().toStdString());
}
return true;
}
return false;
}
QVariant ContractTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if(orientation == Qt::Horizontal)
{
if(role == Qt::DisplayRole && section < columns.size())
{
return columns[section];
}
}
return QVariant();
}
QModelIndex ContractTableModel::index(int row, int column, const QModelIndex &parent) const
{
Q_UNUSED(parent);
ContractTableEntry *data = priv->index(row);
if(data)
{
return createIndex(row, column, priv->index(row));
}
else
{
return QModelIndex();
}
}
void ContractTableModel::updateEntry(const QString &address,
const QString &label, const QString &abi, int status)
{
// Update contract book model from Qtum core
priv->updateEntry(address, label, abi, status);
}
QString ContractTableModel::addRow(const QString &label, const QString &address, const QString &abi)
{
// Check for duplicate entry
if(lookupAddress(address) != -1)
{
editStatus = DUPLICATE_ADDRESS;
return "";
}
// Add new entry
std::string strLabel = label.toStdString();
std::string strAddress = address.toStdString();
std::string strAbi = abi.toStdString();
editStatus = OK;
{
LOCK(wallet->cs_wallet);
wallet->SetContractBook(strAddress, strLabel, strAbi);
}
return address;
}
bool ContractTableModel::removeRows(int row, int count, const QModelIndex &parent)
{
Q_UNUSED(parent);
ContractTableEntry *rec = priv->index(row);
if(count != 1 || !rec )
{
// Can only remove one row at a time, and cannot remove rows not in model.
return false;
}
{
LOCK(wallet->cs_wallet);
wallet->DelContractBook(rec->address.toStdString());
}
return true;
}
/* Label for address in contract book, if not found return empty string.
*/
QString ContractTableModel::labelForAddress(const QString &address) const
{
{
LOCK(wallet->cs_wallet);
std::string address_parsed(address.toStdString());
std::map<std::string, CContractBookData>::iterator mi = wallet->mapContractBook.find(address_parsed);
if (mi != wallet->mapContractBook.end())
{
return QString::fromStdString(mi->second.name);
}
}
return QString();
}
/* ABI for address in contract book, if not found return empty string.
*/
QString ContractTableModel::abiForAddress(const QString &address) const
{
{
LOCK(wallet->cs_wallet);
std::string address_parsed(address.toStdString());
std::map<std::string, CContractBookData>::iterator mi = wallet->mapContractBook.find(address_parsed);
if (mi != wallet->mapContractBook.end())
{
return QString::fromStdString(mi->second.abi);
}
}
return QString();
}
int ContractTableModel::lookupAddress(const QString &address) const
{
QModelIndexList lst = match(index(0, Address, QModelIndex()),
Qt::EditRole, address, 1, Qt::MatchExactly);
if(lst.isEmpty())
{
return -1;
}
else
{
return lst.at(0).row();
}
}
void ContractTableModel::resetEditStatus()
{
editStatus = OK;
}
void ContractTableModel::emitDataChanged(int idx)
{
Q_EMIT dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length()-1, QModelIndex()));
}
void ContractTableModel::updateEditStatus(ContractTableModel::EditStatus status)
{
if(status > editStatus)
{
editStatus = status;
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011-2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
//
// Wraps dumb protocol buffer paymentRequest
// with some extra methods
//
#include "paymentrequestplus.h"
#include "util.h"
#include <stdexcept>
#include <openssl/x509_vfy.h>
#include <QDateTime>
#include <QDebug>
#include <QSslCertificate>
using namespace std;
class SSLVerifyError : public std::runtime_error
{
public:
SSLVerifyError(std::string err) : std::runtime_error(err) { }
};
bool PaymentRequestPlus::parse(const QByteArray& data)
{
bool parseOK = paymentRequest.ParseFromArray(data.data(), data.size());
if (!parseOK) {
qWarning() << "PaymentRequestPlus::parse: Error parsing payment request";
return false;
}
if (paymentRequest.payment_details_version() > 1) {
qWarning() << "PaymentRequestPlus::parse: Received up-version payment details, version=" << paymentRequest.payment_details_version();
return false;
}
parseOK = details.ParseFromString(paymentRequest.serialized_payment_details());
if (!parseOK)
{
qWarning() << "PaymentRequestPlus::parse: Error parsing payment details";
paymentRequest.Clear();
return false;
}
return true;
}
bool PaymentRequestPlus::SerializeToString(string* output) const
{
return paymentRequest.SerializeToString(output);
}
bool PaymentRequestPlus::IsInitialized() const
{
return paymentRequest.IsInitialized();
}
bool PaymentRequestPlus::getMerchant(X509_STORE* certStore, QString& merchant) const
{
merchant.clear();
if (!IsInitialized())
return false;
// One day we'll support more PKI types, but just
// x509 for now:
const EVP_MD* digestAlgorithm = NULL;
if (paymentRequest.pki_type() == "x509+sha256") {
digestAlgorithm = EVP_sha256();
}
else if (paymentRequest.pki_type() == "x509+sha1") {
digestAlgorithm = EVP_sha1();
}
else if (paymentRequest.pki_type() == "none") {
qWarning() << "PaymentRequestPlus::getMerchant: Payment request: pki_type == none";
return false;
}
else {
qWarning() << "PaymentRequestPlus::getMerchant: Payment request: unknown pki_type " << QString::fromStdString(paymentRequest.pki_type());
return false;
}
payments::X509Certificates certChain;
if (!certChain.ParseFromString(paymentRequest.pki_data())) {
qWarning() << "PaymentRequestPlus::getMerchant: Payment request: error parsing pki_data";
return false;
}
std::vector<X509*> certs;
const QDateTime currentTime = QDateTime::currentDateTime();
for (int i = 0; i < certChain.certificate_size(); i++) {
QByteArray certData(certChain.certificate(i).data(), certChain.certificate(i).size());
QSslCertificate qCert(certData, QSsl::Der);
if (currentTime < qCert.effectiveDate() || currentTime > qCert.expiryDate()) {
qWarning() << "PaymentRequestPlus::getMerchant: Payment request: certificate expired or not yet active: " << qCert;
return false;
}
#if QT_VERSION >= 0x050000
if (qCert.isBlacklisted()) {
qWarning() << "PaymentRequestPlus::getMerchant: Payment request: certificate blacklisted: " << qCert;
return false;
}
#endif
const unsigned char *data = (const unsigned char *)certChain.certificate(i).data();
X509 *cert = d2i_X509(NULL, &data, certChain.certificate(i).size());
if (cert)
certs.push_back(cert);
}
if (certs.empty()) {
qWarning() << "PaymentRequestPlus::getMerchant: Payment request: empty certificate chain";
return false;
}
// The first cert is the signing cert, the rest are untrusted certs that chain
// to a valid root authority. OpenSSL needs them separately.
STACK_OF(X509) *chain = sk_X509_new_null();
for (int i = certs.size()-1; i > 0; i--) {
sk_X509_push(chain, certs[i]);
}
X509 *signing_cert = certs[0];
// Now create a "store context", which is a single use object for checking,
// load the signing cert into it and verify.
X509_STORE_CTX *store_ctx = X509_STORE_CTX_new();
if (!store_ctx) {
qWarning() << "PaymentRequestPlus::getMerchant: Payment request: error creating X509_STORE_CTX";
return false;
}
char *website = NULL;
bool fResult = true;
try
{
if (!X509_STORE_CTX_init(store_ctx, certStore, signing_cert, chain))
{
int error = X509_STORE_CTX_get_error(store_ctx);
throw SSLVerifyError(X509_verify_cert_error_string(error));
}
// Now do the verification!
int result = X509_verify_cert(store_ctx);
if (result != 1) {
int error = X509_STORE_CTX_get_error(store_ctx);
// For testing payment requests, we allow self signed root certs!
// This option is just shown in the UI options, if -help-debug is enabled.
if (!(error == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT && GetBoolArg("-allowselfsignedrootcertificates", false))) {
throw SSLVerifyError(X509_verify_cert_error_string(error));
} else {
qDebug() << "PaymentRequestPlus::getMerchant: Allowing self signed root certificate, because -allowselfsignedrootcertificates is true.";
}
}
X509_NAME *certname = X509_get_subject_name(signing_cert);
// Valid cert; check signature:
payments::PaymentRequest rcopy(paymentRequest); // Copy
rcopy.set_signature(std::string(""));
std::string data_to_verify; // Everything but the signature
rcopy.SerializeToString(&data_to_verify);
EVP_MD_CTX ctx;
EVP_PKEY *pubkey = X509_get_pubkey(signing_cert);
EVP_MD_CTX_init(&ctx);
if (!EVP_VerifyInit_ex(&ctx, digestAlgorithm, NULL) ||
!EVP_VerifyUpdate(&ctx, data_to_verify.data(), data_to_verify.size()) ||
!EVP_VerifyFinal(&ctx, (const unsigned char*)paymentRequest.signature().data(), paymentRequest.signature().size(), pubkey)) {
throw SSLVerifyError("Bad signature, invalid PaymentRequest.");
}
// OpenSSL API for getting human printable strings from certs is baroque.
int textlen = X509_NAME_get_text_by_NID(certname, NID_commonName, NULL, 0);
website = new char[textlen + 1];
if (X509_NAME_get_text_by_NID(certname, NID_commonName, website, textlen + 1) == textlen && textlen > 0) {
merchant = website;
}
else {
throw SSLVerifyError("Bad certificate, missing common name.");
}
// TODO: detect EV certificates and set merchant = business name instead of unfriendly NID_commonName ?
}
catch (const SSLVerifyError& err) {
fResult = false;
qWarning() << "PaymentRequestPlus::getMerchant: SSL error: " << err.what();
}
if (website)
delete[] website;
X509_STORE_CTX_free(store_ctx);
for (unsigned int i = 0; i < certs.size(); i++)
X509_free(certs[i]);
return fResult;
}
QList<std::pair<CScript,CAmount> > PaymentRequestPlus::getPayTo() const
{
QList<std::pair<CScript,CAmount> > result;
for (int i = 0; i < details.outputs_size(); i++)
{
const unsigned char* scriptStr = (const unsigned char*)details.outputs(i).script().data();
CScript s(scriptStr, scriptStr+details.outputs(i).script().size());
result.append(make_pair(s, details.outputs(i).amount()));
}
return result;
}
<commit_msg>[Qt] take care of a missing typecast in PaymentRequestPlus::getMerchant()<commit_after>// Copyright (c) 2011-2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
//
// Wraps dumb protocol buffer paymentRequest
// with some extra methods
//
#include "paymentrequestplus.h"
#include "util.h"
#include <stdexcept>
#include <openssl/x509_vfy.h>
#include <QDateTime>
#include <QDebug>
#include <QSslCertificate>
using namespace std;
class SSLVerifyError : public std::runtime_error
{
public:
SSLVerifyError(std::string err) : std::runtime_error(err) { }
};
bool PaymentRequestPlus::parse(const QByteArray& data)
{
bool parseOK = paymentRequest.ParseFromArray(data.data(), data.size());
if (!parseOK) {
qWarning() << "PaymentRequestPlus::parse: Error parsing payment request";
return false;
}
if (paymentRequest.payment_details_version() > 1) {
qWarning() << "PaymentRequestPlus::parse: Received up-version payment details, version=" << paymentRequest.payment_details_version();
return false;
}
parseOK = details.ParseFromString(paymentRequest.serialized_payment_details());
if (!parseOK)
{
qWarning() << "PaymentRequestPlus::parse: Error parsing payment details";
paymentRequest.Clear();
return false;
}
return true;
}
bool PaymentRequestPlus::SerializeToString(string* output) const
{
return paymentRequest.SerializeToString(output);
}
bool PaymentRequestPlus::IsInitialized() const
{
return paymentRequest.IsInitialized();
}
bool PaymentRequestPlus::getMerchant(X509_STORE* certStore, QString& merchant) const
{
merchant.clear();
if (!IsInitialized())
return false;
// One day we'll support more PKI types, but just
// x509 for now:
const EVP_MD* digestAlgorithm = NULL;
if (paymentRequest.pki_type() == "x509+sha256") {
digestAlgorithm = EVP_sha256();
}
else if (paymentRequest.pki_type() == "x509+sha1") {
digestAlgorithm = EVP_sha1();
}
else if (paymentRequest.pki_type() == "none") {
qWarning() << "PaymentRequestPlus::getMerchant: Payment request: pki_type == none";
return false;
}
else {
qWarning() << "PaymentRequestPlus::getMerchant: Payment request: unknown pki_type " << QString::fromStdString(paymentRequest.pki_type());
return false;
}
payments::X509Certificates certChain;
if (!certChain.ParseFromString(paymentRequest.pki_data())) {
qWarning() << "PaymentRequestPlus::getMerchant: Payment request: error parsing pki_data";
return false;
}
std::vector<X509*> certs;
const QDateTime currentTime = QDateTime::currentDateTime();
for (int i = 0; i < certChain.certificate_size(); i++) {
QByteArray certData(certChain.certificate(i).data(), certChain.certificate(i).size());
QSslCertificate qCert(certData, QSsl::Der);
if (currentTime < qCert.effectiveDate() || currentTime > qCert.expiryDate()) {
qWarning() << "PaymentRequestPlus::getMerchant: Payment request: certificate expired or not yet active: " << qCert;
return false;
}
#if QT_VERSION >= 0x050000
if (qCert.isBlacklisted()) {
qWarning() << "PaymentRequestPlus::getMerchant: Payment request: certificate blacklisted: " << qCert;
return false;
}
#endif
const unsigned char *data = (const unsigned char *)certChain.certificate(i).data();
X509 *cert = d2i_X509(NULL, &data, certChain.certificate(i).size());
if (cert)
certs.push_back(cert);
}
if (certs.empty()) {
qWarning() << "PaymentRequestPlus::getMerchant: Payment request: empty certificate chain";
return false;
}
// The first cert is the signing cert, the rest are untrusted certs that chain
// to a valid root authority. OpenSSL needs them separately.
STACK_OF(X509) *chain = sk_X509_new_null();
for (int i = certs.size() - 1; i > 0; i--) {
sk_X509_push(chain, certs[i]);
}
X509 *signing_cert = certs[0];
// Now create a "store context", which is a single use object for checking,
// load the signing cert into it and verify.
X509_STORE_CTX *store_ctx = X509_STORE_CTX_new();
if (!store_ctx) {
qWarning() << "PaymentRequestPlus::getMerchant: Payment request: error creating X509_STORE_CTX";
return false;
}
char *website = NULL;
bool fResult = true;
try
{
if (!X509_STORE_CTX_init(store_ctx, certStore, signing_cert, chain))
{
int error = X509_STORE_CTX_get_error(store_ctx);
throw SSLVerifyError(X509_verify_cert_error_string(error));
}
// Now do the verification!
int result = X509_verify_cert(store_ctx);
if (result != 1) {
int error = X509_STORE_CTX_get_error(store_ctx);
// For testing payment requests, we allow self signed root certs!
// This option is just shown in the UI options, if -help-debug is enabled.
if (!(error == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT && GetBoolArg("-allowselfsignedrootcertificates", false))) {
throw SSLVerifyError(X509_verify_cert_error_string(error));
} else {
qDebug() << "PaymentRequestPlus::getMerchant: Allowing self signed root certificate, because -allowselfsignedrootcertificates is true.";
}
}
X509_NAME *certname = X509_get_subject_name(signing_cert);
// Valid cert; check signature:
payments::PaymentRequest rcopy(paymentRequest); // Copy
rcopy.set_signature(std::string(""));
std::string data_to_verify; // Everything but the signature
rcopy.SerializeToString(&data_to_verify);
EVP_MD_CTX ctx;
EVP_PKEY *pubkey = X509_get_pubkey(signing_cert);
EVP_MD_CTX_init(&ctx);
if (!EVP_VerifyInit_ex(&ctx, digestAlgorithm, NULL) ||
!EVP_VerifyUpdate(&ctx, data_to_verify.data(), data_to_verify.size()) ||
!EVP_VerifyFinal(&ctx, (const unsigned char*)paymentRequest.signature().data(), (unsigned int)paymentRequest.signature().size(), pubkey)) {
throw SSLVerifyError("Bad signature, invalid payment request.");
}
// OpenSSL API for getting human printable strings from certs is baroque.
int textlen = X509_NAME_get_text_by_NID(certname, NID_commonName, NULL, 0);
website = new char[textlen + 1];
if (X509_NAME_get_text_by_NID(certname, NID_commonName, website, textlen + 1) == textlen && textlen > 0) {
merchant = website;
}
else {
throw SSLVerifyError("Bad certificate, missing common name.");
}
// TODO: detect EV certificates and set merchant = business name instead of unfriendly NID_commonName ?
}
catch (const SSLVerifyError& err) {
fResult = false;
qWarning() << "PaymentRequestPlus::getMerchant: SSL error: " << err.what();
}
if (website)
delete[] website;
X509_STORE_CTX_free(store_ctx);
for (unsigned int i = 0; i < certs.size(); i++)
X509_free(certs[i]);
return fResult;
}
QList<std::pair<CScript,CAmount> > PaymentRequestPlus::getPayTo() const
{
QList<std::pair<CScript,CAmount> > result;
for (int i = 0; i < details.outputs_size(); i++)
{
const unsigned char* scriptStr = (const unsigned char*)details.outputs(i).script().data();
CScript s(scriptStr, scriptStr+details.outputs(i).script().size());
result.append(make_pair(s, details.outputs(i).amount()));
}
return result;
}
<|endoftext|> |
<commit_before>/*
SECC Native(c++) Frontend
dependencies : SimpleHttpRequest, nlohmann/json, zlib, md5
ubuntu :
$ sudo apt-get install libssl-dev zlib1g-dev
$ make clean && make
run :
$ SECC_ADDRESS="172.17.42.1" [SECC_PORT="10509"] \
/path/to/secc-native/bin/gcc ...
*/
#include <iostream>
#include "json.hpp"
#include "SimpleHttpRequest.hpp"
#include <sys/utsname.h>
#include "untar.h"
#include "utils.h"
#include "zip.h"
#include "UriCodec.h"
using namespace std;
using namespace request;
using namespace nlohmann;
class _secc_exception : public std::exception
{
virtual const char* what() const throw()
{
return "secc exception";
}
} secc_exception;
int main(int argc, char* argv[])
{
//debug
if (getenv("SECC_CMDLINE")) {
string cmd = "";
for(int i = 0; i < argc; i++)
cmd += "'" + string(argv[i]) + "' ";
LOGI(cmd);
}
// init
auto option = json::object();
auto job = json::object();
auto sourceHash = make_shared<string>();
stringstream infileBuffer;
auto outfileBuffer = make_shared<stringstream>();
auto tempBuffer = make_shared<stringstream>();
string secc_scheduler_address = (getenv("SECC_ADDRESS")) ? getenv("SECC_ADDRESS") : "127.0.0.1";
string secc_scheduler_port = (getenv("SECC_PORT")) ? getenv("SECC_PORT") : "10509";
string secc_scheduler_host = "http://" + secc_scheduler_address + ":" + secc_scheduler_port; //FIXME : from settings
string secc_driver = _basename(argv[0], false); // FIXME : exception
string secc_driver_path = "/usr/bin/" + secc_driver; // FIXME : from PATH
string secc_cwd = getcwd(nullptr, 0);
string secc_mode = "1"; //FIXME : mode 2
bool secc_cache = (getenv("SECC_CACHE") && strcmp(getenv("SECC_CACHE"),"1") == 0) ? true : false;
bool secc_cross = (getenv("SECC_CROSS") && strcmp(getenv("SECC_CROSS"),"1") == 0) ? true : false;
bool _argv_c_exists = false;
auto secc_argv = json::array();
for(int i = 1; i < argc; i++) {
if (strcmp(argv[i],"-c") == 0) _argv_c_exists = true;
secc_argv[i-1] = argv[i];
}
auto funcDaemonCompile = [&]() {
string secc_daemon_host = "http://" + job["daemon"]["daemonAddress"].get<string>() + ":" + std::to_string(job["daemon"]["daemonPort"].get<int>());
string secc_daemon_compile_uri = secc_daemon_host + "/compile/preprocessed/" + job["archive"]["archiveId"].get<string>();
string secc_filename = option["outfile"].is_null()
? _basename(option["infile"], true)
: _basename(option["outfile"], true);
// FIXME : using write() with map<string, string> options
// and map<string, string> headers
LOGI("REQUEST headers ");
//LOGI(headers)
//LOGI(infileBuffer.str());
SimpleHttpRequest request;
request.timeout = 50000;
request
.setHeader("content-type","application/octet-stream")
.setHeader("Content-Encoding", "gzip")
.setHeader("secc-jobid", to_string(job["jobId"].get<int>()))
.setHeader("secc-driver", secc_driver)
.setHeader("secc-language", option["language"])
.setHeader("secc-argv", option["remoteArgv"].dump())
.setHeader("secc-filename", secc_filename)
.setHeader("secc-outfile", option["outfile"].is_null() ? "null" : option["outfile"].get<string>())
.setHeader("secc-cross", secc_cross ? "true" : "false")
.setHeader("secc-target", "x86_64-linux-gnu") // FIXME : from system
.post(secc_daemon_compile_uri, infileBuffer.str())
.on("error", [](Error&& err){
throw secc_exception;
});
request.on("response", [&](Response&& res){
//check secc-code
LOGI("compile - response status code: ", res.statusCode);
if ( res.statusCode != 200
|| res.headers["secc-code"].compare("0") != 0)
throw secc_exception;
if (res.headers.count("secc-stdout"))
cout << UriDecode(res.headers["secc-stdout"]);
if (res.headers.count("secc-stderr"))
cerr << UriDecode(res.headers["secc-stderr"]);
string outdir = (option["outfile"].is_null())
? secc_cwd
: _dirname(option["outfile"].get<string>());
LOGI("outdir : ", outdir);
stringstream tarStream;
int ret = unzip(res, tarStream);
if (ret != 0)
throw secc_exception;
LOGI("unzip done.");
ret = untar(tarStream, outdir.c_str());
if (ret != 0)
throw secc_exception;
LOGI("done");
});
request.end();
}; // funcDaemonCompile
auto funcDaemonCache = [&]() {
try {
string secc_daemon_host = "http://" + job["daemon"]["daemonAddress"].get<string>() + ":" + std::to_string(job["daemon"]["daemonPort"].get<int>());
string secc_daemon_cache_uri = secc_daemon_host + "/cache/" + job["archive"]["archiveId"].get<string>() + "/" + *sourceHash + "/" + option["argvHash"].get<string>();
LOGI("cache is available. try URL : ", secc_daemon_cache_uri);
SimpleHttpRequest requestCache;
requestCache.timeout = 50000;
requestCache.get(secc_daemon_cache_uri)
.on("error", [](Error&& err){
throw secc_exception;
}).on("response", [&](Response&& res){
//check secc-code
LOGI("cache - response status code: ", res.statusCode);
if (res.statusCode != 200)
throw std::runtime_error("unable to get the cache");
if (res.headers.count("secc-stdout"))
cout << UriDecode(res.headers["secc-stdout"]);
if (res.headers.count("secc-stderr"))
cerr << UriDecode(res.headers["secc-stderr"]);
string outdir = (option["outfile"].is_null())
? secc_cwd
: _dirname(option["outfile"].get<string>());
LOGI("outdir : ", outdir);
stringstream tarStream;
int ret = unzip(res, tarStream);
if (ret != 0)
throw secc_exception;
LOGI("unzip done.");
ret = untar(tarStream, outdir.c_str());
if (ret != 0)
throw secc_exception;
LOGI("cache done");
_exit(0);
}).end();
} catch(const std::exception &e) {
LOGE("failed to hit cache.");
funcDaemonCompile();
}
}; // funcDaemonCache
try
{
//quick checks.
if (secc_scheduler_host.size() == 0) {
LOGE("secc_scheduler_host error");
throw secc_exception;
}
if (secc_cwd.find("CMakeFiles") != std::string::npos) {
LOGE("in CMakeFiles");
throw secc_exception;
}
if (!_argv_c_exists) {
LOGE("-c not exists");
throw secc_exception;
}
auto data = json::object();
data["driver"] = secc_driver;
data["cwd"] = secc_cwd;
data["mode"] = secc_mode;
data["argv"] = secc_argv;
LOGI(data.dump());
SimpleHttpRequest requestOptionAnalyze;
requestOptionAnalyze.timeout = 1000;
requestOptionAnalyze.setHeader("content-type","application/json")
.post(secc_scheduler_host + "/option/analyze", data.dump())
.on("error", [](Error&& err){
throw secc_exception;
}).on("response", [&](Response&& res){
LOGI("option - response status code: ", res.statusCode);
if (res.statusCode != 200)
throw secc_exception;
option = json::parse(res.str());
LOGI(option.dump());
//FIXME : check invalid the outfile dirname
if (option["useLocal"].get<bool>()) {
LOGE("useLocal from /option/analyze");
throw secc_exception;
}
//preprocessed file.
string cmd = secc_driver_path;
for(size_t i = 0; i < option["localArgv"].size(); i++)
cmd += " '" + option["localArgv"][i].get<string>() + "'";
LOGI("COMMAND for generating a preprocessed source.");
LOGI(cmd);
//FIXME : use libuv's uv_spawn()
size_t totalSize;
int ret = getZippedStream(cmd.c_str(), infileBuffer, sourceHash, &totalSize);
if (ret != 0)
throw secc_exception;
LOGI("request infile size : ", totalSize);
//system information
struct utsname u;
if (uname(&u) != 0)
throw secc_exception;
string hostname = u.nodename;
string platform = (strcmp(u.sysname,"Linux") == 0)
? "linux"
: (strcmp(u.sysname,"Darwin") == 0)
? "darwin"
: "unknown";
string release = u.release;
string arch = (strcmp(u.machine,"x86_64") == 0) ? "x64" : "unknown"; //FIXME : arm
string compiler_version = _exec(string(secc_driver_path + " --version").c_str());
string compiler_dumpversion = _exec(string(secc_driver_path + " -dumpversion").c_str());
string compiler_dumpmachine = _exec(string(secc_driver_path + " -dumpmachine").c_str());
compiler_dumpversion = trim(compiler_dumpversion);
compiler_dumpmachine = trim(compiler_dumpmachine);
auto data = json::object();
data["systemInformation"] = json::object();
data["systemInformation"]["hostname"] = hostname;
data["systemInformation"]["platform"] = platform;
data["systemInformation"]["release"] = release;
data["systemInformation"]["arch"] = arch;
data["compilerInformation"] = json::object();
data["compilerInformation"]["version"] = compiler_version;
data["compilerInformation"]["dumpversion"] = compiler_dumpversion;
data["compilerInformation"]["dumpmachine"] = compiler_dumpmachine;
data["mode"] = secc_mode;
data["projectId"] = option["projectId"];
data["cachePrefered"] = secc_cache;
data["crossPrefered"] = secc_cross;
data["sourcePath"] = option["infile"];
data["sourceHash"] = *sourceHash;
data["argvHash"] = option["argvHash"];
LOGI("REQUEST body /job/new");
LOGI(data);
SimpleHttpRequest requestJobNew;
requestJobNew.timeout = 50000;
requestJobNew.setHeader("content-type","application/json")
.post(secc_scheduler_host + "/job/new", data.dump())
.on("error", [](Error&& err){
throw secc_exception;
}).on("response", [&](Response&& res){
LOGI("JOB - response status code:", res.statusCode);
if (res.statusCode != 200)
throw secc_exception;
job = json::parse(res.str());
LOGI(job.dump());
if (job["local"].get<bool>()) {
LOGE("useLocal from SCHEDULER /job/new");
throw secc_exception;
}
// FIXME : implement CACHE logic!!
if (secc_cache && job["cache"].get<bool>()) {
funcDaemonCache();
} else {
funcDaemonCompile();
}
}).end();
})
.end();
}
catch (const std::exception &e)
{
LOGE("Error exception: ", e.what());
LOGI("passThrough ", secc_driver_path.c_str());
//passThrough
char pathBuf[1024];
strcpy(pathBuf, secc_driver_path.c_str());
argv[0] = pathBuf;
// FIXME : use uv_spawn
execv(secc_driver_path.c_str(), argv);
}
return 0;
}<commit_msg>refactoring. make lamba functions<commit_after>/*
SECC Native(c++) Frontend
dependencies : SimpleHttpRequest, nlohmann/json, zlib, md5
ubuntu :
$ sudo apt-get install libssl-dev zlib1g-dev
$ make clean && make
run :
$ SECC_ADDRESS="172.17.42.1" [SECC_PORT="10509"] \
/path/to/secc-native/bin/gcc ...
*/
#include <iostream>
#include "json.hpp"
#include "SimpleHttpRequest.hpp"
#include <sys/utsname.h>
#include "untar.h"
#include "utils.h"
#include "zip.h"
#include "UriCodec.h"
using namespace std;
using namespace request;
using namespace nlohmann;
class _secc_exception : public std::exception
{
virtual const char* what() const throw()
{
return "secc exception";
}
} secc_exception;
int main(int argc, char* argv[])
{
//debug
if (getenv("SECC_CMDLINE")) {
string cmd = "";
for(int i = 0; i < argc; i++)
cmd += "'" + string(argv[i]) + "' ";
LOGI(cmd);
}
// init
auto option = json::object();
auto job = json::object();
auto sourceHash = make_shared<string>();
stringstream infileBuffer;
auto outfileBuffer = make_shared<stringstream>();
auto tempBuffer = make_shared<stringstream>();
string secc_scheduler_address = (getenv("SECC_ADDRESS")) ? getenv("SECC_ADDRESS") : "127.0.0.1";
string secc_scheduler_port = (getenv("SECC_PORT")) ? getenv("SECC_PORT") : "10509";
string secc_scheduler_host = "http://" + secc_scheduler_address + ":" + secc_scheduler_port; //FIXME : from settings
string secc_driver = _basename(argv[0], false); // FIXME : exception
string secc_driver_path = "/usr/bin/" + secc_driver; // FIXME : from PATH
string secc_cwd = getcwd(nullptr, 0);
string secc_mode = "1"; //FIXME : mode 2
bool secc_cache = (getenv("SECC_CACHE") && strcmp(getenv("SECC_CACHE"),"1") == 0) ? true : false;
bool secc_cross = (getenv("SECC_CROSS") && strcmp(getenv("SECC_CROSS"),"1") == 0) ? true : false;
bool _argv_c_exists = false;
auto secc_argv = json::array();
for(int i = 1; i < argc; i++) {
if (strcmp(argv[i],"-c") == 0) _argv_c_exists = true;
secc_argv[i-1] = argv[i];
}
auto funcDaemonCompile = [&]() {
string secc_daemon_host = "http://" + job["daemon"]["daemonAddress"].get<string>() + ":" + std::to_string(job["daemon"]["daemonPort"].get<int>());
string secc_daemon_compile_uri = secc_daemon_host + "/compile/preprocessed/" + job["archive"]["archiveId"].get<string>();
string secc_filename = option["outfile"].is_null()
? _basename(option["infile"], true)
: _basename(option["outfile"], true);
// FIXME : using write() with map<string, string> options
// and map<string, string> headers
LOGI("REQUEST headers ");
//LOGI(headers)
//LOGI(infileBuffer.str());
SimpleHttpRequest request;
request.timeout = 50000;
request
.setHeader("content-type","application/octet-stream")
.setHeader("Content-Encoding", "gzip")
.setHeader("secc-jobid", to_string(job["jobId"].get<int>()))
.setHeader("secc-driver", secc_driver)
.setHeader("secc-language", option["language"])
.setHeader("secc-argv", option["remoteArgv"].dump())
.setHeader("secc-filename", secc_filename)
.setHeader("secc-outfile", option["outfile"].is_null() ? "null" : option["outfile"].get<string>())
.setHeader("secc-cross", secc_cross ? "true" : "false")
.setHeader("secc-target", "x86_64-linux-gnu") // FIXME : from system
.post(secc_daemon_compile_uri, infileBuffer.str())
.on("error", [](Error&& err){
throw secc_exception;
});
request.on("response", [&](Response&& res){
//check secc-code
LOGI("compile - response status code: ", res.statusCode);
if ( res.statusCode != 200
|| res.headers["secc-code"].compare("0") != 0)
throw secc_exception;
if (res.headers.count("secc-stdout"))
cout << UriDecode(res.headers["secc-stdout"]);
if (res.headers.count("secc-stderr"))
cerr << UriDecode(res.headers["secc-stderr"]);
string outdir = (option["outfile"].is_null())
? secc_cwd
: _dirname(option["outfile"].get<string>());
LOGI("outdir : ", outdir);
stringstream tarStream;
int ret = unzip(res, tarStream);
if (ret != 0)
throw secc_exception;
LOGI("unzip done.");
ret = untar(tarStream, outdir.c_str());
if (ret != 0)
throw secc_exception;
LOGI("done");
});
request.end();
}; // funcDaemonCompile
auto funcDaemonCache = [&]() {
try {
string secc_daemon_host = "http://" + job["daemon"]["daemonAddress"].get<string>() + ":" + std::to_string(job["daemon"]["daemonPort"].get<int>());
string secc_daemon_cache_uri = secc_daemon_host + "/cache/" + job["archive"]["archiveId"].get<string>() + "/" + *sourceHash + "/" + option["argvHash"].get<string>();
LOGI("cache is available. try URL : ", secc_daemon_cache_uri);
SimpleHttpRequest requestCache;
requestCache.timeout = 50000;
requestCache.get(secc_daemon_cache_uri)
.on("error", [](Error&& err){
throw secc_exception;
}).on("response", [&](Response&& res){
//check secc-code
LOGI("cache - response status code: ", res.statusCode);
if (res.statusCode != 200)
throw std::runtime_error("unable to get the cache");
if (res.headers.count("secc-stdout"))
cout << UriDecode(res.headers["secc-stdout"]);
if (res.headers.count("secc-stderr"))
cerr << UriDecode(res.headers["secc-stderr"]);
string outdir = (option["outfile"].is_null())
? secc_cwd
: _dirname(option["outfile"].get<string>());
LOGI("outdir : ", outdir);
stringstream tarStream;
int ret = unzip(res, tarStream);
if (ret != 0)
throw secc_exception;
LOGI("unzip done.");
ret = untar(tarStream, outdir.c_str());
if (ret != 0)
throw secc_exception;
LOGI("cache done");
_exit(0);
}).end();
} catch(const std::exception &e) {
LOGE("failed to hit cache.");
funcDaemonCompile();
}
}; // funcDaemonCache
auto funcJobNew = [&]() {
//preprocessed file.
string cmd = secc_driver_path;
for(size_t i = 0; i < option["localArgv"].size(); i++)
cmd += " '" + option["localArgv"][i].get<string>() + "'";
LOGI("COMMAND for generating a preprocessed source.");
LOGI(cmd);
//FIXME : use libuv's uv_spawn()
size_t totalSize;
int ret = getZippedStream(cmd.c_str(), infileBuffer, sourceHash, &totalSize);
if (ret != 0)
throw secc_exception;
LOGI("request infile size : ", totalSize);
//system information
struct utsname u;
if (uname(&u) != 0)
throw secc_exception;
string hostname = u.nodename;
string platform = (strcmp(u.sysname,"Linux") == 0)
? "linux"
: (strcmp(u.sysname,"Darwin") == 0)
? "darwin"
: "unknown";
string release = u.release;
string arch = (strcmp(u.machine,"x86_64") == 0) ? "x64" : "unknown"; //FIXME : arm
string compiler_version = _exec(string(secc_driver_path + " --version").c_str());
string compiler_dumpversion = _exec(string(secc_driver_path + " -dumpversion").c_str());
string compiler_dumpmachine = _exec(string(secc_driver_path + " -dumpmachine").c_str());
compiler_dumpversion = trim(compiler_dumpversion);
compiler_dumpmachine = trim(compiler_dumpmachine);
auto data = json::object();
data["systemInformation"] = json::object();
data["systemInformation"]["hostname"] = hostname;
data["systemInformation"]["platform"] = platform;
data["systemInformation"]["release"] = release;
data["systemInformation"]["arch"] = arch;
data["compilerInformation"] = json::object();
data["compilerInformation"]["version"] = compiler_version;
data["compilerInformation"]["dumpversion"] = compiler_dumpversion;
data["compilerInformation"]["dumpmachine"] = compiler_dumpmachine;
data["mode"] = secc_mode;
data["projectId"] = option["projectId"];
data["cachePrefered"] = secc_cache;
data["crossPrefered"] = secc_cross;
data["sourcePath"] = option["infile"];
data["sourceHash"] = *sourceHash;
data["argvHash"] = option["argvHash"];
LOGI("REQUEST body /job/new");
LOGI(data);
SimpleHttpRequest requestJobNew;
requestJobNew.timeout = 50000;
requestJobNew.setHeader("content-type","application/json")
.post(secc_scheduler_host + "/job/new", data.dump())
.on("error", [](Error&& err){
throw secc_exception;
}).on("response", [&](Response&& res){
LOGI("JOB - response status code:", res.statusCode);
if (res.statusCode != 200)
throw secc_exception;
job = json::parse(res.str());
LOGI(job.dump());
if (job["local"].get<bool>()) {
LOGE("useLocal from SCHEDULER /job/new");
throw secc_exception;
}
// FIXME : implement CACHE logic!!
if (secc_cache && job["cache"].get<bool>()) {
funcDaemonCache();
} else {
funcDaemonCompile();
}
}).end();
}; //funcJobNew
auto funcOptionAnalyze = [&]() {
auto data = json::object();
data["driver"] = secc_driver;
data["cwd"] = secc_cwd;
data["mode"] = secc_mode;
data["argv"] = secc_argv;
LOGI(data.dump());
SimpleHttpRequest requestOptionAnalyze;
requestOptionAnalyze.timeout = 1000;
requestOptionAnalyze.setHeader("content-type","application/json")
.post(secc_scheduler_host + "/option/analyze", data.dump())
.on("error", [](Error&& err){
throw secc_exception;
}).on("response", [&](Response&& res){
LOGI("option - response status code: ", res.statusCode);
if (res.statusCode != 200)
throw secc_exception;
option = json::parse(res.str());
LOGI(option.dump());
//FIXME : check invalid the outfile dirname
if (option["useLocal"].get<bool>()) {
LOGE("useLocal from /option/analyze");
throw secc_exception;
}
funcJobNew();
})
.end();
}; // funcOptionAnalyze
try
{
//quick checks.
if (secc_scheduler_host.size() == 0) {
LOGE("secc_scheduler_host error");
throw secc_exception;
}
if (secc_cwd.find("CMakeFiles") != std::string::npos) {
LOGE("in CMakeFiles");
throw secc_exception;
}
if (!_argv_c_exists) {
LOGE("-c not exists");
throw secc_exception;
}
funcOptionAnalyze();
}
catch (const std::exception &e)
{
LOGE("Error exception: ", e.what());
LOGI("passThrough ", secc_driver_path.c_str());
//passThrough
char pathBuf[1024];
strcpy(pathBuf, secc_driver_path.c_str());
argv[0] = pathBuf;
// FIXME : use uv_spawn
execv(secc_driver_path.c_str(), argv);
}
return 0;
}<|endoftext|> |
<commit_before>/*
SECC Native(c++) Frontend
dependencies : SimpleHttpRequest, nlohmann/json, zlib, md5
ubuntu :
$ sudo apt-get install libssl-dev zlib1g-dev
$ make clean && make
run :
$ SECC_ADDRESS="172.17.42.1" [SECC_PORT="10509"] \
/path/to/secc-native/bin/gcc ...
*/
#include <iostream>
#include "json.hpp"
#include "SimpleHttpRequest.hpp"
#include "SimpleProcessSpawn.hpp"
using request::LOGI;
#include <sys/utsname.h>
#include "untar.h"
#include "utils.h"
#include "zip.h"
#include "UriCodec.h"
using namespace std;
using namespace nlohmann;
class _secc_exception : public std::exception
{
virtual const char* what() const throw()
{
return "secc exception";
}
} secc_exception;
int main(int argc, char* argv[])
{
static uv_loop_t* loop = uv_default_loop();
//debug
if (getenv("SECC_CMDLINE")) {
string cmd = "";
for(int i = 0; i < argc; i++)
cmd += "'" + string(argv[i]) + "' ";
LOGI(cmd);
}
// init
auto option = json::object();
auto job = json::object();
auto sourceHash = make_shared<string>();
stringstream infileBuffer;
auto outfileBuffer = make_shared<stringstream>();
auto tempBuffer = make_shared<stringstream>();
string secc_scheduler_address = (getenv("SECC_ADDRESS")) ? getenv("SECC_ADDRESS") : "127.0.0.1";
string secc_scheduler_port = (getenv("SECC_PORT")) ? getenv("SECC_PORT") : "10509";
string secc_scheduler_host = "http://" + secc_scheduler_address + ":" + secc_scheduler_port; //FIXME : from settings
string secc_driver = _basename(argv[0], false); // FIXME : exception
string secc_driver_path = "/usr/bin/" + secc_driver; // FIXME : from PATH
string secc_cwd = getcwd(nullptr, 0);
string secc_mode = "1"; //FIXME : mode 2
bool secc_cache = (getenv("SECC_CACHE") && strcmp(getenv("SECC_CACHE"),"1") == 0) ? true : false;
bool secc_cross = (getenv("SECC_CROSS") && strcmp(getenv("SECC_CROSS"),"1") == 0) ? true : false;
bool _argv_c_exists = false;
auto secc_argv = json::array();
for(int i = 1; i < argc; i++) {
if (strcmp(argv[i],"-c") == 0) _argv_c_exists = true;
secc_argv[i-1] = argv[i];
}
auto funcDaemonCompile = [&]() {
string secc_daemon_host = "http://" + job["daemon"]["daemonAddress"].get<string>() + ":" + std::to_string(job["daemon"]["daemonPort"].get<int>());
string secc_daemon_compile_uri = secc_daemon_host + "/compile/preprocessed/" + job["archive"]["archiveId"].get<string>();
string secc_filename = option["outfile"].is_null()
? _basename(option["infile"], true)
: _basename(option["outfile"], true);
// FIXME : using write() with map<string, string> options
// and map<string, string> headers
LOGI("REQUEST headers ");
//LOGI(headers)
//LOGI(infileBuffer.str());
static request::SimpleHttpRequest request(loop);
request.timeout = 50000;
request
.setHeader("content-type","application/octet-stream")
.setHeader("Content-Encoding", "gzip")
.setHeader("secc-jobid", to_string(job["jobId"].get<int>()))
.setHeader("secc-driver", secc_driver)
.setHeader("secc-language", option["language"])
.setHeader("secc-argv", option["remoteArgv"].dump())
.setHeader("secc-filename", secc_filename)
.setHeader("secc-outfile", option["outfile"].is_null() ? "null" : option["outfile"].get<string>())
.setHeader("secc-cross", secc_cross ? "true" : "false")
.setHeader("secc-target", "x86_64-linux-gnu") // FIXME : from system
.post(secc_daemon_compile_uri, infileBuffer.str())
.on("error", [](request::Error&& err){
throw secc_exception;
});
request.on("response", [&](request::Response&& res){
//check secc-code
LOGI("compile - response status code: ", res.statusCode);
if ( res.statusCode != 200
|| res.headers["secc-code"].compare("0") != 0)
throw secc_exception;
if (res.headers.count("secc-stdout"))
cout << UriDecode(res.headers["secc-stdout"]);
if (res.headers.count("secc-stderr"))
cerr << UriDecode(res.headers["secc-stderr"]);
string outdir = (option["outfile"].is_null())
? secc_cwd
: _dirname(option["outfile"].get<string>());
LOGI("outdir : ", outdir);
stringstream tarStream;
int ret = unzip(res, tarStream);
if (ret != 0)
throw secc_exception;
LOGI("unzip done.");
ret = untar(tarStream, outdir.c_str());
if (ret != 0)
throw secc_exception;
LOGI("done");
});
request.end();
}; // funcDaemonCompile
auto funcDaemonCache = [&]() {
try {
string secc_daemon_host = "http://" + job["daemon"]["daemonAddress"].get<string>() + ":" + std::to_string(job["daemon"]["daemonPort"].get<int>());
string secc_daemon_cache_uri = secc_daemon_host + "/cache/" + job["archive"]["archiveId"].get<string>() + "/" + *sourceHash + "/" + option["argvHash"].get<string>();
LOGI("cache is available. try URL : ", secc_daemon_cache_uri);
static request::SimpleHttpRequest requestCache(loop);
requestCache.timeout = 50000;
requestCache.get(secc_daemon_cache_uri)
.on("error", [](request::Error&& err){
throw secc_exception;
}).on("response", [&](request::Response&& res){
//check secc-code
LOGI("cache - response status code: ", res.statusCode);
if (res.statusCode != 200)
throw std::runtime_error("unable to get the cache");
if (res.headers.count("secc-stdout"))
cout << UriDecode(res.headers["secc-stdout"]);
if (res.headers.count("secc-stderr"))
cerr << UriDecode(res.headers["secc-stderr"]);
string outdir = (option["outfile"].is_null())
? secc_cwd
: _dirname(option["outfile"].get<string>());
LOGI("outdir : ", outdir);
stringstream tarStream;
int ret = unzip(res, tarStream);
if (ret != 0)
throw secc_exception;
LOGI("unzip done.");
ret = untar(tarStream, outdir.c_str());
if (ret != 0)
throw secc_exception;
LOGI("cache done");
_exit(0);
}).end();
} catch(const std::exception &e) {
LOGE("failed to hit cache.");
funcDaemonCompile();
}
}; // funcDaemonCache
auto funcJobNew = [&]() {
// make argv array
char *childArgv[option["localArgv"].size() + 1 + 1] = {NULL};
childArgv[0] = new char[secc_driver_path.length()];
strcpy(childArgv[0], secc_driver_path.c_str());
for(size_t i = 1; i < option["localArgv"].size(); i++) {
string str = option["localArgv"][i].get<string>();
childArgv[i] = new char[str.length()];
strcpy(childArgv[i], str.c_str());
}
LOGI("generating a preprocessed source.");
//preprocessed file.
static spawn::SimpleProcessSpawn process(loop, childArgv);
process.timeout = 10000;
process.on("error", [](spawn::Error &&error){
LOGE(error.name);
LOGE(error.message);
throw secc_exception; // spawn error or timeout
})
.on("response", [&](spawn::Response &&response){
if (response.exitStatus != 0 ||
(response.exitStatus == 0 && response.termSignal != 0)) {
LOGE(response.exitStatus);
LOGE(response.termSignal);
LOGE(response.stderr.str());
throw secc_exception; // something wrong in generating.
}
LOGI(response.stdout.tellp());
size_t totalSize;
int ret = getZippedStream(response.stdout, infileBuffer, sourceHash, &totalSize);
if (ret != 0)
throw secc_exception;
LOGI("request infile size : ", totalSize);
//system information
struct utsname u;
if (uname(&u) != 0)
throw secc_exception;
string hostname = u.nodename;
string platform = (strcmp(u.sysname,"Linux") == 0)
? "linux"
: (strcmp(u.sysname,"Darwin") == 0)
? "darwin"
: "unknown";
string release = u.release;
string arch = (strcmp(u.machine,"x86_64") == 0) ? "x64" : "unknown"; //FIXME : arm
string compiler_version = _exec(string(secc_driver_path + " --version").c_str());
string compiler_dumpversion = _exec(string(secc_driver_path + " -dumpversion").c_str());
string compiler_dumpmachine = _exec(string(secc_driver_path + " -dumpmachine").c_str());
compiler_dumpversion = trim(compiler_dumpversion);
compiler_dumpmachine = trim(compiler_dumpmachine);
auto data = json::object();
data["systemInformation"] = json::object();
data["systemInformation"]["hostname"] = hostname;
data["systemInformation"]["platform"] = platform;
data["systemInformation"]["release"] = release;
data["systemInformation"]["arch"] = arch;
data["compilerInformation"] = json::object();
data["compilerInformation"]["version"] = compiler_version;
data["compilerInformation"]["dumpversion"] = compiler_dumpversion;
data["compilerInformation"]["dumpmachine"] = compiler_dumpmachine;
data["mode"] = secc_mode;
data["projectId"] = option["projectId"];
data["cachePrefered"] = secc_cache;
data["crossPrefered"] = secc_cross;
data["sourcePath"] = option["infile"];
data["sourceHash"] = *sourceHash;
data["argvHash"] = option["argvHash"];
LOGI("REQUEST body /job/new");
LOGI(data);
static request::SimpleHttpRequest requestJobNew(loop);
requestJobNew.timeout = 50000;
requestJobNew.setHeader("content-type","application/json")
.post(secc_scheduler_host + "/job/new", data.dump())
.on("error", [](request::Error&& err){
throw secc_exception;
}).on("response", [&](request::Response&& res){
LOGI("JOB - response status code:", res.statusCode);
if (res.statusCode != 200)
throw secc_exception;
job = json::parse(res.str());
LOGI(job.dump());
if (job["local"].get<bool>()) {
LOGE("useLocal from SCHEDULER /job/new");
throw secc_exception;
}
// FIXME : implement CACHE logic!!
if (secc_cache && job["cache"].get<bool>()) {
funcDaemonCache();
} else {
funcDaemonCompile();
}
}).end();
})
.spawn();
}; //funcJobNew
auto funcOptionAnalyze = [&]() {
auto data = json::object();
data["driver"] = secc_driver;
data["cwd"] = secc_cwd;
data["mode"] = secc_mode;
data["argv"] = secc_argv;
LOGI(data.dump());
static request::SimpleHttpRequest requestOptionAnalyze(loop);
requestOptionAnalyze.timeout = 1000;
requestOptionAnalyze.setHeader("content-type","application/json")
.post(secc_scheduler_host + "/option/analyze", data.dump())
.on("error", [](request::Error&& err){
throw secc_exception;
}).on("response", [&](request::Response&& res){
LOGI("option - response status code: ", res.statusCode);
if (res.statusCode != 200)
throw secc_exception;
option = json::parse(res.str());
LOGI(option.dump());
//FIXME : check invalid the outfile dirname
if (option["useLocal"].get<bool>()) {
LOGE("useLocal from /option/analyze");
throw secc_exception;
}
funcJobNew();
})
.end();
}; // funcOptionAnalyze
auto passThrough = [&]() {
// FIXME : check the driver's path in PATH ENV
char* pathBuf = new char[secc_driver_path.length()];
strcpy(pathBuf, secc_driver_path.c_str());
argv[0] = pathBuf;
//passThrough
static spawn::SimpleProcessSpawn processPassThrough(loop, argv);
processPassThrough.timeout = 60*60*1000;
processPassThrough.on("error", [](spawn::Error &&error){
LOGE(error.name);
LOGE(error.message);
})
.on("response", [&](spawn::Response &&response){
cout << response.stdout.str();
cerr << response.stderr.str();
_exit(response.exitStatus);
})
.spawn();
};
try
{
//quick checks.
if (secc_scheduler_host.size() == 0) {
LOGE("secc_scheduler_host error");
throw secc_exception;
}
if (secc_cwd.find("CMakeFiles") != std::string::npos) {
LOGE("in CMakeFiles");
throw secc_exception;
}
if (!_argv_c_exists) {
LOGE("-c not exists");
throw secc_exception;
}
funcOptionAnalyze();
}
catch (const std::exception &e)
{
LOGE("Error exception: ", e.what());
LOGI("passThrough ", secc_driver_path.c_str());
//passThrough
passThrough();
}
return uv_run(loop, UV_RUN_DEFAULT);
}<commit_msg>refactoring. add 'x-' prefix to 'secc custom headers'<commit_after>/*
SECC Native(c++) Frontend
dependencies : SimpleHttpRequest, nlohmann/json, zlib, md5
ubuntu :
$ sudo apt-get install libssl-dev zlib1g-dev
$ make clean && make
run :
$ SECC_ADDRESS="172.17.42.1" [SECC_PORT="10509"] \
/path/to/secc-native/bin/gcc ...
*/
#include <iostream>
#include "json.hpp"
#include "SimpleHttpRequest.hpp"
#include "SimpleProcessSpawn.hpp"
using request::LOGI;
#include <sys/utsname.h>
#include "untar.h"
#include "utils.h"
#include "zip.h"
#include "UriCodec.h"
using namespace std;
using namespace nlohmann;
class _secc_exception : public std::exception
{
virtual const char* what() const throw()
{
return "secc exception";
}
} secc_exception;
int main(int argc, char* argv[])
{
static uv_loop_t* loop = uv_default_loop();
//debug
if (getenv("SECC_CMDLINE")) {
string cmd = "";
for(int i = 0; i < argc; i++)
cmd += "'" + string(argv[i]) + "' ";
LOGI(cmd);
}
// init
auto option = json::object();
auto job = json::object();
auto sourceHash = make_shared<string>();
stringstream infileBuffer;
auto outfileBuffer = make_shared<stringstream>();
auto tempBuffer = make_shared<stringstream>();
string secc_scheduler_address = (getenv("SECC_ADDRESS")) ? getenv("SECC_ADDRESS") : "127.0.0.1";
string secc_scheduler_port = (getenv("SECC_PORT")) ? getenv("SECC_PORT") : "10509";
string secc_scheduler_host = "http://" + secc_scheduler_address + ":" + secc_scheduler_port; //FIXME : from settings
string secc_driver = _basename(argv[0], false); // FIXME : exception
string secc_driver_path = "/usr/bin/" + secc_driver; // FIXME : from PATH
string secc_cwd = getcwd(nullptr, 0);
string secc_mode = "1"; //FIXME : mode 2
bool secc_cache = (getenv("SECC_CACHE") && strcmp(getenv("SECC_CACHE"),"1") == 0) ? true : false;
bool secc_cross = (getenv("SECC_CROSS") && strcmp(getenv("SECC_CROSS"),"1") == 0) ? true : false;
bool _argv_c_exists = false;
auto secc_argv = json::array();
for(int i = 1; i < argc; i++) {
if (strcmp(argv[i],"-c") == 0) _argv_c_exists = true;
secc_argv[i-1] = argv[i];
}
auto funcDaemonCompile = [&]() {
string secc_daemon_host = "http://" + job["daemon"]["daemonAddress"].get<string>() + ":" + std::to_string(job["daemon"]["daemonPort"].get<int>());
string secc_daemon_compile_uri = secc_daemon_host + "/compile/preprocessed/" + job["archive"]["archiveId"].get<string>();
string secc_filename = option["outfile"].is_null()
? _basename(option["infile"], true)
: _basename(option["outfile"], true);
// FIXME : using write() with map<string, string> options
// and map<string, string> headers
LOGI("REQUEST headers ");
//LOGI(headers)
//LOGI(infileBuffer.str());
static request::SimpleHttpRequest request(loop);
request.timeout = 50000;
request
.setHeader("content-type","application/octet-stream")
.setHeader("Content-Encoding", "gzip")
.setHeader("x-secc-jobid", to_string(job["jobId"].get<int>()))
.setHeader("x-secc-driver", secc_driver)
.setHeader("x-secc-language", option["language"])
.setHeader("x-secc-argv", option["remoteArgv"].dump())
.setHeader("x-secc-filename", secc_filename)
.setHeader("x-secc-outfile", option["outfile"].is_null() ? "null" : option["outfile"].get<string>())
.setHeader("x-secc-cross", secc_cross ? "true" : "false")
.setHeader("x-secc-target", "x86_64-linux-gnu") // FIXME : from system
.post(secc_daemon_compile_uri, infileBuffer.str())
.on("error", [](request::Error&& err){
throw secc_exception;
});
request.on("response", [&](request::Response&& res){
//check x-secc-code
LOGI("compile - response status code: ", res.statusCode);
if ( res.statusCode != 200
|| res.headers["x-secc-code"].compare("0") != 0)
throw secc_exception;
if (res.headers.count("x-secc-stdout"))
cout << UriDecode(res.headers["x-secc-stdout"]);
if (res.headers.count("x-secc-stderr"))
cerr << UriDecode(res.headers["x-secc-stderr"]);
string outdir = (option["outfile"].is_null())
? secc_cwd
: _dirname(option["outfile"].get<string>());
LOGI("outdir : ", outdir);
stringstream tarStream;
int ret = unzip(res, tarStream);
if (ret != 0)
throw secc_exception;
LOGI("unzip done.");
ret = untar(tarStream, outdir.c_str());
if (ret != 0)
throw secc_exception;
LOGI("done");
});
request.end();
}; // funcDaemonCompile
auto funcDaemonCache = [&]() {
try {
string secc_daemon_host = "http://" + job["daemon"]["daemonAddress"].get<string>() + ":" + std::to_string(job["daemon"]["daemonPort"].get<int>());
string secc_daemon_cache_uri = secc_daemon_host + "/cache/" + job["archive"]["archiveId"].get<string>() + "/" + *sourceHash + "/" + option["argvHash"].get<string>();
LOGI("cache is available. try URL : ", secc_daemon_cache_uri);
static request::SimpleHttpRequest requestCache(loop);
requestCache.timeout = 50000;
requestCache.get(secc_daemon_cache_uri)
.on("error", [](request::Error&& err){
throw secc_exception;
}).on("response", [&](request::Response&& res){
//check x-secc-code
LOGI("cache - response status code: ", res.statusCode);
if (res.statusCode != 200)
throw std::runtime_error("unable to get the cache");
if (res.headers.count("x-secc-stdout"))
cout << UriDecode(res.headers["x-secc-stdout"]);
if (res.headers.count("x-secc-stderr"))
cerr << UriDecode(res.headers["x-secc-stderr"]);
string outdir = (option["outfile"].is_null())
? secc_cwd
: _dirname(option["outfile"].get<string>());
LOGI("outdir : ", outdir);
stringstream tarStream;
int ret = unzip(res, tarStream);
if (ret != 0)
throw secc_exception;
LOGI("unzip done.");
ret = untar(tarStream, outdir.c_str());
if (ret != 0)
throw secc_exception;
LOGI("cache done");
_exit(0);
}).end();
} catch(const std::exception &e) {
LOGE("failed to hit cache.");
funcDaemonCompile();
}
}; // funcDaemonCache
auto funcJobNew = [&]() {
// make argv array
char *childArgv[option["localArgv"].size() + 1 + 1] = {NULL};
childArgv[0] = new char[secc_driver_path.length()];
strcpy(childArgv[0], secc_driver_path.c_str());
for(size_t i = 1; i < option["localArgv"].size(); i++) {
string str = option["localArgv"][i].get<string>();
childArgv[i] = new char[str.length()];
strcpy(childArgv[i], str.c_str());
}
LOGI("generating a preprocessed source.");
//preprocessed file.
static spawn::SimpleProcessSpawn process(loop, childArgv);
process.timeout = 10000;
process.on("error", [](spawn::Error &&error){
LOGE(error.name);
LOGE(error.message);
throw secc_exception; // spawn error or timeout
})
.on("response", [&](spawn::Response &&response){
if (response.exitStatus != 0 ||
(response.exitStatus == 0 && response.termSignal != 0)) {
LOGE(response.exitStatus);
LOGE(response.termSignal);
LOGE(response.stderr.str());
throw secc_exception; // something wrong in generating.
}
LOGI(response.stdout.tellp());
size_t totalSize;
int ret = getZippedStream(response.stdout, infileBuffer, sourceHash, &totalSize);
if (ret != 0)
throw secc_exception;
LOGI("request infile size : ", totalSize);
//system information
struct utsname u;
if (uname(&u) != 0)
throw secc_exception;
string hostname = u.nodename;
string platform = (strcmp(u.sysname,"Linux") == 0)
? "linux"
: (strcmp(u.sysname,"Darwin") == 0)
? "darwin"
: "unknown";
string release = u.release;
string arch = (strcmp(u.machine,"x86_64") == 0) ? "x64" : "unknown"; //FIXME : arm
string compiler_version = _exec(string(secc_driver_path + " --version").c_str());
string compiler_dumpversion = _exec(string(secc_driver_path + " -dumpversion").c_str());
string compiler_dumpmachine = _exec(string(secc_driver_path + " -dumpmachine").c_str());
compiler_dumpversion = trim(compiler_dumpversion);
compiler_dumpmachine = trim(compiler_dumpmachine);
auto data = json::object();
data["systemInformation"] = json::object();
data["systemInformation"]["hostname"] = hostname;
data["systemInformation"]["platform"] = platform;
data["systemInformation"]["release"] = release;
data["systemInformation"]["arch"] = arch;
data["compilerInformation"] = json::object();
data["compilerInformation"]["version"] = compiler_version;
data["compilerInformation"]["dumpversion"] = compiler_dumpversion;
data["compilerInformation"]["dumpmachine"] = compiler_dumpmachine;
data["mode"] = secc_mode;
data["projectId"] = option["projectId"];
data["cachePrefered"] = secc_cache;
data["crossPrefered"] = secc_cross;
data["sourcePath"] = option["infile"];
data["sourceHash"] = *sourceHash;
data["argvHash"] = option["argvHash"];
LOGI("REQUEST body /job/new");
LOGI(data);
static request::SimpleHttpRequest requestJobNew(loop);
requestJobNew.timeout = 50000;
requestJobNew.setHeader("content-type","application/json")
.post(secc_scheduler_host + "/job/new", data.dump())
.on("error", [](request::Error&& err){
throw secc_exception;
}).on("response", [&](request::Response&& res){
LOGI("JOB - response status code:", res.statusCode);
if (res.statusCode != 200)
throw secc_exception;
job = json::parse(res.str());
LOGI(job.dump());
if (job["local"].get<bool>()) {
LOGE("useLocal from SCHEDULER /job/new");
throw secc_exception;
}
// FIXME : implement CACHE logic!!
if (secc_cache && job["cache"].get<bool>()) {
funcDaemonCache();
} else {
funcDaemonCompile();
}
}).end();
})
.spawn();
}; //funcJobNew
auto funcOptionAnalyze = [&]() {
auto data = json::object();
data["driver"] = secc_driver;
data["cwd"] = secc_cwd;
data["mode"] = secc_mode;
data["argv"] = secc_argv;
LOGI(data.dump());
static request::SimpleHttpRequest requestOptionAnalyze(loop);
requestOptionAnalyze.timeout = 1000;
requestOptionAnalyze.setHeader("content-type","application/json")
.post(secc_scheduler_host + "/option/analyze", data.dump())
.on("error", [](request::Error&& err){
throw secc_exception;
}).on("response", [&](request::Response&& res){
LOGI("option - response status code: ", res.statusCode);
if (res.statusCode != 200)
throw secc_exception;
option = json::parse(res.str());
LOGI(option.dump());
//FIXME : check invalid the outfile dirname
if (option["useLocal"].get<bool>()) {
LOGE("useLocal from /option/analyze");
throw secc_exception;
}
funcJobNew();
})
.end();
}; // funcOptionAnalyze
auto passThrough = [&]() {
// FIXME : check the driver's path in PATH ENV
char* pathBuf = new char[secc_driver_path.length()];
strcpy(pathBuf, secc_driver_path.c_str());
argv[0] = pathBuf;
//passThrough
static spawn::SimpleProcessSpawn processPassThrough(loop, argv);
processPassThrough.timeout = 60*60*1000;
processPassThrough.on("error", [](spawn::Error &&error){
LOGE(error.name);
LOGE(error.message);
})
.on("response", [&](spawn::Response &&response){
cout << response.stdout.str();
cerr << response.stderr.str();
_exit(response.exitStatus);
})
.spawn();
};
try
{
//quick checks.
if (secc_scheduler_host.size() == 0) {
LOGE("secc_scheduler_host error");
throw secc_exception;
}
if (secc_cwd.find("CMakeFiles") != std::string::npos) {
LOGE("in CMakeFiles");
throw secc_exception;
}
if (!_argv_c_exists) {
LOGE("-c not exists");
throw secc_exception;
}
funcOptionAnalyze();
}
catch (const std::exception &e)
{
LOGE("Error exception: ", e.what());
LOGI("passThrough ", secc_driver_path.c_str());
//passThrough
passThrough();
}
return uv_run(loop, UV_RUN_DEFAULT);
}<|endoftext|> |
<commit_before>/*
* spinbox2.cpp - spin box with extra pair of spin buttons (for QT3)
* Program: kalarm
* (C) 2001, 2002 by David Jarvie software@astrojar.org.uk
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include <qglobal.h>
#if QT_VERSION >= 300
#include <stdlib.h>
#include <qstyle.h>
#include <qobjectlist.h>
#include "spinbox2.moc"
SpinBox2::SpinBox2(QWidget* parent, const char* name)
: QFrame(parent, name)
{
updown2Frame = new QFrame(this);
spinboxFrame = new QFrame(this);
updown2 = new SpinBox(updown2Frame, "updown2");
spinbox = new SB2_SpinBox(0, 1, 1, this, spinboxFrame);
init();
}
SpinBox2::SpinBox2(int minValue, int maxValue, int step, int step2, QWidget* parent, const char* name)
: QFrame(parent, name),
mMinValue(minValue),
mMaxValue(maxValue)
{
updown2Frame = new QFrame(this);
spinboxFrame = new QFrame(this);
updown2 = new SpinBox(minValue, maxValue, step2, updown2Frame, "updown2");
spinbox = new SB2_SpinBox(minValue, maxValue, step, this, spinboxFrame);
setSteps(step, step2);
init();
}
void SpinBox2::init()
{
spinbox->setSelectOnStep(false); // default
updown2->setSelectOnStep(false); // always false
setFocusProxy(spinbox);
connect(spinbox, SIGNAL(valueChanged(int)), SLOT(valueChange()));
connect(spinbox, SIGNAL(valueChanged(int)), SIGNAL(valueChanged(int)));
connect(spinbox, SIGNAL(valueChanged(const QString&)), SIGNAL(valueChanged(const QString&)));
connect(updown2, SIGNAL(stepped(int)), SLOT(stepPage(int)));
}
void SpinBox2::setReadOnly(bool ro)
{
if (static_cast<int>(ro) != static_cast<int>(spinbox->isReadOnly()))
{
spinbox->setReadOnly(ro);
updown2->setReadOnly(ro);
}
}
void SpinBox2::setButtonSymbols(QSpinBox::ButtonSymbols newSymbols)
{
if (spinbox->buttonSymbols() == newSymbols)
return;
spinbox->setButtonSymbols(newSymbols);
updown2->setButtonSymbols(newSymbols);
}
int SpinBox2::bound(int val) const
{
return (val < mMinValue) ? mMinValue : (val > mMaxValue) ? mMaxValue : val;
}
void SpinBox2::setMinValue(int val)
{
mMinValue = val;
spinbox->setMinValue(val);
updown2->setMinValue(val);
}
void SpinBox2::setMaxValue(int val)
{
mMaxValue = val;
spinbox->setMaxValue(val);
updown2->setMaxValue(val);
}
void SpinBox2::valueChange()
{
int val = spinbox->value();
bool blocked = updown2->signalsBlocked();
updown2->blockSignals(true);
updown2->setValue(val);
updown2->blockSignals(blocked);
}
void SpinBox2::stepPage(int step)
{
// bool focus = spinbox->selectOnStep() && updown2->hasFocus();
// if (focus)
// spinbox->setFocus(); // make displayed text be selected, as for stepping with the spinbox buttons
if (abs(step) == updown2->lineStep())
spinbox->setValue(updown2->value());
else
{
int val = spinbox->value();
int pageStep = updown2->lineStep();
int pageShiftStep = updown2->lineShiftStep();
int adjust = (step > 0) ? -((val - val % pageStep) % pageShiftStep)
: pageShiftStep - (((val - val % pageStep) + pageShiftStep - 1) % pageShiftStep + 1);
spinbox->addValue(adjust + step);
}
bool focus = spinbox->selectOnStep() && updown2->hasFocus();
if (focus)
spinbox->selectAll();
// if (focus)
// updown2->setFocus();
}
// Called when the widget is about to be displayed.
// (At construction time, the spin button widths cannot be determined correctly,
// so we need to wait until now to definitively rearrange the widget.)
void SpinBox2::showEvent(QShowEvent*)
{
arrange();
}
QSize SpinBox2::sizeHint() const
{
getMetrics();
QSize size = spinbox->sizeHint();
size.setWidth(size.width() - xSpinbox + wUpdown2 + wGap);
return size;
}
QSize SpinBox2::minimumSizeHint() const
{
getMetrics();
QSize size = spinbox->minimumSizeHint();
size.setWidth(size.width() - xSpinbox + wUpdown2 + wGap);
return size;
}
void SpinBox2::arrange()
{
getMetrics();
updown2Frame->setGeometry(QStyle::visualRect(QRect(0, 0, wUpdown2, height()), this));
updown2->setGeometry(-xUpdown2, 0, updown2->width(), height());
spinboxFrame->setGeometry(QStyle::visualRect(QRect(wUpdown2 + wGap, 0, width() - wUpdown2 - wGap, height()), this));
spinbox->setGeometry(-xSpinbox, 0, spinboxFrame->width() + xSpinbox, height());
}
void SpinBox2::getMetrics() const
{
QRect rect = updown2->style().querySubControlMetrics(QStyle::CC_SpinWidget, updown2, QStyle::SC_SpinWidgetButtonField);
xUpdown2 = rect.left();
wUpdown2 = updown2->width() - xUpdown2;
xSpinbox = spinbox->style().querySubControlMetrics(QStyle::CC_SpinWidget, spinbox, QStyle::SC_SpinWidgetEditField).left();
wGap = 0;
// Make style-specific adjustments for a better appearance
if (style().isA("QMotifPlusStyle"))
{
xSpinbox = 0; // show the edit control left border
wGap = 2; // leave a space to the right of the left-hand pair of spin buttons
}
}
#endif // QT_VERSION >= 300
<commit_msg>Fix invisible widget taking keyboard focus when tabbing into time spinboxes<commit_after>/*
* spinbox2.cpp - spin box with extra pair of spin buttons (for QT3)
* Program: kalarm
* (C) 2001, 2002 by David Jarvie software@astrojar.org.uk
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include <qglobal.h>
#if QT_VERSION >= 300
#include <stdlib.h>
#include <qstyle.h>
#include <qobjectlist.h>
#include "spinbox2.moc"
SpinBox2::SpinBox2(QWidget* parent, const char* name)
: QFrame(parent, name)
{
updown2Frame = new QFrame(this);
spinboxFrame = new QFrame(this);
updown2 = new SpinBox(updown2Frame, "updown2");
spinbox = new SB2_SpinBox(0, 1, 1, this, spinboxFrame);
init();
}
SpinBox2::SpinBox2(int minValue, int maxValue, int step, int step2, QWidget* parent, const char* name)
: QFrame(parent, name),
mMinValue(minValue),
mMaxValue(maxValue)
{
updown2Frame = new QFrame(this);
spinboxFrame = new QFrame(this);
updown2 = new SpinBox(minValue, maxValue, step2, updown2Frame, "updown2");
spinbox = new SB2_SpinBox(minValue, maxValue, step, this, spinboxFrame);
setSteps(step, step2);
init();
}
void SpinBox2::init()
{
spinbox->setSelectOnStep(false); // default
updown2->setSelectOnStep(false); // always false
setFocusProxy(spinbox);
updown2->setFocusPolicy(QWidget::NoFocus);
connect(spinbox, SIGNAL(valueChanged(int)), SLOT(valueChange()));
connect(spinbox, SIGNAL(valueChanged(int)), SIGNAL(valueChanged(int)));
connect(spinbox, SIGNAL(valueChanged(const QString&)), SIGNAL(valueChanged(const QString&)));
connect(updown2, SIGNAL(stepped(int)), SLOT(stepPage(int)));
}
void SpinBox2::setReadOnly(bool ro)
{
if (static_cast<int>(ro) != static_cast<int>(spinbox->isReadOnly()))
{
spinbox->setReadOnly(ro);
updown2->setReadOnly(ro);
}
}
void SpinBox2::setButtonSymbols(QSpinBox::ButtonSymbols newSymbols)
{
if (spinbox->buttonSymbols() == newSymbols)
return;
spinbox->setButtonSymbols(newSymbols);
updown2->setButtonSymbols(newSymbols);
}
int SpinBox2::bound(int val) const
{
return (val < mMinValue) ? mMinValue : (val > mMaxValue) ? mMaxValue : val;
}
void SpinBox2::setMinValue(int val)
{
mMinValue = val;
spinbox->setMinValue(val);
updown2->setMinValue(val);
}
void SpinBox2::setMaxValue(int val)
{
mMaxValue = val;
spinbox->setMaxValue(val);
updown2->setMaxValue(val);
}
void SpinBox2::valueChange()
{
int val = spinbox->value();
bool blocked = updown2->signalsBlocked();
updown2->blockSignals(true);
updown2->setValue(val);
updown2->blockSignals(blocked);
}
void SpinBox2::stepPage(int step)
{
// bool focus = spinbox->selectOnStep() && updown2->hasFocus();
// if (focus)
// spinbox->setFocus(); // make displayed text be selected, as for stepping with the spinbox buttons
if (abs(step) == updown2->lineStep())
spinbox->setValue(updown2->value());
else
{
int val = spinbox->value();
int pageStep = updown2->lineStep();
int pageShiftStep = updown2->lineShiftStep();
int adjust = (step > 0) ? -((val - val % pageStep) % pageShiftStep)
: pageShiftStep - (((val - val % pageStep) + pageShiftStep - 1) % pageShiftStep + 1);
spinbox->addValue(adjust + step);
}
bool focus = spinbox->selectOnStep() && updown2->hasFocus();
if (focus)
spinbox->selectAll();
// if (focus)
// updown2->setFocus();
}
// Called when the widget is about to be displayed.
// (At construction time, the spin button widths cannot be determined correctly,
// so we need to wait until now to definitively rearrange the widget.)
void SpinBox2::showEvent(QShowEvent*)
{
arrange();
}
QSize SpinBox2::sizeHint() const
{
getMetrics();
QSize size = spinbox->sizeHint();
size.setWidth(size.width() - xSpinbox + wUpdown2 + wGap);
return size;
}
QSize SpinBox2::minimumSizeHint() const
{
getMetrics();
QSize size = spinbox->minimumSizeHint();
size.setWidth(size.width() - xSpinbox + wUpdown2 + wGap);
return size;
}
void SpinBox2::arrange()
{
getMetrics();
updown2Frame->setGeometry(QStyle::visualRect(QRect(0, 0, wUpdown2, height()), this));
updown2->setGeometry(-xUpdown2, 0, updown2->width(), height());
spinboxFrame->setGeometry(QStyle::visualRect(QRect(wUpdown2 + wGap, 0, width() - wUpdown2 - wGap, height()), this));
spinbox->setGeometry(-xSpinbox, 0, spinboxFrame->width() + xSpinbox, height());
}
void SpinBox2::getMetrics() const
{
QRect rect = updown2->style().querySubControlMetrics(QStyle::CC_SpinWidget, updown2, QStyle::SC_SpinWidgetButtonField);
xUpdown2 = rect.left();
wUpdown2 = updown2->width() - xUpdown2;
xSpinbox = spinbox->style().querySubControlMetrics(QStyle::CC_SpinWidget, spinbox, QStyle::SC_SpinWidgetEditField).left();
wGap = 0;
// Make style-specific adjustments for a better appearance
if (style().isA("QMotifPlusStyle"))
{
xSpinbox = 0; // show the edit control left border
wGap = 2; // leave a space to the right of the left-hand pair of spin buttons
}
}
#endif // QT_VERSION >= 300
<|endoftext|> |
<commit_before>// ======================================================================== //
// Copyright 2009-2017 Intel Corporation //
// //
// 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 "bvh_builder.h"
#include "bvh_rotate.h"
#define ROTATE_TREE 0
namespace embree
{
namespace isa
{
/* tree rotations */
template<int N>
__forceinline size_t rotate(typename BVHN<N>::AlignedNode* node, const size_t* counts, const size_t num) {
return 0;
}
template<int N>
__forceinline size_t dummy(typename BVHN<N>::AlignedNode* node, const size_t* counts, const size_t num) {
return 0;
}
#if ROTATE_TREE
template<>
__forceinline size_t rotate<4>(BVH4::AlignedNode* node, const size_t* counts, const size_t num)
{
size_t n = 0;
assert(num <= 4);
for (size_t i=0; i<num; i++)
n += counts[i];
if (n >= 4096) {
for (size_t i=0; i<num; i++) {
if (counts[i] < 4096) {
for (int j=0; j<ROTATE_TREE; j++)
BVHNRotate<4>::rotate(node->child(i));
node->child(i).setBarrier();
}
}
}
return n;
}
#endif
template<int N>
void BVHNBuilder<N>::BVHNBuilderV::build(BVH* bvh, BuildProgressMonitor& progress_in, PrimRef* prims, const PrimInfo& pinfo, const size_t blockSize, const size_t minLeafSize, const size_t maxLeafSize, const float travCost, const float intCost, const size_t singleThreadThreshold)
{
//bvh->alloc.init_estimate(pinfo.size()*sizeof(PrimRef));
auto progressFunc = [&] (size_t dn) {
progress_in(dn);
};
auto createLeafFunc = [&] (const BVHBuilderBinnedSAH::BuildRecord& current, Allocator* alloc) -> size_t {
return createLeaf(current,alloc);
};
NodeRef root;
BVHBuilderBinnedSAH::build_reduce<NodeRef>
(root,typename BVH::CreateAlloc(bvh),size_t(0),typename BVH::CreateAlignedNode(bvh),rotate<N>,createLeafFunc,progressFunc,
prims,pinfo,N,BVH::maxBuildDepthLeaf,blockSize,minLeafSize,maxLeafSize,travCost,intCost,singleThreadThreshold);
bvh->set(root,LBBox3fa(pinfo.geomBounds),pinfo.size());
#if ROTATE_TREE
if (N == 4)
{
for (int i=0; i<ROTATE_TREE; i++)
BVHNRotate<N>::rotate(bvh->root);
bvh->clearBarrier(bvh->root);
}
#endif
bvh->layoutLargeNodes(size_t(pinfo.size()*0.005f));
}
template<int N>
void BVHNBuilderQuantized<N>::BVHNBuilderV::build(BVH* bvh, BuildProgressMonitor& progress_in, PrimRef* prims, const PrimInfo& pinfo, const size_t blockSize, const size_t minLeafSize, const size_t maxLeafSize, const float travCost, const float intCost, const size_t singleThreadThreshold)
{
//bvh->alloc.init_estimate(pinfo.size()*sizeof(PrimRef));
auto progressFunc = [&] (size_t dn) {
progress_in(dn);
};
auto createLeafFunc = [&] (const BVHBuilderBinnedSAH::BuildRecord& current, Allocator* alloc) -> size_t {
return createLeaf(current,alloc);
};
NodeRef root = 0;
BVHBuilderBinnedSAH::build_reduce<NodeRef>
(root,typename BVH::CreateAlloc(bvh),size_t(0),typename BVH::CreateQuantizedNode(bvh),dummy<N>,createLeafFunc,progressFunc,
prims,pinfo,N,BVH::maxBuildDepthLeaf,blockSize,minLeafSize,maxLeafSize,travCost,intCost,singleThreadThreshold);
NodeRef new_root = (size_t)root | BVH::tyQuantizedNode;
// todo: COPY LAYOUT FOR LARGE NODES !!!
//bvh->layoutLargeNodes(pinfo.size()*0.005f);
assert(new_root.isQuantizedNode());
bvh->set(new_root,LBBox3fa(pinfo.geomBounds),pinfo.size());
}
template<int N>
struct CreateAlignedNodeMB
{
typedef BVHN<N> BVH;
typedef typename BVH::AlignedNodeMB AlignedNodeMB;
__forceinline CreateAlignedNodeMB (BVH* bvh) : bvh(bvh) {}
__forceinline AlignedNodeMB* operator() (const isa::BVHBuilderBinnedSAH::BuildRecord& current, BVHBuilderBinnedSAH::BuildRecord* children, const size_t num, FastAllocator::ThreadLocal2* alloc)
{
AlignedNodeMB* node = (AlignedNodeMB*) alloc->alloc0->malloc(sizeof(AlignedNodeMB),BVH::byteNodeAlignment); node->clear();
for (size_t i=0; i<num; i++) {
children[i].parent = (size_t*)&node->child(i);
}
*current.parent = bvh->encodeNode(node);
return node;
}
BVH* bvh;
};
template<int N>
std::tuple<typename BVHN<N>::NodeRef,LBBox3fa> BVHNBuilderMblur<N>::BVHNBuilderV::build(BVH* bvh, BuildProgressMonitor& progress_in, PrimRef* prims, const PrimInfo& pinfo, const size_t blockSize, const size_t minLeafSize, const size_t maxLeafSize, const float travCost, const float intCost, const size_t singleThreadThreshold)
{
auto progressFunc = [&] (size_t dn) {
progress_in(dn);
};
auto createLeafFunc = [&] (const BVHBuilderBinnedSAH::BuildRecord& current, Allocator* alloc) -> LBBox3fa {
return createLeaf(current,alloc);
};
/* reduction function */
auto reduce = [] (AlignedNodeMB* node, const LBBox3fa* bounds, const size_t num) -> LBBox3fa
{
assert(num <= N);
LBBox3fa allBounds = empty;
for (size_t i=0; i<num; i++) {
node->set(i, bounds[i]);
allBounds.extend(bounds[i]);
}
return allBounds;
};
auto identity = LBBox3fa(empty);
NodeRef root;
LBBox3fa root_bounds = BVHBuilderBinnedSAH::build_reduce<NodeRef>
(root,typename BVH::CreateAlloc(bvh),identity,CreateAlignedNodeMB<N>(bvh),reduce,createLeafFunc,progressFunc,
prims,pinfo,N,BVH::maxBuildDepthLeaf,blockSize,minLeafSize,maxLeafSize,travCost,intCost,singleThreadThreshold);
/* set bounding box to merge bounds of all time steps */
bvh->set(root,root_bounds,pinfo.size()); // FIXME: remove later
#if ROTATE_TREE
if (N == 4)
{
for (int i=0; i<ROTATE_TREE; i++)
BVHNRotate<N>::rotate(bvh->root);
bvh->clearBarrier(bvh->root);
}
#endif
//bvh->layoutLargeNodes(pinfo.size()*0.005f); // FIXME: implement for Mblur nodes and activate
return std::make_tuple(root,root_bounds);
}
template struct BVHNBuilder<4>;
template struct BVHNBuilderQuantized<4>;
template struct BVHNBuilderMblur<4>;
#if defined(__AVX__)
template struct BVHNBuilder<8>;
template struct BVHNBuilderQuantized<8>;
template struct BVHNBuilderMblur<8>;
#endif
}
}
<commit_msg>removed tree rotations from bvh_builder.cpp, was not used and never gave consistent speedup<commit_after>// ======================================================================== //
// Copyright 2009-2017 Intel Corporation //
// //
// 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 "bvh_builder.h"
namespace embree
{
namespace isa
{
template<int N>
__forceinline size_t dummy(typename BVHN<N>::AlignedNode* node, const size_t* counts, const size_t num) {
return 0;
}
template<int N>
void BVHNBuilder<N>::BVHNBuilderV::build(BVH* bvh, BuildProgressMonitor& progress_in, PrimRef* prims, const PrimInfo& pinfo, const size_t blockSize, const size_t minLeafSize, const size_t maxLeafSize, const float travCost, const float intCost, const size_t singleThreadThreshold)
{
//bvh->alloc.init_estimate(pinfo.size()*sizeof(PrimRef));
auto progressFunc = [&] (size_t dn) {
progress_in(dn);
};
auto createLeafFunc = [&] (const BVHBuilderBinnedSAH::BuildRecord& current, Allocator* alloc) -> size_t {
return createLeaf(current,alloc);
};
NodeRef root;
BVHBuilderBinnedSAH::build_reduce<NodeRef>
(root,typename BVH::CreateAlloc(bvh),size_t(0),typename BVH::CreateAlignedNode(bvh),dummy<N>,createLeafFunc,progressFunc,
prims,pinfo,N,BVH::maxBuildDepthLeaf,blockSize,minLeafSize,maxLeafSize,travCost,intCost,singleThreadThreshold);
bvh->set(root,LBBox3fa(pinfo.geomBounds),pinfo.size());
bvh->layoutLargeNodes(size_t(pinfo.size()*0.005f));
}
template<int N>
void BVHNBuilderQuantized<N>::BVHNBuilderV::build(BVH* bvh, BuildProgressMonitor& progress_in, PrimRef* prims, const PrimInfo& pinfo, const size_t blockSize, const size_t minLeafSize, const size_t maxLeafSize, const float travCost, const float intCost, const size_t singleThreadThreshold)
{
//bvh->alloc.init_estimate(pinfo.size()*sizeof(PrimRef));
auto progressFunc = [&] (size_t dn) {
progress_in(dn);
};
auto createLeafFunc = [&] (const BVHBuilderBinnedSAH::BuildRecord& current, Allocator* alloc) -> size_t {
return createLeaf(current,alloc);
};
NodeRef root = 0;
BVHBuilderBinnedSAH::build_reduce<NodeRef>
(root,typename BVH::CreateAlloc(bvh),size_t(0),typename BVH::CreateQuantizedNode(bvh),dummy<N>,createLeafFunc,progressFunc,
prims,pinfo,N,BVH::maxBuildDepthLeaf,blockSize,minLeafSize,maxLeafSize,travCost,intCost,singleThreadThreshold);
NodeRef new_root = (size_t)root | BVH::tyQuantizedNode;
// todo: COPY LAYOUT FOR LARGE NODES !!!
//bvh->layoutLargeNodes(pinfo.size()*0.005f);
assert(new_root.isQuantizedNode());
bvh->set(new_root,LBBox3fa(pinfo.geomBounds),pinfo.size());
}
template<int N>
struct CreateAlignedNodeMB
{
typedef BVHN<N> BVH;
typedef typename BVH::AlignedNodeMB AlignedNodeMB;
__forceinline CreateAlignedNodeMB (BVH* bvh) : bvh(bvh) {}
__forceinline AlignedNodeMB* operator() (const isa::BVHBuilderBinnedSAH::BuildRecord& current, BVHBuilderBinnedSAH::BuildRecord* children, const size_t num, FastAllocator::ThreadLocal2* alloc)
{
AlignedNodeMB* node = (AlignedNodeMB*) alloc->alloc0->malloc(sizeof(AlignedNodeMB),BVH::byteNodeAlignment); node->clear();
for (size_t i=0; i<num; i++) {
children[i].parent = (size_t*)&node->child(i);
}
*current.parent = bvh->encodeNode(node);
return node;
}
BVH* bvh;
};
template<int N>
std::tuple<typename BVHN<N>::NodeRef,LBBox3fa> BVHNBuilderMblur<N>::BVHNBuilderV::build(BVH* bvh, BuildProgressMonitor& progress_in, PrimRef* prims, const PrimInfo& pinfo, const size_t blockSize, const size_t minLeafSize, const size_t maxLeafSize, const float travCost, const float intCost, const size_t singleThreadThreshold)
{
auto progressFunc = [&] (size_t dn) {
progress_in(dn);
};
auto createLeafFunc = [&] (const BVHBuilderBinnedSAH::BuildRecord& current, Allocator* alloc) -> LBBox3fa {
return createLeaf(current,alloc);
};
/* reduction function */
auto reduce = [] (AlignedNodeMB* node, const LBBox3fa* bounds, const size_t num) -> LBBox3fa
{
assert(num <= N);
LBBox3fa allBounds = empty;
for (size_t i=0; i<num; i++) {
node->set(i, bounds[i]);
allBounds.extend(bounds[i]);
}
return allBounds;
};
auto identity = LBBox3fa(empty);
NodeRef root;
LBBox3fa root_bounds = BVHBuilderBinnedSAH::build_reduce<NodeRef>
(root,typename BVH::CreateAlloc(bvh),identity,CreateAlignedNodeMB<N>(bvh),reduce,createLeafFunc,progressFunc,
prims,pinfo,N,BVH::maxBuildDepthLeaf,blockSize,minLeafSize,maxLeafSize,travCost,intCost,singleThreadThreshold);
/* set bounding box to merge bounds of all time steps */
bvh->set(root,root_bounds,pinfo.size()); // FIXME: remove later
//bvh->layoutLargeNodes(pinfo.size()*0.005f); // FIXME: implement for Mblur nodes and activate
return std::make_tuple(root,root_bounds);
}
template struct BVHNBuilder<4>;
template struct BVHNBuilderQuantized<4>;
template struct BVHNBuilderMblur<4>;
#if defined(__AVX__)
template struct BVHNBuilder<8>;
template struct BVHNBuilderQuantized<8>;
template struct BVHNBuilderMblur<8>;
#endif
}
}
<|endoftext|> |
<commit_before>#define QT_NO_CAST_ASCII
#define QT_NO_COMPAT
// configuredialog_p.cpp: classes internal to ConfigureDialog
// see configuredialog.cpp for details.
// my header:
#include "configuredialog_p.h"
// other KMail headers:
#include "kmidentity.h" // for IdentityList::{export,import}Data
// other kdenetwork headers: (none)
// other KDE headers:
#include <kemailsettings.h> // for IdentityEntry::fromControlCenter()
#include <kmessagebox.h>
#include <klocale.h> // for i18n
// Qt headers:
#include <qradiobutton.h>
#include <qbuttongroup.h>
#include <qlabel.h>
#include <qframe.h>
#include <qwidget.h>
#include <qlayout.h>
// used in IdentityList::{import,export}Data
static QString pipeSymbol = QString::fromLatin1("|");
//********************************************************
// Identity handling
//********************************************************
IdentityEntry IdentityEntry::fromControlCenter()
{
KEMailSettings emailSettings;
emailSettings.setProfile( emailSettings.defaultProfileName() );
return // use return optimization (saves a copy)
IdentityEntry( emailSettings.getSetting( KEMailSettings::RealName ),
emailSettings.getSetting( KEMailSettings::EmailAddress ),
emailSettings.getSetting( KEMailSettings::Organization ),
emailSettings.getSetting( KEMailSettings::ReplyToAddress ) );
}
QStringList IdentityList::names() const
{
QStringList list;
QValueListConstIterator<IdentityEntry> it = begin();
for( ; it != end() ; ++it )
list << (*it).identityName();
return list;
}
IdentityEntry & IdentityList::getByName( const QString & i )
{
QValueListIterator<IdentityEntry> it = begin();
for( ; it != end() ; ++it )
if( i == (*it).identityName() )
return (*it);
assert( 0 ); // one should throw an exception instead, but well...
}
void IdentityList::importData()
{
clear();
bool defaultIdentity = true;
QStringList identities = KMIdentity::identities();
QStringList::Iterator it = identities.begin();
for( ; it != identities.end(); ++it )
{
KMIdentity ident( *it );
ident.readConfig();
IdentityEntry entry;
entry.setIsDefault( defaultIdentity );
// only the first entry is the default one:
defaultIdentity = false;
entry.setIdentityName( ident.identity() );
entry.setFullName( ident.fullName() );
entry.setOrganization( ident.organization() );
entry.setPgpIdentity( ident.pgpIdentity() );
entry.setEmailAddress( ident.emailAddr() );
entry.setReplyToAddress( ident.replyToAddr() );
// We encode the "use output of command" case with a trailing pipe
// symbol to distinguish it from the case of a normal data file.
QString signatureFileName = ident.signatureFile();
if( signatureFileName.endsWith( pipeSymbol ) ) {
// it's a command: chop off the "|".
entry.setSignatureFileName( signatureFileName
.left( signatureFileName.length() - 1 ) );
entry.setSignatureFileIsAProgram( true );
} else {
// it's an ordinary file:
entry.setSignatureFileName( signatureFileName );
entry.setSignatureFileIsAProgram( false );
}
entry.setSignatureInlineText( ident.signatureInlineText() );
entry.setUseSignatureFile( ident.useSignatureFile() );
entry.setTransport(ident.transport());
entry.setFcc(ident.fcc());
append( entry );
}
}
void IdentityList::exportData() const
{
QStringList identityNames;
QValueListConstIterator<IdentityEntry> it = begin();
for( ; it != end() ; ++it )
{
KMIdentity ident( (*it).identityName() );
ident.setFullName( (*it).fullName() );
ident.setOrganization( (*it).organization() );
ident.setPgpIdentity( (*it).pgpIdentity().local8Bit() );
ident.setEmailAddr( (*it).emailAddress() );
ident.setReplyToAddr( (*it).replyToAddress() );
ident.setUseSignatureFile( (*it).useSignatureFile() );
// We encode the "use output of command" case with a trailing pipe
// symbol to distinguish it from the case of a normal data file.
QString signatureFileName = (*it).signatureFileName();
if ( (*it).signatureFileIsAProgram() )
signatureFileName += pipeSymbol;
ident.setSignatureFile( signatureFileName );
ident.setSignatureInlineText( (*it).signatureInlineText() );
ident.setTransport( (*it).transport() );
ident.setFcc( (*it).fcc() );
ident.writeConfig( false ); // saves the identity data
identityNames << (*it).identityName();
}
KMIdentity::saveIdentities( identityNames, false ); // writes a list of names
}
// FIXME: Add the help button again if there actually _is_ a
// help text for this dialog!
NewIdentityDialog::NewIdentityDialog( const QStringList & identities,
QWidget *parent, const char *name,
bool modal )
: KDialogBase( parent, name, modal, i18n("New Identity"),
Ok|Cancel/*|Help*/, Ok, true ), mDuplicateMode( Empty )
{
QFrame *page = makeMainWidget();
QVBoxLayout *vlay = new QVBoxLayout( page, marginHint(), spacingHint() );
QGridLayout *glay = new QGridLayout( vlay, 5, 2 );
vlay->addStretch( 1 );
// row 0: line edit with label
mLineEdit = new QLineEdit( page );
mLineEdit->setFocus();
glay->addWidget( new QLabel( mLineEdit, i18n("&New Identity:"), page ), 0, 0 );
glay->addWidget( mLineEdit, 0, 1 );
QButtonGroup *buttonGroup = new QButtonGroup( page );
buttonGroup->hide();
connect( buttonGroup, SIGNAL(clicked(int)),
this, SLOT(slotRadioClicked(int)) ); // keep track of DuplicateMode
// row 1: radio button
QRadioButton *radio = new QRadioButton( i18n("&With empty fields"), page );
radio->setChecked( true );
buttonGroup->insert( radio, Empty );
glay->addMultiCellWidget( radio, 1, 1, 0, 1 );
// row 2: radio button
radio = new QRadioButton( i18n("&Use Control Center settings"), page );
buttonGroup->insert( radio, ControlCenter );
glay->addMultiCellWidget( radio, 2, 2, 0, 1 );
// row 3: radio button
radio = new QRadioButton( i18n("&Duplicate existing identity"), page );
buttonGroup->insert( radio, ExistingEntry );
glay->addMultiCellWidget( radio, 3, 3, 0, 1 );
// row 4: combobox with existing identities and label
mComboBox = new QComboBox( false, page );
mComboBox->insertStringList( identities );
mComboBox->setEnabled( false );
QLabel *label = new QLabel( mComboBox, i18n("&Existing identities:"), page );
label->setEnabled( false );
glay->addWidget( label, 4, 0 );
glay->addWidget( mComboBox, 4, 1 );
// enable/disable combobox and label depending on the third radio
// button's state:
connect( radio, SIGNAL(toggled(bool)),
label, SLOT(setEnabled(bool)) );
connect( radio, SIGNAL(toggled(bool)),
mComboBox, SLOT(setEnabled(bool)) );
}
void NewIdentityDialog::slotOk( void )
{
QString identity = identityName().stripWhiteSpace();
if( identity.isEmpty() ) {
KMessageBox::error( this, i18n("You must specify an identity name!") );
return; // don't leave the dialog
}
for( int i=0 ; i < mComboBox->count() ; i++ )
if( identity == mComboBox->text( i ) ) {
QString message = i18n("An identity named \"%1\" already exists!\n"
"Please choose another name.").arg(identity);
KMessageBox::error( this, message );
return; // don't leave the dialog
}
accept();
}
void NewIdentityDialog::slotRadioClicked( int which )
{
assert( which == (int)Empty ||
which == (int)ControlCenter ||
which == (int)ExistingEntry );
mDuplicateMode = static_cast<DuplicateMode>( which );
}
#include "configuredialog_p.moc"
<commit_msg>make KMail compile again (missing header include)<commit_after>#define QT_NO_CAST_ASCII
#define QT_NO_COMPAT
// configuredialog_p.cpp: classes internal to ConfigureDialog
// see configuredialog.cpp for details.
// my header:
#include "configuredialog_p.h"
// other KMail headers:
#include "kmidentity.h" // for IdentityList::{export,import}Data
// other kdenetwork headers: (none)
// other KDE headers:
#include <kemailsettings.h> // for IdentityEntry::fromControlCenter()
#include <kmessagebox.h>
#include <klocale.h> // for i18n
// Qt headers:
#include <qradiobutton.h>
#include <qbuttongroup.h>
#include <qlabel.h>
#include <qframe.h>
#include <qwidget.h>
#include <qlayout.h>
// Other headers:
#include <assert.h>
// used in IdentityList::{import,export}Data
static QString pipeSymbol = QString::fromLatin1("|");
//********************************************************
// Identity handling
//********************************************************
IdentityEntry IdentityEntry::fromControlCenter()
{
KEMailSettings emailSettings;
emailSettings.setProfile( emailSettings.defaultProfileName() );
return // use return optimization (saves a copy)
IdentityEntry( emailSettings.getSetting( KEMailSettings::RealName ),
emailSettings.getSetting( KEMailSettings::EmailAddress ),
emailSettings.getSetting( KEMailSettings::Organization ),
emailSettings.getSetting( KEMailSettings::ReplyToAddress ) );
}
QStringList IdentityList::names() const
{
QStringList list;
QValueListConstIterator<IdentityEntry> it = begin();
for( ; it != end() ; ++it )
list << (*it).identityName();
return list;
}
IdentityEntry & IdentityList::getByName( const QString & i )
{
QValueListIterator<IdentityEntry> it = begin();
for( ; it != end() ; ++it )
if( i == (*it).identityName() )
return (*it);
assert( 0 ); // one should throw an exception instead, but well...
}
void IdentityList::importData()
{
clear();
bool defaultIdentity = true;
QStringList identities = KMIdentity::identities();
QStringList::Iterator it = identities.begin();
for( ; it != identities.end(); ++it )
{
KMIdentity ident( *it );
ident.readConfig();
IdentityEntry entry;
entry.setIsDefault( defaultIdentity );
// only the first entry is the default one:
defaultIdentity = false;
entry.setIdentityName( ident.identity() );
entry.setFullName( ident.fullName() );
entry.setOrganization( ident.organization() );
entry.setPgpIdentity( ident.pgpIdentity() );
entry.setEmailAddress( ident.emailAddr() );
entry.setReplyToAddress( ident.replyToAddr() );
// We encode the "use output of command" case with a trailing pipe
// symbol to distinguish it from the case of a normal data file.
QString signatureFileName = ident.signatureFile();
if( signatureFileName.endsWith( pipeSymbol ) ) {
// it's a command: chop off the "|".
entry.setSignatureFileName( signatureFileName
.left( signatureFileName.length() - 1 ) );
entry.setSignatureFileIsAProgram( true );
} else {
// it's an ordinary file:
entry.setSignatureFileName( signatureFileName );
entry.setSignatureFileIsAProgram( false );
}
entry.setSignatureInlineText( ident.signatureInlineText() );
entry.setUseSignatureFile( ident.useSignatureFile() );
entry.setTransport(ident.transport());
entry.setFcc(ident.fcc());
append( entry );
}
}
void IdentityList::exportData() const
{
QStringList identityNames;
QValueListConstIterator<IdentityEntry> it = begin();
for( ; it != end() ; ++it )
{
KMIdentity ident( (*it).identityName() );
ident.setFullName( (*it).fullName() );
ident.setOrganization( (*it).organization() );
ident.setPgpIdentity( (*it).pgpIdentity().local8Bit() );
ident.setEmailAddr( (*it).emailAddress() );
ident.setReplyToAddr( (*it).replyToAddress() );
ident.setUseSignatureFile( (*it).useSignatureFile() );
// We encode the "use output of command" case with a trailing pipe
// symbol to distinguish it from the case of a normal data file.
QString signatureFileName = (*it).signatureFileName();
if ( (*it).signatureFileIsAProgram() )
signatureFileName += pipeSymbol;
ident.setSignatureFile( signatureFileName );
ident.setSignatureInlineText( (*it).signatureInlineText() );
ident.setTransport( (*it).transport() );
ident.setFcc( (*it).fcc() );
ident.writeConfig( false ); // saves the identity data
identityNames << (*it).identityName();
}
KMIdentity::saveIdentities( identityNames, false ); // writes a list of names
}
// FIXME: Add the help button again if there actually _is_ a
// help text for this dialog!
NewIdentityDialog::NewIdentityDialog( const QStringList & identities,
QWidget *parent, const char *name,
bool modal )
: KDialogBase( parent, name, modal, i18n("New Identity"),
Ok|Cancel/*|Help*/, Ok, true ), mDuplicateMode( Empty )
{
QFrame *page = makeMainWidget();
QVBoxLayout *vlay = new QVBoxLayout( page, marginHint(), spacingHint() );
QGridLayout *glay = new QGridLayout( vlay, 5, 2 );
vlay->addStretch( 1 );
// row 0: line edit with label
mLineEdit = new QLineEdit( page );
mLineEdit->setFocus();
glay->addWidget( new QLabel( mLineEdit, i18n("&New Identity:"), page ), 0, 0 );
glay->addWidget( mLineEdit, 0, 1 );
QButtonGroup *buttonGroup = new QButtonGroup( page );
buttonGroup->hide();
connect( buttonGroup, SIGNAL(clicked(int)),
this, SLOT(slotRadioClicked(int)) ); // keep track of DuplicateMode
// row 1: radio button
QRadioButton *radio = new QRadioButton( i18n("&With empty fields"), page );
radio->setChecked( true );
buttonGroup->insert( radio, Empty );
glay->addMultiCellWidget( radio, 1, 1, 0, 1 );
// row 2: radio button
radio = new QRadioButton( i18n("&Use Control Center settings"), page );
buttonGroup->insert( radio, ControlCenter );
glay->addMultiCellWidget( radio, 2, 2, 0, 1 );
// row 3: radio button
radio = new QRadioButton( i18n("&Duplicate existing identity"), page );
buttonGroup->insert( radio, ExistingEntry );
glay->addMultiCellWidget( radio, 3, 3, 0, 1 );
// row 4: combobox with existing identities and label
mComboBox = new QComboBox( false, page );
mComboBox->insertStringList( identities );
mComboBox->setEnabled( false );
QLabel *label = new QLabel( mComboBox, i18n("&Existing identities:"), page );
label->setEnabled( false );
glay->addWidget( label, 4, 0 );
glay->addWidget( mComboBox, 4, 1 );
// enable/disable combobox and label depending on the third radio
// button's state:
connect( radio, SIGNAL(toggled(bool)),
label, SLOT(setEnabled(bool)) );
connect( radio, SIGNAL(toggled(bool)),
mComboBox, SLOT(setEnabled(bool)) );
}
void NewIdentityDialog::slotOk( void )
{
QString identity = identityName().stripWhiteSpace();
if( identity.isEmpty() ) {
KMessageBox::error( this, i18n("You must specify an identity name!") );
return; // don't leave the dialog
}
for( int i=0 ; i < mComboBox->count() ; i++ )
if( identity == mComboBox->text( i ) ) {
QString message = i18n("An identity named \"%1\" already exists!\n"
"Please choose another name.").arg(identity);
KMessageBox::error( this, message );
return; // don't leave the dialog
}
accept();
}
void NewIdentityDialog::slotRadioClicked( int which )
{
assert( which == (int)Empty ||
which == (int)ControlCenter ||
which == (int)ExistingEntry );
mDuplicateMode = static_cast<DuplicateMode>( which );
}
#include "configuredialog_p.moc"
<|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 "mitkImage.h"
#include "mitkDataNodeFactory.h"
#include "mitkImageTimeSelector.h"
#include "mitkImageGenerator.h"
#include "mitkTestingMacros.h"
#include "mitkIOUtil.h"
#include <itksys/SystemTools.hxx>
#include <fstream>
/** Global members common for all subtests */
namespace
{
std::string m_Filename;
mitk::Image::Pointer m_Image;
} // end of anonymous namespace
/** @brief Global test setup */
static void Setup( )
{
try
{
m_Image = mitk::IOUtil::LoadImage( m_Filename );
}
catch( const itk::ExceptionObject &e)
{
MITK_TEST_FAILED_MSG(<< "(Setup) Caught exception from IOUtil while loading input : " << m_Filename <<"\n")
}
}
static void Valid_AllInputTimesteps_ReturnsTrue()
{
Setup();
mitk::ImageTimeSelector::Pointer timeSelector = mitk::ImageTimeSelector::New();
timeSelector->SetInput(m_Image);
// test all timesteps
const unsigned int maxTimeStep = m_Image->GetTimeSteps();
for( unsigned int t=0; t<maxTimeStep; t++)
{
timeSelector->SetTimeNr(t);
timeSelector->Update();
mitk::Image::Pointer currentTimestepImage = timeSelector->GetOutput();
std::stringstream ss;
ss << " : Valid image in timestep " << t ;
MITK_TEST_CONDITION_REQUIRED( currentTimestepImage.IsNotNull()
, ss.str().c_str() );
}
}
static void Valid_ImageExpandedByTimestep_ReturnsTrue()
{
Setup();
mitk::ImageTimeSelector::Pointer timeSelector = mitk::ImageTimeSelector::New();
const unsigned int maxTimeStep = m_Image->GetTimeSteps();
mitk::TimeGeometry* tsg = m_Image->GetTimeGeometry();
mitk::ProportionalTimeGeometry* ptg = dynamic_cast<mitk::ProportionalTimeGeometry*>(tsg);
ptg->Expand(maxTimeStep+1);
ptg->SetTimeStepGeometry( ptg->GetGeometryForTimeStep(0), maxTimeStep );
mitk::Image::Pointer expandedImage = mitk::Image::New();
expandedImage->Initialize( m_Image->GetPixelType(0), *tsg );
timeSelector->SetInput(expandedImage);
for( unsigned int t=0; t<maxTimeStep+1; t++)
{
timeSelector->SetTimeNr(t);
timeSelector->Update();
mitk::Image::Pointer currentTimestepImage = timeSelector->GetOutput();
std::stringstream ss;
ss << " : Valid image in timestep " << t ;
MITK_TEST_CONDITION_REQUIRED( currentTimestepImage.IsNotNull()
, ss.str().c_str() );
}
}
int mitkImageTimeSelectorTest(int argc, char* argv[])
{
MITK_TEST_BEGIN(mitkImageTimeSelectorTest);
m_Filename = std::string( argv[1] );
Valid_AllInputTimesteps_ReturnsTrue();
Valid_ImageExpandedByTimestep_ReturnsTrue();
MITK_TEST_END();
}
<commit_msg>COMP: Use unused local variable<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 "mitkImage.h"
#include "mitkDataNodeFactory.h"
#include "mitkImageTimeSelector.h"
#include "mitkImageGenerator.h"
#include "mitkTestingMacros.h"
#include "mitkIOUtil.h"
#include <itksys/SystemTools.hxx>
#include <fstream>
/** Global members common for all subtests */
namespace
{
std::string m_Filename;
mitk::Image::Pointer m_Image;
} // end of anonymous namespace
/** @brief Global test setup */
static void Setup( )
{
try
{
m_Image = mitk::IOUtil::LoadImage( m_Filename );
}
catch( const itk::ExceptionObject &e)
{
MITK_TEST_FAILED_MSG(<< "(Setup) Caught exception from IOUtil while loading input : " << m_Filename <<"\n" << e.what())
}
}
static void Valid_AllInputTimesteps_ReturnsTrue()
{
Setup();
mitk::ImageTimeSelector::Pointer timeSelector = mitk::ImageTimeSelector::New();
timeSelector->SetInput(m_Image);
// test all timesteps
const unsigned int maxTimeStep = m_Image->GetTimeSteps();
for( unsigned int t=0; t<maxTimeStep; t++)
{
timeSelector->SetTimeNr(t);
timeSelector->Update();
mitk::Image::Pointer currentTimestepImage = timeSelector->GetOutput();
std::stringstream ss;
ss << " : Valid image in timestep " << t ;
MITK_TEST_CONDITION_REQUIRED( currentTimestepImage.IsNotNull()
, ss.str().c_str() );
}
}
static void Valid_ImageExpandedByTimestep_ReturnsTrue()
{
Setup();
mitk::ImageTimeSelector::Pointer timeSelector = mitk::ImageTimeSelector::New();
const unsigned int maxTimeStep = m_Image->GetTimeSteps();
mitk::TimeGeometry* tsg = m_Image->GetTimeGeometry();
mitk::ProportionalTimeGeometry* ptg = dynamic_cast<mitk::ProportionalTimeGeometry*>(tsg);
ptg->Expand(maxTimeStep+1);
ptg->SetTimeStepGeometry( ptg->GetGeometryForTimeStep(0), maxTimeStep );
mitk::Image::Pointer expandedImage = mitk::Image::New();
expandedImage->Initialize( m_Image->GetPixelType(0), *tsg );
timeSelector->SetInput(expandedImage);
for( unsigned int t=0; t<maxTimeStep+1; t++)
{
timeSelector->SetTimeNr(t);
timeSelector->Update();
mitk::Image::Pointer currentTimestepImage = timeSelector->GetOutput();
std::stringstream ss;
ss << " : Valid image in timestep " << t ;
MITK_TEST_CONDITION_REQUIRED( currentTimestepImage.IsNotNull()
, ss.str().c_str() );
}
}
int mitkImageTimeSelectorTest(int argc, char* argv[])
{
MITK_TEST_BEGIN(mitkImageTimeSelectorTest);
m_Filename = std::string( argv[1] );
Valid_AllInputTimesteps_ReturnsTrue();
Valid_ImageExpandedByTimestep_ReturnsTrue();
MITK_TEST_END();
}
<|endoftext|> |
<commit_before>#include "csettings.h"
#include "qmessagebox.h"
#include "qfiledialog.h"
#include <QtGui>
#include "mdichild.h"
#define WIDGET(t,f) ((t*)findChild<t *>(#f))
QString stripFileExtension(QString fileName)
{
int idx;
for (idx=fileName.length();idx >=0 ; idx --)
{
if(fileName.mid(idx,1)==".")
break;
}
return fileName.left(idx);
}
char* graph_reader( char * str, int num, FILE * stream ) //helper function to load / parse graphs from tstring
{
CFrmSettings* s=reinterpret_cast<CFrmSettings*>(stream); //as ugly as it gets :)
if (s->cur >= strlen(s->graphData.toUtf8().constData()))
return NULL;
strcpy(str,(char*)s->graphData.mid(s->cur,num).toUtf8().constData());
s->cur=s->cur+num;
return str;
}
CFrmSettings::CFrmSettings()
{
aginit();
this->gvc=gvContext();
Ui_Dialog tempDia;
tempDia.setupUi(this);
graph=NULL;
connect(WIDGET(QPushButton,pbAdd),SIGNAL(clicked()),this,SLOT(addSlot()));
connect(WIDGET(QPushButton,pbNew),SIGNAL(clicked()),this,SLOT(newSlot()));
connect(WIDGET(QPushButton,pbOpen),SIGNAL(clicked()),this,SLOT(openSlot()));
connect(WIDGET(QPushButton,pbSave),SIGNAL(clicked()),this,SLOT(saveSlot()));
connect(WIDGET(QPushButton,btnOK),SIGNAL(clicked()),this,SLOT(okSlot()));
connect(WIDGET(QPushButton,pbOut),SIGNAL(clicked()),this,SLOT(outputSlot()));
}
void CFrmSettings::outputSlot()
{
QString _filter="Output File(*."+WIDGET(QComboBox,cbExtension)->currentText()+")";
QString fileName = QFileDialog::getSaveFileName(this, tr("Save Graph As.."),"/",_filter);
if (!fileName.isEmpty())
WIDGET(QLineEdit,leOutput)->setText(fileName);
}
void CFrmSettings::addSlot()
{
QString _scope=WIDGET (QComboBox,cbScope)->currentText();
QString _name=WIDGET (QComboBox,cbName)->currentText();
QString _value=WIDGET(QLineEdit,leValue)->text();
if (_value.trimmed().length() == 0)
QMessageBox::warning(this, tr("GvEdit"),tr("Please enter a value for selected attribute!"),QMessageBox::Ok,QMessageBox::Ok);
else
{
QString str=_scope+"["+_name+"=\"";
if(WIDGET (QTextEdit,teAttributes)->toPlainText().contains(str))
{
QMessageBox::warning(this, tr("GvEdit"),tr("Attribute is already defined!"),QMessageBox::Ok,QMessageBox::Ok);
return;
}
else
{
str = str + _value+"\"]";
WIDGET (QTextEdit,teAttributes)->setPlainText(WIDGET (QTextEdit,teAttributes)->toPlainText()+str+"\n");
}
}
}
void CFrmSettings::helpSlot(){}
void CFrmSettings::cancelSlot(){}
void CFrmSettings::okSlot()
{
saveContent();
this->done(drawGraph());
}
void CFrmSettings::newSlot()
{
WIDGET (QTextEdit,teAttributes)->setPlainText(tr(""));
}
void CFrmSettings::openSlot()
{
QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),"/",tr("Text file (*.*)"));
if (!fileName.isEmpty())
{
QFile file(fileName);
if (!file.open(QFile::ReadOnly | QFile::Text)) {
QMessageBox::warning(this, tr("MDI"),
tr("Cannot read file %1:\n%2.")
.arg(fileName)
.arg(file.errorString()));
return;
}
QTextStream in(&file);
WIDGET (QTextEdit,teAttributes)->setPlainText(in.readAll());
}
}
void CFrmSettings::saveSlot(){
if(WIDGET (QTextEdit,teAttributes)->toPlainText().trimmed().length()==0)
{
QMessageBox::warning(this, tr("GvEdit"),tr("Nothing to save!"),QMessageBox::Ok,QMessageBox::Ok);
return;
}
QString fileName = QFileDialog::getSaveFileName(this, tr("Open File"),
"/",
tr("Text File(*.*)"));
if (!fileName.isEmpty())
{
QFile file(fileName);
if (!file.open(QFile::WriteOnly | QFile::Text)) {
QMessageBox::warning(this, tr("MDI"),
tr("Cannot write file %1:\n%2.")
.arg(fileName)
.arg(file.errorString()));
return;
}
QTextStream out(&file);
out << WIDGET (QTextEdit,teAttributes)->toPlainText();
return;
}
}
QString CFrmSettings::buildOutputFile(QString _fileName)
{
return QString("sfsdfdf");
}
void CFrmSettings::addAttribute(QString _scope,QString _name,QString _value){}
bool CFrmSettings::loadGraph(MdiChild* m)
{
cur=0;
if(graph)
agclose(graph);
graphData.clear();
graphData.append(m->toPlainText());
setActiveWindow(m);
return true;
}
bool CFrmSettings::createLayout()
{
//first attach attributes to graph
int _pos=graphData.indexOf(tr("{"));
graphData.replace(_pos,1,"{"+WIDGET(QTextEdit,teAttributes)->toPlainText());
graph=agread_usergets(reinterpret_cast<FILE*>(this),(gets_f)graph_reader);
if(!graph)
return false;
Agraph_t* G=this->graph;
gvLayout (gvc, G, (char*)WIDGET(QComboBox,cbLayout)->currentText().toUtf8().constData()); /* library function */
return true;
}
bool CFrmSettings::renderLayout()
{
if(graph)
{
QString _fileName(WIDGET(QLineEdit,leOutput)->text());
_fileName=stripFileExtension(_fileName);
_fileName=_fileName+"."+WIDGET(QComboBox,cbExtension)->currentText();
int rv=gvRenderFilename(gvc,graph,(char*)WIDGET(QComboBox,cbExtension)->currentText().toUtf8().constData(),(char*)_fileName.toUtf8().constData());
this->getActiveWindow()->loadPreview(_fileName);
if(rv)
this->getActiveWindow()->loadPreview(_fileName);
return rv;
}
return false;
}
bool CFrmSettings::loadLayouts()
{
return false;
}
bool CFrmSettings::loadRenderers()
{
return false;
}
void CFrmSettings::refreshContent()
{
WIDGET(QComboBox,cbLayout)->setCurrentIndex(activeWindow->layoutIdx);
WIDGET(QComboBox,cbExtension)->setCurrentIndex(activeWindow->renderIdx);
if(!activeWindow->outputFile.isEmpty())
WIDGET(QLineEdit,leOutput)->setText(activeWindow->outputFile);
else
WIDGET(QLineEdit,leOutput)->setText(stripFileExtension(activeWindow->currentFile())+ "."+WIDGET(QComboBox,cbExtension)->currentText());
WIDGET(QTextEdit,teAttributes)->setText(activeWindow->attributes);
WIDGET(QCheckBox,chbPreview)->setChecked(activeWindow->preview);
WIDGET(QCheckBox,chbCairo)->setChecked(activeWindow->applyCairo);
WIDGET(QLineEdit,leValue)->setText("");
}
void CFrmSettings::saveContent()
{
activeWindow->layoutIdx=WIDGET(QComboBox,cbLayout)->currentIndex();
activeWindow->renderIdx=WIDGET(QComboBox,cbExtension)->currentIndex();
activeWindow->outputFile=WIDGET(QLineEdit,leOutput)->text();
activeWindow->attributes=WIDGET(QTextEdit,teAttributes)->toPlainText();
activeWindow->preview= WIDGET(QCheckBox,chbPreview)->isChecked();
activeWindow->applyCairo= WIDGET(QCheckBox,chbCairo)->isChecked();
}
int CFrmSettings::drawGraph()
{
createLayout();
renderLayout();
return QDialog::Accepted;
}
int CFrmSettings::runSettings(MdiChild* m)
{
if ((m) && (m==getActiveWindow()))
{
if(this->loadGraph(m))
return drawGraph();
else
return QDialog::Rejected;
}
else
return showSettings(m);
}
int CFrmSettings::showSettings(MdiChild* m)
{
if(this->loadGraph(m))
{
refreshContent();
return this->exec();
}
else
return QDialog::Rejected;
}
void CFrmSettings::setActiveWindow(MdiChild* m)
{
this->activeWindow=m;
}
MdiChild* CFrmSettings::getActiveWindow()
{
return activeWindow;
}
<commit_msg>Put in call to reset line numbers before parsing<commit_after>#include "csettings.h"
#include "qmessagebox.h"
#include "qfiledialog.h"
#include <QtGui>
#include "mdichild.h"
#define WIDGET(t,f) ((t*)findChild<t *>(#f))
QString stripFileExtension(QString fileName)
{
int idx;
for (idx=fileName.length();idx >=0 ; idx --)
{
if(fileName.mid(idx,1)==".")
break;
}
return fileName.left(idx);
}
char* graph_reader( char * str, int num, FILE * stream ) //helper function to load / parse graphs from tstring
{
CFrmSettings* s=reinterpret_cast<CFrmSettings*>(stream); //as ugly as it gets :)
if (s->cur >= strlen(s->graphData.toUtf8().constData()))
return NULL;
strcpy(str,(char*)s->graphData.mid(s->cur,num).toUtf8().constData());
s->cur=s->cur+num;
return str;
}
CFrmSettings::CFrmSettings()
{
aginit();
this->gvc=gvContext();
Ui_Dialog tempDia;
tempDia.setupUi(this);
graph=NULL;
connect(WIDGET(QPushButton,pbAdd),SIGNAL(clicked()),this,SLOT(addSlot()));
connect(WIDGET(QPushButton,pbNew),SIGNAL(clicked()),this,SLOT(newSlot()));
connect(WIDGET(QPushButton,pbOpen),SIGNAL(clicked()),this,SLOT(openSlot()));
connect(WIDGET(QPushButton,pbSave),SIGNAL(clicked()),this,SLOT(saveSlot()));
connect(WIDGET(QPushButton,btnOK),SIGNAL(clicked()),this,SLOT(okSlot()));
connect(WIDGET(QPushButton,pbOut),SIGNAL(clicked()),this,SLOT(outputSlot()));
}
void CFrmSettings::outputSlot()
{
QString _filter="Output File(*."+WIDGET(QComboBox,cbExtension)->currentText()+")";
QString fileName = QFileDialog::getSaveFileName(this, tr("Save Graph As.."),"/",_filter);
if (!fileName.isEmpty())
WIDGET(QLineEdit,leOutput)->setText(fileName);
}
void CFrmSettings::addSlot()
{
QString _scope=WIDGET (QComboBox,cbScope)->currentText();
QString _name=WIDGET (QComboBox,cbName)->currentText();
QString _value=WIDGET(QLineEdit,leValue)->text();
if (_value.trimmed().length() == 0)
QMessageBox::warning(this, tr("GvEdit"),tr("Please enter a value for selected attribute!"),QMessageBox::Ok,QMessageBox::Ok);
else
{
QString str=_scope+"["+_name+"=\"";
if(WIDGET (QTextEdit,teAttributes)->toPlainText().contains(str))
{
QMessageBox::warning(this, tr("GvEdit"),tr("Attribute is already defined!"),QMessageBox::Ok,QMessageBox::Ok);
return;
}
else
{
str = str + _value+"\"]";
WIDGET (QTextEdit,teAttributes)->setPlainText(WIDGET (QTextEdit,teAttributes)->toPlainText()+str+"\n");
}
}
}
void CFrmSettings::helpSlot(){}
void CFrmSettings::cancelSlot(){}
void CFrmSettings::okSlot()
{
saveContent();
this->done(drawGraph());
}
void CFrmSettings::newSlot()
{
WIDGET (QTextEdit,teAttributes)->setPlainText(tr(""));
}
void CFrmSettings::openSlot()
{
QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),"/",tr("Text file (*.*)"));
if (!fileName.isEmpty())
{
QFile file(fileName);
if (!file.open(QFile::ReadOnly | QFile::Text)) {
QMessageBox::warning(this, tr("MDI"),
tr("Cannot read file %1:\n%2.")
.arg(fileName)
.arg(file.errorString()));
return;
}
QTextStream in(&file);
WIDGET (QTextEdit,teAttributes)->setPlainText(in.readAll());
}
}
void CFrmSettings::saveSlot(){
if(WIDGET (QTextEdit,teAttributes)->toPlainText().trimmed().length()==0)
{
QMessageBox::warning(this, tr("GvEdit"),tr("Nothing to save!"),QMessageBox::Ok,QMessageBox::Ok);
return;
}
QString fileName = QFileDialog::getSaveFileName(this, tr("Open File"),
"/",
tr("Text File(*.*)"));
if (!fileName.isEmpty())
{
QFile file(fileName);
if (!file.open(QFile::WriteOnly | QFile::Text)) {
QMessageBox::warning(this, tr("MDI"),
tr("Cannot write file %1:\n%2.")
.arg(fileName)
.arg(file.errorString()));
return;
}
QTextStream out(&file);
out << WIDGET (QTextEdit,teAttributes)->toPlainText();
return;
}
}
QString CFrmSettings::buildOutputFile(QString _fileName)
{
return QString("sfsdfdf");
}
void CFrmSettings::addAttribute(QString _scope,QString _name,QString _value){}
bool CFrmSettings::loadGraph(MdiChild* m)
{
cur=0;
if(graph)
agclose(graph);
graphData.clear();
graphData.append(m->toPlainText());
setActiveWindow(m);
return true;
}
bool CFrmSettings::createLayout()
{
//first attach attributes to graph
int _pos=graphData.indexOf(tr("{"));
graphData.replace(_pos,1,"{"+WIDGET(QTextEdit,teAttributes)->toPlainText());
/* Reset line number and file name;
* If known, might want to use real name
*/
agsetfile("<gvedit>");
graph=agread_usergets(reinterpret_cast<FILE*>(this),(gets_f)graph_reader);
if(!graph)
return false;
Agraph_t* G=this->graph;
gvLayout (gvc, G, (char*)WIDGET(QComboBox,cbLayout)->currentText().toUtf8().constData()); /* library function */
return true;
}
bool CFrmSettings::renderLayout()
{
if(graph)
{
QString _fileName(WIDGET(QLineEdit,leOutput)->text());
_fileName=stripFileExtension(_fileName);
_fileName=_fileName+"."+WIDGET(QComboBox,cbExtension)->currentText();
int rv=gvRenderFilename(gvc,graph,(char*)WIDGET(QComboBox,cbExtension)->currentText().toUtf8().constData(),(char*)_fileName.toUtf8().constData());
this->getActiveWindow()->loadPreview(_fileName);
if(rv)
this->getActiveWindow()->loadPreview(_fileName);
return rv;
}
return false;
}
bool CFrmSettings::loadLayouts()
{
return false;
}
bool CFrmSettings::loadRenderers()
{
return false;
}
void CFrmSettings::refreshContent()
{
WIDGET(QComboBox,cbLayout)->setCurrentIndex(activeWindow->layoutIdx);
WIDGET(QComboBox,cbExtension)->setCurrentIndex(activeWindow->renderIdx);
if(!activeWindow->outputFile.isEmpty())
WIDGET(QLineEdit,leOutput)->setText(activeWindow->outputFile);
else
WIDGET(QLineEdit,leOutput)->setText(stripFileExtension(activeWindow->currentFile())+ "."+WIDGET(QComboBox,cbExtension)->currentText());
WIDGET(QTextEdit,teAttributes)->setText(activeWindow->attributes);
WIDGET(QCheckBox,chbPreview)->setChecked(activeWindow->preview);
WIDGET(QCheckBox,chbCairo)->setChecked(activeWindow->applyCairo);
WIDGET(QLineEdit,leValue)->setText("");
}
void CFrmSettings::saveContent()
{
activeWindow->layoutIdx=WIDGET(QComboBox,cbLayout)->currentIndex();
activeWindow->renderIdx=WIDGET(QComboBox,cbExtension)->currentIndex();
activeWindow->outputFile=WIDGET(QLineEdit,leOutput)->text();
activeWindow->attributes=WIDGET(QTextEdit,teAttributes)->toPlainText();
activeWindow->preview= WIDGET(QCheckBox,chbPreview)->isChecked();
activeWindow->applyCairo= WIDGET(QCheckBox,chbCairo)->isChecked();
}
int CFrmSettings::drawGraph()
{
createLayout();
renderLayout();
return QDialog::Accepted;
}
int CFrmSettings::runSettings(MdiChild* m)
{
if ((m) && (m==getActiveWindow()))
{
if(this->loadGraph(m))
return drawGraph();
else
return QDialog::Rejected;
}
else
return showSettings(m);
}
int CFrmSettings::showSettings(MdiChild* m)
{
if(this->loadGraph(m))
{
refreshContent();
return this->exec();
}
else
return QDialog::Rejected;
}
void CFrmSettings::setActiveWindow(MdiChild* m)
{
this->activeWindow=m;
}
MdiChild* CFrmSettings::getActiveWindow()
{
return activeWindow;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkHyperTreeFractalSource.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/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 notice for more information.
=========================================================================*/
#include "vtkHyperTreeFractalSource.h"
#include "vtkHyperTreeGrid.h"
#include "vtkHyperTreeCursor.h"
#include "vtkObjectFactory.h"
#include "vtkInformationVector.h"
#include "vtkInformation.h"
#include <assert.h>
#include "vtkMath.h"
#include "vtkPointData.h"
#include "vtkDataArray.h"
#include "vtkUnsignedCharArray.h"
#include "vtkDoubleArray.h"
#include "vtkGarbageCollector.h"
vtkStandardNewMacro(vtkHyperTreeFractalSource);
//----------------------------------------------------------------------------
vtkHyperTreeFractalSource::vtkHyperTreeFractalSource()
{
this->GridSize[0] = 1;
this->GridSize[1] = 1;
this->GridSize[2] = 1;
this->AxisBranchFactor = 2;
this->MaximumLevel = 1;
this->Dimension = 3;
this->Dual = false;
}
//----------------------------------------------------------------------------
vtkHyperTreeFractalSource::~vtkHyperTreeFractalSource()
{
}
//----------------------------------------------------------------------------
vtkHyperTreeGrid* vtkHyperTreeFractalSource::NewHyperTreeGrid()
{
// Instantiate hyper tree grid
vtkHyperTreeGrid* output = vtkHyperTreeGrid::New();
output->SetGridSize( this->GridSize );
output->SetDimension( this->Dimension );
output->SetAxisBranchFactor( this->AxisBranchFactor );
// Per-axis scaling
double scale[3];
scale[0] = 1.5;
scale[1] = 1.;
scale[2] = .7;
// Create geometry
for ( int i = 0; i < 3; ++ i )
{
vtkDoubleArray *coords = vtkDoubleArray::New();
int n = this->GridSize[i] + 1;
coords->SetNumberOfValues( n );
for ( int j = 0; j < n; ++ j )
{
coords->SetValue( j, scale[i] * static_cast<double>( j ) );
}
if ( i == 0 )
{
output->SetXCoordinates( coords );
}
else if ( i == 1 )
{
output->SetYCoordinates( coords );
}
else // i must be 2 here
{
output->SetZCoordinates( coords );
}
// Clean up
coords->Delete();
}
vtkDoubleArray *scalars = vtkDoubleArray::New();
scalars->SetNumberOfComponents( 1 );
vtkIdType fact = 1;
for ( int i = 1; i < this->MaximumLevel; ++ i )
{
fact *= this->AxisBranchFactor;
}
scalars->Allocate( fact * fact );
scalars->SetName( "Test" );
output->GetLeafData()->SetScalars( scalars );
scalars->UnRegister( this );
int n[3];
output->GetGridSize( n );
for ( int i = 0; i < n[0]; ++ i )
{
for ( int j = 0; j < n[1]; ++ j )
{
for ( int k = 0; k < n[2]; ++ k )
{
int index = ( k * this->GridSize[1] + j ) * this->GridSize[0] + i;
vtkHyperTreeCursor* cursor = output->NewCellCursor( i, j, k );
cursor->ToRoot();
int idx[3];
idx[0] = idx[1] = idx[2] = 0;
int offset = output->GetLeafData()->GetScalars()->GetNumberOfTuples();
this->Subdivide( cursor, 1, output, index, idx, offset );
cursor->UnRegister( this );
} // k
} // j
} // i
output->SetDualGridFlag( this->Dual );
scalars->Squeeze();
assert("post: dataset_and_data_size_match" && output->CheckAttributes()==0);
return output;
}
//----------------------------------------------------------------------------
void vtkHyperTreeFractalSource::Subdivide( vtkHyperTreeCursor* cursor,
int level,
vtkHyperTreeGrid* output,
int index,
int idx[3],
int offset )
{
// Determine whether to subdivide.
int subdivide = 1;
if ( idx[0] || idx[1] || idx[2] )
{
subdivide = 0;
}
if ( ! index && idx[1] == 1 && ! idx[2] )
{
subdivide = 1;
}
// Check for hard coded minimum and maximum level restrictions.
if ( level >= this->MaximumLevel )
{
subdivide = 0;
}
if ( subdivide )
{
output->SubdivideLeaf( cursor, index );
// Now traverse to children.
int xDim, yDim, zDim;
xDim = yDim = zDim = 1;
if ( this->Dimension == 1 )
{
xDim = this->AxisBranchFactor;
}
else if ( this->Dimension == 2 )
{
xDim = yDim = this->AxisBranchFactor;
}
else if ( this->Dimension == 3 )
{
xDim = yDim = zDim = this->AxisBranchFactor;
}
int childIdx = 0;
int newIdx[3];
for ( int z = 0; z < zDim; ++ z )
{
newIdx[2] = idx[2] * zDim + z;
for ( int y = 0; y < yDim; ++ y )
{
newIdx[1] = idx[1] * yDim + y;
for ( int x = 0; x < xDim; ++ x )
{
newIdx[0] = idx[0] * xDim + x;
cursor->ToChild(childIdx);
this->Subdivide( cursor,
level + 1,
output,
index,
newIdx,
offset );
cursor->ToParent();
++ childIdx;
}
}
}
}
else
{
// Cell value
float val = idx[0] + idx[1] + idx[2];
// Offset cell index as needed
vtkIdType id = offset + cursor->GetLeafId();
output->GetLeafData()->GetScalars()->InsertTuple1( id, val );
}
}
//-----------------------------------------------------------------------------
void vtkHyperTreeFractalSource::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
}
<commit_msg>Header clean up and reorg<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkHyperTreeFractalSource.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/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 notice for more information.
=========================================================================*/
#include "vtkHyperTreeFractalSource.h"
#include "vtkObjectFactory.h"
#include "vtkDataArray.h"
#include "vtkDoubleArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkHyperTreeCursor.h"
#include "vtkHyperTreeGrid.h"
#include "vtkMath.h"
#include "vtkPointData.h"
#include "vtkSmartPointer.h"
#include "vtkUnsignedCharArray.h"
#include <assert.h>
vtkStandardNewMacro(vtkHyperTreeFractalSource);
//----------------------------------------------------------------------------
vtkHyperTreeFractalSource::vtkHyperTreeFractalSource()
{
this->GridSize[0] = 1;
this->GridSize[1] = 1;
this->GridSize[2] = 1;
this->AxisBranchFactor = 2;
this->MaximumLevel = 1;
this->Dimension = 3;
this->Dual = false;
}
//----------------------------------------------------------------------------
vtkHyperTreeFractalSource::~vtkHyperTreeFractalSource()
{
}
//----------------------------------------------------------------------------
vtkHyperTreeGrid* vtkHyperTreeFractalSource::NewHyperTreeGrid()
{
// Instantiate hyper tree grid
vtkHyperTreeGrid* output = vtkHyperTreeGrid::New();
// Set grid parameters
output->SetGridSize( this->GridSize );
output->SetDimension( this->Dimension );
output->SetAxisBranchFactor( this->AxisBranchFactor );
// Per-axis scaling
double scale[3];
scale[0] = 1.5;
scale[1] = 1.;
scale[2] = .7;
// Create geometry
for ( int i = 0; i < 3; ++ i )
{
vtkDoubleArray *coords = vtkDoubleArray::New();
int n = this->GridSize[i] + 1;
coords->SetNumberOfValues( n );
for ( int j = 0; j < n; ++ j )
{
coords->SetValue( j, scale[i] * static_cast<double>( j ) );
}
if ( i == 0 )
{
output->SetXCoordinates( coords );
}
else if ( i == 1 )
{
output->SetYCoordinates( coords );
}
else // i must be 2 here
{
output->SetZCoordinates( coords );
}
// Clean up
coords->Delete();
}
vtkDoubleArray *scalars = vtkDoubleArray::New();
scalars->SetNumberOfComponents( 1 );
vtkIdType fact = 1;
for ( int i = 1; i < this->MaximumLevel; ++ i )
{
fact *= this->AxisBranchFactor;
}
scalars->Allocate( fact * fact );
scalars->SetName( "Test" );
output->GetLeafData()->SetScalars( scalars );
scalars->UnRegister( this );
int n[3];
output->GetGridSize( n );
for ( int i = 0; i < n[0]; ++ i )
{
for ( int j = 0; j < n[1]; ++ j )
{
for ( int k = 0; k < n[2]; ++ k )
{
int index = ( k * this->GridSize[1] + j ) * this->GridSize[0] + i;
vtkHyperTreeCursor* cursor = output->NewCellCursor( i, j, k );
cursor->ToRoot();
int idx[3];
idx[0] = idx[1] = idx[2] = 0;
int offset = output->GetLeafData()->GetScalars()->GetNumberOfTuples();
this->Subdivide( cursor, 1, output, index, idx, offset );
cursor->UnRegister( this );
} // k
} // j
} // i
output->SetDualGridFlag( this->Dual );
scalars->Squeeze();
assert("post: dataset_and_data_size_match" && output->CheckAttributes()==0);
return output;
}
//----------------------------------------------------------------------------
void vtkHyperTreeFractalSource::Subdivide( vtkHyperTreeCursor* cursor,
int level,
vtkHyperTreeGrid* output,
int index,
int idx[3],
int offset )
{
// Determine whether to subdivide.
int subdivide = 1;
if ( idx[0] || idx[1] || idx[2] )
{
subdivide = 0;
}
if ( ! index && idx[1] == 1 && ! idx[2] )
{
subdivide = 1;
}
// Check for hard coded minimum and maximum level restrictions.
if ( level >= this->MaximumLevel )
{
subdivide = 0;
}
if ( subdivide )
{
output->SubdivideLeaf( cursor, index );
// Now traverse to children.
int xDim, yDim, zDim;
xDim = yDim = zDim = 1;
if ( this->Dimension == 1 )
{
xDim = this->AxisBranchFactor;
}
else if ( this->Dimension == 2 )
{
xDim = yDim = this->AxisBranchFactor;
}
else if ( this->Dimension == 3 )
{
xDim = yDim = zDim = this->AxisBranchFactor;
}
int childIdx = 0;
int newIdx[3];
for ( int z = 0; z < zDim; ++ z )
{
newIdx[2] = idx[2] * zDim + z;
for ( int y = 0; y < yDim; ++ y )
{
newIdx[1] = idx[1] * yDim + y;
for ( int x = 0; x < xDim; ++ x )
{
newIdx[0] = idx[0] * xDim + x;
cursor->ToChild(childIdx);
this->Subdivide( cursor,
level + 1,
output,
index,
newIdx,
offset );
cursor->ToParent();
++ childIdx;
}
}
}
}
else
{
// Cell value
float val = idx[0] + idx[1] + idx[2];
// Offset cell index as needed
vtkIdType id = offset + cursor->GetLeafId();
output->GetLeafData()->GetScalars()->InsertTuple1( id, val );
}
}
//-----------------------------------------------------------------------------
void vtkHyperTreeFractalSource::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
}
<|endoftext|> |
<commit_before>//!
//! @file FileAccess.cc
//! @author Robert Braun <robert.braun@liu.se>
//! @date 2010-02-03
//!
//! @brief Contains the file access functions
//!
//$Id$
#include "FileAccess.h"
#include "Component.h"
#include <iostream>
#include "HopsanCore.h"
FileAccess::FileAccess()
{
//Nothing
}
FileAccess::FileAccess(string filename)
{
mFilename = filename;
}
void FileAccess::setFilename(string filename)
{
mFilename = filename;
}
ComponentSystem FileAccess::loadModel(double *startTime, double *stopTime, string *plotComponent, string *plotPort)
{
//Read from file
ifstream modelFile (mFilename.c_str());
if(!modelFile.is_open())
{
cout <<"Model file does not exist!\n";
assert(false);
//TODO: Cast an exception
}
//Necessary declarations
HopsanEssentials Hopsan;
ComponentSystem mainModel("mainModel");
typedef map<string, Component*> mapComponentType;
typedef map<string, ComponentSystem*> mapSystemType;
mapComponentType componentMap;
mapSystemType componentSystemMap;
string inputLine;
string inputWord;
while (! modelFile.eof() )
{
//Read the line
getline(modelFile,inputLine); //Read a line
stringstream inputStream(inputLine);
//Extract first word unless stream is empty
if ( inputStream >> inputWord )
{
//----------- Create New SubSystem -----------//
if ( inputWord == "SUBSYSTEM" )
{
ComponentSystem *tempComponentSystem = new ComponentSystem();
inputStream >> inputWord;
tempComponentSystem->setName(inputWord);
componentSystemMap.insert(pair<string, ComponentSystem*>(inputWord, &*tempComponentSystem));
inputStream >> inputWord;
tempComponentSystem->setTypeCQS(inputWord);
if ( inputStream >> inputWord )
{
componentSystemMap.find(inputWord)->second->addComponent(tempComponentSystem); //Subsystem belongs to other subsystem
}
else
{
mainModel.addComponent(tempComponentSystem); //Subsystem belongs to main system
}
}
//----------- Add Port To SubSystem -----------//
else if ( inputWord == "SYSTEMPORT")
{
string subSystemName, portName;Component* getComponent(string name);
inputStream >> subSystemName;
inputStream >> portName;
componentSystemMap.find(subSystemName)->second->addSystemPort(portName);
}
//----------- Create New Component -----------//
else if ( inputWord == "COMPONENT" )
{
inputStream >> inputWord;
Component *tempComponent = Hopsan.CreateComponent(inputWord);
inputStream >> inputWord;
tempComponent->setName(inputWord);
componentMap.insert(pair<string, Component*>(inputWord, &*tempComponent));
if ( inputStream >> inputWord )
{
componentSystemMap.find(inputWord)->second->addComponent(tempComponent); //Componenet belongs to subsystem
}
else
{
mainModel.addComponent(tempComponent); //Component belongs to main system
}
}
//----------- Connect Components -----------//
else if ( inputWord == "CONNECT" )
{
string firstComponent, firstPort, secondComponent, secondPort;
inputStream >> firstComponent;
inputStream >> firstPort;
inputStream >> secondComponent;
inputStream >> secondPort;
if ( componentMap.count(firstComponent) > 0 && componentMap.count(secondComponent) > 0 ) //Connecting two components
{
componentMap.find(firstComponent)->second->getSystemparent().connect(*componentMap.find(firstComponent)->second, firstPort, *componentMap.find(secondComponent)->second, secondPort);
}
else if ( componentMap.count(firstComponent) > 0 && componentSystemMap.count(secondComponent) > 0 ) //Connecting component with subsystem
{
componentMap.find(firstComponent)->second->getSystemparent().connect(*componentMap.find(firstComponent)->second, firstPort, *componentSystemMap.find(secondComponent)->second, secondPort);
}
else if ( componentSystemMap.count(firstComponent) > 0 && componentMap.count(secondComponent) > 0 ) //Connecting subsystem with component
{
componentMap.find(secondComponent)->second->getSystemparent().connect(*componentSystemMap.find(firstComponent)->second, firstPort, *componentMap.find(secondComponent)->second, secondPort);
}
else //Connecting subsystem with subsystem
{
componentMap.find(firstComponent)->second->getSystemparent().connect(*componentSystemMap.find(firstComponent)->second, firstPort, *componentSystemMap.find(secondComponent)->second, secondPort);
}
}
//Execute commands
//----------- Set Parameter Value -----------//
else if ( inputWord == "SET" )
{
string componentName, parameterName;
double parameterValue;
inputStream >> componentName;
inputStream >> parameterName;
inputStream >> parameterValue;
componentMap.find(componentName)->second->setParameter(parameterName, parameterValue);
}
//----------- Set Simulation Parameters -----------//
else if ( inputWord == "SIMULATE" )
{
double temp;
inputStream >> temp;
*startTime = temp;
inputStream >> temp;
*stopTime = temp;
}
//----------- Select Plotting Parameters -----------//
else if ( inputWord == "PLOT" )
{
inputStream >> *plotComponent;
inputStream >> *plotPort;
}
//----------- Unrecognized Command -----------//
else
{
cout << "Unidentified command in model file ignored.\n";
}
}
else
{
//cout << "Ignoring empty line.\n";
}
}
modelFile.close();
return mainModel;
}
ComponentSystem FileAccess::loadModel(string filename, double *startTime, double *stopTime, string *plotComponent, string *plotPort)
{
setFilename(filename);
return loadModel(&*startTime, &*stopTime, &*plotComponent, &*plotPort);
}
void FileAccess::saveModel(ComponentSystem mainModel)
{
//Do something here!
return;
}
<commit_msg>added #include <cassert> to FileAccess.cc<commit_after>//!
//! @file FileAccess.cc
//! @author Robert Braun <robert.braun@liu.se>
//! @date 2010-02-03
//!
//! @brief Contains the file access functions
//!
//$Id$
#include "FileAccess.h"
#include "Component.h"
#include <iostream>
#include <cassert>
#include "HopsanCore.h"
FileAccess::FileAccess()
{
//Nothing
}
FileAccess::FileAccess(string filename)
{
mFilename = filename;
}
void FileAccess::setFilename(string filename)
{
mFilename = filename;
}
ComponentSystem FileAccess::loadModel(double *startTime, double *stopTime, string *plotComponent, string *plotPort)
{
//Read from file
ifstream modelFile (mFilename.c_str());
if(!modelFile.is_open())
{
cout <<"Model file does not exist!\n";
assert(false);
//TODO: Cast an exception
}
//Necessary declarations
HopsanEssentials Hopsan;
ComponentSystem mainModel("mainModel");
typedef map<string, Component*> mapComponentType;
typedef map<string, ComponentSystem*> mapSystemType;
mapComponentType componentMap;
mapSystemType componentSystemMap;
string inputLine;
string inputWord;
while (! modelFile.eof() )
{
//Read the line
getline(modelFile,inputLine); //Read a line
stringstream inputStream(inputLine);
//Extract first word unless stream is empty
if ( inputStream >> inputWord )
{
//----------- Create New SubSystem -----------//
if ( inputWord == "SUBSYSTEM" )
{
ComponentSystem *tempComponentSystem = new ComponentSystem();
inputStream >> inputWord;
tempComponentSystem->setName(inputWord);
componentSystemMap.insert(pair<string, ComponentSystem*>(inputWord, &*tempComponentSystem));
inputStream >> inputWord;
tempComponentSystem->setTypeCQS(inputWord);
if ( inputStream >> inputWord )
{
componentSystemMap.find(inputWord)->second->addComponent(tempComponentSystem); //Subsystem belongs to other subsystem
}
else
{
mainModel.addComponent(tempComponentSystem); //Subsystem belongs to main system
}
}
//----------- Add Port To SubSystem -----------//
else if ( inputWord == "SYSTEMPORT")
{
string subSystemName, portName;Component* getComponent(string name);
inputStream >> subSystemName;
inputStream >> portName;
componentSystemMap.find(subSystemName)->second->addSystemPort(portName);
}
//----------- Create New Component -----------//
else if ( inputWord == "COMPONENT" )
{
inputStream >> inputWord;
Component *tempComponent = Hopsan.CreateComponent(inputWord);
inputStream >> inputWord;
tempComponent->setName(inputWord);
componentMap.insert(pair<string, Component*>(inputWord, &*tempComponent));
if ( inputStream >> inputWord )
{
componentSystemMap.find(inputWord)->second->addComponent(tempComponent); //Componenet belongs to subsystem
}
else
{
mainModel.addComponent(tempComponent); //Component belongs to main system
}
}
//----------- Connect Components -----------//
else if ( inputWord == "CONNECT" )
{
string firstComponent, firstPort, secondComponent, secondPort;
inputStream >> firstComponent;
inputStream >> firstPort;
inputStream >> secondComponent;
inputStream >> secondPort;
if ( componentMap.count(firstComponent) > 0 && componentMap.count(secondComponent) > 0 ) //Connecting two components
{
componentMap.find(firstComponent)->second->getSystemparent().connect(*componentMap.find(firstComponent)->second, firstPort, *componentMap.find(secondComponent)->second, secondPort);
}
else if ( componentMap.count(firstComponent) > 0 && componentSystemMap.count(secondComponent) > 0 ) //Connecting component with subsystem
{
componentMap.find(firstComponent)->second->getSystemparent().connect(*componentMap.find(firstComponent)->second, firstPort, *componentSystemMap.find(secondComponent)->second, secondPort);
}
else if ( componentSystemMap.count(firstComponent) > 0 && componentMap.count(secondComponent) > 0 ) //Connecting subsystem with component
{
componentMap.find(secondComponent)->second->getSystemparent().connect(*componentSystemMap.find(firstComponent)->second, firstPort, *componentMap.find(secondComponent)->second, secondPort);
}
else //Connecting subsystem with subsystem
{
componentMap.find(firstComponent)->second->getSystemparent().connect(*componentSystemMap.find(firstComponent)->second, firstPort, *componentSystemMap.find(secondComponent)->second, secondPort);
}
}
//Execute commands
//----------- Set Parameter Value -----------//
else if ( inputWord == "SET" )
{
string componentName, parameterName;
double parameterValue;
inputStream >> componentName;
inputStream >> parameterName;
inputStream >> parameterValue;
componentMap.find(componentName)->second->setParameter(parameterName, parameterValue);
}
//----------- Set Simulation Parameters -----------//
else if ( inputWord == "SIMULATE" )
{
double temp;
inputStream >> temp;
*startTime = temp;
inputStream >> temp;
*stopTime = temp;
}
//----------- Select Plotting Parameters -----------//
else if ( inputWord == "PLOT" )
{
inputStream >> *plotComponent;
inputStream >> *plotPort;
}
//----------- Unrecognized Command -----------//
else
{
cout << "Unidentified command in model file ignored.\n";
}
}
else
{
//cout << "Ignoring empty line.\n";
}
}
modelFile.close();
return mainModel;
}
ComponentSystem FileAccess::loadModel(string filename, double *startTime, double *stopTime, string *plotComponent, string *plotPort)
{
setFilename(filename);
return loadModel(&*startTime, &*stopTime, &*plotComponent, &*plotPort);
}
void FileAccess::saveModel(ComponentSystem mainModel)
{
//Do something here!
return;
}
<|endoftext|> |
<commit_before>/*
* SnapFind
* An interactive image search application
* Version 1
*
* Copyright (c) 2009 Carnegie Mellon University
* All Rights Reserved.
*
* This software is distributed under the terms of the Eclipse Public
* License, Version 1.0 which can be found in the file named LICENSE.
* ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS SOFTWARE CONSTITUTES
* RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT
*/
#include <cstdlib>
#include <cstdio>
#include "plugin-runner.h"
#include "factory.h"
#include "read_config.h"
static bool
sc(const char *a, const char *b) {
return strcmp(a, b) == 0;
}
void
print_key_value(const char *key,
const char *value) {
printf("K %d\n%s\n", strlen(key), key);
printf("V %d\n%s\n", strlen(value), value);
}
void
print_key_value(const char *key,
int value_len,
void *value) {
printf("K %d\n%s\n", strlen(key), key);
printf("V %d\n", value_len);
fwrite(value, value_len, 1, stdout);
printf("\n");
}
static void
print_plugin(const char *type, img_factory *imgf) {
print_key_value("type", type);
print_key_value("display-name", imgf->get_name());
print_key_value("internal-name", imgf->get_description());
printf("\n");
}
void
list_plugins(void) {
void *cookie;
img_factory *imgf;
imgf = get_first_factory(&cookie);
if (imgf != NULL) {
do {
print_plugin("filter", imgf);
} while((imgf = get_next_factory(&cookie)));
}
imgf = get_first_codec_factory(&cookie);
if (imgf != NULL) {
do {
print_plugin("codec", imgf);
} while((imgf = get_next_factory(&cookie)));
}
}
static img_search
*get_plugin(const char *type,
const char *internal_name) {
img_factory *imgf;
if (sc(type, "filter")) {
imgf = find_factory(internal_name);
} else if (sc(type, "codec")) {
imgf = find_codec_factory(internal_name);
} else {
printf("Invalid type\n");
return NULL;
}
if (!imgf) {
return NULL;
}
img_search *search = imgf->create("filter");
search->set_plugin_runner_mode(true);
search->set_searchlet_lib_path(imgf->get_searchlet_lib_path());
return search;
}
static void
print_search_config(img_search *search) {
// editable?
print_key_value("is-editable", search->is_editable() ? "true" : "false");
// print blob
print_key_value("blob", search->get_auxiliary_data_length(),
search->get_auxiliary_data());
// print config (also prints patches)
if (search->is_editable()) {
char *config;
size_t config_size;
FILE *memfile = open_memstream(&config, &config_size);
search->write_config(memfile, NULL);
fclose(memfile);
print_key_value("config", config_size, config);
free(config);
}
// print fspec
char *fspec;
size_t fspec_size;
FILE *memfile = open_memstream(&fspec, &fspec_size);
search->write_fspec(memfile);
fclose(memfile);
print_key_value("fspec", fspec_size, fspec);
free(fspec);
// print diamond files
print_key_value("searchlet-lib-path", search->get_searchlet_lib_path());
}
struct len_data {
int len;
void *data;
};
static int
expect_token_get_size(char token) {
char *line = NULL;
size_t n;
int result = -1;
int c;
// expect token
c = getchar();
// g_debug("%c", c);
if (c != token) {
goto OUT;
}
c = getchar();
// g_debug("%c", c);
if (c != ' ') {
goto OUT;
}
// read size
if (getline(&line, &n, stdin) == -1) {
goto OUT;
}
result = atoi(line);
// g_debug("size: %d", result);
OUT:
free(line);
return result;
}
static void
populate_search(img_search *search, GHashTable *user_config) {
struct len_data *ld;
// blob
ld = (struct len_data *) g_hash_table_lookup(user_config, "blob");
if (ld) {
search->set_auxiliary_data_length(ld->len);
search->set_auxiliary_data(ld->data);
}
// config
ld = (struct len_data *) g_hash_table_lookup(user_config, "config");
if (ld) {
read_search_config_for_plugin_runner(ld->data, ld->len, search);
}
}
static void
destroy_len_data(gpointer data) {
struct len_data *ld = (struct len_data *) data;
g_free(ld->data);
g_free(data);
}
static GHashTable *
read_key_value_pairs() {
GHashTable *ht = g_hash_table_new_full(g_str_hash, g_str_equal,
g_free, destroy_len_data);
while(true) {
// read key size
int keysize = expect_token_get_size('K');
if (keysize == -1) {
break;
}
// read key + \n
char *key = (char *) g_malloc(keysize + 1);
if (keysize > 0) {
if (fread(key, keysize + 1, 1, stdin) != 1) {
g_free(key);
break;
}
}
key[keysize] = '\0'; // key is a string
// read value size
int valuesize = expect_token_get_size('V');
if (valuesize == -1) {
g_free(key);
}
// read value + \n
void *value = g_malloc(valuesize);
if (valuesize > 0) {
if (fread(value, valuesize, 1, stdin) != 1) {
g_free(key);
g_free(value);
break;
}
}
getchar(); // value is not null terminated
// add entry
//fprintf(stderr, "key: %s, valuesize: %d\n", key, valuesize);
struct len_data *ld = g_new(struct len_data, 1);
ld->len = valuesize;
ld->data = value;
g_hash_table_insert(ht, key, ld);
}
return ht;
}
int
get_plugin_initial_config(const char *type,
const char *internal_name) {
img_search *search = get_plugin(type, internal_name);
if (search == NULL) {
printf("Can't find %s\n", internal_name);
return 1;
}
print_search_config(search);
return 0;
}
int
edit_plugin_config(const char *type,
const char *internal_name) {
img_search *search = get_plugin(type, internal_name);
if (search == NULL) {
printf("Can't find %s\n", internal_name);
return 1;
}
if (!search->is_editable()) {
printf("Not editable");
return 1;
}
GHashTable *user_config = read_key_value_pairs();
populate_search(search, user_config);
g_hash_table_unref(user_config);
search->edit_search();
gtk_main();
print_search_config(search);
return 0;
}
<commit_msg>Don't fail when editing a non-editable plugin<commit_after>/*
* SnapFind
* An interactive image search application
* Version 1
*
* Copyright (c) 2009 Carnegie Mellon University
* All Rights Reserved.
*
* This software is distributed under the terms of the Eclipse Public
* License, Version 1.0 which can be found in the file named LICENSE.
* ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS SOFTWARE CONSTITUTES
* RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT
*/
#include <cstdlib>
#include <cstdio>
#include "plugin-runner.h"
#include "factory.h"
#include "read_config.h"
static bool
sc(const char *a, const char *b) {
return strcmp(a, b) == 0;
}
void
print_key_value(const char *key,
const char *value) {
printf("K %d\n%s\n", strlen(key), key);
printf("V %d\n%s\n", strlen(value), value);
}
void
print_key_value(const char *key,
int value_len,
void *value) {
printf("K %d\n%s\n", strlen(key), key);
printf("V %d\n", value_len);
fwrite(value, value_len, 1, stdout);
printf("\n");
}
static void
print_plugin(const char *type, img_factory *imgf) {
print_key_value("type", type);
print_key_value("display-name", imgf->get_name());
print_key_value("internal-name", imgf->get_description());
printf("\n");
}
void
list_plugins(void) {
void *cookie;
img_factory *imgf;
imgf = get_first_factory(&cookie);
if (imgf != NULL) {
do {
print_plugin("filter", imgf);
} while((imgf = get_next_factory(&cookie)));
}
imgf = get_first_codec_factory(&cookie);
if (imgf != NULL) {
do {
print_plugin("codec", imgf);
} while((imgf = get_next_factory(&cookie)));
}
}
static img_search
*get_plugin(const char *type,
const char *internal_name) {
img_factory *imgf;
if (sc(type, "filter")) {
imgf = find_factory(internal_name);
} else if (sc(type, "codec")) {
imgf = find_codec_factory(internal_name);
} else {
printf("Invalid type\n");
return NULL;
}
if (!imgf) {
return NULL;
}
img_search *search = imgf->create("filter");
search->set_plugin_runner_mode(true);
search->set_searchlet_lib_path(imgf->get_searchlet_lib_path());
return search;
}
static void
print_search_config(img_search *search) {
// editable?
print_key_value("is-editable", search->is_editable() ? "true" : "false");
// print blob
print_key_value("blob", search->get_auxiliary_data_length(),
search->get_auxiliary_data());
// print config (also prints patches)
if (search->is_editable()) {
char *config;
size_t config_size;
FILE *memfile = open_memstream(&config, &config_size);
search->write_config(memfile, NULL);
fclose(memfile);
print_key_value("config", config_size, config);
free(config);
}
// print fspec
char *fspec;
size_t fspec_size;
FILE *memfile = open_memstream(&fspec, &fspec_size);
search->write_fspec(memfile);
fclose(memfile);
print_key_value("fspec", fspec_size, fspec);
free(fspec);
// print diamond files
print_key_value("searchlet-lib-path", search->get_searchlet_lib_path());
}
struct len_data {
int len;
void *data;
};
static int
expect_token_get_size(char token) {
char *line = NULL;
size_t n;
int result = -1;
int c;
// expect token
c = getchar();
// g_debug("%c", c);
if (c != token) {
goto OUT;
}
c = getchar();
// g_debug("%c", c);
if (c != ' ') {
goto OUT;
}
// read size
if (getline(&line, &n, stdin) == -1) {
goto OUT;
}
result = atoi(line);
// g_debug("size: %d", result);
OUT:
free(line);
return result;
}
static void
populate_search(img_search *search, GHashTable *user_config) {
struct len_data *ld;
// blob
ld = (struct len_data *) g_hash_table_lookup(user_config, "blob");
if (ld) {
search->set_auxiliary_data_length(ld->len);
search->set_auxiliary_data(ld->data);
}
// config
ld = (struct len_data *) g_hash_table_lookup(user_config, "config");
if (ld) {
read_search_config_for_plugin_runner(ld->data, ld->len, search);
}
}
static void
destroy_len_data(gpointer data) {
struct len_data *ld = (struct len_data *) data;
g_free(ld->data);
g_free(data);
}
static GHashTable *
read_key_value_pairs() {
GHashTable *ht = g_hash_table_new_full(g_str_hash, g_str_equal,
g_free, destroy_len_data);
while(true) {
// read key size
int keysize = expect_token_get_size('K');
if (keysize == -1) {
break;
}
// read key + \n
char *key = (char *) g_malloc(keysize + 1);
if (keysize > 0) {
if (fread(key, keysize + 1, 1, stdin) != 1) {
g_free(key);
break;
}
}
key[keysize] = '\0'; // key is a string
// read value size
int valuesize = expect_token_get_size('V');
if (valuesize == -1) {
g_free(key);
}
// read value + \n
void *value = g_malloc(valuesize);
if (valuesize > 0) {
if (fread(value, valuesize, 1, stdin) != 1) {
g_free(key);
g_free(value);
break;
}
}
getchar(); // value is not null terminated
// add entry
//fprintf(stderr, "key: %s, valuesize: %d\n", key, valuesize);
struct len_data *ld = g_new(struct len_data, 1);
ld->len = valuesize;
ld->data = value;
g_hash_table_insert(ht, key, ld);
}
return ht;
}
int
get_plugin_initial_config(const char *type,
const char *internal_name) {
img_search *search = get_plugin(type, internal_name);
if (search == NULL) {
printf("Can't find %s\n", internal_name);
return 1;
}
print_search_config(search);
return 0;
}
int
edit_plugin_config(const char *type,
const char *internal_name) {
img_search *search = get_plugin(type, internal_name);
if (search == NULL) {
printf("Can't find %s\n", internal_name);
return 1;
}
GHashTable *user_config = read_key_value_pairs();
populate_search(search, user_config);
g_hash_table_unref(user_config);
if (search->is_editable()) {
search->edit_search();
gtk_main();
}
print_search_config(search);
return 0;
}
<|endoftext|> |
<commit_before>#include "vtkDebugLeaks.h"
#include "vtkObjectFactory.h"
// A singleton that prints out the table, and deletes the table.
class vtkPrintLeaksAtExit
{
public:
inline void Use()
{
}
~vtkPrintLeaksAtExit()
{
vtkObjectFactory::UnRegisterAllFactories();
vtkDebugLeaks::PrintCurrentLeaks();
vtkDebugLeaks::DeleteTable();
}
};
#ifdef VTK_DEBUG_LEAKS
// the global varible that should be destroyed at exit
static vtkPrintLeaksAtExit vtkPrintLeaksAtExitGlobal;
#endif
// A hash function for converting a string to a long
inline size_t vtkHashString(const char* s)
{
unsigned long h = 0;
for ( ; *s; ++s)
h = 5*h + *s;
return size_t(h);
}
class vtkDebugLeaksHashNode
{
public:
vtkDebugLeaksHashNode()
{
count =1; // if it goes in, then there is one of them
key = 0;
next =0;
}
void Print()
{
if(this->count)
{
vtkGenericWarningMacro("Class " << this->key << " has "
<< this->count << " instances still around" );
}
}
~vtkDebugLeaksHashNode()
{
delete [] key;
}
public:
vtkDebugLeaksHashNode *next;
char *key;
int count;
};
class vtkDebugLeaksHashTable
{
public:
vtkDebugLeaksHashTable();
vtkDebugLeaksHashNode* GetNode(const char* name);
void IncrementCount(const char *name);
unsigned int GetCount(const char *name);
int DecrementCount(const char* name);
void PrintTable();
int IsEmpty();
private:
vtkDebugLeaksHashNode* nodes[64];
};
vtkDebugLeaksHashTable::vtkDebugLeaksHashTable()
{
int i;
for (i = 0; i < 64; i++)
{
this->nodes[i] = NULL;
}
}
vtkDebugLeaks* vtkDebugLeaks::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkDebugLeaks");
if(ret)
{
return (vtkDebugLeaks*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkDebugLeaks;
}
void vtkDebugLeaksHashTable::IncrementCount(const char * name)
{
vtkDebugLeaksHashNode *pos;
vtkDebugLeaksHashNode *newpos;
int loc;
pos = this->GetNode(name);
if(pos)
{
pos->count++;
return;
}
newpos = new vtkDebugLeaksHashNode;
newpos->key = strcpy(new char[strlen(name)+1], name);
loc = (((unsigned long)vtkHashString(name)) & 0x03f0) / 16;
pos = this->nodes[loc];
if (!pos)
{
this->nodes[loc] = newpos;
return;
}
while (pos->next)
{
pos = pos->next;
}
pos->next = newpos;
}
vtkDebugLeaksHashNode* vtkDebugLeaksHashTable::GetNode(const char* key)
{
vtkDebugLeaksHashNode *pos;
int loc = (((unsigned long)vtkHashString(key)) & 0x03f0) / 16;
pos = this->nodes[loc];
if (!pos)
{
return NULL;
}
while ((pos) && (strcmp(pos->key, key) != 0) )
{
pos = pos->next;
}
return pos;
}
unsigned int vtkDebugLeaksHashTable::GetCount(const char* key)
{
vtkDebugLeaksHashNode *pos;
int loc = (((unsigned long)vtkHashString(key)) & 0x03f0) / 16;
pos = this->nodes[loc];
if (!pos)
{
return 0;
}
while ((pos)&&(pos->key != key))
{
pos = pos->next;
}
if (pos)
{
return pos->count;
}
return 0;
}
int vtkDebugLeaksHashTable::IsEmpty()
{
int count = 0;
for(int i =0; i < 64; i++)
{
vtkDebugLeaksHashNode *pos = this->nodes[i];
if(pos)
{
count += pos->count;
while(pos->next)
{
pos = pos->next;
count += pos->count;
}
}
}
return !count;
}
int vtkDebugLeaksHashTable::DecrementCount(const char *key)
{
vtkDebugLeaksHashNode *pos = this->GetNode(key);
if(pos)
{
pos->count--;
return 1;
}
else
{
return 0;
}
}
void vtkDebugLeaksHashTable::PrintTable()
{
for(int i =0; i < 64; i++)
{
vtkDebugLeaksHashNode *pos = this->nodes[i];
if(pos)
{
pos->Print();
while(pos->next)
{
pos = pos->next;
pos->Print();
}
}
}
}
vtkDebugLeaksHashTable* vtkDebugLeaks::MemoryTable = 0;
void vtkDebugLeaks::ConstructClass(const char* name)
{
#ifdef VTK_DEBUG_LEAKS
// force the use of the global varible so it gets constructed
// but only do this if VTK_DEBUG_LEAKS is on
vtkPrintLeaksAtExitGlobal.Use();
#endif
if(!vtkDebugLeaks::MemoryTable)
vtkDebugLeaks::MemoryTable = new vtkDebugLeaksHashTable;
vtkDebugLeaks::MemoryTable->IncrementCount(name);
}
void vtkDebugLeaks::DestructClass(const char* p)
{
if(!vtkDebugLeaks::MemoryTable->DecrementCount(p))
{
vtkGenericWarningMacro("Deleting unknown object: " << p);
}
}
void vtkDebugLeaks::PrintCurrentLeaks()
{
if(!vtkDebugLeaks::MemoryTable)
{
return;
}
if(vtkDebugLeaks::MemoryTable->IsEmpty())
{
return;
}
vtkGenericWarningMacro("vtkDebugLeaks has detected LEAKS!\n ");
vtkDebugLeaks::MemoryTable->PrintTable();
}
void vtkDebugLeaks::DeleteTable()
{
delete vtkDebugLeaks::MemoryTable;
vtkDebugLeaks::MemoryTable = 0;
}
<commit_msg>BUG: remove segfault at exit when leaks found<commit_after>#include "vtkDebugLeaks.h"
#include "vtkObjectFactory.h"
// A singleton that prints out the table, and deletes the table.
class vtkPrintLeaksAtExit
{
public:
inline void Use()
{
}
~vtkPrintLeaksAtExit()
{
vtkObjectFactory::UnRegisterAllFactories();
vtkDebugLeaks::PrintCurrentLeaks();
vtkDebugLeaks::DeleteTable();
}
};
#ifdef VTK_DEBUG_LEAKS
// the global varible that should be destroyed at exit
static vtkPrintLeaksAtExit vtkPrintLeaksAtExitGlobal;
#endif
// A hash function for converting a string to a long
inline size_t vtkHashString(const char* s)
{
unsigned long h = 0;
for ( ; *s; ++s)
h = 5*h + *s;
return size_t(h);
}
class vtkDebugLeaksHashNode
{
public:
vtkDebugLeaksHashNode()
{
count =1; // if it goes in, then there is one of them
key = 0;
next =0;
}
void Print()
{
if(this->count)
{
vtkGenericWarningMacro("Class " << this->key << " has "
<< this->count << " instances still around" );
}
}
~vtkDebugLeaksHashNode()
{
delete [] key;
}
public:
vtkDebugLeaksHashNode *next;
char *key;
int count;
};
class vtkDebugLeaksHashTable
{
public:
vtkDebugLeaksHashTable();
vtkDebugLeaksHashNode* GetNode(const char* name);
void IncrementCount(const char *name);
unsigned int GetCount(const char *name);
int DecrementCount(const char* name);
void PrintTable();
int IsEmpty();
private:
vtkDebugLeaksHashNode* nodes[64];
};
vtkDebugLeaksHashTable::vtkDebugLeaksHashTable()
{
int i;
for (i = 0; i < 64; i++)
{
this->nodes[i] = NULL;
}
}
vtkDebugLeaks* vtkDebugLeaks::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkDebugLeaks");
if(ret)
{
return (vtkDebugLeaks*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkDebugLeaks;
}
void vtkDebugLeaksHashTable::IncrementCount(const char * name)
{
vtkDebugLeaksHashNode *pos;
vtkDebugLeaksHashNode *newpos;
int loc;
pos = this->GetNode(name);
if(pos)
{
pos->count++;
return;
}
newpos = new vtkDebugLeaksHashNode;
newpos->key = strcpy(new char[strlen(name)+1], name);
loc = (((unsigned long)vtkHashString(name)) & 0x03f0) / 16;
pos = this->nodes[loc];
if (!pos)
{
this->nodes[loc] = newpos;
return;
}
while (pos->next)
{
pos = pos->next;
}
pos->next = newpos;
}
vtkDebugLeaksHashNode* vtkDebugLeaksHashTable::GetNode(const char* key)
{
vtkDebugLeaksHashNode *pos;
int loc = (((unsigned long)vtkHashString(key)) & 0x03f0) / 16;
pos = this->nodes[loc];
if (!pos)
{
return NULL;
}
while ((pos) && (strcmp(pos->key, key) != 0) )
{
pos = pos->next;
}
return pos;
}
unsigned int vtkDebugLeaksHashTable::GetCount(const char* key)
{
vtkDebugLeaksHashNode *pos;
int loc = (((unsigned long)vtkHashString(key)) & 0x03f0) / 16;
pos = this->nodes[loc];
if (!pos)
{
return 0;
}
while ((pos)&&(pos->key != key))
{
pos = pos->next;
}
if (pos)
{
return pos->count;
}
return 0;
}
int vtkDebugLeaksHashTable::IsEmpty()
{
int count = 0;
for(int i =0; i < 64; i++)
{
vtkDebugLeaksHashNode *pos = this->nodes[i];
if(pos)
{
count += pos->count;
while(pos->next)
{
pos = pos->next;
count += pos->count;
}
}
}
return !count;
}
int vtkDebugLeaksHashTable::DecrementCount(const char *key)
{
vtkDebugLeaksHashNode *pos = this->GetNode(key);
if(pos)
{
pos->count--;
return 1;
}
else
{
return 0;
}
}
void vtkDebugLeaksHashTable::PrintTable()
{
for(int i =0; i < 64; i++)
{
vtkDebugLeaksHashNode *pos = this->nodes[i];
if(pos)
{
pos->Print();
while(pos->next)
{
pos = pos->next;
pos->Print();
}
}
}
}
vtkDebugLeaksHashTable* vtkDebugLeaks::MemoryTable = 0;
void vtkDebugLeaks::ConstructClass(const char* name)
{
#ifdef VTK_DEBUG_LEAKS
// force the use of the global varible so it gets constructed
// but only do this if VTK_DEBUG_LEAKS is on
vtkPrintLeaksAtExitGlobal.Use();
#endif
if(!vtkDebugLeaks::MemoryTable)
vtkDebugLeaks::MemoryTable = new vtkDebugLeaksHashTable;
vtkDebugLeaks::MemoryTable->IncrementCount(name);
}
void vtkDebugLeaks::DestructClass(const char* p)
{
// Due to globals being deleted, this table may already have
// been deleted.
if(vtkDebugLeaks::MemoryTable)
{
if(!vtkDebugLeaks::MemoryTable->DecrementCount(p))
{
vtkGenericWarningMacro("Deleting unknown object: " << p);
}
}
}
void vtkDebugLeaks::PrintCurrentLeaks()
{
if(!vtkDebugLeaks::MemoryTable)
{
return;
}
if(vtkDebugLeaks::MemoryTable->IsEmpty())
{
return;
}
vtkGenericWarningMacro("vtkDebugLeaks has detected LEAKS!\n ");
vtkDebugLeaks::MemoryTable->PrintTable();
}
void vtkDebugLeaks::DeleteTable()
{
delete vtkDebugLeaks::MemoryTable;
vtkDebugLeaks::MemoryTable = 0;
}
<|endoftext|> |
<commit_before>// Copyright (c)2008-2011, Preferred Infrastructure 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 Preferred Infrastructure nor the names of other
// 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 <gtest/gtest.h>
#include "time_util.h"
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <unistd.h>
using namespace pfi::system::time;
using namespace std;
class time_util : public testing::TestWithParam<const char *> {
protected:
void SetUp() {
has_tz_ = false;
char *tz = getenv("TZ");
// NOTE: null != empty
if (tz) {
has_tz_ = true;
original_tz_ = tz;
}
// world tour
setenv("TZ", GetParam(), 1);
}
void TearDown() {
if (has_tz_) {
setenv("TZ", original_tz_.c_str(), 1);
} else {
unsetenv("TZ");
}
}
private:
bool has_tz_;
std::string original_tz_;
};
INSTANTIATE_TEST_CASE_P(time_util_instance,
time_util,
::testing::Values("Asia/Tokyo", // +09:00 / no dst
"US/Hawaii", // -10:00 / no dst
"Europe/London", // +00:00 / dst
"PST", // -08:00 / dst
"GMT" // +00:00 / no dst
));
TEST_P(time_util, causality){
clock_time ct=get_clock_time();
cout << ct.sec << " : " << ct.usec << endl;
EXPECT_TRUE(get_clock_time()>=ct);
}
TEST_P(time_util, metric){
double begin=get_clock_time();
sleep(1);
double end=get_clock_time();
EXPECT_TRUE(end-begin>=1-1e-2);
}
TEST_P(time_util, calendar){
{
calendar_time ct(2009, 7, 17);
EXPECT_EQ(197, ct.yday);
EXPECT_EQ(5, ct.wday);
}
{
calendar_time cat1(get_clock_time());
clock_time clt(cat1);
calendar_time cat2(clt);
EXPECT_EQ(cat1.yday, cat2.yday);
EXPECT_EQ(cat1.wday, cat2.wday);
EXPECT_EQ(cat1.year, cat2.year);
EXPECT_EQ(cat1.mon, cat2.mon);
EXPECT_EQ(cat1.mday, cat2.mday);
EXPECT_EQ(cat1.hour, cat2.hour);
EXPECT_EQ(cat1.min, cat2.min);
EXPECT_EQ(cat1.sec, cat2.sec);
EXPECT_EQ(cat1.usec, cat2.usec);
EXPECT_EQ(cat1.isdst, cat2.isdst);
}
}
TEST_P(time_util, isdst){
calendar_time cal(1987, 7, 16, 17, 55, 0, 0); // summer day
bool tz_use_dst = cal.isdst;
// force rewrite isdst to check constructor of clock_time
cal.isdst=false;
clock_time clt1(cal);
cal.isdst=true;
clock_time clt2(cal);
if (tz_use_dst) {
EXPECT_EQ(clt1.sec, clt2.sec + 3600 /* sec */);
} else {
EXPECT_EQ(clt1.sec, clt2.sec);
}
}
<commit_msg>Remove sleep<commit_after>// Copyright (c)2008-2011, Preferred Infrastructure 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 Preferred Infrastructure nor the names of other
// 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 <gtest/gtest.h>
#include "time_util.h"
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <unistd.h>
using namespace pfi::system::time;
using namespace std;
class time_util : public testing::TestWithParam<const char *> {
protected:
void SetUp() {
has_tz_ = false;
char *tz = getenv("TZ");
// NOTE: null != empty
if (tz) {
has_tz_ = true;
original_tz_ = tz;
}
// world tour
setenv("TZ", GetParam(), 1);
}
void TearDown() {
if (has_tz_) {
setenv("TZ", original_tz_.c_str(), 1);
} else {
unsetenv("TZ");
}
}
private:
bool has_tz_;
std::string original_tz_;
};
INSTANTIATE_TEST_CASE_P(time_util_instance,
time_util,
::testing::Values("Asia/Tokyo", // +09:00 / no dst
"US/Hawaii", // -10:00 / no dst
"Europe/London", // +00:00 / dst
"PST", // -08:00 / dst
"GMT" // +00:00 / no dst
));
TEST_P(time_util, causality){
clock_time ct=get_clock_time();
cout << ct.sec << " : " << ct.usec << endl;
EXPECT_TRUE(get_clock_time()>=ct);
}
TEST_P(time_util, metric){
double begin=get_clock_time();
double end=get_clock_time();
EXPECT_TRUE(end-begin<=1e-2);
}
TEST_P(time_util, calendar){
{
calendar_time ct(2009, 7, 17);
EXPECT_EQ(197, ct.yday);
EXPECT_EQ(5, ct.wday);
}
{
calendar_time cat1(get_clock_time());
clock_time clt(cat1);
calendar_time cat2(clt);
EXPECT_EQ(cat1.yday, cat2.yday);
EXPECT_EQ(cat1.wday, cat2.wday);
EXPECT_EQ(cat1.year, cat2.year);
EXPECT_EQ(cat1.mon, cat2.mon);
EXPECT_EQ(cat1.mday, cat2.mday);
EXPECT_EQ(cat1.hour, cat2.hour);
EXPECT_EQ(cat1.min, cat2.min);
EXPECT_EQ(cat1.sec, cat2.sec);
EXPECT_EQ(cat1.usec, cat2.usec);
EXPECT_EQ(cat1.isdst, cat2.isdst);
}
}
TEST_P(time_util, isdst){
calendar_time cal(1987, 7, 16, 17, 55, 0, 0); // summer day
bool tz_use_dst = cal.isdst;
// force rewrite isdst to check constructor of clock_time
cal.isdst=false;
clock_time clt1(cal);
cal.isdst=true;
clock_time clt2(cal);
if (tz_use_dst) {
EXPECT_EQ(clt1.sec, clt2.sec + 3600 /* sec */);
} else {
EXPECT_EQ(clt1.sec, clt2.sec);
}
}
<|endoftext|> |
<commit_before>/** @file
This file produces Unicorns and Rainbows for the ATS community
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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 "ts/ink_defs.h"
#include "ts/ink_assert.h"
#include "ts/ink_sys_control.h"
rlim_t
ink_max_out_rlimit(int which, bool max_it, bool unlim_it)
{
struct rlimit rl;
#if defined(linux)
#define MAGIC_CAST(x) (enum __rlimit_resource)(x)
#else
#define MAGIC_CAST(x) x
#endif
if (max_it) {
ink_release_assert(getrlimit(MAGIC_CAST(which), &rl) >= 0);
if (rl.rlim_cur != rl.rlim_max) {
#if defined(darwin)
if (which == RLIMIT_NOFILE)
rl.rlim_cur = fmin(OPEN_MAX, rl.rlim_max);
else
rl.rlim_cur = rl.rlim_max;
#else
rl.rlim_cur = rl.rlim_max;
#endif
ink_release_assert(setrlimit(MAGIC_CAST(which), &rl) >= 0);
}
}
#if !(defined(darwin) || defined(freebsd))
if (unlim_it) {
ink_release_assert(getrlimit(MAGIC_CAST(which), &rl) >= 0);
if (rl.rlim_cur != (rlim_t)RLIM_INFINITY) {
rl.rlim_cur = (rl.rlim_max = RLIM_INFINITY);
ink_release_assert(setrlimit(MAGIC_CAST(which), &rl) >= 0);
}
}
#endif
ink_release_assert(getrlimit(MAGIC_CAST(which), &rl) >= 0);
return rl.rlim_cur;
}
rlim_t
ink_get_max_files()
{
FILE *fd;
struct rlimit lim;
// Linux-only ...
if ((fd = fopen("/proc/sys/fs/file-max", "r"))) {
uint64_t fmax;
if (fscanf(fd, "%" PRIu64 "", &fmax) == 1) {
fclose(fd);
return static_cast<rlim_t>(fmax);
}
fclose(fd);
}
if (getrlimit(RLIMIT_NOFILE, &lim) == 0) {
return lim.rlim_max;
}
return RLIM_INFINITY;
}
<commit_msg>Add missing include, which otherwise breaks on OSX<commit_after>/** @file
This file produces Unicorns and Rainbows for the ATS community
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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 <cmath>
#include "ts/ink_defs.h"
#include "ts/ink_assert.h"
#include "ts/ink_sys_control.h"
rlim_t
ink_max_out_rlimit(int which, bool max_it, bool unlim_it)
{
struct rlimit rl;
#if defined(linux)
#define MAGIC_CAST(x) (enum __rlimit_resource)(x)
#else
#define MAGIC_CAST(x) x
#endif
if (max_it) {
ink_release_assert(getrlimit(MAGIC_CAST(which), &rl) >= 0);
if (rl.rlim_cur != rl.rlim_max) {
#if defined(darwin)
if (which == RLIMIT_NOFILE)
rl.rlim_cur = fmin(OPEN_MAX, rl.rlim_max);
else
rl.rlim_cur = rl.rlim_max;
#else
rl.rlim_cur = rl.rlim_max;
#endif
ink_release_assert(setrlimit(MAGIC_CAST(which), &rl) >= 0);
}
}
#if !(defined(darwin) || defined(freebsd))
if (unlim_it) {
ink_release_assert(getrlimit(MAGIC_CAST(which), &rl) >= 0);
if (rl.rlim_cur != (rlim_t)RLIM_INFINITY) {
rl.rlim_cur = (rl.rlim_max = RLIM_INFINITY);
ink_release_assert(setrlimit(MAGIC_CAST(which), &rl) >= 0);
}
}
#endif
ink_release_assert(getrlimit(MAGIC_CAST(which), &rl) >= 0);
return rl.rlim_cur;
}
rlim_t
ink_get_max_files()
{
FILE *fd;
struct rlimit lim;
// Linux-only ...
if ((fd = fopen("/proc/sys/fs/file-max", "r"))) {
uint64_t fmax;
if (fscanf(fd, "%" PRIu64 "", &fmax) == 1) {
fclose(fd);
return static_cast<rlim_t>(fmax);
}
fclose(fd);
}
if (getrlimit(RLIMIT_NOFILE, &lim) == 0) {
return lim.rlim_max;
}
return RLIM_INFINITY;
}
<|endoftext|> |
<commit_before>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2015 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#include "caf/config.hpp"
#define CAF_SUITE aout
#include "caf/test/unit_test.hpp"
#include "caf/all.hpp"
using namespace caf;
using std::endl;
namespace {
struct fixture {
~fixture() {
await_all_actors_done();
shutdown();
}
};
constexpr const char* global_redirect = ":test";
constexpr const char* local_redirect = ":test2";
constexpr const char* chatty_line = "hi there! :)";
constexpr const char* chattier_line = "hello there, fellow friend! :)";
void chatty_actor(event_based_actor* self) {
aout(self) << chatty_line << endl;
}
void chattier_actor(event_based_actor* self, const std::string& fn) {
aout(self) << chatty_line << endl;
actor_ostream::redirect(self, fn);
aout(self) << chattier_line << endl;
}
} // namespace <anonymous>
CAF_TEST_FIXTURE_SCOPE(aout_tests, fixture)
CAF_TEST(global_redirect) {
scoped_actor self;
self->join(group::get("local", global_redirect));
actor_ostream::redirect_all(global_redirect);
spawn(chatty_actor);
self->receive(
[](const std::string& virtual_file, std::string& line) {
// drop trailing '\n'
if (! line.empty())
line.pop_back();
CAF_CHECK_EQUAL(virtual_file, ":test");
CAF_CHECK_EQUAL(line, chatty_line);
}
);
self->await_all_other_actors_done();
CAF_CHECK_EQUAL(self->mailbox().count(), 0);
}
CAF_TEST(global_and_local_redirect) {
scoped_actor self;
self->join(group::get("local", global_redirect));
self->join(group::get("local", local_redirect));
actor_ostream::redirect_all(global_redirect);
spawn(chatty_actor);
spawn(chattier_actor, local_redirect);
int i = 0;
self->receive_for(i, 2)(
on(global_redirect, arg_match) >> [](std::string& line) {
// drop trailing '\n'
if (! line.empty())
line.pop_back();
CAF_CHECK_EQUAL(line, chatty_line);
}
);
self->receive(
on(local_redirect, arg_match) >> [](std::string& line) {
// drop trailing '\n'
if (! line.empty())
line.pop_back();
CAF_CHECK_EQUAL(line, chattier_line);
}
);
self->await_all_other_actors_done();
CAF_CHECK_EQUAL(self->mailbox().count(), 0);
}
CAF_TEST_FIXTURE_SCOPE_END()
<commit_msg>Implement aout unit test w/o advanced match case<commit_after>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2015 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#include "caf/config.hpp"
#define CAF_SUITE aout
#include "caf/test/unit_test.hpp"
#include "caf/all.hpp"
using namespace caf;
using std::endl;
namespace {
struct fixture {
~fixture() {
await_all_actors_done();
shutdown();
}
};
constexpr const char* global_redirect = ":test";
constexpr const char* local_redirect = ":test2";
constexpr const char* chatty_line = "hi there! :)";
constexpr const char* chattier_line = "hello there, fellow friend! :)";
void chatty_actor(event_based_actor* self) {
aout(self) << chatty_line << endl;
}
void chattier_actor(event_based_actor* self, const std::string& fn) {
aout(self) << chatty_line << endl;
actor_ostream::redirect(self, fn);
aout(self) << chattier_line << endl;
}
} // namespace <anonymous>
CAF_TEST_FIXTURE_SCOPE(aout_tests, fixture)
CAF_TEST(global_redirect) {
scoped_actor self;
self->join(group::get("local", global_redirect));
actor_ostream::redirect_all(global_redirect);
spawn(chatty_actor);
self->receive(
[](const std::string& virtual_file, std::string& line) {
// drop trailing '\n'
if (! line.empty())
line.pop_back();
CAF_CHECK_EQUAL(virtual_file, ":test");
CAF_CHECK_EQUAL(line, chatty_line);
}
);
self->await_all_other_actors_done();
CAF_CHECK_EQUAL(self->mailbox().count(), 0);
}
CAF_TEST(global_and_local_redirect) {
scoped_actor self;
self->join(group::get("local", global_redirect));
self->join(group::get("local", local_redirect));
actor_ostream::redirect_all(global_redirect);
spawn(chatty_actor);
spawn(chattier_actor, local_redirect);
std::vector<std::pair<std::string, std::string>> expected {
{":test", chatty_line},
{":test", chatty_line},
{":test2", chattier_line}
};
std::vector<std::pair<std::string, std::string>> lines;
int i = 0;
self->receive_for(i, 3)(
[&](std::string& virtual_file, std::string& line) {
// drop trailing '\n'
if (! line.empty())
line.pop_back();
lines.emplace_back(std::move(virtual_file), std::move(line));
}
);
CAF_CHECK(std::is_permutation(lines.begin(), lines.end(), expected.begin()));
self->await_all_other_actors_done();
CAF_CHECK_EQUAL(self->mailbox().count(), 0);
}
CAF_TEST_FIXTURE_SCOPE_END()
<|endoftext|> |
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* Razor - a lightweight, Qt based, desktop toolset
* http://razor-qt.org
*
* Copyright: 2013 Razor team
* Authors:
* Kuzma Shapran <kuzma.shapran@gmail.com>
*
* This program or library is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General
* Public License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*
* END_COMMON_COPYRIGHT_HEADER */
#include "default_model.h"
#include "actions.h"
DefaultModel::DefaultModel(Actions *actions, const QColor &grayedOutColour, const QFont &highlightedFont, const QFont &italicFont, const QFont &highlightedItalicFont, QObject *parent)
: QAbstractTableModel(parent)
, mActions(actions)
, mGrayedOutColour(grayedOutColour)
, mHighlightedFont(highlightedFont)
, mItalicFont(italicFont)
, mHighlightedItalicFont(highlightedItalicFont)
{
connect(actions, SIGNAL(daemonDisappeared()), SLOT(daemonDisappeared()));
connect(actions, SIGNAL(daemonAppeared()), SLOT(daemonAppeared()));
connect(actions, SIGNAL(actionAdded(qulonglong)), SLOT(actionAdded(qulonglong)));
connect(actions, SIGNAL(actionModified(qulonglong)), SLOT(actionModified(qulonglong)));
connect(actions, SIGNAL(actionEnabled(qulonglong, bool)), SLOT(actionEnabled(qulonglong, bool)));
connect(actions, SIGNAL(actionsSwapped(qulonglong, qulonglong)), SLOT(actionsSwapped(qulonglong, qulonglong)));
connect(actions, SIGNAL(actionRemoved(qulonglong)), SLOT(actionRemoved(qulonglong)));
mVerboseType["command"] = tr("Command");
mVerboseType["method"] = tr("DBus call");
mVerboseType["client"] = tr("Client");
}
DefaultModel::~DefaultModel()
{
}
int DefaultModel::rowCount(const QModelIndex &/*parent*/) const
{
return mContent.size();
}
int DefaultModel::columnCount(const QModelIndex &/*parent*/) const
{
return 5;
}
QVariant DefaultModel::data(const QModelIndex &index, int role) const
{
switch (role)
{
case Qt::DisplayRole:
if ((index.row() >= 0) && (index.row() < rowCount()) && (index.column() >= 0) && (index.column() < columnCount()))
switch (index.column())
{
case 0:
return mContent.keys()[index.row()];
case 1:
return mContent[mContent.keys()[index.row()]].shortcut;
case 2:
return mContent[mContent.keys()[index.row()]].description;
case 3:
return mVerboseType[mContent[mContent.keys()[index.row()]].type];
case 4:
return mContent[mContent.keys()[index.row()]].info;
}
break;
case Qt::EditRole:
if ((index.row() >= 0) && (index.row() < rowCount()) && (index.column() >= 0) && (index.column() < columnCount()))
switch (index.column())
{
case 1:
return mContent[mContent.keys()[index.row()]].shortcut;
}
break;
case Qt::FontRole:
{
if ((index.row() >= 0) && (index.row() < rowCount()))
{
qulonglong id = mContent.keys()[index.row()];
bool multiple = (index.column() == 1) && (mShortcuts[mContent[id].shortcut].size() > 1);
bool inactive = (mContent[id].type == "client") && (mActions->getClientActionSender(id).isEmpty());
if (multiple || inactive)
return multiple ? (inactive ? mHighlightedItalicFont : mHighlightedFont) : mItalicFont;
}
}
break;
case Qt::ForegroundRole:
if (!mContent[mContent.keys()[index.row()]].enabled)
{
return mGrayedOutColour;
}
break;
case Qt::CheckStateRole:
if ((index.row() >= 0) && (index.row() < rowCount()) && (index.column() == 0))
{
return mContent[mContent.keys()[index.row()]].enabled ? Qt::Checked : Qt::Unchecked;
}
break;
default:
;
}
return QVariant();
}
QVariant DefaultModel::headerData(int section, Qt::Orientation orientation, int role) const
{
switch (role)
{
case Qt::DisplayRole:
switch (orientation)
{
case Qt::Horizontal:
switch (section)
{
case 0:
return tr("Id");
case 1:
return tr("Shortcut");
case 2:
return tr("Description");
case 3:
return tr("Type");
case 4:
return tr("Info");
}
break;
default:
;
}
break;
default:
;
}
return QAbstractTableModel::headerData(section, orientation, role);
}
Qt::ItemFlags DefaultModel::flags(const QModelIndex &index) const
{
Qt::ItemFlags result = Qt::ItemIsSelectable | Qt::ItemIsEnabled;
if (index.column() == 0)
{
result |= Qt::ItemIsUserCheckable;
}
if (index.column() == 1)
{
result |= Qt::ItemIsEditable;
}
return result;
}
bool DefaultModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
switch (role)
{
case Qt::EditRole:
if ((index.row() >= 0) && (index.row() < rowCount()) && index.column() == 1)
{
mActions->changeShortcut(mContent.keys()[index.row()], value.toString());
return true;
}
break;
}
return false;
}
qulonglong DefaultModel::id(const QModelIndex &index) const
{
if ((index.row() >= 0) && (index.row() < rowCount()))
{
return mContent.keys()[index.row()];
}
return 0ull;
}
void DefaultModel::daemonDisappeared()
{
beginResetModel();
mContent.clear();
mShortcuts.clear();
endResetModel();
}
void DefaultModel::daemonAppeared()
{
QList<qulonglong> allIds = mActions->allActionIds();
beginInsertRows(QModelIndex(), 0, allIds.size() - 1);
foreach(qulonglong id, allIds)
{
mContent[id] = mActions->actionById(id).second;
mShortcuts[mContent[id].shortcut].insert(id);
}
endInsertRows();
}
void DefaultModel::actionAdded(qulonglong id)
{
if (!mContent.contains(id))
{
QPair<bool, GeneralActionInfo> result = mActions->actionById(id);
if (result.first)
{
QList<qulonglong> keys = mContent.keys();
int row = qBinaryFind(keys, mContent.lowerBound(id).key()) - keys.constBegin();
beginInsertRows(QModelIndex(), row, row);
mContent[id] = result.second;
mShortcuts[mContent[id].shortcut].insert(id);
endInsertRows();
keys = mContent.keys();
foreach(qulonglong siblingId, mShortcuts[mContent[id].shortcut])
{
if (id != siblingId)
{
int siblingRow = qBinaryFind(keys, siblingId) - keys.constBegin();
emit dataChanged(index(siblingRow, 1), index(siblingRow, 1));
}
}
}
}
}
void DefaultModel::actionEnabled(qulonglong id, bool enabled)
{
if (mContent.contains(id))
{
QList<qulonglong> keys = mContent.keys();
int row = qBinaryFind(keys, id) - keys.constBegin();
mContent[id].enabled = enabled;
emit dataChanged(index(row, 0), index(row, 3));
}
}
void DefaultModel::actionModified(qulonglong id)
{
if (mContent.contains(id))
{
QPair<bool, GeneralActionInfo> result = mActions->actionById(id);
if (result.first)
{
QList<qulonglong> keys = mContent.keys();
int row = qBinaryFind(keys, id) - keys.constBegin();
if (mContent[id].shortcut != result.second.shortcut)
{
mShortcuts[result.second.shortcut].insert(id);
mShortcuts[mContent[id].shortcut].remove(id);
foreach(qulonglong siblingId, mShortcuts[mContent[id].shortcut])
{
int siblingRow = qBinaryFind(keys, siblingId) - keys.constBegin();
emit dataChanged(index(siblingRow, 1), index(siblingRow, 1));
}
foreach(qulonglong siblingId, mShortcuts[result.second.shortcut])
{
int siblingRow = qBinaryFind(keys, siblingId) - keys.constBegin();
emit dataChanged(index(siblingRow, 1), index(siblingRow, 1));
}
}
mContent[id] = result.second;
emit dataChanged(index(row, 0), index(row, 3));
}
}
}
void DefaultModel::actionsSwapped(qulonglong id1, qulonglong id2)
{
if (mContent.contains(id1) && mContent.contains(id2))
{
QList<qulonglong> keys = mContent.keys();
int row1 = qBinaryFind(keys, id1) - keys.constBegin();
int row2 = qBinaryFind(keys, id2) - keys.constBegin();
std::swap(mContent[id1], mContent[id2]);
emit dataChanged(index(row1, 0), index(row1, 3));
emit dataChanged(index(row2, 0), index(row2, 3));
}
}
void DefaultModel::actionRemoved(qulonglong id)
{
if (mContent.contains(id))
{
QList<qulonglong> keys = mContent.keys();
int row = qBinaryFind(keys, id) - keys.constBegin();
beginRemoveRows(QModelIndex(), row, row);
mShortcuts[mContent[id].shortcut].remove(id);
QString shortcut = mContent[id].shortcut;
mContent.remove(id);
endRemoveRows();
foreach(qulonglong siblingId, mShortcuts[shortcut])
{
int siblingRow = qBinaryFind(keys, siblingId) - keys.constBegin();
emit dataChanged(index(siblingRow, 1), index(siblingRow, 1));
}
}
}
<commit_msg>No dependencies on STL<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* Razor - a lightweight, Qt based, desktop toolset
* http://razor-qt.org
*
* Copyright: 2013 Razor team
* Authors:
* Kuzma Shapran <kuzma.shapran@gmail.com>
*
* This program or library is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General
* Public License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*
* END_COMMON_COPYRIGHT_HEADER */
#include "default_model.h"
#include "actions.h"
DefaultModel::DefaultModel(Actions *actions, const QColor &grayedOutColour, const QFont &highlightedFont, const QFont &italicFont, const QFont &highlightedItalicFont, QObject *parent)
: QAbstractTableModel(parent)
, mActions(actions)
, mGrayedOutColour(grayedOutColour)
, mHighlightedFont(highlightedFont)
, mItalicFont(italicFont)
, mHighlightedItalicFont(highlightedItalicFont)
{
connect(actions, SIGNAL(daemonDisappeared()), SLOT(daemonDisappeared()));
connect(actions, SIGNAL(daemonAppeared()), SLOT(daemonAppeared()));
connect(actions, SIGNAL(actionAdded(qulonglong)), SLOT(actionAdded(qulonglong)));
connect(actions, SIGNAL(actionModified(qulonglong)), SLOT(actionModified(qulonglong)));
connect(actions, SIGNAL(actionEnabled(qulonglong, bool)), SLOT(actionEnabled(qulonglong, bool)));
connect(actions, SIGNAL(actionsSwapped(qulonglong, qulonglong)), SLOT(actionsSwapped(qulonglong, qulonglong)));
connect(actions, SIGNAL(actionRemoved(qulonglong)), SLOT(actionRemoved(qulonglong)));
mVerboseType["command"] = tr("Command");
mVerboseType["method"] = tr("DBus call");
mVerboseType["client"] = tr("Client");
}
DefaultModel::~DefaultModel()
{
}
int DefaultModel::rowCount(const QModelIndex &/*parent*/) const
{
return mContent.size();
}
int DefaultModel::columnCount(const QModelIndex &/*parent*/) const
{
return 5;
}
QVariant DefaultModel::data(const QModelIndex &index, int role) const
{
switch (role)
{
case Qt::DisplayRole:
if ((index.row() >= 0) && (index.row() < rowCount()) && (index.column() >= 0) && (index.column() < columnCount()))
switch (index.column())
{
case 0:
return mContent.keys()[index.row()];
case 1:
return mContent[mContent.keys()[index.row()]].shortcut;
case 2:
return mContent[mContent.keys()[index.row()]].description;
case 3:
return mVerboseType[mContent[mContent.keys()[index.row()]].type];
case 4:
return mContent[mContent.keys()[index.row()]].info;
}
break;
case Qt::EditRole:
if ((index.row() >= 0) && (index.row() < rowCount()) && (index.column() >= 0) && (index.column() < columnCount()))
switch (index.column())
{
case 1:
return mContent[mContent.keys()[index.row()]].shortcut;
}
break;
case Qt::FontRole:
{
if ((index.row() >= 0) && (index.row() < rowCount()))
{
qulonglong id = mContent.keys()[index.row()];
bool multiple = (index.column() == 1) && (mShortcuts[mContent[id].shortcut].size() > 1);
bool inactive = (mContent[id].type == "client") && (mActions->getClientActionSender(id).isEmpty());
if (multiple || inactive)
return multiple ? (inactive ? mHighlightedItalicFont : mHighlightedFont) : mItalicFont;
}
}
break;
case Qt::ForegroundRole:
if (!mContent[mContent.keys()[index.row()]].enabled)
{
return mGrayedOutColour;
}
break;
case Qt::CheckStateRole:
if ((index.row() >= 0) && (index.row() < rowCount()) && (index.column() == 0))
{
return mContent[mContent.keys()[index.row()]].enabled ? Qt::Checked : Qt::Unchecked;
}
break;
default:
;
}
return QVariant();
}
QVariant DefaultModel::headerData(int section, Qt::Orientation orientation, int role) const
{
switch (role)
{
case Qt::DisplayRole:
switch (orientation)
{
case Qt::Horizontal:
switch (section)
{
case 0:
return tr("Id");
case 1:
return tr("Shortcut");
case 2:
return tr("Description");
case 3:
return tr("Type");
case 4:
return tr("Info");
}
break;
default:
;
}
break;
default:
;
}
return QAbstractTableModel::headerData(section, orientation, role);
}
Qt::ItemFlags DefaultModel::flags(const QModelIndex &index) const
{
Qt::ItemFlags result = Qt::ItemIsSelectable | Qt::ItemIsEnabled;
if (index.column() == 0)
{
result |= Qt::ItemIsUserCheckable;
}
if (index.column() == 1)
{
result |= Qt::ItemIsEditable;
}
return result;
}
bool DefaultModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
switch (role)
{
case Qt::EditRole:
if ((index.row() >= 0) && (index.row() < rowCount()) && index.column() == 1)
{
mActions->changeShortcut(mContent.keys()[index.row()], value.toString());
return true;
}
break;
}
return false;
}
qulonglong DefaultModel::id(const QModelIndex &index) const
{
if ((index.row() >= 0) && (index.row() < rowCount()))
{
return mContent.keys()[index.row()];
}
return 0ull;
}
void DefaultModel::daemonDisappeared()
{
beginResetModel();
mContent.clear();
mShortcuts.clear();
endResetModel();
}
void DefaultModel::daemonAppeared()
{
QList<qulonglong> allIds = mActions->allActionIds();
beginInsertRows(QModelIndex(), 0, allIds.size() - 1);
foreach(qulonglong id, allIds)
{
mContent[id] = mActions->actionById(id).second;
mShortcuts[mContent[id].shortcut].insert(id);
}
endInsertRows();
}
void DefaultModel::actionAdded(qulonglong id)
{
if (!mContent.contains(id))
{
QPair<bool, GeneralActionInfo> result = mActions->actionById(id);
if (result.first)
{
QList<qulonglong> keys = mContent.keys();
int row = qBinaryFind(keys, mContent.lowerBound(id).key()) - keys.constBegin();
beginInsertRows(QModelIndex(), row, row);
mContent[id] = result.second;
mShortcuts[mContent[id].shortcut].insert(id);
endInsertRows();
keys = mContent.keys();
foreach(qulonglong siblingId, mShortcuts[mContent[id].shortcut])
{
if (id != siblingId)
{
int siblingRow = qBinaryFind(keys, siblingId) - keys.constBegin();
emit dataChanged(index(siblingRow, 1), index(siblingRow, 1));
}
}
}
}
}
void DefaultModel::actionEnabled(qulonglong id, bool enabled)
{
if (mContent.contains(id))
{
QList<qulonglong> keys = mContent.keys();
int row = qBinaryFind(keys, id) - keys.constBegin();
mContent[id].enabled = enabled;
emit dataChanged(index(row, 0), index(row, 3));
}
}
void DefaultModel::actionModified(qulonglong id)
{
if (mContent.contains(id))
{
QPair<bool, GeneralActionInfo> result = mActions->actionById(id);
if (result.first)
{
QList<qulonglong> keys = mContent.keys();
int row = qBinaryFind(keys, id) - keys.constBegin();
if (mContent[id].shortcut != result.second.shortcut)
{
mShortcuts[result.second.shortcut].insert(id);
mShortcuts[mContent[id].shortcut].remove(id);
foreach(qulonglong siblingId, mShortcuts[mContent[id].shortcut])
{
int siblingRow = qBinaryFind(keys, siblingId) - keys.constBegin();
emit dataChanged(index(siblingRow, 1), index(siblingRow, 1));
}
foreach(qulonglong siblingId, mShortcuts[result.second.shortcut])
{
int siblingRow = qBinaryFind(keys, siblingId) - keys.constBegin();
emit dataChanged(index(siblingRow, 1), index(siblingRow, 1));
}
}
mContent[id] = result.second;
emit dataChanged(index(row, 0), index(row, 3));
}
}
}
void DefaultModel::actionsSwapped(qulonglong id1, qulonglong id2)
{
if (mContent.contains(id1) && mContent.contains(id2))
{
QList<qulonglong> keys = mContent.keys();
int row1 = qBinaryFind(keys, id1) - keys.constBegin();
int row2 = qBinaryFind(keys, id2) - keys.constBegin();
// swap
GeneralActionInfo tmp = mContent[id1];
mContent[id1] = mContent[id2];
mContent[id2] = tmp;
emit dataChanged(index(row1, 0), index(row1, 3));
emit dataChanged(index(row2, 0), index(row2, 3));
}
}
void DefaultModel::actionRemoved(qulonglong id)
{
if (mContent.contains(id))
{
QList<qulonglong> keys = mContent.keys();
int row = qBinaryFind(keys, id) - keys.constBegin();
beginRemoveRows(QModelIndex(), row, row);
mShortcuts[mContent[id].shortcut].remove(id);
QString shortcut = mContent[id].shortcut;
mContent.remove(id);
endRemoveRows();
foreach(qulonglong siblingId, mShortcuts[shortcut])
{
int siblingRow = qBinaryFind(keys, siblingId) - keys.constBegin();
emit dataChanged(index(siblingRow, 1), index(siblingRow, 1));
}
}
}
<|endoftext|> |
<commit_before>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2008 Ulrich von Zadow
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Current versions can be found at www.libavg.de
//
// Original author of this file is Jan Boelsche (regular.gonzales@googlemail.com).
//
#define AVG_PLUGIN
#include "api.h"
#include "player/AreaNode.h"
#include "player/NodeDefinition.h"
#include "base/Logger.h"
#include "graphics/OGLHelper.h"
#include "wrapper/WrapHelper.h"
#include <string>
#include <iostream>
#include <sstream>
#include <iomanip>
using namespace std;
using namespace boost::python;
namespace avg {
class ColorNode : public AreaNode
{
public:
static NodeDefinition createNodeDefinition();
ColorNode(const ArgList& Args, bool bFromXML);
void setFillColor(const std::string& sColor);
const std::string& getFillColor() const;
virtual void maybeRender(const DRect& Rect);
virtual void render (const DRect& Rect);
protected:
void parseColor(const std::string& sColorSreing);
std::string m_sFillColorName;
float m_r, m_g, m_b;
};
ColorNode::ColorNode(const ArgList& Args, bool bFromXML) :
m_sFillColorName("FFFFFF")
{
AVG_TRACE(Logger::PLUGIN, "ColorNode c'tor gets Argument fillcolor= " << Args.getArgVal<string>("fillcolor"));
Args.setMembers(this);
AVG_TRACE(Logger::PLUGIN, "ColorNode constructed with " << m_sFillColorName);
parseColor(m_sFillColorName);
}
void ColorNode::setFillColor(const string& sFillColor)
{
AVG_TRACE(Logger::PLUGIN, "setFillColor called with " << sFillColor);
m_sFillColorName = sFillColor;
parseColor(m_sFillColorName);
}
const std::string& ColorNode::getFillColor() const
{
return m_sFillColorName;
}
void ColorNode::parseColor(const std::string& sColorSreing)
{
istringstream(sColorSreing.substr(0,2)) >> hex >> m_r;
istringstream(sColorSreing.substr(2,2)) >> hex >> m_g;
istringstream(sColorSreing.substr(4,2)) >> hex >> m_b;
}
void ColorNode::maybeRender(const DRect& rect)
{
render(rect);
}
void ColorNode::render (const DRect& rect)
{
//AVG_TRACE(Logger::PLUGIN, "ColorNode::render");
glClearColor(m_r, m_g, m_b, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
}
NodeDefinition ColorNode::createNodeDefinition()
{
class_<ColorNode, bases<AreaNode>, boost::noncopyable>("ColorNode", no_init)
.add_property("fillcolor", make_function(&ColorNode::getFillColor,
return_value_policy<copy_const_reference>()), &ColorNode::setFillColor);
return NodeDefinition("colornode", (NodeBuilder)ColorNode::buildNode<ColorNode>)
.extendDefinition(AreaNode::createDefinition())
.addArg(Arg<string>("fillcolor", "0F0F0F", false,
offsetof(ColorNode, m_sFillColorName)));
}
}
AVG_PLUGIN_API avg::NodeDefinition getNodeDefinition()
{
return avg::ColorNode::createNodeDefinition();
}
AVG_PLUGIN_API const char** getAllowedParentNodeNames()
{
static const char *names[] = {"avg", 0};
return names;
}
<commit_msg>relocated plugin test now works in win32<commit_after>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2008 Ulrich von Zadow
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Current versions can be found at www.libavg.de
//
// Original author of this file is Jan Boelsche (regular.gonzales@googlemail.com).
//
#define AVG_PLUGIN
#include "../../api.h"
#include "../../player/AreaNode.h"
#include "../../player/NodeDefinition.h"
#include "../../base/Logger.h"
#include "../../graphics/OGLHelper.h"
#include "../../wrapper/WrapHelper.h"
#include <string>
#include <iostream>
#include <sstream>
#include <iomanip>
using namespace std;
using namespace boost::python;
namespace avg {
class ColorNode : public AreaNode
{
public:
static NodeDefinition createNodeDefinition();
ColorNode(const ArgList& Args, bool bFromXML);
void setFillColor(const std::string& sColor);
const std::string& getFillColor() const;
virtual void maybeRender(const DRect& Rect);
virtual void render (const DRect& Rect);
protected:
void parseColor(const std::string& sColorSreing);
std::string m_sFillColorName;
float m_r, m_g, m_b;
};
ColorNode::ColorNode(const ArgList& Args, bool bFromXML) :
m_sFillColorName("FFFFFF")
{
AVG_TRACE(Logger::PLUGIN, "ColorNode c'tor gets Argument fillcolor= " << Args.getArgVal<string>("fillcolor"));
Args.setMembers(this);
AVG_TRACE(Logger::PLUGIN, "ColorNode constructed with " << m_sFillColorName);
parseColor(m_sFillColorName);
}
void ColorNode::setFillColor(const string& sFillColor)
{
AVG_TRACE(Logger::PLUGIN, "setFillColor called with " << sFillColor);
m_sFillColorName = sFillColor;
parseColor(m_sFillColorName);
}
const std::string& ColorNode::getFillColor() const
{
return m_sFillColorName;
}
void ColorNode::parseColor(const std::string& sColorSreing)
{
istringstream(sColorSreing.substr(0,2)) >> hex >> m_r;
istringstream(sColorSreing.substr(2,2)) >> hex >> m_g;
istringstream(sColorSreing.substr(4,2)) >> hex >> m_b;
}
void ColorNode::maybeRender(const DRect& rect)
{
render(rect);
}
void ColorNode::render (const DRect& rect)
{
//AVG_TRACE(Logger::PLUGIN, "ColorNode::render");
glClearColor(m_r, m_g, m_b, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
}
NodeDefinition ColorNode::createNodeDefinition()
{
class_<ColorNode, bases<AreaNode>, boost::noncopyable>("ColorNode", no_init)
.add_property("fillcolor", make_function(&ColorNode::getFillColor,
return_value_policy<copy_const_reference>()), &ColorNode::setFillColor);
return NodeDefinition("colornode", (NodeBuilder)ColorNode::buildNode<ColorNode>)
.extendDefinition(AreaNode::createDefinition())
.addArg(Arg<string>("fillcolor", "0F0F0F", false,
offsetof(ColorNode, m_sFillColorName)));
}
}
AVG_PLUGIN_API avg::NodeDefinition getNodeDefinition()
{
return avg::ColorNode::createNodeDefinition();
}
AVG_PLUGIN_API const char** getAllowedParentNodeNames()
{
static const char *names[] = {"avg", 0};
return names;
}
<|endoftext|> |
<commit_before>#include "integral.h"
#include <cassert>
using namespace memseries::statistic;
void BaseIntegral::call(const memseries::Meas&m){
if(_is_first){
_last=m;
_is_first=false;
}else{
this->calc(_last,m);
_last=m;
}
}
BaseIntegral::BaseIntegral() {
_is_first = true;
_result = 0;
}
RectangleMethod::RectangleMethod(const RectangleMethod::Kind k):
BaseIntegral(),
_kind(k)
{}
void RectangleMethod::calc(const memseries::Meas&a, const memseries::Meas&b){
switch (_kind)
{
case Kind::LEFT:
_result += a.value*(b.time - a.time);
break;
case Kind::RIGHT:
_result += b.value*(b.time - a.time);
break;
case Kind::MIDLE:
_result += ((a.value + b.value) / 2.0)*(b.time - a.time);
break;
default:
assert(false);
}
}
memseries::Value BaseIntegral::result()const {
return _result;
}<commit_msg>refact<commit_after>#include "integral.h"
#include <cassert>
using namespace memseries::statistic;
BaseIntegral::BaseIntegral() {
_is_first = true;
_result = 0;
}
void BaseIntegral::call(const memseries::Meas&m){
if(_is_first){
_last=m;
_is_first=false;
}else{
this->calc(_last,m);
_last=m;
}
}
memseries::Value BaseIntegral::result()const {
return _result;
}
RectangleMethod::RectangleMethod(const RectangleMethod::Kind k):
BaseIntegral(),
_kind(k)
{}
void RectangleMethod::calc(const memseries::Meas&a, const memseries::Meas&b){
switch (_kind)
{
case Kind::LEFT:
_result += a.value*(b.time - a.time);
break;
case Kind::RIGHT:
_result += b.value*(b.time - a.time);
break;
case Kind::MIDLE:
_result += ((a.value + b.value) / 2.0)*(b.time - a.time);
break;
default:
assert(false);
}
}
<|endoftext|> |
<commit_before>/*-------------------------------------------------------------------------
*
* FILE
* cursor.cxx
*
* DESCRIPTION
* implementation of the pqxx::Cursor class.
* pqxx::Cursor represents a database cursor.
*
* Copyright (c) 2001-2004, Jeroen T. Vermeulen <jtv@xs4all.nl>
*
* See COPYING for copyright license. If you did not receive a file called
* COPYING with this source code, please notify the distributor of this mistake,
* or contact the author.
*
*-------------------------------------------------------------------------
*/
#define PQXXYES_I_KNOW_DEPRECATED_HEADER
#include "pqxx/compiler.h"
#include <cstdlib>
// Note: this imports the obsolete definitions, also in the headers below!
#include "pqxx/cursor.h"
#include "pqxx/result"
#include "pqxx/transaction"
using namespace PGSTD;
void pqxx::Cursor::init(const string &BaseName, const char Query[])
{
// Give ourselves a locally unique name based on connection name
m_Name += "\"" +
BaseName + "_" +
m_Trans.name() + "_" +
to_string(m_Trans.GetUniqueCursorNum()) +
"\"";
m_Trans.Exec("DECLARE " + m_Name + " SCROLL CURSOR FOR " + Query);
}
pqxx::Cursor::difference_type pqxx::Cursor::SetCount(difference_type Count)
{
difference_type Old = m_Count;
m_Done = false;
m_Count = Count;
return Old;
}
pqxx::Cursor &pqxx::Cursor::operator>>(pqxx::result &R)
{
R = Fetch(m_Count);
m_Done = R.empty();
return *this;
}
pqxx::result pqxx::Cursor::Fetch(difference_type Count)
{
result R;
if (!Count)
{
m_Trans.MakeEmpty(R);
return R;
}
const string Cmd( MakeFetchCmd(Count) );
try
{
R = m_Trans.Exec(Cmd.c_str());
}
catch (const exception &)
{
m_Pos = pos_unknown;
throw;
}
NormalizedMove(Count, R.size());
return R;
}
pqxx::result::difference_type pqxx::Cursor::Move(difference_type Count)
{
if (!Count) return 0;
if ((Count < 0) && (m_Pos == pos_start)) return 0;
m_Done = false;
const string Cmd( "MOVE " + OffsetString(Count) + " IN " + m_Name);
long int A = 0;
try
{
result R( m_Trans.Exec(Cmd.c_str()) );
if (!sscanf(R.CmdStatus(), "MOVE %ld", &A))
throw runtime_error("Didn't understand database's reply to MOVE: "
"'" + string(R.CmdStatus()) + "'");
}
catch (const exception &)
{
m_Pos = pos_unknown;
throw;
}
return NormalizedMove(Count, A);
}
pqxx::Cursor::difference_type
pqxx::Cursor::NormalizedMove(difference_type Intended,
difference_type Actual)
{
if (Actual < 0)
throw logic_error("libpqxx internal error: Negative rowcount");
if (Actual > labs(Intended))
throw logic_error("libpqxx internal error: Moved/fetched too many rows "
"(wanted " + to_string(Intended) + ", "
"got " + to_string(Actual) + ")");
difference_type Offset = Actual;
if (m_Pos == size_type(pos_unknown))
{
if (Actual < labs(Intended))
{
if (Intended < 0)
{
// Must have gone back to starting position
m_Pos = pos_start;
}
else if (m_Size == pos_unknown)
{
// Oops. We'd want to set result set size at this point, but we can't
// because we don't know our position.
throw runtime_error("Can't determine result set size: "
"Cursor position unknown at end of set");
}
}
// Nothing more we can do to update our position
return (Intended > 0) ? Actual : -Actual;
}
if (Actual < labs(Intended))
{
// There is a nonexistant row before the first one in the result set, and
// one after the last row, where we may be positioned. Unfortunately
// PostgreSQL only reports "real" rows, making it really hard to figure out
// how many rows we've really moved.
if (Actual)
{
// We've moved off either edge of our result set; add the one,
// nonexistant row that wasn't counted in the status string we got.
Offset++;
}
else if (Intended < 0)
{
// We've either moved off the "left" edge of our result set from the
// first actual row, or we were on the nonexistant row before the first
// actual row and so didn't move at all. Just set up Actual so that we
// end up at our starting position, which is where we must be.
Offset = m_Pos - pos_start;
}
else if (m_Size != pos_unknown)
{
// We either just walked off the right edge (moving at least one row in
// the process), or had done so already (in which case we haven't moved).
// In the case at hand, we already know where the right-hand edge of the
// result set is, so we use that to compute our offset.
Offset = (m_Size + pos_start + 1) - m_Pos;
}
else
{
// This is the hard one. Assume that we haven't seen the "right edge"
// before, because m_Size hasn't been set yet. Therefore, we must have
// just stepped off the edge (and m_Size will be set now).
Offset++;
}
if ((Offset > labs(Intended)) && (m_Pos != size_type(pos_unknown)))
{
m_Pos = pos_unknown;
throw logic_error("libpqxx internal error: Confused cursor position");
}
}
if (Intended < 0) Offset = -Offset;
m_Pos += Offset;
if ((Intended > 0) && (Actual < Intended) && (m_Size == pos_unknown))
m_Size = m_Pos - pos_start - 1;
m_Done = !Actual;
return Offset;
}
void pqxx::Cursor::MoveTo(size_type Dest)
{
// If we don't know where we are, go back to the beginning first.
if (m_Pos == size_type(pos_unknown)) Move(BACKWARD_ALL());
Move(Dest - Pos());
}
pqxx::Cursor::difference_type pqxx::Cursor::ALL() throw ()
{
#ifdef _WIN32
return INT_MAX;
#else // _WIN32
return numeric_limits<result::difference_type>::max();
#endif // _WIN32
}
pqxx::Cursor::difference_type pqxx::Cursor::BACKWARD_ALL() throw ()
{
#ifdef _WIN32
return INT_MIN + 1;
#else // _WIN32
return numeric_limits<result::difference_type>::min() + 1;
#endif // _WIN32
}
string pqxx::Cursor::OffsetString(difference_type Count)
{
if (Count == ALL()) return "ALL";
else if (Count == BACKWARD_ALL()) return "BACKWARD ALL";
return to_string(Count);
}
string pqxx::Cursor::MakeFetchCmd(difference_type Count) const
{
return "FETCH " + OffsetString(Count) + " IN " + m_Name;
}
<commit_msg>Fixed warnings for unsigned size_type<commit_after>/*-------------------------------------------------------------------------
*
* FILE
* cursor.cxx
*
* DESCRIPTION
* implementation of the pqxx::Cursor class.
* pqxx::Cursor represents a database cursor.
*
* Copyright (c) 2001-2004, Jeroen T. Vermeulen <jtv@xs4all.nl>
*
* See COPYING for copyright license. If you did not receive a file called
* COPYING with this source code, please notify the distributor of this mistake,
* or contact the author.
*
*-------------------------------------------------------------------------
*/
#define PQXXYES_I_KNOW_DEPRECATED_HEADER
#include "pqxx/compiler.h"
#include <cstdlib>
// Note: this imports the obsolete definitions, also in the headers below!
#include "pqxx/cursor.h"
#include "pqxx/result"
#include "pqxx/transaction"
using namespace PGSTD;
void pqxx::Cursor::init(const string &BaseName, const char Query[])
{
// Give ourselves a locally unique name based on connection name
m_Name += "\"" +
BaseName + "_" +
m_Trans.name() + "_" +
to_string(m_Trans.GetUniqueCursorNum()) +
"\"";
m_Trans.Exec("DECLARE " + m_Name + " SCROLL CURSOR FOR " + Query);
}
pqxx::Cursor::difference_type pqxx::Cursor::SetCount(difference_type Count)
{
difference_type Old = m_Count;
m_Done = false;
m_Count = Count;
return Old;
}
pqxx::Cursor &pqxx::Cursor::operator>>(pqxx::result &R)
{
R = Fetch(m_Count);
m_Done = R.empty();
return *this;
}
pqxx::result pqxx::Cursor::Fetch(difference_type Count)
{
result R;
if (!Count)
{
m_Trans.MakeEmpty(R);
return R;
}
const string Cmd( MakeFetchCmd(Count) );
try
{
R = m_Trans.Exec(Cmd.c_str());
}
catch (const exception &)
{
m_Pos = size_type(pos_unknown);
throw;
}
NormalizedMove(Count, R.size());
return R;
}
pqxx::result::difference_type pqxx::Cursor::Move(difference_type Count)
{
if (!Count) return 0;
if ((Count < 0) && (m_Pos == pos_start)) return 0;
m_Done = false;
const string Cmd( "MOVE " + OffsetString(Count) + " IN " + m_Name);
long int A = 0;
try
{
result R( m_Trans.Exec(Cmd.c_str()) );
if (!sscanf(R.CmdStatus(), "MOVE %ld", &A))
throw runtime_error("Didn't understand database's reply to MOVE: "
"'" + string(R.CmdStatus()) + "'");
}
catch (const exception &)
{
m_Pos = size_type(pos_unknown);
throw;
}
return NormalizedMove(Count, A);
}
pqxx::Cursor::difference_type
pqxx::Cursor::NormalizedMove(difference_type Intended,
difference_type Actual)
{
if (Actual < 0)
throw logic_error("libpqxx internal error: Negative rowcount");
if (Actual > labs(Intended))
throw logic_error("libpqxx internal error: Moved/fetched too many rows "
"(wanted " + to_string(Intended) + ", "
"got " + to_string(Actual) + ")");
difference_type Offset = Actual;
if (m_Pos == size_type(pos_unknown))
{
if (Actual < labs(Intended))
{
if (Intended < 0)
{
// Must have gone back to starting position
m_Pos = pos_start;
}
else if (m_Size == pos_unknown)
{
// Oops. We'd want to set result set size at this point, but we can't
// because we don't know our position.
throw runtime_error("Can't determine result set size: "
"Cursor position unknown at end of set");
}
}
// Nothing more we can do to update our position
return (Intended > 0) ? Actual : -Actual;
}
if (Actual < labs(Intended))
{
// There is a nonexistant row before the first one in the result set, and
// one after the last row, where we may be positioned. Unfortunately
// PostgreSQL only reports "real" rows, making it really hard to figure out
// how many rows we've really moved.
if (Actual)
{
// We've moved off either edge of our result set; add the one,
// nonexistant row that wasn't counted in the status string we got.
Offset++;
}
else if (Intended < 0)
{
// We've either moved off the "left" edge of our result set from the
// first actual row, or we were on the nonexistant row before the first
// actual row and so didn't move at all. Just set up Actual so that we
// end up at our starting position, which is where we must be.
Offset = m_Pos - pos_start;
}
else if (m_Size != pos_unknown)
{
// We either just walked off the right edge (moving at least one row in
// the process), or had done so already (in which case we haven't moved).
// In the case at hand, we already know where the right-hand edge of the
// result set is, so we use that to compute our offset.
Offset = (m_Size + pos_start + 1) - m_Pos;
}
else
{
// This is the hard one. Assume that we haven't seen the "right edge"
// before, because m_Size hasn't been set yet. Therefore, we must have
// just stepped off the edge (and m_Size will be set now).
Offset++;
}
if ((Offset > labs(Intended)) && (m_Pos != size_type(pos_unknown)))
{
m_Pos = size_type(pos_unknown);
throw logic_error("libpqxx internal error: Confused cursor position");
}
}
if (Intended < 0) Offset = -Offset;
m_Pos += Offset;
if ((Intended > 0) && (Actual < Intended) && (m_Size == pos_unknown))
m_Size = m_Pos - pos_start - 1;
m_Done = !Actual;
return Offset;
}
void pqxx::Cursor::MoveTo(size_type Dest)
{
// If we don't know where we are, go back to the beginning first.
if (m_Pos == size_type(pos_unknown)) Move(BACKWARD_ALL());
Move(Dest - Pos());
}
pqxx::Cursor::difference_type pqxx::Cursor::ALL() throw ()
{
#ifdef _WIN32
return INT_MAX;
#else // _WIN32
return numeric_limits<result::difference_type>::max();
#endif // _WIN32
}
pqxx::Cursor::difference_type pqxx::Cursor::BACKWARD_ALL() throw ()
{
#ifdef _WIN32
return INT_MIN + 1;
#else // _WIN32
return numeric_limits<result::difference_type>::min() + 1;
#endif // _WIN32
}
string pqxx::Cursor::OffsetString(difference_type Count)
{
if (Count == ALL()) return "ALL";
else if (Count == BACKWARD_ALL()) return "BACKWARD ALL";
return to_string(Count);
}
string pqxx::Cursor::MakeFetchCmd(difference_type Count) const
{
return "FETCH " + OffsetString(Count) + " IN " + m_Name;
}
<|endoftext|> |
<commit_before>/*
* QEMU USB HID devices
*
* Copyright (c) 2005 Fabrice Bellard
*
* 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 "../qemu-usb/vl.h"
/* HID interface requests */
#define GET_REPORT 0xa101
#define GET_IDLE 0xa102
#define GET_PROTOCOL 0xa103
#define SET_IDLE 0x210a
#define SET_PROTOCOL 0x210b
#define USB_MOUSE 1
#define USB_TABLET 2
#include "type.h"
#include "usb.h"
#include "audio.h"
#include "usbcfg.h"
#include "usbdesc.h"
typedef struct SINGSTARMICState {
USBDevice dev;
//nothing yet
} SINGSTARMICState;
/* descriptor dumped from a real singstar MIC adapter */
static const uint8_t singstar_mic_dev_descriptor[] = {
/* bLength */ 0x12, //(18)
/* bDescriptorType */ 0x01, //(1)
/* bcdUSB */ WBVAL(0x0110), //(272)
/* bDeviceClass */ 0x00, //(0)
/* bDeviceSubClass */ 0x00, //(0)
/* bDeviceProtocol */ 0x00, //(0)
/* bMaxPacketSize0 */ 0x08, //(8)
/* idVendor */ WBVAL(0x1415), //(5141)
/* idProduct */ WBVAL(0x0000), //(0)
/* bcdDevice */ WBVAL(0x0001), //(1)
/* iManufacturer */ 0x01, //(1)
/* iProduct */ 0x02, //(2)
/* iSerialNumber */ 0x00, //(0)
/* bNumConfigurations */ 0x01, //(1)
};
static const uint8_t singstar_mic_config_descriptor[] = {
/* Configuration 1 */
0x09, /* bLength */
USB_CONFIGURATION_DESCRIPTOR_TYPE, /* bDescriptorType */
WBVAL(0x00b1), /* wTotalLength */
0x02, /* bNumInterfaces */
0x01, /* bConfigurationValue */
0x00, /* iConfiguration */
USB_CONFIG_BUS_POWERED, /* bmAttributes */
USB_CONFIG_POWER_MA(90), /* bMaxPower */
/* Interface 0, Alternate Setting 0, Audio Control */
USB_INTERFACE_DESC_SIZE, /* bLength */
USB_INTERFACE_DESCRIPTOR_TYPE, /* bDescriptorType */
0x00, /* bInterfaceNumber */
0x00, /* bAlternateSetting */
0x00, /* bNumEndpoints */
USB_DEVICE_CLASS_AUDIO, /* bInterfaceClass */
AUDIO_SUBCLASS_AUDIOCONTROL, /* bInterfaceSubClass */
AUDIO_PROTOCOL_UNDEFINED, /* bInterfaceProtocol */
0x00, /* iInterface */
/* Audio Control Interface */
AUDIO_CONTROL_INTERFACE_DESC_SZ(1), /* bLength */
AUDIO_INTERFACE_DESCRIPTOR_TYPE, /* bDescriptorType */
AUDIO_CONTROL_HEADER, /* bDescriptorSubtype */
WBVAL(0x0100), /* 1.00 */ /* bcdADC */
WBVAL(0x0028), /* wTotalLength */
0x01, /* bInCollection */
0x01, /* baInterfaceNr */
/* Audio Input Terminal */
AUDIO_INPUT_TERMINAL_DESC_SIZE, /* bLength */
AUDIO_INTERFACE_DESCRIPTOR_TYPE, /* bDescriptorType */
AUDIO_CONTROL_INPUT_TERMINAL, /* bDescriptorSubtype */
0x01, /* bTerminalID */
WBVAL(AUDIO_TERMINAL_MICROPHONE), /* wTerminalType */
0x02, /* bAssocTerminal */
0x02, /* bNrChannels */
WBVAL(AUDIO_CHANNEL_L
|AUDIO_CHANNEL_R), /* wChannelConfig */
0x00, /* iChannelNames */
0x00, /* iTerminal */
/* Audio Output Terminal */
AUDIO_OUTPUT_TERMINAL_DESC_SIZE, /* bLength */
AUDIO_INTERFACE_DESCRIPTOR_TYPE, /* bDescriptorType */
AUDIO_CONTROL_OUTPUT_TERMINAL, /* bDescriptorSubtype */
0x02, /* bTerminalID */
WBVAL(AUDIO_TERMINAL_USB_STREAMING), /* wTerminalType */
0x01, /* bAssocTerminal */
0x03, /* bSourceID */
0x00, /* iTerminal */
/* Audio Feature Unit */
AUDIO_FEATURE_UNIT_DESC_SZ(2,1), /* bLength */
AUDIO_INTERFACE_DESCRIPTOR_TYPE, /* bDescriptorType */
AUDIO_CONTROL_FEATURE_UNIT, /* bDescriptorSubtype */
0x03, /* bUnitID */
0x01, /* bSourceID */
0x01, /* bControlSize */
0x01, /* bmaControls(0) */
0x02, /* bmaControls(1) */
0x02, /* bmaControls(2) */
0x00, /* iTerminal */
/* Interface 1, Alternate Setting 0, Audio Streaming - Zero Bandwith */
USB_INTERFACE_DESC_SIZE, /* bLength */
USB_INTERFACE_DESCRIPTOR_TYPE, /* bDescriptorType */
0x01, /* bInterfaceNumber */
0x00, /* bAlternateSetting */
0x00, /* bNumEndpoints */
USB_DEVICE_CLASS_AUDIO, /* bInterfaceClass */
AUDIO_SUBCLASS_AUDIOSTREAMING, /* bInterfaceSubClass */
AUDIO_PROTOCOL_UNDEFINED, /* bInterfaceProtocol */
0x00, /* iInterface */
/* Interface 1, Alternate Setting 1, Audio Streaming - Operational */
USB_INTERFACE_DESC_SIZE, /* bLength */
USB_INTERFACE_DESCRIPTOR_TYPE, /* bDescriptorType */
0x01, /* bInterfaceNumber */
0x01, /* bAlternateSetting */
0x01, /* bNumEndpoints */
USB_DEVICE_CLASS_AUDIO, /* bInterfaceClass */
AUDIO_SUBCLASS_AUDIOSTREAMING, /* bInterfaceSubClass */
AUDIO_PROTOCOL_UNDEFINED, /* bInterfaceProtocol */
0x00, /* iInterface */
/* Audio Streaming Interface */
AUDIO_STREAMING_INTERFACE_DESC_SIZE, /* bLength */
AUDIO_INTERFACE_DESCRIPTOR_TYPE, /* bDescriptorType */
AUDIO_STREAMING_GENERAL, /* bDescriptorSubtype */
0x02, /* bTerminalLink */
0x01, /* bDelay */
WBVAL(AUDIO_FORMAT_PCM), /* wFormatTag */
/* Audio Type I Format */
AUDIO_FORMAT_TYPE_I_DESC_SZ(5), /* bLength */
AUDIO_INTERFACE_DESCRIPTOR_TYPE, /* bDescriptorType */
AUDIO_STREAMING_FORMAT_TYPE, /* bDescriptorSubtype */
AUDIO_FORMAT_TYPE_I, /* bFormatType */
0x01, /* bNrChannels */
0x02, /* bSubFrameSize */
0x10, /* bBitResolution */
0x05, /* bSamFreqType */
B3VAL(8000), /* tSamFreq 1 */
B3VAL(11025), /* tSamFreq 2 */
B3VAL(22050), /* tSamFreq 3 */
B3VAL(44100), /* tSamFreq 4 */
B3VAL(48000), /* tSamFreq 5 */
/* Endpoint - Standard Descriptor */
AUDIO_STANDARD_ENDPOINT_DESC_SIZE, /* bLength */
USB_ENDPOINT_DESCRIPTOR_TYPE, /* bDescriptorType */
USB_ENDPOINT_OUT(0x81), /* bEndpointAddress */
USB_ENDPOINT_TYPE_ISOCHRONOUS
| USB_ENDPOINT_SYNC_ASYNCHRONOUS, /* bmAttributes */
WBVAL(0x0064), /* wMaxPacketSize */
0x01, /* bInterval */
0x00, /* bRefresh */
0x00, /* bSynchAddress */
/* Endpoint - Audio Streaming */
AUDIO_STREAMING_ENDPOINT_DESC_SIZE, /* bLength */
AUDIO_ENDPOINT_DESCRIPTOR_TYPE, /* bDescriptorType */
AUDIO_ENDPOINT_GENERAL, /* bDescriptor */
0x01, /* bmAttributes */
0x00, /* bLockDelayUnits */
WBVAL(0x0000), /* wLockDelay */
/* Interface 1, Alternate Setting 2, Audio Streaming - ? */
USB_INTERFACE_DESC_SIZE, /* bLength */
USB_INTERFACE_DESCRIPTOR_TYPE, /* bDescriptorType */
0x01, /* bInterfaceNumber */
0x02, /* bAlternateSetting */
0x01, /* bNumEndpoints */
USB_DEVICE_CLASS_AUDIO, /* bInterfaceClass */
AUDIO_SUBCLASS_AUDIOSTREAMING, /* bInterfaceSubClass */
AUDIO_PROTOCOL_UNDEFINED, /* bInterfaceProtocol */
0x00, /* iInterface */
/* Audio Streaming Interface */
AUDIO_STREAMING_INTERFACE_DESC_SIZE, /* bLength */
AUDIO_INTERFACE_DESCRIPTOR_TYPE, /* bDescriptorType */
AUDIO_STREAMING_GENERAL, /* bDescriptorSubtype */
0x02, /* bTerminalLink */
0x01, /* bDelay */
WBVAL(AUDIO_FORMAT_PCM), /* wFormatTag */
/* Audio Type I Format */
AUDIO_FORMAT_TYPE_I_DESC_SZ(5), /* bLength */
AUDIO_INTERFACE_DESCRIPTOR_TYPE, /* bDescriptorType */
AUDIO_STREAMING_FORMAT_TYPE, /* bDescriptorSubtype */
AUDIO_FORMAT_TYPE_I, /* bFormatType */
0x02, /* bNrChannels */
0x02, /* bSubFrameSize */
0x10, /* bBitResolution */
0x05, /* bSamFreqType */
B3VAL(8000), /* tSamFreq 1 */
B3VAL(11025), /* tSamFreq 2 */
B3VAL(22050), /* tSamFreq 3 */
B3VAL(44100), /* tSamFreq 4 */
B3VAL(48000), /* tSamFreq 5 */
/* Endpoint - Standard Descriptor */
AUDIO_STANDARD_ENDPOINT_DESC_SIZE, /* bLength */
USB_ENDPOINT_DESCRIPTOR_TYPE, /* bDescriptorType */
USB_ENDPOINT_OUT(0x81), /* bEndpointAddress */
USB_ENDPOINT_TYPE_ISOCHRONOUS
| USB_ENDPOINT_SYNC_ASYNCHRONOUS, /* bmAttributes */
WBVAL(0x00c8), /* wMaxPacketSize */
0x01, /* bInterval */
0x00, /* bRefresh */
0x00, /* bSynchAddress */
/* Endpoint - Audio Streaming */
AUDIO_STREAMING_ENDPOINT_DESC_SIZE, /* bLength */
AUDIO_ENDPOINT_DESCRIPTOR_TYPE, /* bDescriptorType */
AUDIO_ENDPOINT_GENERAL, /* bDescriptor */
0x01, /* bmAttributes */
0x00, /* bLockDelayUnits */
WBVAL(0x0000), /* wLockDelay */
/* Terminator */
0 /* bLength */
};
static void singstar_mic_handle_reset(USBDevice *dev)
{
/* XXX: do it */
return;
}
static int singstar_mic_handle_control(USBDevice *dev, int request, int value,
int index, int length, uint8_t *data)
{
SINGSTARMICState *s = (SINGSTARMICState *)dev;
int ret = 0;
switch(request) {
case DeviceRequest | USB_REQ_GET_STATUS:
data[0] = (dev->remote_wakeup << USB_DEVICE_REMOTE_WAKEUP);
data[1] = 0x00;
ret = 2;
break;
case DeviceOutRequest | USB_REQ_CLEAR_FEATURE:
if (value == USB_DEVICE_REMOTE_WAKEUP) {
dev->remote_wakeup = 0;
} else {
goto fail;
}
ret = 0;
break;
case DeviceOutRequest | USB_REQ_SET_FEATURE:
if (value == USB_DEVICE_REMOTE_WAKEUP) {
dev->remote_wakeup = 1;
} else {
goto fail;
}
ret = 0;
break;
case DeviceOutRequest | USB_REQ_SET_ADDRESS:
dev->addr = value;
ret = 0;
break;
case DeviceRequest | USB_REQ_GET_DESCRIPTOR:
switch(value >> 8) {
case USB_DT_DEVICE:
memcpy(data, singstar_mic_dev_descriptor,
sizeof(singstar_mic_dev_descriptor));
ret = sizeof(singstar_mic_dev_descriptor);
break;
case USB_DT_CONFIG:
memcpy(data, singstar_mic_config_descriptor,
sizeof(singstar_mic_config_descriptor));
ret = sizeof(singstar_mic_config_descriptor);
break;
case USB_DT_STRING:
switch(value & 0xff) {
case 0:
/* language ids */
data[0] = 4;
data[1] = 3;
data[2] = 0x09;
data[3] = 0x04;
ret = 4;
break;
case 1:
/* serial number */
ret = set_usb_string(data, "3X0420811");
break;
case 2:
/* product description */
ret = set_usb_string(data, "EyeToy USB camera Namtai");
break;
case 3:
/* vendor description */
ret = set_usb_string(data, "PCSX2/QEMU");
break;
default:
goto fail;
}
break;
default:
goto fail;
}
break;
case DeviceRequest | USB_REQ_GET_CONFIGURATION:
data[0] = 1;
ret = 1;
break;
case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
ret = 0;
break;
case DeviceRequest | USB_REQ_GET_INTERFACE:
data[0] = 0;
ret = 1;
break;
case DeviceOutRequest | USB_REQ_SET_INTERFACE:
ret = 0;
break;
/* hid specific requests */
case InterfaceRequest | USB_REQ_GET_DESCRIPTOR:
//switch(value >> 8) {
//((case 0x22:
// memcpy(data, qemu_mouse_hid_report_descriptor,
// sizeof(qemu_mouse_hid_report_descriptor));
// ret = sizeof(qemu_mouse_hid_report_descriptor);
// break;
//default:
goto fail;
//}
break;
case GET_REPORT:
ret = 0;
break;
case SET_IDLE:
ret = 0;
break;
default:
fail:
ret = USB_RET_STALL;
break;
}
return ret;
}
static int singstar_mic_handle_data(USBDevice *dev, int pid,
uint8_t devep, uint8_t *data, int len)
{
SINGSTARMICState *s = (SINGSTARMICState *)dev;
int ret = 0;
switch(pid) {
case USB_TOKEN_IN:
if (devep == 1) {
goto fail;
}
break;
case USB_TOKEN_OUT:
default:
fail:
ret = USB_RET_STALL;
break;
}
return ret;
}
static void singstar_mic_handle_destroy(USBDevice *dev)
{
SINGSTARMICState *s = (SINGSTARMICState *)dev;
free(s);
}
int singstar_mic_handle_packet(USBDevice *s, int pid,
uint8_t devaddr, uint8_t devep,
uint8_t *data, int len)
{
fprintf(stderr,"usb-singstar_mic: packet received with pid=%x, devaddr=%x, devep=%x and len=%x\n",pid,devaddr,devep,len);
return usb_generic_handle_packet(s,pid,devaddr,devep,data,len);
}
USBDevice *singstar_mic_init()
{
SINGSTARMICState *s;
s = (SINGSTARMICState *)qemu_mallocz(sizeof(SINGSTARMICState));
if (!s)
return NULL;
s->dev.speed = USB_SPEED_FULL;
s->dev.handle_packet = singstar_mic_handle_packet;
s->dev.handle_reset = singstar_mic_handle_reset;
s->dev.handle_control = singstar_mic_handle_control;
s->dev.handle_data = singstar_mic_handle_data;
s->dev.handle_destroy = singstar_mic_handle_destroy;
strncpy(s->dev.devname, "EyeToy USB camera Namtai", sizeof(s->dev.devname));
return (USBDevice *)s;
}
<commit_msg>delete usb-mic-dummy.cpp<commit_after><|endoftext|> |
<commit_before>#include "fish_annotator/video_annotator/player.h"
#include <QTime>
#include <QCoreApplication>
#include <QEventLoop>
#include <QMutexLocker>
namespace fish_annotator { namespace video_annotator {
Player::Player()
: QObject()
, video_path_()
, frame_rate_(0.0)
, stopped_(true)
, frame_mat_()
, rgb_frame_mat_()
, image_()
, current_speed_(0.0)
, capture_(nullptr)
, delay_(0.0)
, frame_index_(0)
, mutex_()
, condition_() {
}
Player::~Player() {
QMutexLocker locker(&mutex_);
stopped_ = true;
condition_.wakeOne();
}
void Player::loadVideo(QString filename) {
video_path_ = filename;
capture_.reset(new cv::VideoCapture(filename.toStdString()));
if (capture_->isOpened()) {
frame_rate_ = capture_->get(CV_CAP_PROP_FPS);
current_speed_ = frame_rate_;
delay_ = (1000000.0 / frame_rate_);
emit mediaLoaded(filename, frame_rate_);
emit playbackRateChanged(current_speed_);
emit durationChanged(capture_->get(CV_CAP_PROP_FRAME_COUNT));
emit resolutionChanged(
capture_->get(static_cast<qint64>(CV_CAP_PROP_FRAME_WIDTH)),
capture_->get(static_cast<qint64>(CV_CAP_PROP_FRAME_HEIGHT)));
}
else {
std::string msg(
std::string("Failed to load media at ") +
filename.toStdString() +
std::string("!"));
emit error(QString(msg.c_str()));
}
}
void Player::play() {
if(stopped_ == true) {
stopped_ = false;
}
emit stateChanged(stopped_);
while(stopped_ == false) {
auto time = QTime::currentTime();
emit processedImage(getOneFrame(), frame_index_);
double usec = 1000.0 * (QTime::currentTime().msec() - time.msec());
processWait(std::round(delay_ - usec));
}
}
void Player::stop() {
stopped_ = true;
emit stateChanged(stopped_);
}
QImage Player::getOneFrame() {
QMutexLocker locker(&mutex_);
if (capture_->read(frame_mat_) == false) {
stopped_ = true;
}
frame_index_ = capture_->get(CV_CAP_PROP_POS_FRAMES);
if (frame_mat_.channels() == 3) {
cv::cvtColor(frame_mat_, rgb_frame_mat_, CV_BGR2RGB);
image_ = QImage(
(const unsigned char*)(rgb_frame_mat_.data),
frame_mat_.cols,
frame_mat_.rows,
QImage::Format_RGB888);
}
else {
image_ = QImage(
(const unsigned char*)(frame_mat_.data),
frame_mat_.cols,
frame_mat_.rows,
QImage::Format_Indexed8);
}
return image_;
}
void Player::speedUp() {
delay_ /= 2.0;
if(delay_ < 1.0) delay_ = 1.0;
current_speed_ *= 2.0;
emit playbackRateChanged(current_speed_);
}
void Player::slowDown() {
delay_ *= 2.0;
current_speed_ /= 2.0;
emit playbackRateChanged(current_speed_);
}
void Player::nextFrame() {
setCurrentFrame(frame_index_ + 1);
emit processedImage(getOneFrame(), frame_index_);
}
void Player::prevFrame() {
setCurrentFrame(frame_index_ - 1);
emit processedImage(getOneFrame(), frame_index_);
}
void Player::setCurrentFrame(qint64 frame_num) {
QMutexLocker locker(&mutex_);
capture_->set(CV_CAP_PROP_POS_MSEC,
1000.0 * static_cast<double>(frame_num - 1) / frame_rate_);
if (frame_num > 0) {
frame_index_ = capture_->get(CV_CAP_PROP_POS_FRAMES);
}
else {
frame_index_ = 0;
}
}
void Player::setFrame(qint64 frame) {
setCurrentFrame(frame);
emit processedImage(getOneFrame(), frame_index_);
}
void Player::processWait(qint64 usec) {
QTime die_time = QTime::currentTime().addMSecs(usec / 1000);
while(QTime::currentTime() < die_time) {
QCoreApplication::processEvents(QEventLoop::AllEvents, 1);
}
}
#include "../../include/fish_annotator/video_annotator/moc_player.cpp"
}} // namespace fish_annotator::gui
<commit_msg>Changed the delay timing calculations by using QTime and start/restart. Fixes #27<commit_after>#include "fish_annotator/video_annotator/player.h"
#include <QTime>
#include <QCoreApplication>
#include <QEventLoop>
#include <QMutexLocker>
namespace fish_annotator { namespace video_annotator {
Player::Player()
: QObject()
, video_path_()
, frame_rate_(0.0)
, stopped_(true)
, frame_mat_()
, rgb_frame_mat_()
, image_()
, current_speed_(0.0)
, capture_(nullptr)
, delay_(0.0)
, frame_index_(0)
, mutex_()
, condition_() {
}
Player::~Player() {
QMutexLocker locker(&mutex_);
stopped_ = true;
condition_.wakeOne();
}
void Player::loadVideo(QString filename) {
video_path_ = filename;
capture_.reset(new cv::VideoCapture(filename.toStdString()));
if (capture_->isOpened()) {
frame_rate_ = capture_->get(CV_CAP_PROP_FPS);
current_speed_ = frame_rate_;
delay_ = (1000000.0 / frame_rate_);
emit mediaLoaded(filename, frame_rate_);
emit playbackRateChanged(current_speed_);
emit durationChanged(capture_->get(CV_CAP_PROP_FRAME_COUNT));
emit resolutionChanged(
capture_->get(static_cast<qint64>(CV_CAP_PROP_FRAME_WIDTH)),
capture_->get(static_cast<qint64>(CV_CAP_PROP_FRAME_HEIGHT)));
}
else {
std::string msg(
std::string("Failed to load media at ") +
filename.toStdString() +
std::string("!"));
emit error(QString(msg.c_str()));
}
}
void Player::play() {
if(stopped_ == true) {
stopped_ = false;
}
emit stateChanged(stopped_);
while(stopped_ == false) {
QTime t;
t.start();
emit processedImage(getOneFrame(), frame_index_);
double usec = 1000.0 * t.restart();
processWait(std::round(delay_ - usec));
}
}
void Player::stop() {
stopped_ = true;
emit stateChanged(stopped_);
}
QImage Player::getOneFrame() {
QMutexLocker locker(&mutex_);
if (capture_->read(frame_mat_) == false) {
stopped_ = true;
}
frame_index_ = capture_->get(CV_CAP_PROP_POS_FRAMES);
if (frame_mat_.channels() == 3) {
cv::cvtColor(frame_mat_, rgb_frame_mat_, CV_BGR2RGB);
image_ = QImage(
(const unsigned char*)(rgb_frame_mat_.data),
frame_mat_.cols,
frame_mat_.rows,
QImage::Format_RGB888);
}
else {
image_ = QImage(
(const unsigned char*)(frame_mat_.data),
frame_mat_.cols,
frame_mat_.rows,
QImage::Format_Indexed8);
}
return image_;
}
void Player::speedUp() {
delay_ /= 2.0;
if(delay_ < 1.0) delay_ = 1.0;
current_speed_ *= 2.0;
emit playbackRateChanged(current_speed_);
}
void Player::slowDown() {
delay_ *= 2.0;
current_speed_ /= 2.0;
emit playbackRateChanged(current_speed_);
}
void Player::nextFrame() {
setCurrentFrame(frame_index_ + 1);
emit processedImage(getOneFrame(), frame_index_);
}
void Player::prevFrame() {
setCurrentFrame(frame_index_ - 1);
emit processedImage(getOneFrame(), frame_index_);
}
void Player::setCurrentFrame(qint64 frame_num) {
QMutexLocker locker(&mutex_);
capture_->set(CV_CAP_PROP_POS_MSEC,
1000.0 * static_cast<double>(frame_num - 1) / frame_rate_);
if (frame_num > 0) {
frame_index_ = capture_->get(CV_CAP_PROP_POS_FRAMES);
}
else {
frame_index_ = 0;
}
}
void Player::setFrame(qint64 frame) {
setCurrentFrame(frame);
emit processedImage(getOneFrame(), frame_index_);
}
void Player::processWait(qint64 usec) {
QTime die_time = QTime::currentTime().addMSecs(usec / 1000);
while(QTime::currentTime() < die_time) {
QCoreApplication::processEvents(QEventLoop::AllEvents, 1);
}
}
#include "../../include/fish_annotator/video_annotator/moc_player.cpp"
}} // namespace fish_annotator::gui
<|endoftext|> |
<commit_before>#include "Renderer.h"
Renderer::Renderer(){
myname = "Renderer";
nextPickingName = 100;
cursorsize = 10;
maxcursors = 20;
captureincrement= 2;
mapsampling = 2;
touchtomouse = true;
mousetotouch = true;
mousetouchid = -1;
currentviewport = ofRectangle(0,0,0,0);
bTuioSetup = false;
bColorPickerSetup = false;
isRenderer = true;
_isAddedToRenderer = true;
drawcursors = true;
idleEventFired = false;
idleTimeout = 30000; // 30 seconds
fboReader.setAsync(true);
}
Renderer::~Renderer(){
}
void Renderer::resize(){
BasicScreenObject::setSize(ofGetWidth(),ofGetHeight());
camera.setupPerspective();
}
void Renderer::setup(){
BasicScreenObject::setSize(ofGetWidth(),ofGetHeight());
camera.setupPerspective();
ofAddListener(ofEvents().mousePressed, this, &Renderer::mousePressed);
ofAddListener(ofEvents().mouseDragged, this, &Renderer::mouseDragged);
ofAddListener(ofEvents().mouseReleased, this, &Renderer::mouseReleased);
ofAddListener(ofEvents().touchDown,this,&Renderer::tuioAdded);
ofAddListener(ofEvents().touchUp,this,&Renderer::tuioRemoved);
ofAddListener(ofEvents().touchMoved,this,&Renderer::tuioUpdated);
}
void Renderer::setupColorPicker(float _width, float _height, float _sampling, float _increment){
BasicScreenObject::setSize(_width,_height);
mapsampling = _sampling;
captureincrement = _increment;
mapscale = 1.0f/(float)mapsampling;
ofFbo::Settings s;
s.width = (float)getWidth() / mapsampling;
s.height = (float)getHeight() / mapsampling;
s.internalformat = GL_RGB; // would be much faster using GL_LUMINANCE or GL_LUMINANCE32F_ARB (32bit resolution should be enough);
s.useDepth = true;
pickingmap.allocate(s);
maxbounds = ofRectangle ( 0 , 0 , pickingmap.getWidth()-1 , pickingmap.getHeight()-1 ) ;
// camera.setupPerspective();
bColorPickerSetup=true;
}
void Renderer::update(){
Tweener.update();
if(bColorPickerSetup){
bool waslighting = glIsEnabled(GL_LIGHTING);
if(waslighting){
glDisable(GL_LIGHTING);
}
if(ofGetFrameNum() % captureincrement==0){
pickingmap.begin();
ofClear(0);
ofScale( mapscale , mapscale , mapscale);
camera.begin();
BasicScreenObject::drawForPicking();
camera.end();
pickingmap.end();
}
if(waslighting){
glEnable(GL_LIGHTING);
}
if (!touchActions.empty()) {
pickingmap.readToPixels(mapPixels); // < takes 20ms for rgb fbo. 1ms for GL_LUMINANCE
//fboReader.readToPixels(pickingmap, mapPixels);
}
while (!touchActions.empty() ) {
notifyObjects(touchActions.front());
touchActions.pop();
}
}
if (!idleEventFired) {
if (ofGetElapsedTimeMillis() > lastinteraction + idleTimeout) {
idleEventFired = true;
ofNotifyEvent(idleEvent, myEventArgs, this);
}
}
}
void Renderer::forceUpdate() { update(); }
void Renderer::draw(){
currentviewport = ofGetCurrentViewport();
camera.begin();
BasicScreenObject::draw();
camera.end();
if (drawcursors) drawCursors();
}
void Renderer::startTuio(int _port) {
port = _port;
tuio.connect(_port);
bTuioSetup = true;
}
void Renderer::tuioAdded(ofTouchEventArgs & _cursor) {
if (touchtomouse && mousetouchid==-1) {
mousetouchid = _cursor.id;
static ofMouseEventArgs mouseEventArgs;
mouseEventArgs.x = _cursor.x*getWidth();
mouseEventArgs.y = _cursor.y*getHeight();
mouseEventArgs.button = 1;
lastfakemouseevent = &mouseEventArgs;
ofNotifyEvent( ofEvents().mousePressed, mouseEventArgs );
}
queueTouchAction(_cursor.x*getWidth(), _cursor.y*getHeight(), _cursor.id, MT_ADD);
}
void Renderer::tuioRemoved(ofTouchEventArgs & _cursor){
if (touchtomouse && mousetouchid==_cursor.id) {
mousetouchid = -1;
static ofMouseEventArgs mouseEventArgs;
mouseEventArgs.x = _cursor.x*getWidth();
mouseEventArgs.y = _cursor.y*getHeight();
mouseEventArgs.button = 1;
lastfakemouseevent = &mouseEventArgs;
ofNotifyEvent( ofEvents().mouseReleased , mouseEventArgs );
}
queueTouchAction(_cursor.x*getWidth(), _cursor.y*getHeight(), _cursor.id, MT_REMOVE);
}
void Renderer::tuioUpdated(ofTouchEventArgs & _cursor){
if (touchtomouse && mousetouchid==_cursor.id) {
static ofMouseEventArgs mouseEventArgs;
mouseEventArgs.x = _cursor.x*getWidth();
mouseEventArgs.y = _cursor.y*getHeight();
mouseEventArgs.button = 1;
lastfakemouseevent = &mouseEventArgs;
ofNotifyEvent( ofEvents().mouseDragged, mouseEventArgs );
}
queueTouchAction(_cursor.x*getWidth(), _cursor.y*getHeight(), _cursor.id, MT_UPDATE);
}
void Renderer::mousePressed(ofMouseEventArgs& _cursor){
if (mousetotouch) {
// ignore this mouse-event, if it was created by emulating a mouse-event from a touch
if (lastfakemouseevent != &_cursor) {
queueTouchAction(_cursor.x, _cursor.y, -1, MT_ADD);
}
}
}
void Renderer::mouseReleased(ofMouseEventArgs& _cursor){
if (mousetotouch) {
// ignore this mouse-event, if it was created by emulating a mouse-event from a touch
if (lastfakemouseevent != &_cursor) {
queueTouchAction(_cursor.x, _cursor.y, -1, MT_REMOVE);
}
}
}
void Renderer::mouseDragged(ofMouseEventArgs& _cursor){
if (mousetotouch) {
// ignore this mouse-event, if it was created by emulating a mouse-event from a touch
if (lastfakemouseevent != &_cursor) {
queueTouchAction(_cursor.x, _cursor.y, -1, MT_UPDATE);
}
}
}
void Renderer::queueTouchAction(float _screenx, float _screeny, int _fingerid, int _action) {
TouchAction touch = {_screenx, _screeny, _fingerid, _action};
touchActions.push(touch);
}
void Renderer::notifyObjects(TouchAction _touchAction) {
mtRay ray;
// y-Axis needs to be flipped from openframeworks 0.8.0 on because of the flipped camera (somehow)
ray.pos = camera.screenToWorld( ofVec3f( _touchAction.screenX, getHeight()-_touchAction.screenY,-1), currentviewport);
ray.dir = camera.screenToWorld( ofVec3f( _touchAction.screenX,getHeight()-_touchAction.screenY, 1), currentviewport) - ray.pos;
ray.screenpos.set(_touchAction.screenX, _touchAction.screenY);
BasicInteractiveObject* overobj = (BasicInteractiveObject*)getObjectAt(_touchAction.screenX, _touchAction.screenY);
for(int i=0;i<pickingObjects.size();i++){
BasicInteractiveObject* obj =(BasicInteractiveObject*) pickingObjects[i];
if (obj != NULL && obj!=overobj) {
switch (_touchAction.action) {
case (MT_ADD) : {
obj->touchDownOutside( ray,_touchAction.fingerId );
break;
}
case (MT_UPDATE) : {
obj->touchMovedOutside( ray,_touchAction.fingerId );
break;
}
case (MT_REMOVE) : {
obj->touchUpOutside( ray,_touchAction.fingerId );
break;
}
}
}
}
if(overobj!=NULL){
switch (_touchAction.action) {
case (MT_ADD) : {
overobj->touchDownOnMe( ray,_touchAction.fingerId );
break;
}
case (MT_UPDATE) : {
overobj->touchMovedOnMe(ray,_touchAction.fingerId );
break;
}
case (MT_REMOVE) : {
overobj->touchUpOnMe( ray,_touchAction.fingerId );
break;
}
}
}
lastinteraction = ofGetElapsedTimeMillis();
if (idleEventFired) {
idleEventFired = false;
ofNotifyEvent(idleFinishEvent, myEventArgs, this);
}
}
void Renderer::drawMap() {
ofSetColor(255, 255, 255);
ofPushMatrix();
// ofScale(1.0/mapscale,1.0/mapscale);
pickingmap.draw(0, 0);
ofPopMatrix();
}
void Renderer::drawCursors(){
ofEnableAlphaBlending();
glBlendFunc(GL_ONE, GL_ONE);
if(bTuioSetup){
std::list<TuioCursor*> cursorList = tuio.client->getTuioCursors();
std::list<TuioCursor*>::iterator tit;
tuio.client->lockCursorList();
for (tit = cursorList.begin(); tit != cursorList.end(); tit++) {
TuioCursor * cur = (*tit);
glColor3f(0.1,0.1, 0.1);
for(int i = 0; i < 5; i++){
ofEllipse(cur->getX()*getWidth(),
cur->getY()*getHeight(),
20.0+i*i,
20.0+i*i);
}
}
tuio.client->unlockCursorList();
}
if (mousetotouch) {
if (ofGetMousePressed()) {
glColor3f(0.1,0.1, 0.1);
for(int i = 0; i < 5; i++){
ofEllipse(ofGetMouseX(),
ofGetMouseY(),
20.0+i*i,
20.0+i*i);
}
}
}
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
}
BasicScreenObject* Renderer::getObjectAt(float _screenx, float _screeny){
int fbox =_screenx/mapsampling;
int fboy =_screeny/mapsampling;
fbox = ofClamp(fbox, 0, maxbounds.width);
fboy = ofClamp(fboy, 0, maxbounds.height);
int index = (fbox + fboy * pickingmap.getWidth()) * 3 ;
//int index = (fbox + fboy * pickingmap.getWidth());
//if (bColorPickerSetup) pickingmap.readToPixels(mapPixels);
ofColor fboc = ofColor( mapPixels[index] , mapPixels[index + 1] , mapPixels[index + 2] );
//ofColor fboc = ofColor( mapPixels[index] , mapPixels[index] , mapPixels[index] );
GLint pickingName = colorToPickingName(fboc);
BasicScreenObject* obj = NULL;
if (pickingObjects.find(pickingName) != pickingObjects.end()) {
obj = pickingObjects[pickingName];
}
return obj;
}
GLuint Renderer::getNextPickingName(BasicInteractiveObject* _object) {
GLuint np = ++nextPickingName;
pickingObjects[np] = _object;
return np;
}
long Renderer::getLastInteractionMillis
(){
return lastinteraction;
}
void Renderer::isDrawCursors(bool _drawCursors) {
drawcursors = _drawCursors;
}
void Renderer::forceInteraction() {
lastinteraction = ofGetElapsedTimeMillis();
if (idleEventFired) {
idleEventFired = false;
ofNotifyEvent(idleFinishEvent, myEventArgs, this);
}
}<commit_msg>weird translate for fob<commit_after>#include "Renderer.h"
Renderer::Renderer(){
myname = "Renderer";
nextPickingName = 100;
cursorsize = 10;
maxcursors = 20;
captureincrement= 2;
mapsampling = 2;
touchtomouse = true;
mousetotouch = true;
mousetouchid = -1;
currentviewport = ofRectangle(0,0,0,0);
bTuioSetup = false;
bColorPickerSetup = false;
isRenderer = true;
_isAddedToRenderer = true;
drawcursors = true;
idleEventFired = false;
idleTimeout = 30000; // 30 seconds
fboReader.setAsync(true);
}
Renderer::~Renderer(){
}
void Renderer::resize(){
BasicScreenObject::setSize(ofGetWidth(),ofGetHeight());
camera.setupPerspective();
}
void Renderer::setup(){
BasicScreenObject::setSize(ofGetWidth(),ofGetHeight());
camera.setupPerspective();
ofAddListener(ofEvents().mousePressed, this, &Renderer::mousePressed);
ofAddListener(ofEvents().mouseDragged, this, &Renderer::mouseDragged);
ofAddListener(ofEvents().mouseReleased, this, &Renderer::mouseReleased);
ofAddListener(ofEvents().touchDown,this,&Renderer::tuioAdded);
ofAddListener(ofEvents().touchUp,this,&Renderer::tuioRemoved);
ofAddListener(ofEvents().touchMoved,this,&Renderer::tuioUpdated);
}
void Renderer::setupColorPicker(float _width, float _height, float _sampling, float _increment){
BasicScreenObject::setSize(_width,_height);
mapsampling = _sampling;
captureincrement = _increment;
mapscale = 1.0f/(float)mapsampling;
ofFbo::Settings s;
s.width = (float)getWidth() /(float) mapsampling;
s.height = (float)getHeight() /(float) mapsampling;
s.internalformat = GL_RGB; // would be much faster using GL_LUMINANCE or GL_LUMINANCE32F_ARB (32bit resolution should be enough);
s.useDepth = true;
pickingmap.allocate(s);
maxbounds = ofRectangle ( 0 , 0 , pickingmap.getWidth()-1 , pickingmap.getHeight()-1 ) ;
// camera.setupPerspective();
bColorPickerSetup=true;
}
void Renderer::update(){
Tweener.update();
if(bColorPickerSetup){
bool waslighting = glIsEnabled(GL_LIGHTING);
if(waslighting){
glDisable(GL_LIGHTING);
}
if(ofGetFrameNum() % captureincrement==0){
pickingmap.begin();
ofClear(0);
ofScale( mapscale , mapscale , mapscale);
camera.begin();
// TODO solve this weird offset!!
// Maybe coming from the window border?!
ofTranslate(0,0,-25);
BasicScreenObject::drawForPicking();
camera.end();
pickingmap.end();
}
if(waslighting){
glEnable(GL_LIGHTING);
}
if (!touchActions.empty()) {
pickingmap.readToPixels(mapPixels); // < takes 20ms for rgb fbo. 1ms for GL_LUMINANCE
//fboReader.readToPixels(pickingmap, mapPixels);
}
while (!touchActions.empty() ) {
notifyObjects(touchActions.front());
touchActions.pop();
}
}
if (!idleEventFired) {
if (ofGetElapsedTimeMillis() > lastinteraction + idleTimeout) {
idleEventFired = true;
ofNotifyEvent(idleEvent, myEventArgs, this);
}
}
}
void Renderer::forceUpdate() { update(); }
void Renderer::draw(){
currentviewport = ofGetCurrentViewport();
camera.begin();
BasicScreenObject::draw();
camera.end();
if (drawcursors) drawCursors();
}
void Renderer::startTuio(int _port) {
port = _port;
tuio.connect(_port);
bTuioSetup = true;
}
void Renderer::tuioAdded(ofTouchEventArgs & _cursor) {
if (touchtomouse && mousetouchid==-1) {
mousetouchid = _cursor.id;
static ofMouseEventArgs mouseEventArgs;
mouseEventArgs.x = _cursor.x*getWidth();
mouseEventArgs.y = _cursor.y*getHeight();
mouseEventArgs.button = 1;
lastfakemouseevent = &mouseEventArgs;
ofNotifyEvent( ofEvents().mousePressed, mouseEventArgs );
}
queueTouchAction(_cursor.x*getWidth(), _cursor.y*getHeight(), _cursor.id, MT_ADD);
}
void Renderer::tuioRemoved(ofTouchEventArgs & _cursor){
if (touchtomouse && mousetouchid==_cursor.id) {
mousetouchid = -1;
static ofMouseEventArgs mouseEventArgs;
mouseEventArgs.x = _cursor.x*getWidth();
mouseEventArgs.y = _cursor.y*getHeight();
mouseEventArgs.button = 1;
lastfakemouseevent = &mouseEventArgs;
ofNotifyEvent( ofEvents().mouseReleased , mouseEventArgs );
}
queueTouchAction(_cursor.x*getWidth(), _cursor.y*getHeight(), _cursor.id, MT_REMOVE);
}
void Renderer::tuioUpdated(ofTouchEventArgs & _cursor){
if (touchtomouse && mousetouchid==_cursor.id) {
static ofMouseEventArgs mouseEventArgs;
mouseEventArgs.x = _cursor.x*getWidth();
mouseEventArgs.y = _cursor.y*getHeight();
mouseEventArgs.button = 1;
lastfakemouseevent = &mouseEventArgs;
ofNotifyEvent( ofEvents().mouseDragged, mouseEventArgs );
}
queueTouchAction(_cursor.x*getWidth(), _cursor.y*getHeight(), _cursor.id, MT_UPDATE);
}
void Renderer::mousePressed(ofMouseEventArgs& _cursor){
if (mousetotouch) {
// ignore this mouse-event, if it was created by emulating a mouse-event from a touch
if (lastfakemouseevent != &_cursor) {
queueTouchAction(_cursor.x, _cursor.y, -1, MT_ADD);
}
}
}
void Renderer::mouseReleased(ofMouseEventArgs& _cursor){
if (mousetotouch) {
// ignore this mouse-event, if it was created by emulating a mouse-event from a touch
if (lastfakemouseevent != &_cursor) {
queueTouchAction(_cursor.x, _cursor.y, -1, MT_REMOVE);
}
}
}
void Renderer::mouseDragged(ofMouseEventArgs& _cursor){
if (mousetotouch) {
// ignore this mouse-event, if it was created by emulating a mouse-event from a touch
if (lastfakemouseevent != &_cursor) {
queueTouchAction(_cursor.x, _cursor.y, -1, MT_UPDATE);
}
}
}
void Renderer::queueTouchAction(float _screenx, float _screeny, int _fingerid, int _action) {
TouchAction touch = {_screenx, _screeny, _fingerid, _action};
touchActions.push(touch);
}
void Renderer::notifyObjects(TouchAction _touchAction) {
mtRay ray;
// y-Axis needs to be flipped from openframeworks 0.8.0 on because of the flipped camera (somehow)
ray.pos = camera.screenToWorld( ofVec3f( _touchAction.screenX, getHeight()-_touchAction.screenY,-1), currentviewport);
ray.dir = camera.screenToWorld( ofVec3f( _touchAction.screenX,getHeight()-_touchAction.screenY, 1), currentviewport) - ray.pos;
ray.screenpos.set(_touchAction.screenX, _touchAction.screenY);
BasicInteractiveObject* overobj = (BasicInteractiveObject*)getObjectAt(_touchAction.screenX, _touchAction.screenY);
for(int i=0;i<pickingObjects.size();i++){
BasicInteractiveObject* obj =(BasicInteractiveObject*) pickingObjects[i];
if (obj != NULL && obj!=overobj) {
switch (_touchAction.action) {
case (MT_ADD) : {
obj->touchDownOutside( ray,_touchAction.fingerId );
break;
}
case (MT_UPDATE) : {
obj->touchMovedOutside( ray,_touchAction.fingerId );
break;
}
case (MT_REMOVE) : {
obj->touchUpOutside( ray,_touchAction.fingerId );
break;
}
}
}
}
if(overobj!=NULL){
switch (_touchAction.action) {
case (MT_ADD) : {
overobj->touchDownOnMe( ray,_touchAction.fingerId );
break;
}
case (MT_UPDATE) : {
overobj->touchMovedOnMe(ray,_touchAction.fingerId );
break;
}
case (MT_REMOVE) : {
overobj->touchUpOnMe( ray,_touchAction.fingerId );
break;
}
}
}
lastinteraction = ofGetElapsedTimeMillis();
if (idleEventFired) {
idleEventFired = false;
ofNotifyEvent(idleFinishEvent, myEventArgs, this);
}
}
void Renderer::drawMap() {
ofSetColor(255, 255, 255);
ofPushMatrix();
ofScale(1.0/mapscale,1.0/mapscale);
pickingmap.draw(0, 0);
ofPopMatrix();
}
void Renderer::drawCursors(){
ofEnableAlphaBlending();
glBlendFunc(GL_ONE, GL_ONE);
if(bTuioSetup){
std::list<TuioCursor*> cursorList = tuio.client->getTuioCursors();
std::list<TuioCursor*>::iterator tit;
tuio.client->lockCursorList();
for (tit = cursorList.begin(); tit != cursorList.end(); tit++) {
TuioCursor * cur = (*tit);
glColor3f(0.1,0.1, 0.1);
for(int i = 0; i < 5; i++){
ofEllipse(cur->getX()*getWidth(),
cur->getY()*getHeight(),
20.0+i*i,
20.0+i*i);
}
}
tuio.client->unlockCursorList();
}
if (mousetotouch) {
if (ofGetMousePressed()) {
glColor3f(0.1,0.1, 0.1);
for(int i = 0; i < 5; i++){
ofEllipse(ofGetMouseX(),
ofGetMouseY(),
20.0+i*i,
20.0+i*i);
}
}
}
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
}
BasicScreenObject* Renderer::getObjectAt(float _screenx, float _screeny){
int fbox =_screenx/mapsampling;
int fboy =_screeny/mapsampling;
fbox = ofClamp(fbox, 0, maxbounds.width);
fboy = ofClamp(fboy, 0, maxbounds.height);
int index = (fbox + fboy * pickingmap.getWidth()) * 3 ;
//int index = (fbox + fboy * pickingmap.getWidth());
//if (bColorPickerSetup) pickingmap.readToPixels(mapPixels);
ofColor fboc = ofColor( mapPixels[index] , mapPixels[index + 1] , mapPixels[index + 2] );
//ofColor fboc = ofColor( mapPixels[index] , mapPixels[index] , mapPixels[index] );
GLint pickingName = colorToPickingName(fboc);
BasicScreenObject* obj = NULL;
if (pickingObjects.find(pickingName) != pickingObjects.end()) {
obj = pickingObjects[pickingName];
}
return obj;
}
GLuint Renderer::getNextPickingName(BasicInteractiveObject* _object) {
GLuint np = ++nextPickingName;
pickingObjects[np] = _object;
return np;
}
long Renderer::getLastInteractionMillis
(){
return lastinteraction;
}
void Renderer::isDrawCursors(bool _drawCursors) {
drawcursors = _drawCursors;
}
void Renderer::forceInteraction() {
lastinteraction = ofGetElapsedTimeMillis();
if (idleEventFired) {
idleEventFired = false;
ofNotifyEvent(idleFinishEvent, myEventArgs, this);
}
}<|endoftext|> |
<commit_before>/*
The MIT License (MIT)
Copyright (c) 2015 Marius Kaufmann, Tamara Frieß, Jannis Hoppe, Christian Hack
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.
*/
/**
* @file
* @brief Contains implementation for taylortrack::vis::OutputVisualizer class.
*/
#include "vis/output_visualizer.h"
#include <string.h>
#include <string>
#include <vector>
#include <ncurses.h>
namespace taylortrack {
namespace vis {
OutputVisualizer::OutputVisualizer(utils::GeneralOptions general_options) {
this->general_options_ = general_options;
// Initialize console window
initscr();
// Disable character echoing
noecho();
// Hide cursor
this->original_cursor_state_ = curs_set(0);
// Activate special keyboard keys
keypad(stdscr, TRUE);
// Disable input line buffering
cbreak();
// Make input calls non-blocking
nodelay(stdscr, true);
// Initialize colors
if (has_colors()) {
start_color();
// Define color pair 1 as white on blue
init_pair(1, COLOR_WHITE, COLOR_BLUE);
// Define color pair 2 as blue on white
init_pair(2, COLOR_BLUE, COLOR_WHITE);
/*
* Redefine colors if terminal supports it
* (We only have 8 colors available, so the names might be a bit unfitting)
*/
init_color(COLOR_RED, 933, 461, 0); // Dark Orange
init_color(COLOR_YELLOW, 1000, 645, 0); // Light Orange
// Define color pair 3 and 4 for use in the diagram
init_pair(3, COLOR_WHITE, COLOR_RED);
init_pair(4, COLOR_WHITE, COLOR_YELLOW);
int rows, cols;
// retrieve window size
getmaxyx(stdscr, rows, cols);
this->rows_ = rows;
this->cols_ = cols;
refresh();
create_top_window();
create_main_window();
} else {
failed_ = true;
}
}
void taylortrack::vis::OutputVisualizer::create_top_window() {
this->top_window_ = newwin(4, this->cols_, 0, 0);
// Set color pair 1 for the top window
wbkgd(this->top_window_, COLOR_PAIR(1));
update_top_window();
}
taylortrack::vis::OutputVisualizer::~OutputVisualizer() {
delwin(this->top_window_);
delwin(this->main_window_);
// Reactivate cursor
curs_set(this->original_cursor_state_);
endwin();
}
void taylortrack::vis::OutputVisualizer::draw_frame() {
this->handle_resize();
this->handle_user_input();
werase(this->main_window_);
this->update_main_window();
}
void taylortrack::vis::OutputVisualizer::handle_resize() {
int rows, cols;
// retrieve window size
getmaxyx(stdscr, rows, cols);
if (rows != this->rows_ || cols != this->cols_) {
if (this->show_top_window_) {
wresize(this->top_window_, 4, cols);
wresize(this->main_window_, rows - 4, cols);
if (cols != this->cols_) {
this->update_top_window();
}
} else {
wresize(this->main_window_, rows, cols);
}
this->rows_ = rows;
this->cols_ = cols;
}
}
void taylortrack::vis::OutputVisualizer::handle_user_input() {
int chr = getch();
if (chr != ERR) {
switch (chr) {
case 27: // ESC key or ALT key
// If we can't read another character right away it was the ESC-Key
if (getch() == ERR)
this->user_quit_ = true;
break;
case 'q':
this->user_quit_ = true;
break;
case 'h':
this->toggle_upper_window();
break;
default:
break;
}
}
}
bool taylortrack::vis::OutputVisualizer::term_supports_color() {
return has_colors();
}
bool taylortrack::vis::OutputVisualizer::user_has_quit() const {
return user_quit_;
}
bool taylortrack::vis::OutputVisualizer::has_failed() const {
return failed_;
}
void taylortrack::vis::OutputVisualizer::update_top_window() {
werase(this->top_window_);
box(this->top_window_, 0, 0);
wmove(this->top_window_, 1, 1);
this->print_center(this->top_window_, "TaylorTrack - Tracking Visualizer");
this->print_center(this->top_window_,
"Press 'q' or ESC to quit and 'h' to toggle this window.");
wrefresh(this->top_window_);
}
/* Prints String in the center of the window's current line
* Assumes a necessary padding in the size of the current cursor position (for box lines etc.)
* Sets the cursor to the next same x position in the next line afterwards
* */
void OutputVisualizer::print_center(WINDOW *window, const char *string) {
int cy, cx;
getyx(window, cy, cx);
int cols = getmaxx(window);
int position = ((cols - 2 * cx) - static_cast<int>(strlen(string))) / 2;
wmove(window, cy, cx + position);
wprintw(window, string);
wmove(window, cy + 1, cx);
}
void taylortrack::vis::OutputVisualizer::toggle_upper_window() {
this->show_top_window_ = !this->show_top_window_;
if (show_top_window_) {
delwin(this->main_window_);
this->create_top_window();
this->create_main_window();
} else {
delwin(this->top_window_);
delwin(this->main_window_);
this->create_main_window();
}
}
void taylortrack::vis::OutputVisualizer::create_main_window() {
if (show_top_window_) {
this->main_window_ = newwin(this->rows_ - 4, this->cols_, 4, 0);
} else {
this->main_window_ = newwin(this->rows_, this->cols_, 0, 0);
}
}
void taylortrack::vis::OutputVisualizer::update_main_window() {
// Create Box around main window
box(this->main_window_, 0, 0);
wmove(this->main_window_, 1, 1);
if (this->data_set_) {
double x_axis_size = diagram_data_.size();
int height, width;
getmaxyx(this->main_window_, height, width);
// Not the entire window usable
width -= 2;
height -= 4;
// Calculate values per character
int vpc = static_cast<int>(ceil(x_axis_size) / static_cast<double>(width));
int actual_size = static_cast<int>(x_axis_size / vpc);
// Calculate max value
double max_value = 0.0f;
for (int i = 0; i < actual_size; ++i) {
double current_value = 0;
for (int j = 0; j < vpc; ++j) {
current_value += diagram_data_[i * vpc + j];
}
if (current_value > max_value) {
max_value = current_value;
}
}
wprintw(this->main_window_,
"Debug-Values: %d %d %d %d %f",
vpc,
actual_size,
COLORS,
can_change_color(),
max_value);
if (max_value > 0.0) {
// calculate the value of one square in the terminal
double delta = max_value / height;
// Add the vpc next values together and draw block if value high enough
for (int y = 0; y < height; ++y) {
for (int x = 0; x < actual_size; ++x) {
double current_value = 0;
for (int j = 0; j < vpc; ++j) {
current_value += diagram_data_[x * vpc + j];
}
if (current_value >= (height - y) * delta) {
wmove(this->main_window_, 1 + y, 1 + x);
if (x % 2 == 0) {
waddch(this->main_window_, ' ' | COLOR_PAIR(3));
} else {
waddch(this->main_window_, ' ' | COLOR_PAIR(4));
}
}
}
}
} else {
height = getmaxy(this->main_window_);
height -= 2;
wmove(this->main_window_, height / 2, 1);
print_center(this->main_window_, "Invalid Data!");
}
} else {
int height;
height = getmaxy(this->main_window_);
height -= 2;
wmove(this->main_window_, height / 2, 1);
print_center(this->main_window_, "Waiting for Data...");
}
// flush display buffer and write to screen
wrefresh(this->main_window_);
}
void OutputVisualizer::set_diagram_data(
const std::vector<double> &diagram_data) {
this->diagram_data_ = diagram_data;
this->data_set_ = true;
}
} // namespace vis
} // namespace taylortrack
<commit_msg>fixed cast<commit_after>/*
The MIT License (MIT)
Copyright (c) 2015 Marius Kaufmann, Tamara Frieß, Jannis Hoppe, Christian Hack
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.
*/
/**
* @file
* @brief Contains implementation for taylortrack::vis::OutputVisualizer class.
*/
#include "vis/output_visualizer.h"
#include <string.h>
#include <string>
#include <vector>
#include <ncurses.h>
namespace taylortrack {
namespace vis {
OutputVisualizer::OutputVisualizer(utils::GeneralOptions general_options) {
this->general_options_ = general_options;
// Initialize console window
initscr();
// Disable character echoing
noecho();
// Hide cursor
this->original_cursor_state_ = curs_set(0);
// Activate special keyboard keys
keypad(stdscr, TRUE);
// Disable input line buffering
cbreak();
// Make input calls non-blocking
nodelay(stdscr, true);
// Initialize colors
if (has_colors()) {
start_color();
// Define color pair 1 as white on blue
init_pair(1, COLOR_WHITE, COLOR_BLUE);
// Define color pair 2 as blue on white
init_pair(2, COLOR_BLUE, COLOR_WHITE);
/*
* Redefine colors if terminal supports it
* (We only have 8 colors available, so the names might be a bit unfitting)
*/
init_color(COLOR_RED, 933, 461, 0); // Dark Orange
init_color(COLOR_YELLOW, 1000, 645, 0); // Light Orange
// Define color pair 3 and 4 for use in the diagram
init_pair(3, COLOR_WHITE, COLOR_RED);
init_pair(4, COLOR_WHITE, COLOR_YELLOW);
int rows, cols;
// retrieve window size
getmaxyx(stdscr, rows, cols);
this->rows_ = rows;
this->cols_ = cols;
refresh();
create_top_window();
create_main_window();
} else {
failed_ = true;
}
}
void taylortrack::vis::OutputVisualizer::create_top_window() {
this->top_window_ = newwin(4, this->cols_, 0, 0);
// Set color pair 1 for the top window
wbkgd(this->top_window_, COLOR_PAIR(1));
update_top_window();
}
taylortrack::vis::OutputVisualizer::~OutputVisualizer() {
delwin(this->top_window_);
delwin(this->main_window_);
// Reactivate cursor
curs_set(this->original_cursor_state_);
endwin();
}
void taylortrack::vis::OutputVisualizer::draw_frame() {
this->handle_resize();
this->handle_user_input();
werase(this->main_window_);
this->update_main_window();
}
void taylortrack::vis::OutputVisualizer::handle_resize() {
int rows, cols;
// retrieve window size
getmaxyx(stdscr, rows, cols);
if (rows != this->rows_ || cols != this->cols_) {
if (this->show_top_window_) {
wresize(this->top_window_, 4, cols);
wresize(this->main_window_, rows - 4, cols);
if (cols != this->cols_) {
this->update_top_window();
}
} else {
wresize(this->main_window_, rows, cols);
}
this->rows_ = rows;
this->cols_ = cols;
}
}
void taylortrack::vis::OutputVisualizer::handle_user_input() {
int chr = getch();
if (chr != ERR) {
switch (chr) {
case 27: // ESC key or ALT key
// If we can't read another character right away it was the ESC-Key
if (getch() == ERR)
this->user_quit_ = true;
break;
case 'q':
this->user_quit_ = true;
break;
case 'h':
this->toggle_upper_window();
break;
default:
break;
}
}
}
bool taylortrack::vis::OutputVisualizer::term_supports_color() {
return has_colors();
}
bool taylortrack::vis::OutputVisualizer::user_has_quit() const {
return user_quit_;
}
bool taylortrack::vis::OutputVisualizer::has_failed() const {
return failed_;
}
void taylortrack::vis::OutputVisualizer::update_top_window() {
werase(this->top_window_);
box(this->top_window_, 0, 0);
wmove(this->top_window_, 1, 1);
this->print_center(this->top_window_, "TaylorTrack - Tracking Visualizer");
this->print_center(this->top_window_,
"Press 'q' or ESC to quit and 'h' to toggle this window.");
wrefresh(this->top_window_);
}
/* Prints String in the center of the window's current line
* Assumes a necessary padding in the size of the current cursor position (for box lines etc.)
* Sets the cursor to the next same x position in the next line afterwards
* */
void OutputVisualizer::print_center(WINDOW *window, const char *string) {
int cy, cx;
getyx(window, cy, cx);
int cols = getmaxx(window);
int position = ((cols - 2 * cx) - static_cast<int>(strlen(string))) / 2;
wmove(window, cy, cx + position);
wprintw(window, string);
wmove(window, cy + 1, cx);
}
void taylortrack::vis::OutputVisualizer::toggle_upper_window() {
this->show_top_window_ = !this->show_top_window_;
if (show_top_window_) {
delwin(this->main_window_);
this->create_top_window();
this->create_main_window();
} else {
delwin(this->top_window_);
delwin(this->main_window_);
this->create_main_window();
}
}
void taylortrack::vis::OutputVisualizer::create_main_window() {
if (show_top_window_) {
this->main_window_ = newwin(this->rows_ - 4, this->cols_, 4, 0);
} else {
this->main_window_ = newwin(this->rows_, this->cols_, 0, 0);
}
}
void taylortrack::vis::OutputVisualizer::update_main_window() {
// Create Box around main window
box(this->main_window_, 0, 0);
wmove(this->main_window_, 1, 1);
if (this->data_set_) {
double x_axis_size = diagram_data_.size();
int height, width;
getmaxyx(this->main_window_, height, width);
// Not the entire window usable
width -= 2;
height -= 4;
// Calculate values per character
int vpc = static_cast<int>(ceil(x_axis_size / static_cast<double>(width)));
int actual_size = static_cast<int>(x_axis_size / vpc);
// Calculate max value
double max_value = 0.0f;
for (int i = 0; i < actual_size; ++i) {
double current_value = 0;
for (int j = 0; j < vpc; ++j) {
current_value += diagram_data_[i * vpc + j];
}
if (current_value > max_value) {
max_value = current_value;
}
}
wprintw(this->main_window_,
"Debug-Values: %d %d %d %d %f",
vpc,
actual_size,
COLORS,
can_change_color(),
max_value);
if (max_value > 0.0) {
// calculate the value of one square in the terminal
double delta = max_value / height;
// Add the vpc next values together and draw block if value high enough
for (int y = 0; y < height; ++y) {
for (int x = 0; x < actual_size; ++x) {
double current_value = 0;
for (int j = 0; j < vpc; ++j) {
current_value += diagram_data_[x * vpc + j];
}
if (current_value >= (height - y) * delta) {
wmove(this->main_window_, 1 + y, 1 + x);
if (x % 2 == 0) {
waddch(this->main_window_, ' ' | COLOR_PAIR(3));
} else {
waddch(this->main_window_, ' ' | COLOR_PAIR(4));
}
}
}
}
} else {
height = getmaxy(this->main_window_);
height -= 2;
wmove(this->main_window_, height / 2, 1);
print_center(this->main_window_, "Invalid Data!");
}
} else {
int height;
height = getmaxy(this->main_window_);
height -= 2;
wmove(this->main_window_, height / 2, 1);
print_center(this->main_window_, "Waiting for Data...");
}
// flush display buffer and write to screen
wrefresh(this->main_window_);
}
void OutputVisualizer::set_diagram_data(
const std::vector<double> &diagram_data) {
this->diagram_data_ = diagram_data;
this->data_set_ = true;
}
} // namespace vis
} // namespace taylortrack
<|endoftext|> |
<commit_before>//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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 "renderProbeMgr.h"
#include "console/consoleTypes.h"
#include "scene/sceneObject.h"
#include "materials/materialManager.h"
#include "scene/sceneRenderState.h"
#include "math/util/sphereMesh.h"
#include "math/util/matrixSet.h"
#include "materials/processedMaterial.h"
#include "renderInstance/renderDeferredMgr.h"
#include "math/mPolyhedron.impl.h"
#include "gfx/gfxTransformSaver.h"
#include "gfx/gfxDebugEvent.h"
IMPLEMENT_CONOBJECT(RenderProbeMgr);
ConsoleDocClass( RenderProbeMgr,
"@brief A render bin which uses object callbacks for rendering.\n\n"
"This render bin gathers object render instances and calls its delegate "
"method to perform rendering. It is used infrequently for specialized "
"scene objects which perform custom rendering.\n\n"
"@ingroup RenderBin\n" );
S32 QSORT_CALLBACK AscendingReflectProbeInfluence(const void* a, const void* b)
{
// Debug Profiling.
PROFILE_SCOPE(AdvancedLightBinManager_AscendingReflectProbeInfluence);
// Fetch asset definitions.
const ProbeRenderInst* pReflectProbeA = (*(ProbeRenderInst**)a);
const ProbeRenderInst* pReflectProbeB = (*(ProbeRenderInst**)b);
//sort by score
return pReflectProbeA->mScore - pReflectProbeB->mScore;
}
RenderProbeMgr::RenderProbeMgr()
: RenderBinManager(RenderPassManager::RIT_Probes, 1.0f, 1.0f)
{
}
RenderProbeMgr::RenderProbeMgr(RenderInstType riType, F32 renderOrder, F32 processAddOrder)
: RenderBinManager(riType, renderOrder, processAddOrder)
{
}
void RenderProbeMgr::initPersistFields()
{
Parent::initPersistFields();
}
void RenderProbeMgr::addElement(RenderInst *inst)
{
// If this instance is translucent handle it in RenderTranslucentMgr
//if (inst->translucentSort)
return;
//AssertFatal(inst->defaultKey != 0, "RenderMeshMgr::addElement() - Got null sort key... did you forget to set it?");
/*internalAddElement(inst);
ProbeRenderInst* probeInst = static_cast<ProbeRenderInst*>(inst);
if (probeInst->mIsSkylight)
{
addSkylightProbe(probeInst);
}
else
{
if (probeInst->mProbeShapeType == ProbeInfo::Sphere)
addSphereReflectionProbe(probeInst);
else
addConvexReflectionProbe(probeInst);
}*/
}
//remove
//Con::setIntVariable("lightMetrics::activeReflectionProbes", mReflectProbeBin.size());
//Con::setIntVariable("lightMetrics::culledReflectProbes", 0/*mNumLightsCulled*/);
//
void RenderProbeMgr::_setupPerFrameParameters(const SceneRenderState *state)
{
PROFILE_SCOPE(RenderProbeMgr_SetupPerFrameParameters);
const Frustum &frustum = state->getCameraFrustum();
MatrixF invCam(frustum.getTransform());
invCam.inverse();
const Point3F *wsFrustumPoints = frustum.getPoints();
const Point3F& cameraPos = frustum.getPosition();
// Perform a camera offset. We need to manually perform this offset on the sun (or vector) light's
// polygon, which is at the far plane.
Point3F cameraOffsetPos = cameraPos;
// Now build the quad for drawing full-screen vector light
// passes.... this is a volatile VB and updates every frame.
FarFrustumQuadVert verts[4];
{
verts[0].point.set(wsFrustumPoints[Frustum::FarTopLeft] - cameraPos);
invCam.mulP(wsFrustumPoints[Frustum::FarTopLeft], &verts[0].normal);
verts[0].texCoord.set(-1.0, 1.0);
verts[0].tangent.set(wsFrustumPoints[Frustum::FarTopLeft] - cameraOffsetPos);
verts[1].point.set(wsFrustumPoints[Frustum::FarTopRight] - cameraPos);
invCam.mulP(wsFrustumPoints[Frustum::FarTopRight], &verts[1].normal);
verts[1].texCoord.set(1.0, 1.0);
verts[1].tangent.set(wsFrustumPoints[Frustum::FarTopRight] - cameraOffsetPos);
verts[2].point.set(wsFrustumPoints[Frustum::FarBottomLeft] - cameraPos);
invCam.mulP(wsFrustumPoints[Frustum::FarBottomLeft], &verts[2].normal);
verts[2].texCoord.set(-1.0, -1.0);
verts[2].tangent.set(wsFrustumPoints[Frustum::FarBottomLeft] - cameraOffsetPos);
verts[3].point.set(wsFrustumPoints[Frustum::FarBottomRight] - cameraPos);
invCam.mulP(wsFrustumPoints[Frustum::FarBottomRight], &verts[3].normal);
verts[3].texCoord.set(1.0, -1.0);
verts[3].tangent.set(wsFrustumPoints[Frustum::FarBottomRight] - cameraOffsetPos);
}
mFarFrustumQuadVerts.set(GFX, 4);
dMemcpy(mFarFrustumQuadVerts.lock(), verts, sizeof(verts));
mFarFrustumQuadVerts.unlock();
PlaneF farPlane(wsFrustumPoints[Frustum::FarBottomLeft], wsFrustumPoints[Frustum::FarTopLeft], wsFrustumPoints[Frustum::FarTopRight]);
PlaneF vsFarPlane(verts[0].normal, verts[1].normal, verts[2].normal);
// Parameters calculated, assign them to the materials
ProbeManager::SkylightMaterialInfo* skylightMat = PROBEMGR->getSkylightMaterial();
if (skylightMat != nullptr && skylightMat->matInstance != nullptr)
{
skylightMat->setViewParameters(frustum.getNearDist(),
frustum.getFarDist(),
frustum.getPosition(),
farPlane,
vsFarPlane);
}
ProbeManager::ReflectProbeMaterialInfo* reflProbeMat = PROBEMGR->getReflectProbeMaterial();
if (reflProbeMat != nullptr && reflProbeMat->matInstance != nullptr)
{
reflProbeMat->setViewParameters(frustum.getNearDist(),
frustum.getFarDist(),
frustum.getPosition(),
farPlane,
vsFarPlane);
}
}
//-----------------------------------------------------------------------------
// render objects
//-----------------------------------------------------------------------------
void RenderProbeMgr::render( SceneRenderState *state )
{
PROFILE_SCOPE(RenderProbeMgr_render);
// Early out if nothing to draw.
if (!ProbeRenderInst::all.size())
return;
if (!ProbeManager::smRenderReflectionProbes)
return;
GFXTransformSaver saver;
GFXDEBUGEVENT_SCOPE(RenderProbeMgr_render, ColorI::WHITE);
NamedTexTargetRef sceneColorTargetRef = NamedTexTarget::find("AL_FormatToken");
if (sceneColorTargetRef.isNull())
return;
GFXTextureTargetRef probeLightingTargetRef = GFX->allocRenderToTextureTarget();
if (probeLightingTargetRef.isNull())
return;
//Do a quick pass to update our probes if they're dirty
PROBEMGR->updateDirtyProbes();
probeLightingTargetRef->attachTexture(GFXTextureTarget::Color0, sceneColorTargetRef->getTexture(0));
GFX->pushActiveRenderTarget();
GFX->setActiveRenderTarget(probeLightingTargetRef);
GFX->setViewport(sceneColorTargetRef->getViewport());
// Restore transforms
MatrixSet &matrixSet = getRenderPass()->getMatrixSet();
matrixSet.restoreSceneViewProjection();
const MatrixF &worldToCameraXfm = matrixSet.getWorldToCamera();
// Set up the SG Data
SceneData sgData;
sgData.init(state);
// Initialize and set the per-frame parameters after getting
// the vector light material as we use lazy creation.
_setupPerFrameParameters(state);
//Order the probes by size, biggest to smallest
dQsort(ProbeRenderInst::all.address(), ProbeRenderInst::all.size(), sizeof(const ProbeRenderInst*), AscendingReflectProbeInfluence);
//Specular
PROFILE_START(RenderProbeManager_ReflectProbeRender);
ProbeManager::SkylightMaterialInfo* skylightMat = PROBEMGR->getSkylightMaterial();
ProbeManager::ReflectProbeMaterialInfo* reflProbeMat = PROBEMGR->getReflectProbeMaterial();
for (U32 i = 0; i < ProbeRenderInst::all.size(); i++)
{
ProbeRenderInst* curEntry = ProbeRenderInst::all[i];
if (!curEntry->mIsEnabled)
continue;
if (curEntry->numPrims == 0)
continue;
if (curEntry->mIsSkylight && (!skylightMat || !skylightMat->matInstance))
continue;
if (!curEntry->mIsSkylight && (!reflProbeMat || !reflProbeMat->matInstance))
break;
//Setup
MatrixF probeTrans = curEntry->getTransform();
if (!curEntry->mIsSkylight)
{
if (curEntry->mProbeShapeType == ProbeRenderInst::Sphere)
probeTrans.scale(curEntry->mRadius * 1.01f);
}
else
{
probeTrans.scale(10); //force it to be big enough to surround the camera
}
sgData.objTrans = &probeTrans;
if(curEntry->mIsSkylight)
skylightMat->setProbeParameters(curEntry, state, worldToCameraXfm);
else
reflProbeMat->setProbeParameters(curEntry, state, worldToCameraXfm);
// Set geometry
GFX->setVertexBuffer(curEntry->vertBuffer);
GFX->setPrimitiveBuffer(curEntry->primBuffer);
if (curEntry->mIsSkylight)
{
while (skylightMat->matInstance->setupPass(state, sgData))
{
// Set transforms
matrixSet.setWorld(*sgData.objTrans);
skylightMat->matInstance->setTransforms(matrixSet, state);
skylightMat->matInstance->setSceneInfo(state, sgData);
GFX->drawPrimitive(GFXTriangleList, 0, curEntry->numPrims);
}
}
else
{
while (reflProbeMat->matInstance->setupPass(state, sgData))
{
// Set transforms
matrixSet.setWorld(*sgData.objTrans);
reflProbeMat->matInstance->setTransforms(matrixSet, state);
reflProbeMat->matInstance->setSceneInfo(state, sgData);
GFX->drawPrimitive(GFXTriangleList, 0, curEntry->numPrims);
}
}
}
GFX->popActiveRenderTarget();
//PROBEMGR->unregisterAllProbes();
PROFILE_END();
GFX->setVertexBuffer(NULL);
GFX->setPrimitiveBuffer(NULL);
// Fire off a signal to let others know that light-bin rendering is ending now
//getRenderSignal().trigger(state, this);
}<commit_msg>THIS IS AN ABOMINATION UNTO THE CODEBASE AND SHOULD BE REMOVED THE SECOND WE CAN SORT OUT WHAT THE HECK IS GOING ON WITH THAT QSORT stops flickering by itterating through the probe list twice. once looking for the skylight, then doing the rest<commit_after>//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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 "renderProbeMgr.h"
#include "console/consoleTypes.h"
#include "scene/sceneObject.h"
#include "materials/materialManager.h"
#include "scene/sceneRenderState.h"
#include "math/util/sphereMesh.h"
#include "math/util/matrixSet.h"
#include "materials/processedMaterial.h"
#include "renderInstance/renderDeferredMgr.h"
#include "math/mPolyhedron.impl.h"
#include "gfx/gfxTransformSaver.h"
#include "gfx/gfxDebugEvent.h"
IMPLEMENT_CONOBJECT(RenderProbeMgr);
ConsoleDocClass( RenderProbeMgr,
"@brief A render bin which uses object callbacks for rendering.\n\n"
"This render bin gathers object render instances and calls its delegate "
"method to perform rendering. It is used infrequently for specialized "
"scene objects which perform custom rendering.\n\n"
"@ingroup RenderBin\n" );
S32 QSORT_CALLBACK AscendingReflectProbeInfluence(const void* a, const void* b)
{
// Debug Profiling.
PROFILE_SCOPE(AdvancedLightBinManager_AscendingReflectProbeInfluence);
// Fetch asset definitions.
const ProbeRenderInst* pReflectProbeA = (*(ProbeRenderInst**)a);
const ProbeRenderInst* pReflectProbeB = (*(ProbeRenderInst**)b);
//sort by score
return pReflectProbeA->mScore - pReflectProbeB->mScore;
}
RenderProbeMgr::RenderProbeMgr()
: RenderBinManager(RenderPassManager::RIT_Probes, 1.0f, 1.0f)
{
}
RenderProbeMgr::RenderProbeMgr(RenderInstType riType, F32 renderOrder, F32 processAddOrder)
: RenderBinManager(riType, renderOrder, processAddOrder)
{
}
void RenderProbeMgr::initPersistFields()
{
Parent::initPersistFields();
}
void RenderProbeMgr::addElement(RenderInst *inst)
{
// If this instance is translucent handle it in RenderTranslucentMgr
//if (inst->translucentSort)
return;
//AssertFatal(inst->defaultKey != 0, "RenderMeshMgr::addElement() - Got null sort key... did you forget to set it?");
/*internalAddElement(inst);
ProbeRenderInst* probeInst = static_cast<ProbeRenderInst*>(inst);
if (probeInst->mIsSkylight)
{
addSkylightProbe(probeInst);
}
else
{
if (probeInst->mProbeShapeType == ProbeInfo::Sphere)
addSphereReflectionProbe(probeInst);
else
addConvexReflectionProbe(probeInst);
}*/
}
//remove
//Con::setIntVariable("lightMetrics::activeReflectionProbes", mReflectProbeBin.size());
//Con::setIntVariable("lightMetrics::culledReflectProbes", 0/*mNumLightsCulled*/);
//
void RenderProbeMgr::_setupPerFrameParameters(const SceneRenderState *state)
{
PROFILE_SCOPE(RenderProbeMgr_SetupPerFrameParameters);
const Frustum &frustum = state->getCameraFrustum();
MatrixF invCam(frustum.getTransform());
invCam.inverse();
const Point3F *wsFrustumPoints = frustum.getPoints();
const Point3F& cameraPos = frustum.getPosition();
// Perform a camera offset. We need to manually perform this offset on the sun (or vector) light's
// polygon, which is at the far plane.
Point3F cameraOffsetPos = cameraPos;
// Now build the quad for drawing full-screen vector light
// passes.... this is a volatile VB and updates every frame.
FarFrustumQuadVert verts[4];
{
verts[0].point.set(wsFrustumPoints[Frustum::FarTopLeft] - cameraPos);
invCam.mulP(wsFrustumPoints[Frustum::FarTopLeft], &verts[0].normal);
verts[0].texCoord.set(-1.0, 1.0);
verts[0].tangent.set(wsFrustumPoints[Frustum::FarTopLeft] - cameraOffsetPos);
verts[1].point.set(wsFrustumPoints[Frustum::FarTopRight] - cameraPos);
invCam.mulP(wsFrustumPoints[Frustum::FarTopRight], &verts[1].normal);
verts[1].texCoord.set(1.0, 1.0);
verts[1].tangent.set(wsFrustumPoints[Frustum::FarTopRight] - cameraOffsetPos);
verts[2].point.set(wsFrustumPoints[Frustum::FarBottomLeft] - cameraPos);
invCam.mulP(wsFrustumPoints[Frustum::FarBottomLeft], &verts[2].normal);
verts[2].texCoord.set(-1.0, -1.0);
verts[2].tangent.set(wsFrustumPoints[Frustum::FarBottomLeft] - cameraOffsetPos);
verts[3].point.set(wsFrustumPoints[Frustum::FarBottomRight] - cameraPos);
invCam.mulP(wsFrustumPoints[Frustum::FarBottomRight], &verts[3].normal);
verts[3].texCoord.set(1.0, -1.0);
verts[3].tangent.set(wsFrustumPoints[Frustum::FarBottomRight] - cameraOffsetPos);
}
mFarFrustumQuadVerts.set(GFX, 4);
dMemcpy(mFarFrustumQuadVerts.lock(), verts, sizeof(verts));
mFarFrustumQuadVerts.unlock();
PlaneF farPlane(wsFrustumPoints[Frustum::FarBottomLeft], wsFrustumPoints[Frustum::FarTopLeft], wsFrustumPoints[Frustum::FarTopRight]);
PlaneF vsFarPlane(verts[0].normal, verts[1].normal, verts[2].normal);
// Parameters calculated, assign them to the materials
ProbeManager::SkylightMaterialInfo* skylightMat = PROBEMGR->getSkylightMaterial();
if (skylightMat != nullptr && skylightMat->matInstance != nullptr)
{
skylightMat->setViewParameters(frustum.getNearDist(),
frustum.getFarDist(),
frustum.getPosition(),
farPlane,
vsFarPlane);
}
ProbeManager::ReflectProbeMaterialInfo* reflProbeMat = PROBEMGR->getReflectProbeMaterial();
if (reflProbeMat != nullptr && reflProbeMat->matInstance != nullptr)
{
reflProbeMat->setViewParameters(frustum.getNearDist(),
frustum.getFarDist(),
frustum.getPosition(),
farPlane,
vsFarPlane);
}
}
//-----------------------------------------------------------------------------
// render objects
//-----------------------------------------------------------------------------
void RenderProbeMgr::render( SceneRenderState *state )
{
PROFILE_SCOPE(RenderProbeMgr_render);
// Early out if nothing to draw.
if (!ProbeRenderInst::all.size())
return;
if (!ProbeManager::smRenderReflectionProbes)
return;
GFXTransformSaver saver;
GFXDEBUGEVENT_SCOPE(RenderProbeMgr_render, ColorI::WHITE);
NamedTexTargetRef sceneColorTargetRef = NamedTexTarget::find("AL_FormatToken");
if (sceneColorTargetRef.isNull())
return;
GFXTextureTargetRef probeLightingTargetRef = GFX->allocRenderToTextureTarget();
if (probeLightingTargetRef.isNull())
return;
//Do a quick pass to update our probes if they're dirty
PROBEMGR->updateDirtyProbes();
probeLightingTargetRef->attachTexture(GFXTextureTarget::Color0, sceneColorTargetRef->getTexture(0));
GFX->pushActiveRenderTarget();
GFX->setActiveRenderTarget(probeLightingTargetRef);
GFX->setViewport(sceneColorTargetRef->getViewport());
// Restore transforms
MatrixSet &matrixSet = getRenderPass()->getMatrixSet();
matrixSet.restoreSceneViewProjection();
const MatrixF &worldToCameraXfm = matrixSet.getWorldToCamera();
// Set up the SG Data
SceneData sgData;
sgData.init(state);
// Initialize and set the per-frame parameters after getting
// the vector light material as we use lazy creation.
_setupPerFrameParameters(state);
//Order the probes by size, biggest to smallest
//dQsort(ProbeRenderInst::all.address(), ProbeRenderInst::all.size(), sizeof(const ProbeRenderInst*), AscendingReflectProbeInfluence);
//Specular
PROFILE_START(RenderProbeManager_ReflectProbeRender);
ProbeManager::SkylightMaterialInfo* skylightMat = PROBEMGR->getSkylightMaterial();
ProbeManager::ReflectProbeMaterialInfo* reflProbeMat = PROBEMGR->getReflectProbeMaterial();
for (U32 i = 0; i < ProbeRenderInst::all.size(); i++)
{
ProbeRenderInst* curEntry = ProbeRenderInst::all[i];
if (!curEntry->mIsEnabled)
continue;
if (curEntry->numPrims == 0)
continue;
if (curEntry->mIsSkylight && (!skylightMat || !skylightMat->matInstance))
continue;
if (!curEntry->mIsSkylight && (!reflProbeMat || !reflProbeMat->matInstance))
break;
if (curEntry->mIsSkylight)
{
//Setup
MatrixF probeTrans = curEntry->getTransform();
// Set geometry
GFX->setVertexBuffer(curEntry->vertBuffer);
GFX->setPrimitiveBuffer(curEntry->primBuffer);
probeTrans.scale(10); //force it to be big enough to surround the camera
sgData.objTrans = &probeTrans;
skylightMat->setProbeParameters(curEntry, state, worldToCameraXfm);
while (skylightMat->matInstance->setupPass(state, sgData))
{
// Set transforms
matrixSet.setWorld(*sgData.objTrans);
skylightMat->matInstance->setTransforms(matrixSet, state);
skylightMat->matInstance->setSceneInfo(state, sgData);
GFX->drawPrimitive(GFXTriangleList, 0, curEntry->numPrims);
}
}
}
for (U32 i = 0; i < ProbeRenderInst::all.size(); i++)
{
ProbeRenderInst* curEntry = ProbeRenderInst::all[i];
if (!curEntry->mIsEnabled)
continue;
if (curEntry->numPrims == 0)
continue;
if (curEntry->mIsSkylight && (!skylightMat || !skylightMat->matInstance))
continue;
if (!curEntry->mIsSkylight && (!reflProbeMat || !reflProbeMat->matInstance))
break;
//Setup
MatrixF probeTrans = curEntry->getTransform();
if (!curEntry->mIsSkylight)
{
if (curEntry->mProbeShapeType == ProbeRenderInst::Sphere)
probeTrans.scale(curEntry->mRadius * 1.01f);
sgData.objTrans = &probeTrans;
reflProbeMat->setProbeParameters(curEntry, state, worldToCameraXfm);
// Set geometry
GFX->setVertexBuffer(curEntry->vertBuffer);
GFX->setPrimitiveBuffer(curEntry->primBuffer);
while (reflProbeMat->matInstance->setupPass(state, sgData))
{
// Set transforms
matrixSet.setWorld(*sgData.objTrans);
reflProbeMat->matInstance->setTransforms(matrixSet, state);
reflProbeMat->matInstance->setSceneInfo(state, sgData);
GFX->drawPrimitive(GFXTriangleList, 0, curEntry->numPrims);
}
}
}
GFX->popActiveRenderTarget();
//PROBEMGR->unregisterAllProbes();
PROFILE_END();
GFX->setVertexBuffer(NULL);
GFX->setPrimitiveBuffer(NULL);
// Fire off a signal to let others know that light-bin rendering is ending now
//getRenderSignal().trigger(state, this);
}<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: opengrf.cxx,v $
*
* $Revision: 1.17 $
*
* last change: $Author: kz $ $Date: 2004-10-04 17:48:17 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <tools/urlobj.hxx>
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_COMMONFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/CommonFilePickerElementIds.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_EXECUTABLEDIALOGRESULTS_HPP_
#include <com/sun/star/ui/dialogs/ExecutableDialogResults.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_EXTENDEDFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_FILEPREVIEWIMAGEFORMATS_HPP_
#include <com/sun/star/ui/dialogs/FilePreviewImageFormats.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_LISTBOXCONTROLACTIONS_HPP_
#include <com/sun/star/ui/dialogs/ListboxControlActions.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_TEMPLATEDESCRIPTION_HPP_
#include <com/sun/star/ui/dialogs/TemplateDescription.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERCONTROLACCESS_HPP_
#include <com/sun/star/ui/dialogs/XFilePickerControlAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKER_HPP_
#include <com/sun/star/ui/dialogs/XFilePicker.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERLISTENER_HPP_
#include <com/sun/star/ui/dialogs/XFilePickerListener.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERNOTIFIER_HPP_
#include <com/sun/star/ui/dialogs/XFilePickerNotifier.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPREVIEW_HPP_
#include <com/sun/star/ui/dialogs/XFilePreview.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILTERMANAGER_HPP_
#include <com/sun/star/ui/dialogs/XFilterManager.hpp>
#endif
#ifndef SVTOOLS_URIHELPER_HXX
#include <svtools/urihelper.hxx>
#endif
#ifndef _UNOTOOLS_UCBSTREAMHELPER_HXX
#include <unotools/ucbstreamhelper.hxx>
#endif
#ifndef _TRANSFER_HXX //autogen
#include <svtools/transfer.hxx>
#endif
#ifndef _SVDOGRAF_HXX //autogen
#include "svdograf.hxx"
#endif
#ifndef _SOT_FORMATS_HXX //autogen
#include <sot/formats.hxx>
#endif
#ifndef _MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _FILEDLGHELPER_HXX
#include <sfx2/filedlghelper.hxx>
#endif
#ifndef _SFXDOCFILE_HXX
#include <sfx2/docfile.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX
#include <svtools/pathoptions.hxx>
#endif
#ifndef _SVX_DIALMGR_HXX
#include "dialmgr.hxx"
#endif
#ifndef _SVX_OPENGRF_HXX
#include "opengrf.hxx"
#endif
#include "dialogs.hrc"
#include "impgrf.hrc"
//-----------------------------------------------------------------------------
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::ui::dialogs;
using namespace ::com::sun::star::uno;
using namespace ::rtl;
using namespace ::cppu;
//-----------------------------------------------------------------------------
USHORT SvxOpenGrfErr2ResId( short err )
{
switch( err )
{
case GRFILTER_OPENERROR:
return RID_SVXSTR_GRFILTER_OPENERROR;
case GRFILTER_IOERROR:
return RID_SVXSTR_GRFILTER_IOERROR;
case GRFILTER_VERSIONERROR:
return RID_SVXSTR_GRFILTER_VERSIONERROR;
case GRFILTER_FILTERERROR:
return RID_SVXSTR_GRFILTER_FILTERERROR;
case GRFILTER_FORMATERROR:
default:
return RID_SVXSTR_GRFILTER_FORMATERROR;
}
}
struct SvxOpenGrf_Impl
{
SvxOpenGrf_Impl ();
sfx2::FileDialogHelper aFileDlg;
Reference < XFilePickerControlAccess > xCtrlAcc;
};
SvxOpenGrf_Impl::SvxOpenGrf_Impl() :
aFileDlg(SFXWB_GRAPHIC)
{
Reference < XFilePicker > xFP = aFileDlg.GetFilePicker();
xCtrlAcc = Reference < XFilePickerControlAccess >(xFP, UNO_QUERY);
}
SvxOpenGraphicDialog::SvxOpenGraphicDialog( const String& rTitle ) :
mpImpl( new SvxOpenGrf_Impl )
{
mpImpl->aFileDlg.SetTitle(rTitle);
}
SvxOpenGraphicDialog::~SvxOpenGraphicDialog()
{
}
GraphicFilter* GetGrfFilter();
short SvxOpenGraphicDialog::Execute()
{
USHORT nImpRet;
BOOL bQuitLoop(FALSE);
while( bQuitLoop == FALSE &&
mpImpl->aFileDlg.Execute() == ERRCODE_NONE )
{
if( GetPath().Len() )
{
GraphicFilter* pFilter = GetGrfFilter();
INetURLObject aObj( GetPath() );
// check whether we can load the graphic
String aCurFilter( GetCurrentFilter() );
USHORT nFormatNum = pFilter->GetImportFormatNumber( aCurFilter );
USHORT nRetFormat = 0;
USHORT nFound = USHRT_MAX;
// non-local?
if ( INET_PROT_FILE != aObj.GetProtocol() )
{
SfxMedium aMed( aObj.GetMainURL( INetURLObject::NO_DECODE ), STREAM_READ, TRUE );
aMed.DownLoad();
SvStream* pStream = aMed.GetInStream();
if( pStream )
nImpRet = pFilter->CanImportGraphic( aObj.GetMainURL( INetURLObject::NO_DECODE ), *pStream, nFormatNum, &nRetFormat );
else
nImpRet = pFilter->CanImportGraphic( aObj, nFormatNum, &nRetFormat );
if ( GRFILTER_OK != nImpRet )
{
if ( !pStream )
nImpRet = pFilter->CanImportGraphic( aObj, GRFILTER_FORMAT_DONTKNOW, &nRetFormat );
else
nImpRet = pFilter->CanImportGraphic( aObj.GetMainURL( INetURLObject::NO_DECODE ), *pStream,
GRFILTER_FORMAT_DONTKNOW, &nRetFormat );
}
}
else
{
if( (nImpRet=pFilter->CanImportGraphic( aObj, nFormatNum, &nRetFormat )) != GRFILTER_OK )
nImpRet = pFilter->CanImportGraphic( aObj, GRFILTER_FORMAT_DONTKNOW, &nRetFormat );
}
if ( GRFILTER_OK == nImpRet )
nFound = nRetFormat;
// could not load?
if ( nFound == USHRT_MAX )
{
WarningBox aWarningBox( NULL, WB_3DLOOK | WB_RETRY_CANCEL, SVX_RESSTR( SvxOpenGrfErr2ResId(nImpRet) ) );
bQuitLoop = aWarningBox.Execute()==RET_RETRY ? FALSE : TRUE;
}
else
{
// setup appropriate filter (so next time, it will work)
if( pFilter->GetImportFormatCount() )
{
String aFormatName(pFilter->GetImportFormatName(nFound));
SetCurrentFilter(aFormatName);
}
return nImpRet;
}
}
}
// cancel
return -1;
}
void SvxOpenGraphicDialog::SetPath( const String& rPath )
{
mpImpl->aFileDlg.SetDisplayDirectory(rPath);
}
void SvxOpenGraphicDialog::SetPath( const String& rPath, sal_Bool bLinkState )
{
SetPath(rPath);
AsLink(bLinkState);
}
void SvxOpenGraphicDialog::EnableLink( sal_Bool state )
{
if( mpImpl->xCtrlAcc.is() )
{
try
{
mpImpl->xCtrlAcc->enableControl( ExtendedFilePickerElementIds::CHECKBOX_LINK, state );
}
catch(IllegalArgumentException)
{
#ifdef DBG_UTIL
DBG_ERROR( "Cannot enable \"link\" checkbox" );
#endif
}
}
}
void SvxOpenGraphicDialog::AsLink(sal_Bool bState)
{
if( mpImpl->xCtrlAcc.is() )
{
try
{
Any aAny; aAny <<= bState;
mpImpl->xCtrlAcc->setValue( ExtendedFilePickerElementIds::CHECKBOX_LINK, 0, aAny );
}
catch(IllegalArgumentException)
{
#ifdef DBG_UTIL
DBG_ERROR( "Cannot check \"link\" checkbox" );
#endif
}
}
}
sal_Bool SvxOpenGraphicDialog::IsAsLink() const
{
try
{
if( mpImpl->xCtrlAcc.is() )
{
Any aVal = mpImpl->xCtrlAcc->getValue( ExtendedFilePickerElementIds::CHECKBOX_LINK, 0 );
DBG_ASSERT(aVal.hasValue(), "Value CBX_INSERT_AS_LINK not found")
return aVal.hasValue() ? *(sal_Bool*) aVal.getValue() : sal_False;
}
}
catch(IllegalArgumentException)
{
#ifdef DBG_UTIL
DBG_ERROR( "Cannot access \"link\" checkbox" );
#endif
}
return sal_False;
}
int SvxOpenGraphicDialog::GetGraphic(Graphic& rGraphic) const
{
return mpImpl->aFileDlg.GetGraphic(rGraphic);
}
String SvxOpenGraphicDialog::GetPath() const
{
return mpImpl->aFileDlg.GetPath();
}
String SvxOpenGraphicDialog::GetCurrentFilter() const
{
return mpImpl->aFileDlg.GetCurrentFilter();
}
void SvxOpenGraphicDialog::SetCurrentFilter(const String& rStr)
{
mpImpl->aFileDlg.SetCurrentFilter(rStr);
}
void SvxOpenGraphicDialog::SetControlHelpIds( const INT16* _pControlId, const INT32* _pHelpId )
{
mpImpl->aFileDlg.SetControlHelpIds( _pControlId, _pHelpId );
}
void SvxOpenGraphicDialog::SetDialogHelpId( const INT32 _nHelpId )
{
mpImpl->aFileDlg.SetDialogHelpId( _nHelpId );
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.17.700); FILE MERGED 2005/09/05 14:21:25 rt 1.17.700.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: opengrf.cxx,v $
*
* $Revision: 1.18 $
*
* last change: $Author: rt $ $Date: 2005-09-08 21:38:01 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <tools/urlobj.hxx>
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_COMMONFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/CommonFilePickerElementIds.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_EXECUTABLEDIALOGRESULTS_HPP_
#include <com/sun/star/ui/dialogs/ExecutableDialogResults.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_EXTENDEDFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_FILEPREVIEWIMAGEFORMATS_HPP_
#include <com/sun/star/ui/dialogs/FilePreviewImageFormats.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_LISTBOXCONTROLACTIONS_HPP_
#include <com/sun/star/ui/dialogs/ListboxControlActions.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_TEMPLATEDESCRIPTION_HPP_
#include <com/sun/star/ui/dialogs/TemplateDescription.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERCONTROLACCESS_HPP_
#include <com/sun/star/ui/dialogs/XFilePickerControlAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKER_HPP_
#include <com/sun/star/ui/dialogs/XFilePicker.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERLISTENER_HPP_
#include <com/sun/star/ui/dialogs/XFilePickerListener.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERNOTIFIER_HPP_
#include <com/sun/star/ui/dialogs/XFilePickerNotifier.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPREVIEW_HPP_
#include <com/sun/star/ui/dialogs/XFilePreview.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILTERMANAGER_HPP_
#include <com/sun/star/ui/dialogs/XFilterManager.hpp>
#endif
#ifndef SVTOOLS_URIHELPER_HXX
#include <svtools/urihelper.hxx>
#endif
#ifndef _UNOTOOLS_UCBSTREAMHELPER_HXX
#include <unotools/ucbstreamhelper.hxx>
#endif
#ifndef _TRANSFER_HXX //autogen
#include <svtools/transfer.hxx>
#endif
#ifndef _SVDOGRAF_HXX //autogen
#include "svdograf.hxx"
#endif
#ifndef _SOT_FORMATS_HXX //autogen
#include <sot/formats.hxx>
#endif
#ifndef _MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _FILEDLGHELPER_HXX
#include <sfx2/filedlghelper.hxx>
#endif
#ifndef _SFXDOCFILE_HXX
#include <sfx2/docfile.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX
#include <svtools/pathoptions.hxx>
#endif
#ifndef _SVX_DIALMGR_HXX
#include "dialmgr.hxx"
#endif
#ifndef _SVX_OPENGRF_HXX
#include "opengrf.hxx"
#endif
#include "dialogs.hrc"
#include "impgrf.hrc"
//-----------------------------------------------------------------------------
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::ui::dialogs;
using namespace ::com::sun::star::uno;
using namespace ::rtl;
using namespace ::cppu;
//-----------------------------------------------------------------------------
USHORT SvxOpenGrfErr2ResId( short err )
{
switch( err )
{
case GRFILTER_OPENERROR:
return RID_SVXSTR_GRFILTER_OPENERROR;
case GRFILTER_IOERROR:
return RID_SVXSTR_GRFILTER_IOERROR;
case GRFILTER_VERSIONERROR:
return RID_SVXSTR_GRFILTER_VERSIONERROR;
case GRFILTER_FILTERERROR:
return RID_SVXSTR_GRFILTER_FILTERERROR;
case GRFILTER_FORMATERROR:
default:
return RID_SVXSTR_GRFILTER_FORMATERROR;
}
}
struct SvxOpenGrf_Impl
{
SvxOpenGrf_Impl ();
sfx2::FileDialogHelper aFileDlg;
Reference < XFilePickerControlAccess > xCtrlAcc;
};
SvxOpenGrf_Impl::SvxOpenGrf_Impl() :
aFileDlg(SFXWB_GRAPHIC)
{
Reference < XFilePicker > xFP = aFileDlg.GetFilePicker();
xCtrlAcc = Reference < XFilePickerControlAccess >(xFP, UNO_QUERY);
}
SvxOpenGraphicDialog::SvxOpenGraphicDialog( const String& rTitle ) :
mpImpl( new SvxOpenGrf_Impl )
{
mpImpl->aFileDlg.SetTitle(rTitle);
}
SvxOpenGraphicDialog::~SvxOpenGraphicDialog()
{
}
GraphicFilter* GetGrfFilter();
short SvxOpenGraphicDialog::Execute()
{
USHORT nImpRet;
BOOL bQuitLoop(FALSE);
while( bQuitLoop == FALSE &&
mpImpl->aFileDlg.Execute() == ERRCODE_NONE )
{
if( GetPath().Len() )
{
GraphicFilter* pFilter = GetGrfFilter();
INetURLObject aObj( GetPath() );
// check whether we can load the graphic
String aCurFilter( GetCurrentFilter() );
USHORT nFormatNum = pFilter->GetImportFormatNumber( aCurFilter );
USHORT nRetFormat = 0;
USHORT nFound = USHRT_MAX;
// non-local?
if ( INET_PROT_FILE != aObj.GetProtocol() )
{
SfxMedium aMed( aObj.GetMainURL( INetURLObject::NO_DECODE ), STREAM_READ, TRUE );
aMed.DownLoad();
SvStream* pStream = aMed.GetInStream();
if( pStream )
nImpRet = pFilter->CanImportGraphic( aObj.GetMainURL( INetURLObject::NO_DECODE ), *pStream, nFormatNum, &nRetFormat );
else
nImpRet = pFilter->CanImportGraphic( aObj, nFormatNum, &nRetFormat );
if ( GRFILTER_OK != nImpRet )
{
if ( !pStream )
nImpRet = pFilter->CanImportGraphic( aObj, GRFILTER_FORMAT_DONTKNOW, &nRetFormat );
else
nImpRet = pFilter->CanImportGraphic( aObj.GetMainURL( INetURLObject::NO_DECODE ), *pStream,
GRFILTER_FORMAT_DONTKNOW, &nRetFormat );
}
}
else
{
if( (nImpRet=pFilter->CanImportGraphic( aObj, nFormatNum, &nRetFormat )) != GRFILTER_OK )
nImpRet = pFilter->CanImportGraphic( aObj, GRFILTER_FORMAT_DONTKNOW, &nRetFormat );
}
if ( GRFILTER_OK == nImpRet )
nFound = nRetFormat;
// could not load?
if ( nFound == USHRT_MAX )
{
WarningBox aWarningBox( NULL, WB_3DLOOK | WB_RETRY_CANCEL, SVX_RESSTR( SvxOpenGrfErr2ResId(nImpRet) ) );
bQuitLoop = aWarningBox.Execute()==RET_RETRY ? FALSE : TRUE;
}
else
{
// setup appropriate filter (so next time, it will work)
if( pFilter->GetImportFormatCount() )
{
String aFormatName(pFilter->GetImportFormatName(nFound));
SetCurrentFilter(aFormatName);
}
return nImpRet;
}
}
}
// cancel
return -1;
}
void SvxOpenGraphicDialog::SetPath( const String& rPath )
{
mpImpl->aFileDlg.SetDisplayDirectory(rPath);
}
void SvxOpenGraphicDialog::SetPath( const String& rPath, sal_Bool bLinkState )
{
SetPath(rPath);
AsLink(bLinkState);
}
void SvxOpenGraphicDialog::EnableLink( sal_Bool state )
{
if( mpImpl->xCtrlAcc.is() )
{
try
{
mpImpl->xCtrlAcc->enableControl( ExtendedFilePickerElementIds::CHECKBOX_LINK, state );
}
catch(IllegalArgumentException)
{
#ifdef DBG_UTIL
DBG_ERROR( "Cannot enable \"link\" checkbox" );
#endif
}
}
}
void SvxOpenGraphicDialog::AsLink(sal_Bool bState)
{
if( mpImpl->xCtrlAcc.is() )
{
try
{
Any aAny; aAny <<= bState;
mpImpl->xCtrlAcc->setValue( ExtendedFilePickerElementIds::CHECKBOX_LINK, 0, aAny );
}
catch(IllegalArgumentException)
{
#ifdef DBG_UTIL
DBG_ERROR( "Cannot check \"link\" checkbox" );
#endif
}
}
}
sal_Bool SvxOpenGraphicDialog::IsAsLink() const
{
try
{
if( mpImpl->xCtrlAcc.is() )
{
Any aVal = mpImpl->xCtrlAcc->getValue( ExtendedFilePickerElementIds::CHECKBOX_LINK, 0 );
DBG_ASSERT(aVal.hasValue(), "Value CBX_INSERT_AS_LINK not found")
return aVal.hasValue() ? *(sal_Bool*) aVal.getValue() : sal_False;
}
}
catch(IllegalArgumentException)
{
#ifdef DBG_UTIL
DBG_ERROR( "Cannot access \"link\" checkbox" );
#endif
}
return sal_False;
}
int SvxOpenGraphicDialog::GetGraphic(Graphic& rGraphic) const
{
return mpImpl->aFileDlg.GetGraphic(rGraphic);
}
String SvxOpenGraphicDialog::GetPath() const
{
return mpImpl->aFileDlg.GetPath();
}
String SvxOpenGraphicDialog::GetCurrentFilter() const
{
return mpImpl->aFileDlg.GetCurrentFilter();
}
void SvxOpenGraphicDialog::SetCurrentFilter(const String& rStr)
{
mpImpl->aFileDlg.SetCurrentFilter(rStr);
}
void SvxOpenGraphicDialog::SetControlHelpIds( const INT16* _pControlId, const INT32* _pHelpId )
{
mpImpl->aFileDlg.SetControlHelpIds( _pControlId, _pHelpId );
}
void SvxOpenGraphicDialog::SetDialogHelpId( const INT32 _nHelpId )
{
mpImpl->aFileDlg.SetDialogHelpId( _nHelpId );
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: rotmodit.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 23:39:19 $
*
* 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 _STREAM_HXX //autogen
#include <tools/stream.hxx>
#endif
#pragma hdrstop
#ifndef _COM_SUN_STAR_TABLE_BORDERLINE_HPP_
#include <com/sun/star/table/BorderLine.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_CELLVERTJUSTIFY_HPP_
#include <com/sun/star/table/CellVertJustify.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_SHADOWLOCATION_HPP_
#include <com/sun/star/table/ShadowLocation.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_TABLEBORDER_HPP_
#include <com/sun/star/table/TableBorder.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_SHADOWFORMAT_HPP_
#include <com/sun/star/table/ShadowFormat.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_CELLRANGEADDRESS_HPP_
#include <com/sun/star/table/CellRangeAddress.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_CELLCONTENTTYPE_HPP_
#include <com/sun/star/table/CellContentType.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_TABLEORIENTATION_HPP_
#include <com/sun/star/table/TableOrientation.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_CELLHORIJUSTIFY_HPP_
#include <com/sun/star/table/CellHoriJustify.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_SORTFIELD_HPP_
#include <com/sun/star/util/SortField.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_SORTFIELDTYPE_HPP_
#include <com/sun/star/util/SortFieldType.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_CELLORIENTATION_HPP_
#include <com/sun/star/table/CellOrientation.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_CELLADDRESS_HPP_
#include <com/sun/star/table/CellAddress.hpp>
#endif
#include "rotmodit.hxx"
using namespace ::rtl;
using namespace ::com::sun::star;
// STATIC DATA -----------------------------------------------------------
TYPEINIT1_AUTOFACTORY(SvxRotateModeItem, SfxEnumItem);
//-----------------------------------------------------------------------
// SvxRotateModeItem - Ausrichtung bei gedrehtem Text
//-----------------------------------------------------------------------
SvxRotateModeItem::SvxRotateModeItem( SvxRotateMode eMode, USHORT nWhich )
: SfxEnumItem( nWhich, eMode )
{
}
SvxRotateModeItem::SvxRotateModeItem( const SvxRotateModeItem& rItem )
: SfxEnumItem( rItem )
{
}
__EXPORT SvxRotateModeItem::~SvxRotateModeItem()
{
}
SfxPoolItem* __EXPORT SvxRotateModeItem::Create( SvStream& rStream, USHORT ) const
{
USHORT nVal;
rStream >> nVal;
return new SvxRotateModeItem( (SvxRotateMode) nVal,Which() );
}
SfxItemPresentation __EXPORT SvxRotateModeItem::GetPresentation(
SfxItemPresentation ePres,
SfxMapUnit eCoreUnit, SfxMapUnit ePresUnit,
String& rText, const IntlWrapper * ) const
{
rText.Erase();
switch ( ePres )
{
case SFX_ITEM_PRESENTATION_COMPLETE:
rText.AppendAscii("...");
rText.AppendAscii(": ");
// break; // DURCHFALLEN!!!
case SFX_ITEM_PRESENTATION_NAMELESS:
rText += UniString::CreateFromInt32( GetValue() );
break;
}
return ePres;
}
String __EXPORT SvxRotateModeItem::GetValueText( USHORT nVal ) const
{
String aText;
switch ( nVal )
{
case SVX_ROTATE_MODE_STANDARD:
case SVX_ROTATE_MODE_TOP:
case SVX_ROTATE_MODE_CENTER:
case SVX_ROTATE_MODE_BOTTOM:
aText.AppendAscii("...");
break;
default:
DBG_ERROR("SvxRotateModeItem: falscher enum");
break;
}
return aText;
}
USHORT __EXPORT SvxRotateModeItem::GetValueCount() const
{
return 4; // STANDARD, TOP, CENTER, BOTTOM
}
SfxPoolItem* __EXPORT SvxRotateModeItem::Clone( SfxItemPool* ) const
{
return new SvxRotateModeItem( *this );
}
USHORT __EXPORT SvxRotateModeItem::GetVersion( USHORT nFileVersion ) const
{
return 0;
}
// QueryValue/PutValue: Der ::com::sun::star::table::CellVertJustify enum wird mitbenutzt...
sal_Bool SvxRotateModeItem::QueryValue( uno::Any& rVal, BYTE nMemberId ) const
{
table::CellVertJustify eUno = table::CellVertJustify_STANDARD;
switch ( (SvxRotateMode)GetValue() )
{
case SVX_ROTATE_MODE_STANDARD: eUno = table::CellVertJustify_STANDARD; break;
case SVX_ROTATE_MODE_TOP: eUno = table::CellVertJustify_TOP; break;
case SVX_ROTATE_MODE_CENTER: eUno = table::CellVertJustify_CENTER; break;
case SVX_ROTATE_MODE_BOTTOM: eUno = table::CellVertJustify_BOTTOM; break;
}
rVal <<= eUno;
return sal_True;
}
sal_Bool SvxRotateModeItem::PutValue( const uno::Any& rVal, BYTE nMemberId )
{
table::CellVertJustify eUno;
if(!(rVal >>= eUno))
{
sal_Int32 nValue;
if(!(rVal >>= nValue))
return sal_False;
eUno = (table::CellVertJustify)nValue;
}
SvxRotateMode eSvx = SVX_ROTATE_MODE_STANDARD;
switch (eUno)
{
case table::CellVertJustify_STANDARD: eSvx = SVX_ROTATE_MODE_STANDARD; break;
case table::CellVertJustify_TOP: eSvx = SVX_ROTATE_MODE_TOP; break;
case table::CellVertJustify_CENTER: eSvx = SVX_ROTATE_MODE_CENTER; break;
case table::CellVertJustify_BOTTOM: eSvx = SVX_ROTATE_MODE_BOTTOM; break;
}
SetValue( eSvx );
return sal_True;
}
<commit_msg>INTEGRATION: CWS warnings01 (1.4.220); FILE MERGED 2006/04/24 09:54:28 os 1.4.220.2: warnings removed 2006/04/20 14:49:56 cl 1.4.220.1: warning free code changes<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: rotmodit.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2006-06-19 16:14:45 $
*
* 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 _STREAM_HXX //autogen
#include <tools/stream.hxx>
#endif
#ifndef _COM_SUN_STAR_TABLE_BORDERLINE_HPP_
#include <com/sun/star/table/BorderLine.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_CELLVERTJUSTIFY_HPP_
#include <com/sun/star/table/CellVertJustify.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_SHADOWLOCATION_HPP_
#include <com/sun/star/table/ShadowLocation.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_TABLEBORDER_HPP_
#include <com/sun/star/table/TableBorder.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_SHADOWFORMAT_HPP_
#include <com/sun/star/table/ShadowFormat.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_CELLRANGEADDRESS_HPP_
#include <com/sun/star/table/CellRangeAddress.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_CELLCONTENTTYPE_HPP_
#include <com/sun/star/table/CellContentType.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_TABLEORIENTATION_HPP_
#include <com/sun/star/table/TableOrientation.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_CELLHORIJUSTIFY_HPP_
#include <com/sun/star/table/CellHoriJustify.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_SORTFIELD_HPP_
#include <com/sun/star/util/SortField.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_SORTFIELDTYPE_HPP_
#include <com/sun/star/util/SortFieldType.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_CELLORIENTATION_HPP_
#include <com/sun/star/table/CellOrientation.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_CELLADDRESS_HPP_
#include <com/sun/star/table/CellAddress.hpp>
#endif
#include "rotmodit.hxx"
using namespace ::rtl;
using namespace ::com::sun::star;
// STATIC DATA -----------------------------------------------------------
TYPEINIT1_AUTOFACTORY(SvxRotateModeItem, SfxEnumItem);
//-----------------------------------------------------------------------
// SvxRotateModeItem - Ausrichtung bei gedrehtem Text
//-----------------------------------------------------------------------
SvxRotateModeItem::SvxRotateModeItem( SvxRotateMode eMode, USHORT _nWhich )
: SfxEnumItem( _nWhich, eMode )
{
}
SvxRotateModeItem::SvxRotateModeItem( const SvxRotateModeItem& rItem )
: SfxEnumItem( rItem )
{
}
__EXPORT SvxRotateModeItem::~SvxRotateModeItem()
{
}
SfxPoolItem* __EXPORT SvxRotateModeItem::Create( SvStream& rStream, USHORT ) const
{
USHORT nVal;
rStream >> nVal;
return new SvxRotateModeItem( (SvxRotateMode) nVal,Which() );
}
SfxItemPresentation __EXPORT SvxRotateModeItem::GetPresentation(
SfxItemPresentation ePres,
SfxMapUnit /*eCoreUnit*/, SfxMapUnit /*ePresUnit*/,
String& rText, const IntlWrapper * ) const
{
rText.Erase();
switch ( ePres )
{
case SFX_ITEM_PRESENTATION_COMPLETE:
rText.AppendAscii("...");
rText.AppendAscii(": ");
// break; // DURCHFALLEN!!!
case SFX_ITEM_PRESENTATION_NAMELESS:
rText += UniString::CreateFromInt32( GetValue() );
break;
default: ;//prevent warning
}
return ePres;
}
String __EXPORT SvxRotateModeItem::GetValueText( USHORT nVal ) const
{
String aText;
switch ( nVal )
{
case SVX_ROTATE_MODE_STANDARD:
case SVX_ROTATE_MODE_TOP:
case SVX_ROTATE_MODE_CENTER:
case SVX_ROTATE_MODE_BOTTOM:
aText.AppendAscii("...");
break;
default:
DBG_ERROR("SvxRotateModeItem: falscher enum");
break;
}
return aText;
}
USHORT __EXPORT SvxRotateModeItem::GetValueCount() const
{
return 4; // STANDARD, TOP, CENTER, BOTTOM
}
SfxPoolItem* __EXPORT SvxRotateModeItem::Clone( SfxItemPool* ) const
{
return new SvxRotateModeItem( *this );
}
USHORT __EXPORT SvxRotateModeItem::GetVersion( USHORT /*nFileVersion*/ ) const
{
return 0;
}
// QueryValue/PutValue: Der ::com::sun::star::table::CellVertJustify enum wird mitbenutzt...
sal_Bool SvxRotateModeItem::QueryValue( uno::Any& rVal, BYTE /*nMemberId*/ ) const
{
table::CellVertJustify eUno = table::CellVertJustify_STANDARD;
switch ( (SvxRotateMode)GetValue() )
{
case SVX_ROTATE_MODE_STANDARD: eUno = table::CellVertJustify_STANDARD; break;
case SVX_ROTATE_MODE_TOP: eUno = table::CellVertJustify_TOP; break;
case SVX_ROTATE_MODE_CENTER: eUno = table::CellVertJustify_CENTER; break;
case SVX_ROTATE_MODE_BOTTOM: eUno = table::CellVertJustify_BOTTOM; break;
}
rVal <<= eUno;
return sal_True;
}
sal_Bool SvxRotateModeItem::PutValue( const uno::Any& rVal, BYTE /*nMemberId*/ )
{
table::CellVertJustify eUno;
if(!(rVal >>= eUno))
{
sal_Int32 nValue;
if(!(rVal >>= nValue))
return sal_False;
eUno = (table::CellVertJustify)nValue;
}
SvxRotateMode eSvx = SVX_ROTATE_MODE_STANDARD;
switch (eUno)
{
case table::CellVertJustify_STANDARD: eSvx = SVX_ROTATE_MODE_STANDARD; break;
case table::CellVertJustify_TOP: eSvx = SVX_ROTATE_MODE_TOP; break;
case table::CellVertJustify_CENTER: eSvx = SVX_ROTATE_MODE_CENTER; break;
case table::CellVertJustify_BOTTOM: eSvx = SVX_ROTATE_MODE_BOTTOM; break;
default: ;//prevent warning
}
SetValue( eSvx );
return sal_True;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: idxmrk.cxx,v $
*
* $Revision: 1.36 $
*
* last change: $Author: hr $ $Date: 2007-09-27 12:17:17 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _HELPID_H
#include <helpid.h>
#endif
#define _SVSTDARR_STRINGSSORT
#include <svtools/svstdarr.hxx>
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_SEARCHOPTIONS_HPP_
#include <com/sun/star/util/SearchOptions.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_SEARCHFLAGS_HPP_
#include <com/sun/star/util/SearchFlags.hpp>
#endif
#ifndef _COM_SUN_STAR_I18N_TRANSLITERATIONMODULES_HPP_
#include <com/sun/star/i18n/TransliterationModules.hpp>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _TXTCMP_HXX //autogen
#include <svtools/txtcmp.hxx>
#endif
#ifndef _SVX_SCRIPTTYPEITEM_HXX
#include <svx/scripttypeitem.hxx>
#endif
#ifndef _SFXITEMSET_HXX
#include <svtools/itemset.hxx>
#endif
#ifndef _SVX_LANGITEM_HXX
#include <svx/langitem.hxx>
#endif
#ifndef _SWTYPES_HXX
#include <swtypes.hxx>
#endif
#ifndef _IDXMRK_HXX
#include <idxmrk.hxx>
#endif
#ifndef _TXTTXMRK_HXX
#include <txttxmrk.hxx>
#endif
#ifndef _WRTSH_HXX
#include <wrtsh.hxx>
#endif
#ifndef _VIEW_HXX
#include <view.hxx>
#endif
#ifndef _MULTMRK_HXX
#include <multmrk.hxx>
#endif
#ifndef _SWUNDO_HXX
#include <swundo.hxx> // fuer Undo-Ids
#endif
#ifndef _CMDID_H
#include <cmdid.h>
#endif
#ifndef _INDEX_HRC
#include <index.hrc>
#endif
#ifndef _IDXMRK_HRC
#include <idxmrk.hrc>
#endif
#ifndef _SWMODULE_HXX
#include <swmodule.hxx>
#endif
#ifndef _FLDMGR_HXX
#include <fldmgr.hxx>
#endif
#ifndef _FLDBAS_HXX
#include <fldbas.hxx>
#endif
#include <utlui.hrc>
#ifndef _SWCONT_HXX
#include <swcont.hxx>
#endif
#ifndef _SVTOOLS_CJKOPTIONS_HXX
#include <svtools/cjkoptions.hxx>
#endif
#ifndef _NDTXT_HXX
#include <ndtxt.hxx>
#endif
#ifndef _BREAKIT_HXX
#include <breakit.hxx>
#endif
/* -----------------07.09.99 08:15-------------------
--------------------------------------------------*/
SFX_IMPL_CHILDWINDOW(SwInsertIdxMarkWrapper, FN_INSERT_IDX_ENTRY_DLG)
SwInsertIdxMarkWrapper::SwInsertIdxMarkWrapper( Window *pParentWindow,
sal_uInt16 nId,
SfxBindings* pBindings,
SfxChildWinInfo* pInfo ) :
SfxChildWindow(pParentWindow, nId)
{
SwAbstractDialogFactory* pFact = SwAbstractDialogFactory::Create();
DBG_ASSERT(pFact, "SwAbstractDialogFactory fail!");
pAbstDlg = pFact->CreateIndexMarkFloatDlg( DLG_INSIDXMARK , pBindings, this, pParentWindow, pInfo );
DBG_ASSERT(pAbstDlg, "Dialogdiet fail!");
pWindow = pAbstDlg->GetWindow();
pWindow->Show(); // at this point,because before pSh has to be initialized in ReInitDlg()
// -> Show() will invoke StateChanged() and save pos
eChildAlignment = SFX_ALIGN_NOALIGNMENT;
}
/* -----------------07.09.99 09:14-------------------
--------------------------------------------------*/
SfxChildWinInfo SwInsertIdxMarkWrapper::GetInfo() const
{
SfxChildWinInfo aInfo = SfxChildWindow::GetInfo();
return aInfo;
}
void SwInsertIdxMarkWrapper::ReInitDlg(SwWrtShell& rWrtShell)
{
pAbstDlg->ReInitDlg(rWrtShell);
}
/* -----------------07.09.99 08:15-------------------
--------------------------------------------------*/
SFX_IMPL_CHILDWINDOW(SwInsertAuthMarkWrapper, FN_INSERT_AUTH_ENTRY_DLG)
SwInsertAuthMarkWrapper::SwInsertAuthMarkWrapper( Window *pParentWindow,
sal_uInt16 nId,
SfxBindings* pBindings,
SfxChildWinInfo* pInfo ) :
SfxChildWindow(pParentWindow, nId)
{
SwAbstractDialogFactory* pFact = SwAbstractDialogFactory::Create();
DBG_ASSERT(pFact, "SwAbstractDialogFactory fail!");
pAbstDlg = pFact->CreateAuthMarkFloatDlg( DLG_INSAUTHMARK, pBindings, this, pParentWindow, pInfo );
DBG_ASSERT(pAbstDlg, "Dialogdiet fail!");
pWindow = pAbstDlg->GetWindow();
eChildAlignment = SFX_ALIGN_NOALIGNMENT;
}
/* -----------------07.09.99 09:14-------------------
--------------------------------------------------*/
SfxChildWinInfo SwInsertAuthMarkWrapper::GetInfo() const
{
SfxChildWinInfo aInfo = SfxChildWindow::GetInfo();
return aInfo;
}
/* -----------------19.10.99 11:16-------------------
--------------------------------------------------*/
void SwInsertAuthMarkWrapper::ReInitDlg(SwWrtShell& rWrtShell)
{
pAbstDlg->ReInitDlg(rWrtShell);
}
<commit_msg>INTEGRATION: CWS changefileheader (1.36.242); FILE MERGED 2008/04/01 15:59:30 thb 1.36.242.3: #i85898# Stripping all external header guards 2008/04/01 12:55:41 thb 1.36.242.2: #i85898# Stripping all external header guards 2008/03/31 16:58:57 rt 1.36.242.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: idxmrk.cxx,v $
* $Revision: 1.37 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#include <hintids.hxx>
#ifndef _HELPID_H
#include <helpid.h>
#endif
#define _SVSTDARR_STRINGSSORT
#include <svtools/svstdarr.hxx>
#include <comphelper/processfactory.hxx>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/util/SearchOptions.hpp>
#include <com/sun/star/util/SearchFlags.hpp>
#include <com/sun/star/i18n/TransliterationModules.hpp>
#include <svtools/stritem.hxx>
#ifndef _MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#include <sfx2/dispatch.hxx>
#include <svtools/eitem.hxx>
#include <svtools/txtcmp.hxx>
#include <svx/scripttypeitem.hxx>
#include <svtools/itemset.hxx>
#include <svx/langitem.hxx>
#include <swtypes.hxx>
#include <idxmrk.hxx>
#include <txttxmrk.hxx>
#include <wrtsh.hxx>
#ifndef _VIEW_HXX
#include <view.hxx>
#endif
#include <multmrk.hxx>
#include <swundo.hxx> // fuer Undo-Ids
#ifndef _CMDID_H
#include <cmdid.h>
#endif
#ifndef _INDEX_HRC
#include <index.hrc>
#endif
#ifndef _IDXMRK_HRC
#include <idxmrk.hrc>
#endif
#include <swmodule.hxx>
#include <fldmgr.hxx>
#include <fldbas.hxx>
#include <utlui.hrc>
#include <swcont.hxx>
#include <svtools/cjkoptions.hxx>
#include <ndtxt.hxx>
#include <breakit.hxx>
/* -----------------07.09.99 08:15-------------------
--------------------------------------------------*/
SFX_IMPL_CHILDWINDOW(SwInsertIdxMarkWrapper, FN_INSERT_IDX_ENTRY_DLG)
SwInsertIdxMarkWrapper::SwInsertIdxMarkWrapper( Window *pParentWindow,
sal_uInt16 nId,
SfxBindings* pBindings,
SfxChildWinInfo* pInfo ) :
SfxChildWindow(pParentWindow, nId)
{
SwAbstractDialogFactory* pFact = SwAbstractDialogFactory::Create();
DBG_ASSERT(pFact, "SwAbstractDialogFactory fail!");
pAbstDlg = pFact->CreateIndexMarkFloatDlg( DLG_INSIDXMARK , pBindings, this, pParentWindow, pInfo );
DBG_ASSERT(pAbstDlg, "Dialogdiet fail!");
pWindow = pAbstDlg->GetWindow();
pWindow->Show(); // at this point,because before pSh has to be initialized in ReInitDlg()
// -> Show() will invoke StateChanged() and save pos
eChildAlignment = SFX_ALIGN_NOALIGNMENT;
}
/* -----------------07.09.99 09:14-------------------
--------------------------------------------------*/
SfxChildWinInfo SwInsertIdxMarkWrapper::GetInfo() const
{
SfxChildWinInfo aInfo = SfxChildWindow::GetInfo();
return aInfo;
}
void SwInsertIdxMarkWrapper::ReInitDlg(SwWrtShell& rWrtShell)
{
pAbstDlg->ReInitDlg(rWrtShell);
}
/* -----------------07.09.99 08:15-------------------
--------------------------------------------------*/
SFX_IMPL_CHILDWINDOW(SwInsertAuthMarkWrapper, FN_INSERT_AUTH_ENTRY_DLG)
SwInsertAuthMarkWrapper::SwInsertAuthMarkWrapper( Window *pParentWindow,
sal_uInt16 nId,
SfxBindings* pBindings,
SfxChildWinInfo* pInfo ) :
SfxChildWindow(pParentWindow, nId)
{
SwAbstractDialogFactory* pFact = SwAbstractDialogFactory::Create();
DBG_ASSERT(pFact, "SwAbstractDialogFactory fail!");
pAbstDlg = pFact->CreateAuthMarkFloatDlg( DLG_INSAUTHMARK, pBindings, this, pParentWindow, pInfo );
DBG_ASSERT(pAbstDlg, "Dialogdiet fail!");
pWindow = pAbstDlg->GetWindow();
eChildAlignment = SFX_ALIGN_NOALIGNMENT;
}
/* -----------------07.09.99 09:14-------------------
--------------------------------------------------*/
SfxChildWinInfo SwInsertAuthMarkWrapper::GetInfo() const
{
SfxChildWinInfo aInfo = SfxChildWindow::GetInfo();
return aInfo;
}
/* -----------------19.10.99 11:16-------------------
--------------------------------------------------*/
void SwInsertAuthMarkWrapper::ReInitDlg(SwWrtShell& rWrtShell)
{
pAbstDlg->ReInitDlg(rWrtShell);
}
<|endoftext|> |
<commit_before>#ifndef CWRAPPER_HPP_INCLUDED
#define CWRAPPER_HPP_INCLUDED
#define HAS_STATIC_MEMBER_DETECTOR(member) \
template<typename T> \
class HAS_STATIC_MEMBER_DETECTOR_CLASS_ ## member \
{ \
struct two_ints_type { int two_ints_1, two_ints_2; }; \
template<typename U> \
static two_ints_type has_func_helper(...) { } \
template<typename U> \
static int has_func_helper(int, decltype(U::member)* func = nullptr) \
{ return 0; } \
public: \
static constexpr bool value = \
sizeof(decltype(has_func_helper<T>(0))) == sizeof(int); \
}
#define HAS_STATIC_MEMBER(type, member) \
(HAS_STATIC_MEMBER_DETECTOR_CLASS_ ## member<type>::value)
#define HAS_NESTED_TYPE_DETECTOR(member) \
template<typename T> \
class HAS_NESTED_TYPE_DETECTOR_CLASS_ ## member \
{ \
struct two_ints_type { int two_ints_1, two_ints_2; }; \
template<typename U> \
static two_ints_type has_func_helper(...) { } \
template<typename U> \
static int has_func_helper(int, typename U::member* ty = nullptr) \
{ return 0; } \
public: \
static constexpr bool value = \
sizeof(decltype(has_func_helper<T>(0))) == sizeof(int); \
}
#define HAS_NESTED_TYPE(type, member) \
(HAS_NESTED_TYPE_DETECTOR_CLASS_ ## member<type>::value)
namespace CW {
enum class CWrapperType
{
Implicit,
Explicit,
Get,
};
template<
typename H,
typename F,
CWrapperType TY = CWrapperType::Get,
bool C = true>
class CWrapperFriend
{
template<
typename HANDLE_T,
typename BASE,
bool CONSTSAFE>
struct ArrowHandler
{ };
template<
typename PTR_T,
typename BASE>
struct ArrowHandler<PTR_T*, BASE, false>
{
PTR_T* operator->() const
{ return static_cast<BASE*>(this)->ptr; }
};
template<
typename PTR_T,
typename BASE>
struct ArrowHandler<PTR_T*, BASE, true>
{
PTR_T* operator->()
{ return static_cast<BASE*>(this)->ptr; }
PTR_T const* operator->() const
{ return static_cast<const BASE*>(this)->ptr; }
};
template<
typename HANDLE_T,
typename BASE,
CWrapperType TYPE,
bool CONSTSAFE>
struct ConversionHandler : public ArrowHandler<HANDLE_T, BASE, CONSTSAFE>
{ };
template<
typename HANDLE_T,
typename BASE,
bool CONSTSAFE>
struct ConversionHandler<HANDLE_T, BASE, CWrapperType::Implicit, CONSTSAFE>
: public ArrowHandler<HANDLE_T, BASE, CONSTSAFE>
{
operator HANDLE_T() const
{ return static_cast<const BASE*>(this)->ptr; }
};
template<
typename HANDLE_T,
typename BASE,
bool CONSTSAFE>
struct ConversionHandler<HANDLE_T, BASE, CWrapperType::Explicit, CONSTSAFE>
: public ArrowHandler<HANDLE_T, BASE, CONSTSAFE>
{
explicit operator HANDLE_T() const
{ return static_cast<const BASE*>(this)->ptr; }
};
template<
typename HANDLE_T,
typename BASE,
bool CONSTSAFE>
struct ConversionHandler<HANDLE_T, BASE, CWrapperType::Get, CONSTSAFE>
: public ArrowHandler<HANDLE_T, BASE, CONSTSAFE>
{
HANDLE_T get() const
{ return static_cast<const BASE*>(this)->ptr; }
};
template<
typename PTR_T,
typename BASE>
struct ConversionHandler<PTR_T*, BASE, CWrapperType::Implicit, true>
: public ArrowHandler<PTR_T*, BASE, true>
{
operator PTR_T*()
{ return static_cast<BASE*>(this)->ptr; }
operator PTR_T const*() const
{ return static_cast<const BASE*>(this)->ptr; }
};
template<
typename PTR_T,
typename BASE>
struct ConversionHandler<PTR_T*, BASE, CWrapperType::Explicit, true>
: public ArrowHandler<PTR_T*, BASE, true>
{
explicit operator PTR_T*()
{ return static_cast<BASE*>(this)->ptr; }
explicit operator PTR_T const*() const
{ return static_cast<const BASE*>(this)->ptr; }
};
template<
typename PTR_T,
typename BASE>
struct ConversionHandler<PTR_T*, BASE, CWrapperType::Get, true>
: public ArrowHandler<PTR_T*, BASE, true>
{
PTR_T* get()
{ return static_cast<BASE*>(this)->ptr; }
PTR_T const* get() const
{ return static_cast<const BASE*>(this)->ptr; }
};
template<
typename HANDLE_T,
typename FUNCTIONS,
CWrapperType TYPE,
bool CONSTSAFE,
typename EXCEPTION_T,
typename INVALID_T,
typename VALIDATE_T>
class CWrapperBase
: public ConversionHandler<
HANDLE_T,
CWrapperBase<HANDLE_T, FUNCTIONS, TYPE, CONSTSAFE, EXCEPTION_T, INVALID_T, VALIDATE_T>,
TYPE,
CONSTSAFE>
{
friend class ConversionHandler<
HANDLE_T,
CWrapperBase<HANDLE_T, FUNCTIONS, TYPE, CONSTSAFE, EXCEPTION_T, INVALID_T, VALIDATE_T>,
TYPE,
CONSTSAFE>;
protected:
HANDLE_T ptr;
public:
explicit CWrapperBase(HANDLE_T ptr) :
ptr{ptr}
{
if(!VALIDATE_T::validate_func(ptr))
throw typename EXCEPTION_T::exception{};
}
CWrapperBase(CWrapperBase const& other) :
CWrapperBase{FUNCTIONS::copy_func(other.ptr)}
{ }
// This one is needed to prevent variadic ctor to be called
// when you want to copy a non-const object.
CWrapperBase(CWrapperBase& other) :
CWrapperBase{FUNCTIONS::copy_func(other.ptr)}
{ }
template<typename... ARGS>
explicit CWrapperBase(ARGS&&... args) :
CWrapperBase{FUNCTIONS::ctor_func(std::forward<ARGS>(args)...)}
{ }
CWrapperBase(CWrapperBase&& old) :
CWrapperBase{old.ptr}
{
old.ptr = INVALID_T::invalid_value;
}
CWrapperBase& operator=(CWrapperBase&& old)
{
if(this != &old)
{
if(VALIDATE_T::validate_func(ptr))
FUNCTIONS::dtor_func(ptr);
ptr = old.ptr;
old.ptr = INVALID_T::invalid_value;
}
return *this;
}
~CWrapperBase()
{
if(VALIDATE_T::validate_func(ptr))
FUNCTIONS::dtor_func(ptr);
}
CWrapperBase& operator=(CWrapperBase const& other)
{
if(this != &other)
{
HANDLE_T new_ptr = FUNCTIONS::copy_func(other.ptr);
if(!VALIDATE_T::validate_func(new_ptr))
throw typename EXCEPTION_T::exception{};
if(VALIDATE_T::validate_func(ptr))
FUNCTIONS::dtor_func(ptr);
ptr = new_ptr;
}
return *this;
}
};
template<
typename HANDLE_T,
typename FUNCTIONS,
CWrapperType TYPE,
bool CONSTSAFE,
typename EXCEPTION_T,
typename INVALID_T,
typename VALIDATE_T>
class CWrapperNonCopiable
: public ConversionHandler<
HANDLE_T,
CWrapperNonCopiable<HANDLE_T, FUNCTIONS, TYPE, CONSTSAFE, EXCEPTION_T, INVALID_T, VALIDATE_T>,
TYPE,
CONSTSAFE>
{
friend class ConversionHandler<
HANDLE_T,
CWrapperNonCopiable<HANDLE_T, FUNCTIONS, TYPE, CONSTSAFE, EXCEPTION_T, INVALID_T, VALIDATE_T>,
TYPE,
CONSTSAFE>;
protected:
HANDLE_T ptr;
public:
explicit CWrapperNonCopiable(HANDLE_T ptr) :
ptr{ptr}
{
if(!VALIDATE_T::validate_func(ptr))
throw typename EXCEPTION_T::exception{};
}
template<typename... ARGS>
explicit CWrapperNonCopiable(ARGS&&... args) :
CWrapperNonCopiable{FUNCTIONS::ctor_func(std::forward<ARGS>(args)...)}
{ }
CWrapperNonCopiable(CWrapperNonCopiable&& old) :
CWrapperNonCopiable{old.ptr}
{
old.ptr = INVALID_T::invalid_value;
}
CWrapperNonCopiable& operator=(CWrapperNonCopiable&& old)
{
if(this != &old)
{
if(VALIDATE_T::validate_func(ptr))
FUNCTIONS::dtor_func(ptr);
ptr = old.ptr;
old.ptr = INVALID_T::invalid_value;
}
return *this;
}
~CWrapperNonCopiable()
{
if(VALIDATE_T::validate_func(ptr))
FUNCTIONS::dtor_func(ptr);
}
// This one is needed to prevent variadic ctor to be called
// when you want to copy a non-const object.
CWrapperNonCopiable(CWrapperNonCopiable& other) = delete;
CWrapperNonCopiable(CWrapperNonCopiable const& other) = delete;
CWrapperNonCopiable& operator=(CWrapperNonCopiable const& other) = delete;
};
template<bool condition, typename TRUE_TYPE, typename FALSE_TYPE>
struct COND
{
using type = TRUE_TYPE;
};
template<typename TRUE_TYPE, typename FALSE_TYPE>
struct COND<false, TRUE_TYPE, FALSE_TYPE>
{
using type = FALSE_TYPE;
};
HAS_NESTED_TYPE_DETECTOR(exception);
HAS_STATIC_MEMBER_DETECTOR(copy_func);
HAS_STATIC_MEMBER_DETECTOR(invalid_value);
HAS_STATIC_MEMBER_DETECTOR(validate_func);
struct default_exception_type
{
using exception = std::bad_alloc;
};
template<typename T>
struct default_invalid_value
{
static constexpr T invalid_value = 0;
};
template<typename T>
struct default_invalid_value<T*>
{
static constexpr T* invalid_value = nullptr;
};
template<typename T, typename INVALID_T>
struct default_validate_func
{
static constexpr bool validate_func(T ptr)
{
return ptr != INVALID_T::invalid_value;
}
};
using E = typename COND< HAS_NESTED_TYPE(F, exception),
F, default_exception_type>::type;
using D = typename COND< HAS_STATIC_MEMBER(F, invalid_value),
F, default_invalid_value<H>>::type;
using V = typename COND< HAS_STATIC_MEMBER(F, validate_func),
F, default_validate_func<H, D>>::type;
public:
using type = typename COND< HAS_STATIC_MEMBER(F, copy_func),
CWrapperBase<H, F, TY, C, E, D, V>,
CWrapperNonCopiable<H, F, TY, C, E, D, V>>::type;
};
template<
typename HANDLE_T,
typename FUNCTIONS,
CWrapperType TYPE = CWrapperType::Get,
bool CONSTSAFE = true>
using CWrapper = typename CWrapperFriend<HANDLE_T, FUNCTIONS, TYPE, CONSTSAFE>::type;
}
#undef HAS_STATIC_MEMBER_DETECTOR
#undef HAS_STATIC_MEMBER
#undef HAS_NESTED_TYPE_DETECTOR
#undef HAS_NESTED_TYPE
#endif // CWRAPPER_HPP_INCLUDED
<commit_msg>Copy ctor magic intensified, op= changed to copy-and-swap<commit_after>#ifndef CWRAPPER_HPP_INCLUDED
#define CWRAPPER_HPP_INCLUDED
#include <utility>
#include <new> // this one is needed only for std::bad_alloc
#define HAS_STATIC_MEMBER_DETECTOR(member) \
template<typename T> \
class HAS_STATIC_MEMBER_DETECTOR_CLASS_ ## member \
{ \
struct two_ints_type { int two_ints_1, two_ints_2; }; \
template<typename U> \
static two_ints_type has_func_helper(...) { } \
template<typename U> \
static int has_func_helper(int, decltype(U::member)* func = nullptr) \
{ return 0; } \
public: \
static constexpr bool value = \
sizeof(decltype(has_func_helper<T>(0))) == sizeof(int); \
}
#define HAS_STATIC_MEMBER(type, member) \
(HAS_STATIC_MEMBER_DETECTOR_CLASS_ ## member<type>::value)
#define HAS_NESTED_TYPE_DETECTOR(member) \
template<typename T> \
class HAS_NESTED_TYPE_DETECTOR_CLASS_ ## member \
{ \
struct two_ints_type { int two_ints_1, two_ints_2; }; \
template<typename U> \
static two_ints_type has_func_helper(...) { } \
template<typename U> \
static int has_func_helper(int, typename U::member* ty = nullptr) \
{ return 0; } \
public: \
static constexpr bool value = \
sizeof(decltype(has_func_helper<T>(0))) == sizeof(int); \
}
#define HAS_NESTED_TYPE(type, member) \
(HAS_NESTED_TYPE_DETECTOR_CLASS_ ## member<type>::value)
namespace CW {
enum class CWrapperType
{
Implicit,
Explicit,
Get,
};
template<
typename H,
typename F,
CWrapperType TY = CWrapperType::Get,
bool C = true>
class CWrapperFriend
{
template<
typename HANDLE_T,
typename BASE,
bool CONSTSAFE>
struct ArrowHandler
{ };
template<
typename PTR_T,
typename BASE>
struct ArrowHandler<PTR_T*, BASE, false>
{
PTR_T* operator->() const
{ return static_cast<BASE*>(this)->ptr; }
};
template<
typename PTR_T,
typename BASE>
struct ArrowHandler<PTR_T*, BASE, true>
{
PTR_T* operator->()
{ return static_cast<BASE*>(this)->ptr; }
PTR_T const* operator->() const
{ return static_cast<const BASE*>(this)->ptr; }
};
template<
typename HANDLE_T,
typename BASE,
CWrapperType TYPE,
bool CONSTSAFE>
struct ConversionHandler : public ArrowHandler<HANDLE_T, BASE, CONSTSAFE>
{ };
template<
typename HANDLE_T,
typename BASE,
bool CONSTSAFE>
struct ConversionHandler<HANDLE_T, BASE, CWrapperType::Implicit, CONSTSAFE>
: public ArrowHandler<HANDLE_T, BASE, CONSTSAFE>
{
operator HANDLE_T() const
{ return static_cast<const BASE*>(this)->ptr; }
};
template<
typename HANDLE_T,
typename BASE,
bool CONSTSAFE>
struct ConversionHandler<HANDLE_T, BASE, CWrapperType::Explicit, CONSTSAFE>
: public ArrowHandler<HANDLE_T, BASE, CONSTSAFE>
{
explicit operator HANDLE_T() const
{ return static_cast<const BASE*>(this)->ptr; }
};
template<
typename HANDLE_T,
typename BASE,
bool CONSTSAFE>
struct ConversionHandler<HANDLE_T, BASE, CWrapperType::Get, CONSTSAFE>
: public ArrowHandler<HANDLE_T, BASE, CONSTSAFE>
{
HANDLE_T get() const
{ return static_cast<const BASE*>(this)->ptr; }
};
template<
typename PTR_T,
typename BASE>
struct ConversionHandler<PTR_T*, BASE, CWrapperType::Implicit, true>
: public ArrowHandler<PTR_T*, BASE, true>
{
operator PTR_T*()
{ return static_cast<BASE*>(this)->ptr; }
operator PTR_T const*() const
{ return static_cast<const BASE*>(this)->ptr; }
};
template<
typename PTR_T,
typename BASE>
struct ConversionHandler<PTR_T*, BASE, CWrapperType::Explicit, true>
: public ArrowHandler<PTR_T*, BASE, true>
{
explicit operator PTR_T*()
{ return static_cast<BASE*>(this)->ptr; }
explicit operator PTR_T const*() const
{ return static_cast<const BASE*>(this)->ptr; }
};
template<
typename PTR_T,
typename BASE>
struct ConversionHandler<PTR_T*, BASE, CWrapperType::Get, true>
: public ArrowHandler<PTR_T*, BASE, true>
{
PTR_T* get()
{ return static_cast<BASE*>(this)->ptr; }
PTR_T const* get() const
{ return static_cast<const BASE*>(this)->ptr; }
};
template<bool b, typename T>
struct hider
{
static constexpr bool value = b;
};
// Works exactly like std::enable if. I didn't want to include
// type_traits for this one and COND
template<bool cond, typename T = void>
struct enabler
{ };
template<typename T>
struct enabler<true, T>
{
using type = T;
};
template<
typename HANDLE_T,
typename FUNCTIONS,
CWrapperType TYPE,
bool CONSTSAFE,
typename EXCEPTION_T,
typename INVALID_T,
typename VALIDATE_T,
typename COPY_T,
bool HAS_COPY>
class CWrapperBase
: public ConversionHandler<
HANDLE_T,
CWrapperBase<HANDLE_T, FUNCTIONS, TYPE, CONSTSAFE, EXCEPTION_T,
INVALID_T, VALIDATE_T, COPY_T, HAS_COPY>,
TYPE,
CONSTSAFE>
{
friend class ConversionHandler<
HANDLE_T,
CWrapperBase<HANDLE_T, FUNCTIONS, TYPE, CONSTSAFE, EXCEPTION_T,
INVALID_T, VALIDATE_T, COPY_T, HAS_COPY>,
TYPE,
CONSTSAFE>;
protected:
HANDLE_T ptr;
private:
template<typename DUMMY = void,
typename = typename enabler<hider<!HAS_COPY, DUMMY>::value>::type>
CWrapperBase(CWrapperBase const& other, void ** ptr = nullptr) :
CWrapperBase{COPY_T::copy_func(other.ptr)}
{ }
// This one is needed to prevent variadic ctor to be
// called when you want to copy a non-const object.
template<typename DUMMY = void,
typename = typename enabler<hider<!HAS_COPY, DUMMY>::value>::type>
CWrapperBase(CWrapperBase& other, void ** ptr = nullptr) :
CWrapperBase{COPY_T::copy_func(other.ptr)}
{ }
public:
explicit CWrapperBase(HANDLE_T ptr) :
ptr{ptr}
{
if(!VALIDATE_T::validate_func(ptr))
throw typename EXCEPTION_T::exception{};
}
template<typename DUMMY = void,
typename = typename enabler<hider<HAS_COPY, DUMMY>::value>::type>
CWrapperBase(CWrapperBase const& other) :
CWrapperBase{COPY_T::copy_func(other.ptr)}
{ }
// This one is needed to prevent variadic ctor to be
// called when you want to copy a non-const object.
template<typename DUMMY = void,
typename = typename enabler<hider<HAS_COPY, DUMMY>::value>::type>
CWrapperBase(CWrapperBase& other) :
CWrapperBase{COPY_T::copy_func(other.ptr)}
{ }
template<typename... ARGS>
explicit CWrapperBase(ARGS&&... args) :
CWrapperBase{FUNCTIONS::ctor_func(std::forward<ARGS>(args)...)}
{ }
CWrapperBase(CWrapperBase&& old) :
CWrapperBase{old.ptr}
{
old.ptr = INVALID_T::invalid_value;
}
~CWrapperBase()
{
if(VALIDATE_T::validate_func(ptr))
FUNCTIONS::dtor_func(ptr);
}
CWrapperBase& operator=(CWrapperBase other)
{
std::swap(ptr, other.ptr);
return *this;
}
};
template<bool condition, typename TRUE_TYPE, typename FALSE_TYPE>
struct COND
{
using type = TRUE_TYPE;
};
template<typename TRUE_TYPE, typename FALSE_TYPE>
struct COND<false, TRUE_TYPE, FALSE_TYPE>
{
using type = FALSE_TYPE;
};
HAS_NESTED_TYPE_DETECTOR(exception);
HAS_STATIC_MEMBER_DETECTOR(copy_func);
HAS_STATIC_MEMBER_DETECTOR(invalid_value);
HAS_STATIC_MEMBER_DETECTOR(validate_func);
struct default_exception_type
{
using exception = std::bad_alloc;
};
template<typename T>
struct default_invalid_value
{
static constexpr T invalid_value = 0;
};
template<typename T>
struct default_invalid_value<T*>
{
static constexpr T* invalid_value = nullptr;
};
template<typename T, typename INVALID_T>
struct default_validate_func
{
static constexpr bool validate_func(T ptr)
{
return ptr != INVALID_T::invalid_value;
}
};
// this one is never called, but necessary to compile if copy ctor is "deleted"
template<typename T>
struct default_copy_func
{
static constexpr T copy_func(T const& other)
{
return other;
}
};
using E = typename COND< HAS_NESTED_TYPE(F, exception),
F, default_exception_type>::type;
using D = typename COND< HAS_STATIC_MEMBER(F, invalid_value),
F, default_invalid_value<H>>::type;
using V = typename COND< HAS_STATIC_MEMBER(F, validate_func),
F, default_validate_func<H, D>>::type;
static constexpr bool has_copy_value = HAS_STATIC_MEMBER(F, copy_func);
using COPY = typename COND< has_copy_value,
F, default_copy_func<H>>::type;
public:
using type = CWrapperBase<H, F, TY, C, E, D, V, COPY, has_copy_value>;
};
template<
typename HANDLE_T,
typename FUNCTIONS,
CWrapperType TYPE = CWrapperType::Get,
bool CONSTSAFE = true>
using CWrapper = typename CWrapperFriend<HANDLE_T, FUNCTIONS, TYPE, CONSTSAFE>::type;
}
#undef HAS_STATIC_MEMBER_DETECTOR
#undef HAS_STATIC_MEMBER
#undef HAS_NESTED_TYPE_DETECTOR
#undef HAS_NESTED_TYPE
#endif // CWRAPPER_HPP_INCLUDED
<|endoftext|> |
<commit_before>#include <iostream>
#include <iomanip>
#include <cmath>
#include <chrono>
#include <random>
using namespace std;
#define DBG 1
#define DRAM_SIZE (64*1024*1024)
#define CACHE_SIZE (32*1024)
std::mt19937 generator;
enum cacheResType { MISS = 0, HIT = 1 };
unsigned int m_w = 0xABABAB55; /* must not be zero, nor 0x464fffff */
unsigned int m_z = 0x05080902; /* must not be zero, nor 0x9068ffff */
unsigned int rand_()
{
m_z = 36969 * (m_z & 65535) + (m_z >> 16);
m_w = 18000 * (m_w & 65535) + (m_w >> 16);
return (m_z << 16) + m_w; /* 32-bit result */
}
unsigned int memGen1()
{
static unsigned int addr = 0;
return (addr++) % (DRAM_SIZE);
}
unsigned int memGen2()
{
return rand_() % (DRAM_SIZE);
}
unsigned int memGen3()
{
static unsigned int addr = 0;
return (addr++) % (1024 * 8);
}
unsigned int memGen4()
{
static unsigned int addr = 0;
return (addr++) % (1024 * 64);
}
unsigned int (*genFunctions[4])() = {
memGen1,
memGen2,
memGen3,
memGen4
};
// Direct Mapped Cache Simulator
cacheResType cacheSimDM(unsigned int addr)
{
return MISS;
}
struct FullyAssociativeLine
{
unsigned int tag;
bool valid = false;
};
FullyAssociativeLine* cacheBlocks;
int blockNumber;
int shiftAmount;
// Fully Associative Cache Simulator
cacheResType cacheSimFA(unsigned int addr)
{
int tag = addr >> shiftAmount;
for (int i = 0; i < blockNumber; ++i)
{
if (cacheBlocks[i].tag == tag && cacheBlocks[i].valid)
return HIT;
}
int blockReplaced = generator() % blockNumber;
cacheBlocks[blockReplaced].tag = tag;
cacheBlocks[blockReplaced].valid = true;
return MISS;
}
void runCacheBlockSize(int blockSize)
{
cout << "Cache line size: " << blockSize << endl;
blockNumber = CACHE_SIZE / blockSize;
shiftAmount = log2(blockSize);
cacheBlocks = new FullyAssociativeLine[blockNumber]{};
cacheResType r;
unsigned int addr;
cout << "Fully Associative Cache Simulator\n";
int hits[4]{};
for (int inst = 0; inst < 1000000; inst++)
{
for (int i = 0; i < 4; ++i)
{
addr = genFunctions[i]();
r = cacheSimFA(addr);
if (r == HIT)
hits[i]++;
}
}
cout << "memGen1 Hits: " << hits[0] << endl;
cout << "memGen2 Hits: " << hits[1] << endl;
cout << "memGen3 Hits: " << hits[2] << endl;
cout << "memGen4 Hits: " << hits[3] << endl << endl;
delete[] cacheBlocks;
}
int main()
{
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
generator = std::mt19937(seed);
for (int i = 8; i <= 128; i *= 2)
{
runCacheBlockSize(i);
}
}<commit_msg>Cleaned some code<commit_after>#include <iostream>
#include <iomanip>
#include <cmath>
#include <chrono>
#include <random>
using namespace std;
#define DBG 1
#define DRAM_SIZE (64*1024*1024)
#define CACHE_SIZE (32*1024)
std::mt19937 generator(unsigned int(std::chrono::system_clock::now().time_since_epoch().count()));
enum cacheResType { MISS = 0, HIT = 1 };
unsigned int m_w = 0xABABAB55; /* must not be zero, nor 0x464fffff */
unsigned int m_z = 0x05080902; /* must not be zero, nor 0x9068ffff */
unsigned int rand_()
{
m_z = 36969 * (m_z & 65535) + (m_z >> 16);
m_w = 18000 * (m_w & 65535) + (m_w >> 16);
return (m_z << 16) + m_w; /* 32-bit result */
}
unsigned int memGen1()
{
static unsigned int addr = 0;
return (addr++) % (DRAM_SIZE);
}
unsigned int memGen2()
{
return rand_() % (DRAM_SIZE);
}
unsigned int memGen3()
{
static unsigned int addr = 0;
return (addr++) % (1024 * 8);
}
unsigned int memGen4()
{
static unsigned int addr = 0;
return (addr++) % (1024 * 64);
}
unsigned int (*genFunctions[4])() = {
memGen1,
memGen2,
memGen3,
memGen4
};
// Direct Mapped Cache Simulator
cacheResType cacheSimDM(unsigned int addr)
{
return MISS;
}
struct FullyAssociativeLine
{
unsigned int tag;
bool valid = false;
};
FullyAssociativeLine* cacheBlocks;
int blockNumber;
int shiftAmount;
// Fully Associative Cache Simulator
cacheResType cacheSimFA(unsigned int addr)
{
int tag = addr >> shiftAmount;
for (int i = 0; i < blockNumber; ++i)
{
if (cacheBlocks[i].tag == tag && cacheBlocks[i].valid)
return HIT;
}
int blockReplaced = generator() % blockNumber;
cacheBlocks[blockReplaced].tag = tag;
cacheBlocks[blockReplaced].valid = true;
return MISS;
}
void runCacheBlockSize(int blockSize)
{
cout << "Cache line size: " << blockSize << endl;
blockNumber = CACHE_SIZE / blockSize;
shiftAmount = int(log2(blockSize));
cacheBlocks = new FullyAssociativeLine[blockNumber]{};
cacheResType r;
unsigned int addr;
cout << "Fully Associative Cache Simulator\n";
int hits[4]{};
for (int inst = 0; inst < 1000000; inst++)
{
for (int i = 0; i < 4; ++i)
{
addr = genFunctions[i]();
r = cacheSimFA(addr);
if (r == HIT)
hits[i]++;
}
}
cout << "memGen1 Hits: " << hits[0] << endl;
cout << "memGen2 Hits: " << hits[1] << endl;
cout << "memGen3 Hits: " << hits[2] << endl;
cout << "memGen4 Hits: " << hits[3] << endl << endl;
delete[] cacheBlocks;
}
int main()
{
for (int i = 8; i <= 128; i *= 2)
{
runCacheBlockSize(i);
}
}<|endoftext|> |
<commit_before>/*
Copyright (C) 2000 by W.C.A. Wijngaards
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "csgfxldr/bumpmap.h"
#include "csgfxldr/rgbpixel.h"
#include "iimage.h"
csBumpMap :: csBumpMap(iImage* src, int fmt)
{
int u;
bumpmap = 0;
width = src->GetWidth();
height = src->GetHeight();
format = fmt;
/// Get the truecolor image.
iImage *rgbimage = src;
bool delete_rgb = false;
if(src->GetFormat() != CS_IMGFMT_TRUECOLOR)
{
rgbimage = src->Clone();
rgbimage->SetFormat(CS_IMGFMT_TRUECOLOR);
delete_rgb = true;
}
/// Now create the height bumpmap using the grayscale data of the image.
RGBPixel* rgbdata = (RGBPixel*)rgbimage->GetImageData();
uint8* heightdata = new uint8[width*height];
for(u=0; u< width*height; u++)
heightdata[u] = rgbdata[u].Intensity();
/// now convert the height data to the desired format.
if(format == CS_BUMPFMT_HEIGHT_8)
{
bumpmap = new uint8[width*height];
uint8* map = (uint8*)bumpmap;
for(u=0; u< width*height; u++)
map[u] = heightdata[u];
}
else if(format == CS_BUMPFMT_SLOPE_44)
{
bumpmap = new uint8[width*height];
uint8* map = (uint8*)bumpmap;
for(int y=0; y<height; y++)
for(int x=0; x<width; x++)
{
int dx = heightdata[ y*width + (x+1)%width ] -
heightdata[ y*width + (x-1)%width ];
int dy = heightdata[ ((y+1)%height)*width + x ] -
heightdata[ ((y-1)%height)*width + x ];
/// now dx,dy are -255 ... 255, but must fit in -8..+7
dx >>=5;
dy >>=5;
map[ y*width+x ] = (dx << 4) | dy;
}
}
delete[] heightdata;
if(delete_rgb)
rgbimage->DecRef();
}
csBumpMap :: ~csBumpMap()
{
delete[] bumpmap;
}
<commit_msg>minor fix.<commit_after>/*
Copyright (C) 2000 by W.C.A. Wijngaards
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "csgfxldr/bumpmap.h"
#include "csgfxldr/rgbpixel.h"
#include "iimage.h"
csBumpMap :: csBumpMap(iImage* src, int fmt)
{
int u;
bumpmap = 0;
width = src->GetWidth();
height = src->GetHeight();
format = fmt;
/// Get the truecolor image.
iImage *rgbimage = src;
bool delete_rgb = false;
if(src->GetFormat() != CS_IMGFMT_TRUECOLOR)
{
rgbimage = src->Clone();
rgbimage->SetFormat(CS_IMGFMT_TRUECOLOR);
delete_rgb = true;
}
/// Now create the height bumpmap using the grayscale data of the image.
RGBPixel* rgbdata = (RGBPixel*)rgbimage->GetImageData();
uint8* heightdata = new uint8[width*height];
for(u=0; u< width*height; u++)
heightdata[u] = rgbdata[u].Intensity();
/// now convert the height data to the desired format.
if(format == CS_BUMPFMT_HEIGHT_8)
{
bumpmap = new uint8[width*height];
uint8* map = (uint8*)bumpmap;
for(u=0; u< width*height; u++)
map[u] = heightdata[u];
}
else if(format == CS_BUMPFMT_SLOPE_44)
{
bumpmap = new uint8[width*height];
uint8* map = (uint8*)bumpmap;
for(int y=0; y<height; y++)
for(int x=0; x<width; x++)
{
int dx = heightdata[ y*width + (x+1)%width ] -
heightdata[ y*width + (x-1)%width ];
int dy = heightdata[ ((y+1)%height)*width + x ] -
heightdata[ ((y-1)%height)*width + x ];
/// now dx,dy are -255 ... 255, but must fit in -8..+7
dx >>=5;
dy >>=5;
map[ y*width+x ] = ((dx << 4)&0xF0) | (dy&0xF);
}
}
delete[] heightdata;
if(delete_rgb)
rgbimage->DecRef();
}
csBumpMap :: ~csBumpMap()
{
delete[] bumpmap;
}
<|endoftext|> |
<commit_before>#include "editor.h"
#include "ui_editor.h"
#include "ui/link_item.h"
#include "ui/socket_item.h"
#include "ui/colors.h"
#include "ui/elements_list.h"
#include <QAction>
#include <QDebug>
#include <QDesktopServices>
#include <QDir>
#include <QDockWidget>
#include <QFileDialog>
#include <QGraphicsItem>
#include <QGraphicsScene>
#include <QMessageBox>
#include <QPainterPath>
#include <QPolygonF>
#include <QPushButton>
#include <QToolBox>
#include <QUrl>
#include <cctype>
#include <fstream>
#include <typeinfo>
#include <vector>
#include "core/registry.h"
#include "core/version.h"
#include "elements/logic/all.h"
#include "nodes/node.h"
#include "ui/package_view.h"
QString const PACKAGES_DIR{ "../packages" };
Editor::Editor(QWidget *a_parent)
: QMainWindow{ a_parent }
, m_ui{ new Ui::Editor }
{
setObjectName("SpaghettiEditor");
m_ui->setupUi(this);
m_ui->libraryToolBox->removeItem(0);
m_ui->tabWidget->removeTab(0);
connect(m_ui->actionNew, &QAction::triggered, this, &Editor::newPackage);
connect(m_ui->actionOpen, &QAction::triggered, this, &Editor::openPackage);
connect(m_ui->actionSave, &QAction::triggered, this, &Editor::savePackage);
connect(m_ui->actionClose, &QAction::triggered, this, &Editor::closePackage);
connect(m_ui->actionCloseAll, &QAction::triggered, this, &Editor::closeAllPackages);
connect(m_ui->actionDeleteElement, &QAction::triggered, this, &Editor::deleteElement);
connect(m_ui->actionShowLibrary, &QAction::triggered, this, &Editor::showLibrary);
connect(m_ui->actionShowProperties, &QAction::triggered, this, &Editor::showProperties);
connect(m_ui->actionBuildCommit, &QAction::triggered, this, &Editor::buildCommit);
connect(m_ui->actionRecentChanges, &QAction::triggered, this, &Editor::recentChanges);
connect(m_ui->actionAbout, &QAction::triggered, this, &Editor::about);
connect(m_ui->actionAboutQt, &QAction::triggered, this, &Editor::aboutQt);
connect(m_ui->tabWidget, &QTabWidget::tabCloseRequested, this, &Editor::tabCloseRequested);
connect(m_ui->tabWidget, &QTabWidget::currentChanged, this, &Editor::tabChanged);
QDir packagesDir{ PACKAGES_DIR };
if (!packagesDir.exists()) packagesDir.mkpath(".");
m_ui->propertiesTable->clear();
m_ui->propertiesTable->setColumnCount(2);
m_ui->propertiesTable->setHorizontalHeaderLabels(QString("Name;Value").split(";"));
m_ui->propertiesTable->horizontalHeader()->setStretchLastSection(true);
m_ui->propertiesTable->setRowCount(3);
populateLibrary();
newPackage();
}
Editor::~Editor()
{
delete m_ui;
}
void Editor::tabCloseRequested(int a_index)
{
QTabWidget *const tab{ m_ui->tabWidget };
QWidget *const widget{ tab->widget(a_index) };
PackageView *const packageView{ reinterpret_cast<PackageView *>(widget) };
if (packageView->canClose()) {
tab->removeTab(a_index);
delete packageView;
}
}
void Editor::tabChanged(int a_index)
{
m_packageViewIndex = a_index;
}
void Editor::populateLibrary()
{
core::Registry const ®istry{ core::Registry::get() };
auto const &elements{ registry.elements() };
for (auto &&element : elements) {
auto const &info = element.second;
std::string const path{ info.type };
std::string category{ path };
if (auto const it = path.find_first_of('/'); it != std::string::npos) category = path.substr(0, it);
category[0] = static_cast<char>(std::toupper(category[0]));
addElement(QString::fromStdString(category), QString::fromStdString(info.name), QString::fromStdString(info.type),
QString::fromStdString(info.icon));
}
}
void Editor::addElement(QString a_category, QString a_name, QString a_type, QString a_icon)
{
QToolBox *const toolbox{ m_ui->libraryToolBox };
ElementsList *list{};
int const count{ toolbox->count() };
for (int i = 0; i < count; ++i) {
QString const text{ toolbox->itemText(i) };
if (text != a_category) continue;
list = qobject_cast<ElementsList *>(toolbox->widget(i));
assert(list);
break;
}
if (list == nullptr) {
list = new ElementsList{ this };
toolbox->addItem(list, a_category);
}
QListWidgetItem *const item{ new QListWidgetItem{ a_name } };
item->setData(ElementsList::eMetaDataType, a_type);
item->setData(ElementsList::eMetaDataName, a_name);
item->setData(ElementsList::eMetaDataIcon, a_icon);
item->setIcon(QIcon(a_icon));
list->addItem(item);
list->sortItems();
}
void Editor::aboutToQuit() {}
void Editor::showEvent(QShowEvent *a_event)
{
static bool s_firstTime{ true };
if (s_firstTime) {
s_firstTime = false;
auto *const tab = m_ui->tabWidget;
auto const index = tab->currentIndex();
auto packageView = qobject_cast<PackageView *const>(tab->widget(index));
packageView->center();
}
QMainWindow::showEvent(a_event);
}
PackageView *Editor::packageViewForIndex(int const a_index) const
{
auto *const tabWidget = m_ui->tabWidget;
auto const index = a_index == -1 ? tabWidget->currentIndex() : a_index;
auto packageView = qobject_cast<PackageView *const>(tabWidget->widget(index));
return packageView;
}
int Editor::openPackageViews() const
{
return m_ui->tabWidget->count();
}
void Editor::newPackage()
{
auto *const packageView = new PackageView{ m_ui->propertiesTable };
m_packageViewIndex = m_ui->tabWidget->addTab(packageView, "New package");
m_ui->tabWidget->setCurrentIndex(m_packageViewIndex);
packageView->showProperties();
}
void Editor::openPackage()
{
QString const filename{ QFileDialog::getOpenFileName(this, "Open .package", PACKAGES_DIR, "*.package") };
if (filename.isEmpty()) return;
newPackage();
auto *const packageView = packageViewForIndex(m_packageViewIndex);
packageView->setFilename(filename);
QDir const packagesDir{ PACKAGES_DIR };
m_ui->tabWidget->setTabText(m_packageViewIndex, packagesDir.relativeFilePath(filename));
packageView->open();
packageView->showProperties();
}
void Editor::savePackage()
{
assert(m_packageViewIndex >= 0);
auto *const packageView = packageViewForIndex(m_packageViewIndex);
if (packageView->filename().isEmpty()) {
QString filename{ QFileDialog::getSaveFileName(this, "Save .package", PACKAGES_DIR, "*.package") };
if (filename.isEmpty()) return;
if (!filename.endsWith(".package")) filename += ".package";
packageView->setFilename(filename);
QDir const packagesDir{ PACKAGES_DIR };
m_ui->tabWidget->setTabText(m_packageViewIndex, packagesDir.relativeFilePath(filename));
}
packageView->save();
}
void Editor::closePackage()
{
closePackageView(m_packageViewIndex);
}
void Editor::closeAllPackages()
{
while (int count = openPackageViews()) closePackageView(count - 1);
}
void Editor::closePackageView(int const a_index)
{
auto *const packageView = packageViewForIndex(a_index);
if (packageView->canClose()) m_ui->tabWidget->removeTab(a_index);
delete packageView;
}
void Editor::deleteElement()
{
auto *const packageView = packageViewForIndex(m_packageViewIndex);
packageView->deleteElement();
}
void Editor::showLibrary(bool a_checked)
{
m_ui->library->setVisible(a_checked);
}
void Editor::showProperties(bool a_checked)
{
m_ui->properties->setVisible(a_checked);
}
void Editor::buildCommit()
{
QUrl const url{ QString("https://github.com/aljen/spaghetti/tree/%1").arg(core::version::COMMIT_HASH) };
QDesktopServices::openUrl(url);
}
void Editor::recentChanges()
{
QUrl const url{ QString("https://github.com/aljen/spaghetti/compare/%1...master").arg(core::version::COMMIT_HASH) };
QDesktopServices::openUrl(url);
}
void Editor::about()
{
QMessageBox::about(
this, "About Spaghetti",
QString("<a href='https://github.com/aljen/spaghetti'>Spaghetti</a> version: %1<br>"
"<br>"
"Copyright © 2017 <b>Artur Wyszyński</b><br>"
"<br>"
"Build date: <b>%2, %3</b><br>"
"Git branch: <b>%4</b><br>"
"Git commit: <b>%5</b><br>"
"<br>"
"Used libraries:<br>"
"<a href='https://github.com/nlohmann/json'>JSON for Modern C++</a> by <b>Niels Lohmann</b><br>"
"<a href='https://github.com/cameron314/concurrentqueue'>An industrial-strength lock-free queue for "
"C++</a> by <b>cameron314</b><br>"
"<a href='https://github.com/greg7mdp/sparsepp'>A fast, memory efficient hash map for C++</a> by "
"<b>Gregory Popovitch</b><br>"
"<a href='http://www.boost.org/'>Boost libraries</a><br>")
.arg(core::version::STRING)
.arg(__DATE__)
.arg(__TIME__)
.arg(core::version::BRANCH)
.arg(core::version::COMMIT_SHORT_HASH));
}
void Editor::aboutQt()
{
QMessageBox::aboutQt(this);
}
<commit_msg>Close all packages on exit<commit_after>#include "editor.h"
#include "ui_editor.h"
#include "ui/link_item.h"
#include "ui/socket_item.h"
#include "ui/colors.h"
#include "ui/elements_list.h"
#include <QAction>
#include <QDebug>
#include <QDesktopServices>
#include <QDir>
#include <QDockWidget>
#include <QFileDialog>
#include <QGraphicsItem>
#include <QGraphicsScene>
#include <QMessageBox>
#include <QPainterPath>
#include <QPolygonF>
#include <QPushButton>
#include <QToolBox>
#include <QUrl>
#include <cctype>
#include <fstream>
#include <typeinfo>
#include <vector>
#include "core/registry.h"
#include "core/version.h"
#include "elements/logic/all.h"
#include "nodes/node.h"
#include "ui/package_view.h"
QString const PACKAGES_DIR{ "../packages" };
Editor::Editor(QWidget *a_parent)
: QMainWindow{ a_parent }
, m_ui{ new Ui::Editor }
{
setObjectName("SpaghettiEditor");
m_ui->setupUi(this);
m_ui->libraryToolBox->removeItem(0);
m_ui->tabWidget->removeTab(0);
connect(m_ui->actionNew, &QAction::triggered, this, &Editor::newPackage);
connect(m_ui->actionOpen, &QAction::triggered, this, &Editor::openPackage);
connect(m_ui->actionSave, &QAction::triggered, this, &Editor::savePackage);
connect(m_ui->actionClose, &QAction::triggered, this, &Editor::closePackage);
connect(m_ui->actionCloseAll, &QAction::triggered, this, &Editor::closeAllPackages);
connect(m_ui->actionDeleteElement, &QAction::triggered, this, &Editor::deleteElement);
connect(m_ui->actionShowLibrary, &QAction::triggered, this, &Editor::showLibrary);
connect(m_ui->actionShowProperties, &QAction::triggered, this, &Editor::showProperties);
connect(m_ui->actionBuildCommit, &QAction::triggered, this, &Editor::buildCommit);
connect(m_ui->actionRecentChanges, &QAction::triggered, this, &Editor::recentChanges);
connect(m_ui->actionAbout, &QAction::triggered, this, &Editor::about);
connect(m_ui->actionAboutQt, &QAction::triggered, this, &Editor::aboutQt);
connect(m_ui->tabWidget, &QTabWidget::tabCloseRequested, this, &Editor::tabCloseRequested);
connect(m_ui->tabWidget, &QTabWidget::currentChanged, this, &Editor::tabChanged);
QDir packagesDir{ PACKAGES_DIR };
if (!packagesDir.exists()) packagesDir.mkpath(".");
m_ui->propertiesTable->clear();
m_ui->propertiesTable->setColumnCount(2);
m_ui->propertiesTable->setHorizontalHeaderLabels(QString("Name;Value").split(";"));
m_ui->propertiesTable->horizontalHeader()->setStretchLastSection(true);
m_ui->propertiesTable->setRowCount(3);
populateLibrary();
newPackage();
}
Editor::~Editor()
{
closeAllPackages();
delete m_ui;
}
void Editor::tabCloseRequested(int a_index)
{
QTabWidget *const tab{ m_ui->tabWidget };
QWidget *const widget{ tab->widget(a_index) };
PackageView *const packageView{ reinterpret_cast<PackageView *>(widget) };
if (packageView->canClose()) {
tab->removeTab(a_index);
delete packageView;
}
}
void Editor::tabChanged(int a_index)
{
m_packageViewIndex = a_index;
}
void Editor::populateLibrary()
{
core::Registry const ®istry{ core::Registry::get() };
auto const &elements{ registry.elements() };
for (auto &&element : elements) {
auto const &info = element.second;
std::string const path{ info.type };
std::string category{ path };
if (auto const it = path.find_first_of('/'); it != std::string::npos) category = path.substr(0, it);
category[0] = static_cast<char>(std::toupper(category[0]));
addElement(QString::fromStdString(category), QString::fromStdString(info.name), QString::fromStdString(info.type),
QString::fromStdString(info.icon));
}
}
void Editor::addElement(QString a_category, QString a_name, QString a_type, QString a_icon)
{
QToolBox *const toolbox{ m_ui->libraryToolBox };
ElementsList *list{};
int const count{ toolbox->count() };
for (int i = 0; i < count; ++i) {
QString const text{ toolbox->itemText(i) };
if (text != a_category) continue;
list = qobject_cast<ElementsList *>(toolbox->widget(i));
assert(list);
break;
}
if (list == nullptr) {
list = new ElementsList{ this };
toolbox->addItem(list, a_category);
}
QListWidgetItem *const item{ new QListWidgetItem{ a_name } };
item->setData(ElementsList::eMetaDataType, a_type);
item->setData(ElementsList::eMetaDataName, a_name);
item->setData(ElementsList::eMetaDataIcon, a_icon);
item->setIcon(QIcon(a_icon));
list->addItem(item);
list->sortItems();
}
void Editor::aboutToQuit() {}
void Editor::showEvent(QShowEvent *a_event)
{
static bool s_firstTime{ true };
if (s_firstTime) {
s_firstTime = false;
auto *const tab = m_ui->tabWidget;
auto const index = tab->currentIndex();
auto packageView = qobject_cast<PackageView *const>(tab->widget(index));
packageView->center();
}
QMainWindow::showEvent(a_event);
}
PackageView *Editor::packageViewForIndex(int const a_index) const
{
auto *const tabWidget = m_ui->tabWidget;
auto const index = a_index == -1 ? tabWidget->currentIndex() : a_index;
auto packageView = qobject_cast<PackageView *const>(tabWidget->widget(index));
return packageView;
}
int Editor::openPackageViews() const
{
return m_ui->tabWidget->count();
}
void Editor::newPackage()
{
auto *const packageView = new PackageView{ m_ui->propertiesTable };
m_packageViewIndex = m_ui->tabWidget->addTab(packageView, "New package");
m_ui->tabWidget->setCurrentIndex(m_packageViewIndex);
packageView->showProperties();
}
void Editor::openPackage()
{
QString const filename{ QFileDialog::getOpenFileName(this, "Open .package", PACKAGES_DIR, "*.package") };
if (filename.isEmpty()) return;
newPackage();
auto *const packageView = packageViewForIndex(m_packageViewIndex);
packageView->setFilename(filename);
QDir const packagesDir{ PACKAGES_DIR };
m_ui->tabWidget->setTabText(m_packageViewIndex, packagesDir.relativeFilePath(filename));
packageView->open();
packageView->showProperties();
}
void Editor::savePackage()
{
assert(m_packageViewIndex >= 0);
auto *const packageView = packageViewForIndex(m_packageViewIndex);
if (packageView->filename().isEmpty()) {
QString filename{ QFileDialog::getSaveFileName(this, "Save .package", PACKAGES_DIR, "*.package") };
if (filename.isEmpty()) return;
if (!filename.endsWith(".package")) filename += ".package";
packageView->setFilename(filename);
QDir const packagesDir{ PACKAGES_DIR };
m_ui->tabWidget->setTabText(m_packageViewIndex, packagesDir.relativeFilePath(filename));
}
packageView->save();
}
void Editor::closePackage()
{
closePackageView(m_packageViewIndex);
}
void Editor::closeAllPackages()
{
while (int count = openPackageViews()) closePackageView(count - 1);
}
void Editor::closePackageView(int const a_index)
{
auto *const packageView = packageViewForIndex(a_index);
if (packageView->canClose()) m_ui->tabWidget->removeTab(a_index);
delete packageView;
}
void Editor::deleteElement()
{
auto *const packageView = packageViewForIndex(m_packageViewIndex);
packageView->deleteElement();
}
void Editor::showLibrary(bool a_checked)
{
m_ui->library->setVisible(a_checked);
}
void Editor::showProperties(bool a_checked)
{
m_ui->properties->setVisible(a_checked);
}
void Editor::buildCommit()
{
QUrl const url{ QString("https://github.com/aljen/spaghetti/tree/%1").arg(core::version::COMMIT_HASH) };
QDesktopServices::openUrl(url);
}
void Editor::recentChanges()
{
QUrl const url{ QString("https://github.com/aljen/spaghetti/compare/%1...master").arg(core::version::COMMIT_HASH) };
QDesktopServices::openUrl(url);
}
void Editor::about()
{
QMessageBox::about(
this, "About Spaghetti",
QString("<a href='https://github.com/aljen/spaghetti'>Spaghetti</a> version: %1<br>"
"<br>"
"Copyright © 2017 <b>Artur Wyszyński</b><br>"
"<br>"
"Build date: <b>%2, %3</b><br>"
"Git branch: <b>%4</b><br>"
"Git commit: <b>%5</b><br>"
"<br>"
"Used libraries:<br>"
"<a href='https://github.com/nlohmann/json'>JSON for Modern C++</a> by <b>Niels Lohmann</b><br>"
"<a href='https://github.com/cameron314/concurrentqueue'>An industrial-strength lock-free queue for "
"C++</a> by <b>cameron314</b><br>"
"<a href='https://github.com/greg7mdp/sparsepp'>A fast, memory efficient hash map for C++</a> by "
"<b>Gregory Popovitch</b><br>"
"<a href='http://www.boost.org/'>Boost libraries</a><br>")
.arg(core::version::STRING)
.arg(__DATE__)
.arg(__TIME__)
.arg(core::version::BRANCH)
.arg(core::version::COMMIT_SHORT_HASH));
}
void Editor::aboutQt()
{
QMessageBox::aboutQt(this);
}
<|endoftext|> |
<commit_before>#include "automata.hpp"
#include "state.hpp"
#include <iostream>
#include <string>
#include <list>
using namespace std;
Automata::Automata() {
this->epsilon = false;
}
Automata::Automata(bool _epsilon, int _nsymbol, int _nstates) {
this->epsilon = _epsilon;
if(this->epsilon)
_nsymbol += 1;
this->nsymbol = _nsymbol;
this->nstates = _nstates;
this->states = new list<State*>;
this->generateFNA();
}
// generate a FNA from file
void Automata::generateFNA() {
int i;
for(i = 0; i < this->nstates; i++) {
states->push_back(new State(this->nsymbol));
}
}
// this method fix any problem reading file
void Automata::newLine() {
while(getc(stdin) != '\n')
continue;
}
void Automata::printAutomata() {
for(State* state : *(this->states)) {
state->printItself();
}
}
void Automata::generateFDA() {
string *_head;
string *_heads[this->nstates];
string **_auxHeads = new string*[100]; // change
int i, j;
i = 0;
for(State *state : *(this->states)) {
_heads[i] = state->getHead();
_auxHeads[i] = state->getHead();
}
int cont;
string **_tr, **_newtr;
for(State *state : *(this->states)) {
_tr = state->getTransitions();
for(i = 0; i < this->nsymbol; i++) {
cont = 0;
for (j = 0; j < this->nstates; j++) {
if(_tr[i]->size() == 3) {
_tr[i]->erase(0, 0);
_tr[i]->pop_back();
}
if(!(*_tr[i]).compare((*_auxHeads[j]))) { // if the new transitions doesn't exist in list of states, create new state
cont++;
}
printf("\n\n\nchegou aqui\n\n\n");
}
if(cont == 0) {
_head = _tr[i];
_auxHeads[this->nstates] = _head;
this->incrementNStates(this->nstates);
_newtr = getNTrasitions(_heads, _head);
}
}
this->states->push_back(new State(_head, _newtr, this->nsymbol)); // make constructor :D
}
}
void Automata::incrementNStates(int _nstates) {
this->nstates = _nstates + 1;
}
string **Automata::getNTrasitions(string **_heads, string* _head) {
int i, j, k;
string **_transitions = new string*[this->nsymbol];
string **_tr, **_states;
_states = new string*[(*_heads)->size()];
j = 0;
int _hsize = (*_heads)->size();
for(i = 0; i < _hsize; i++) {
if(_head->find(*_heads[i]) != string::npos) {
_states[j] = _heads[i];
j++;
}
}
for(i = 0; i < this->nsymbol; i++) {
string *_aux = new string();
for(k = 0; k < j; k++) {
for(State* state : *(this->states)) {
if(state->getHead()->find(*_states[k])) {
_tr = state->getTransitions();
*_aux += *_tr[i];
}
}
_transitions[i] = getFormatedTransition(_aux, _states);
} // não passar daqui com a transição
}
return _transitions;
}
string *Automata::getFormatedTransition(string *_aux, string **_states) {
int size = (*_states)->size();
int i;
string *_newtr = new string();
*_newtr += "{";
for(i = 0; i < size; i++) {
if(_aux->find(*_states[i]) != string::npos) {
*_newtr += *_states[i];
*_newtr += ", ";
}
}
_newtr->pop_back();
_newtr->pop_back();
*_newtr += "}";
return _newtr;
}<commit_msg>creating the states, but messing with the iterator :(<commit_after>#include "automata.hpp"
#include "state.hpp"
#include <iostream>
#include <string>
#include <list>
using namespace std;
Automata::Automata() {
this->epsilon = false;
}
Automata::Automata(bool _epsilon, int _nsymbol, int _nstates) {
this->epsilon = _epsilon;
if(this->epsilon)
_nsymbol += 1;
this->nsymbol = _nsymbol;
this->nstates = _nstates;
this->states = new list<State*>;
this->generateFNA();
}
// generate a FNA from file
void Automata::generateFNA() {
int i;
for(i = 0; i < this->nstates; i++) {
states->push_back(new State(this->nsymbol));
}
}
// this method fix any problem reading file
void Automata::newLine() {
while(getc(stdin) != '\n')
continue;
}
void Automata::printAutomata() {
for(State* state : *(this->states)) {
state->printItself();
}
}
void Automata::generateFDA() {
string *_head;
string *_heads[this->nstates];
string **_auxHeads = new string*[100]; // change
int i, j;
i = 0;
for(State *state : *(this->states)) {
_heads[i] = state->getHead();
_auxHeads[i] = state->getHead();
i++;
}
int cont;
string **_tr, **_newtr;
for(State *state : *(this->states)) {
_tr = state->getTransitions();
for(i = 0; i < this->nsymbol; i++) {
cont = 0;
if (*_tr[i] == "-") {
cont = 1;
}
for (j = 0; j < this->nstates; j++) {
if(_tr[i]->size() == 3) {
_tr[i]->erase(0, 1);
_tr[i]->pop_back();
}
//cout << *_auxHeads[j] << endl;
//cout << *_tr[i] << endl;
if(!(*_tr[i]).compare((*_auxHeads[j]))) { // if the new transitions doesn't exist in list of states, create new state
cont++;
}
}
if(cont == 0) {
_head = _tr[i];
cout << *_head << endl;
_auxHeads[this->nstates] = _head;
this->incrementNStates(this->nstates);
_newtr = getNTrasitions(_heads, _head);
}
}
this->states->push_back(new State(_head, _newtr, this->nsymbol));
cout << "chegou aqui" << endl;
}
}
void Automata::incrementNStates(int _nstates) {
this->nstates = _nstates + 1;
}
string **Automata::getNTrasitions(string **_heads, string* _head) {
int i, j, k;
string **_transitions = new string*[this->nsymbol];
string **_tr, **_states;
_states = new string*[(*_heads)->size()];
j = 0;
int _hsize = (*_heads)->size();
for(i = 0; i < _hsize; i++) {
if(_head->find(*_heads[i]) != string::npos) {
_states[j] = _heads[i];
j++;
}
}
for(i = 0; i < this->nsymbol; i++) {
string *_aux = new string();
for(k = 0; k < j; k++) {
for(State* state : *(this->states)) {
if(state->getHead()->find(*_states[k])) {
_tr = state->getTransitions();
*_aux += *_tr[i];
}
}
_transitions[i] = getFormatedTransition(_aux, _states);
} // não passar daqui com a transição
}
return _transitions;
}
string *Automata::getFormatedTransition(string *_aux, string **_states) {
int size = (*_states)->size();
int i;
string *_newtr = new string();
*_newtr += "{";
for(i = 0; i < size; i++) {
if(_aux->find(*_states[i]) != string::npos) {
*_newtr += *_states[i];
*_newtr += ", ";
}
}
_newtr->pop_back();
_newtr->pop_back();
*_newtr += "}";
return _newtr;
}<|endoftext|> |
<commit_before>/**
* @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may find a copy of the License in the LICENCE file.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @file JPetScopeConfigParser.cpp
*/
#include "JPetScopeConfigParser.h"
#include "../JPetLoggerInclude.h"
#include <boost/regex.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/property_tree/info_parser.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <TApplication.h>
#include <cstdio>
#include <iostream>
#include "../CommonTools/CommonTools.h"
std::vector<scope_config::Config> JPetScopeConfigParser::getConfigs(const std::string& configFileName) const
{
using namespace scope_config;
using boost::property_tree::ptree;
std::vector<Config> configs;
auto prop_tree = getJsonContent(configFileName);
for (ptree::const_iterator it = prop_tree.begin(); it != prop_tree.end(); ++it) {
auto currConfigName = it->first;
auto currConfigContent = it->second;
configs.push_back(getConfig(currConfigName, currConfigContent));
}
return configs;
}
scope_config::Config JPetScopeConfigParser::getConfig(std::string configName, boost::property_tree::ptree const& configContent) const
{
using namespace scope_config;
Config config;
config.fName = configName;
config.fLocation = getLocation(configContent);
config.fCollimatorPositions = getPositions(configContent);
config.fBSlots = getBSlots(configContent);
config.fPMs = getPMs(configContent);
config.fScins = getScins(configContent);
return config;
}
std::vector<std::string> JPetScopeConfigParser::getInputDirectories(const std::string& configFileLocation, const std::vector<scope_config::Config>& configs) const
{
std::vector<std::string> directories;
for(const auto& config: configs)
{
auto path = configFileLocation + "/" +config.fLocation;
auto currDir = generateDirectories(path, transformToNumbers(config.fCollimatorPositions));
directories.insert(directories.end(), currDir.begin(), currDir.end());
}
return directories;
}
std::vector<std::string> JPetScopeConfigParser::getInputFileNames(std::string configFileName) const
{
std::vector<std::string> inputFileNames;
using boost::property_tree::ptree;
auto prop_tree = getJsonContent(configFileName);
///loop over all config sets.
for (ptree::const_iterator it = prop_tree.begin(); it != prop_tree.end(); ++it) {
auto currentConfigName = it->first;
auto currentConfigContent = it->second;
std::vector<std::string> positionsContainer;
BOOST_FOREACH(const ptree::value_type & v, currentConfigContent.get_child("collimator")) {
//! one element positions can contain a string of several numbers e.g. "2 3 10"
positionsContainer.push_back(v.second.get<std::string>("positions"));
}
auto currFileNames = generateFileNames(configFileName, CommonTools::stripFileNameSuffix(currentConfigName), transformToNumbers(positionsContainer));
inputFileNames.insert(inputFileNames.end(), currFileNames.begin(), currFileNames.end());
}
return inputFileNames;
}
// The function takes a vector of string, each string can contain one or more integers separated by
// space and it will transform it to vector of integers.
// If some elements are non-numbers the rest of the string is ignored.
// If floats or doubles are present in the string, the will be cast to int.
// e.g. ["1 2", "3", "7 a 5", "1.2"] -> [1, 2, 3, 7, 1]
std::vector<int> JPetScopeConfigParser::transformToNumbers(const std::vector<std::string>& positions) const
{
std::vector<int> numbers;
for (std::vector<std::string>::const_iterator it = positions.begin(); it != positions.end(); ++it) {
int pos;
std::stringstream buffer(*it);
while (buffer >> pos) {
numbers.push_back(pos);
}
}
return numbers;
}
/// The directory is generated according to the following pattern:
/// base_path/position
/// e.g. "unittests/data/1"
std::vector<std::string> JPetScopeConfigParser::generateDirectories(
const std::string& basePath,
const std::vector<int>& positions) const
{
std::vector<std::string> DirNames(positions.size());
std::transform(positions.begin(), positions.end(), DirNames.begin(),
[ &basePath](int number) {
return basePath + "/" + std::to_string(number);
}
);
return DirNames;
}
/// The filename is generated according to the following pattern:
/// configFileName_configName_positions
/// e.g. "example_config1_5"
std::vector<std::string> JPetScopeConfigParser::generateFileNames(
const std::string& configFileName,
const std::string& configName,
const std::vector<int>& positions) const
{
std::vector<std::string> fileNames(positions.size());
std::transform(positions.begin(), positions.end(), fileNames.begin(),
[&configFileName, &configName](int number) {
return configFileName + "_" + configName + "_" + std::to_string(number);
}
);
return fileNames;
}
std::string JPetScopeConfigParser::getLocation(boost::property_tree::ptree const& content) const
{
std::string location;
try {
location = content.get<std::string>("location");
} catch (const std::runtime_error& error) {
std::string message = "No location found in config file. Error = " + std::string(error.what());
ERROR(message);
}
return location;
}
std::vector<std::string> JPetScopeConfigParser::getPositions(boost::property_tree::ptree const& configContent) const
{
using boost::property_tree::ptree;
std::vector<std::string> positions;
try {
BOOST_FOREACH(const ptree::value_type & v, configContent.get_child("collimator")) {
//! one element positions can contain a string of several numbers e.g. "2 3 10"
positions.push_back(v.second.get<std::string>("positions"));
}
} catch (const std::runtime_error& error) {
std::string message = "Error parsing collimator positions. Error = " + std::string(error.what());
ERROR(message);
}
return positions;
}
std::vector<scope_config::BSlot> JPetScopeConfigParser::getBSlots(boost::property_tree::ptree const& content) const
{
using namespace scope_config;
std::vector<BSlot> bslots;
try {
int bslotid1 = content.get("bslot1.id", -1);
int bslotid2 = content.get("bslot2.id", -1);
bool bslotactive1 = content.get("bslot1.active", false);
bool bslotactive2 = content.get("bslot2.active", false);
std::string bslotname1 = content.get("bslot1.name", std::string(""));
std::string bslotname2 = content.get("bslot2.name", std::string(""));
float bslottheta1 = content.get("bslot1.theta", -1.f);
float bslottheta2 = content.get("bslot2.theta", -1.f);
int bslotframe1 = content.get("bslot1.frame", -1);
int bslotframe2 = content.get("bslot2.frame", -1);
bslots.push_back(BSlot(bslotid1, bslotactive1, bslotname1, bslottheta1, bslotframe1));
bslots.push_back(BSlot(bslotid2, bslotactive2, bslotname2, bslottheta2, bslotframe2));
} catch (const std::runtime_error& error) {
std::string message = "BSlot data error parsing. Error = " + std::string(error.what());
ERROR(message);
}
return bslots;
}
std::vector<scope_config::PM> JPetScopeConfigParser::getPMs(boost::property_tree::ptree const& content) const
{
using namespace scope_config;
std::vector<PM> pms;
try {
int pmid1 = content.get("pm1.id", -1);
int pmid2 = content.get("pm2.id", -1);
int pmid3 = content.get("pm3.id", -1);
int pmid4 = content.get("pm4.id", -1);
std::string pmPrefix1 = content.get<std::string>("pm1.prefix");
std::string pmPrefix2 = content.get<std::string>("pm2.prefix");
std::string pmPrefix3 = content.get<std::string>("pm3.prefix");
std::string pmPrefix4 = content.get<std::string>("pm4.prefix");
pms.push_back(PM(pmid1, pmPrefix1));
pms.push_back(PM(pmid2, pmPrefix2));
pms.push_back(PM(pmid3, pmPrefix3));
pms.push_back(PM(pmid4, pmPrefix4));
} catch (const std::runtime_error& error) {
std::string message = "PM data error parsing. Error = " + std::string(error.what());
ERROR(message);
}
return pms;
}
std::vector<scope_config::Scin> JPetScopeConfigParser::getScins(boost::property_tree::ptree const& content) const
{
using namespace scope_config;
std::vector<Scin> scins;
try {
int scinid1 = content.get("scin1.id", 0);
int scinid2 = content.get("scin2.id", 0);
scins.push_back(Scin(scinid1));
scins.push_back(Scin(scinid2));
} catch (const std::runtime_error& error) {
std::string message = "Scin data error parsing. Error = " + std::string(error.what());
ERROR(message);
}
return scins;
}
//std::string JPetScopeConfigParser::createPath(const std::string &configFileName, const int position)
//{
//std::string starting_loc = boost::filesystem::path(configFileName).parent_path().string();
//starting_loc += "/";
//starting_loc += location;
//starting_loc += "/";
//starting_loc += std::to_string(position);
//return starting_loc;
//}
//bool JPetScopeConfigParser::createOutputFileNames(const std::string &configFileName, const int position)
//{
//std::string starting_loc = createPath(configFileName, position);
//boost::filesystem::path current_dir(starting_loc);
//std::cout << "starting_loc = " << starting_loc << std::endl;
//std::string prefix = pmData.front().prefix; //o co tu chodzi to jest niejasne dla mnie
//boost::regex pattern(Form("%s_\\d*.txt", prefix.c_str()));
//std::cout << "current_dir= " << current_dir << std::endl;
//if (exists(current_dir))
//{
//std::cout << "if" << std::endl;
//for (boost::filesystem::recursive_directory_iterator iter(current_dir), end; iter != end; ++iter)
//{
//std::string name = iter->path().leaf().string();
//std::cout << "name= " << name << std::endl;
//std::string dir = "";
//if (regex_match(name, pattern))
//{
//name[1] = prefix[1];
//dir = iter->path().parent_path().string();
//dir += "/";
//dir += name;
////(*current_config).pFiles.insert(dir);
//outputFileNames.push_back(dir);
//std::cout << "dir= " << dir << std::endl;
//}
//}
//}
//else
//{
//std::string msg = "Directory: \"";
//msg += current_dir.string();
//msg += "\" does not exist.";
////std::cout << "msg= " << msg << std::endl;
//ERROR(msg.c_str());
//return false;
//}
//return true;
//}
boost::property_tree::ptree JPetScopeConfigParser::getJsonContent(const std::string& configFileName) const
{
boost::property_tree::ptree propTree;
try {
read_json(configFileName, propTree);
} catch (const std::runtime_error& error) {
std::string message = "Error opening config file. Error = " + std::string(error.what());
ERROR(message);
}
return propTree;
}
<commit_msg>Remove some commented code<commit_after>/**
* @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may find a copy of the License in the LICENCE file.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @file JPetScopeConfigParser.cpp
*/
#include "JPetScopeConfigParser.h"
#include "../JPetLoggerInclude.h"
#include <boost/regex.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/property_tree/info_parser.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <TApplication.h>
#include <cstdio>
#include <iostream>
#include "../CommonTools/CommonTools.h"
std::vector<scope_config::Config> JPetScopeConfigParser::getConfigs(const std::string& configFileName) const
{
using namespace scope_config;
using boost::property_tree::ptree;
std::vector<Config> configs;
auto prop_tree = getJsonContent(configFileName);
for (ptree::const_iterator it = prop_tree.begin(); it != prop_tree.end(); ++it) {
auto currConfigName = it->first;
auto currConfigContent = it->second;
configs.push_back(getConfig(currConfigName, currConfigContent));
}
return configs;
}
scope_config::Config JPetScopeConfigParser::getConfig(std::string configName, boost::property_tree::ptree const& configContent) const
{
using namespace scope_config;
Config config;
config.fName = configName;
config.fLocation = getLocation(configContent);
config.fCollimatorPositions = getPositions(configContent);
config.fBSlots = getBSlots(configContent);
config.fPMs = getPMs(configContent);
config.fScins = getScins(configContent);
return config;
}
std::vector<std::string> JPetScopeConfigParser::getInputDirectories(const std::string& configFileLocation, const std::vector<scope_config::Config>& configs) const
{
std::vector<std::string> directories;
for(const auto& config: configs)
{
auto path = configFileLocation + "/" +config.fLocation;
auto currDir = generateDirectories(path, transformToNumbers(config.fCollimatorPositions));
directories.insert(directories.end(), currDir.begin(), currDir.end());
}
return directories;
}
std::vector<std::string> JPetScopeConfigParser::getInputFileNames(std::string configFileName) const
{
std::vector<std::string> inputFileNames;
using boost::property_tree::ptree;
auto prop_tree = getJsonContent(configFileName);
///loop over all config sets.
for (ptree::const_iterator it = prop_tree.begin(); it != prop_tree.end(); ++it) {
auto currentConfigName = it->first;
auto currentConfigContent = it->second;
std::vector<std::string> positionsContainer;
BOOST_FOREACH(const ptree::value_type & v, currentConfigContent.get_child("collimator")) {
//! one element positions can contain a string of several numbers e.g. "2 3 10"
positionsContainer.push_back(v.second.get<std::string>("positions"));
}
auto currFileNames = generateFileNames(configFileName, CommonTools::stripFileNameSuffix(currentConfigName), transformToNumbers(positionsContainer));
inputFileNames.insert(inputFileNames.end(), currFileNames.begin(), currFileNames.end());
}
return inputFileNames;
}
// The function takes a vector of string, each string can contain one or more integers separated by
// space and it will transform it to vector of integers.
// If some elements are non-numbers the rest of the string is ignored.
// If floats or doubles are present in the string, the will be cast to int.
// e.g. ["1 2", "3", "7 a 5", "1.2"] -> [1, 2, 3, 7, 1]
std::vector<int> JPetScopeConfigParser::transformToNumbers(const std::vector<std::string>& positions) const
{
std::vector<int> numbers;
for (std::vector<std::string>::const_iterator it = positions.begin(); it != positions.end(); ++it) {
int pos;
std::stringstream buffer(*it);
while (buffer >> pos) {
numbers.push_back(pos);
}
}
return numbers;
}
/// The directory is generated according to the following pattern:
/// base_path/position
/// e.g. "unittests/data/1"
std::vector<std::string> JPetScopeConfigParser::generateDirectories(
const std::string& basePath,
const std::vector<int>& positions) const
{
std::vector<std::string> DirNames(positions.size());
std::transform(positions.begin(), positions.end(), DirNames.begin(),
[ &basePath](int number) {
return basePath + "/" + std::to_string(number);
}
);
return DirNames;
}
/// The filename is generated according to the following pattern:
/// configFileName_configName_positions
/// e.g. "example_config1_5"
std::vector<std::string> JPetScopeConfigParser::generateFileNames(
const std::string& configFileName,
const std::string& configName,
const std::vector<int>& positions) const
{
std::vector<std::string> fileNames(positions.size());
std::transform(positions.begin(), positions.end(), fileNames.begin(),
[&configFileName, &configName](int number) {
return configFileName + "_" + configName + "_" + std::to_string(number);
}
);
return fileNames;
}
std::string JPetScopeConfigParser::getLocation(boost::property_tree::ptree const& content) const
{
std::string location;
try {
location = content.get<std::string>("location");
} catch (const std::runtime_error& error) {
std::string message = "No location found in config file. Error = " + std::string(error.what());
ERROR(message);
}
return location;
}
std::vector<std::string> JPetScopeConfigParser::getPositions(boost::property_tree::ptree const& configContent) const
{
using boost::property_tree::ptree;
std::vector<std::string> positions;
try {
BOOST_FOREACH(const ptree::value_type & v, configContent.get_child("collimator")) {
//! one element positions can contain a string of several numbers e.g. "2 3 10"
positions.push_back(v.second.get<std::string>("positions"));
}
} catch (const std::runtime_error& error) {
std::string message = "Error parsing collimator positions. Error = " + std::string(error.what());
ERROR(message);
}
return positions;
}
std::vector<scope_config::BSlot> JPetScopeConfigParser::getBSlots(boost::property_tree::ptree const& content) const
{
using namespace scope_config;
std::vector<BSlot> bslots;
try {
int bslotid1 = content.get("bslot1.id", -1);
int bslotid2 = content.get("bslot2.id", -1);
bool bslotactive1 = content.get("bslot1.active", false);
bool bslotactive2 = content.get("bslot2.active", false);
std::string bslotname1 = content.get("bslot1.name", std::string(""));
std::string bslotname2 = content.get("bslot2.name", std::string(""));
float bslottheta1 = content.get("bslot1.theta", -1.f);
float bslottheta2 = content.get("bslot2.theta", -1.f);
int bslotframe1 = content.get("bslot1.frame", -1);
int bslotframe2 = content.get("bslot2.frame", -1);
bslots.push_back(BSlot(bslotid1, bslotactive1, bslotname1, bslottheta1, bslotframe1));
bslots.push_back(BSlot(bslotid2, bslotactive2, bslotname2, bslottheta2, bslotframe2));
} catch (const std::runtime_error& error) {
std::string message = "BSlot data error parsing. Error = " + std::string(error.what());
ERROR(message);
}
return bslots;
}
std::vector<scope_config::PM> JPetScopeConfigParser::getPMs(boost::property_tree::ptree const& content) const
{
using namespace scope_config;
std::vector<PM> pms;
try {
int pmid1 = content.get("pm1.id", -1);
int pmid2 = content.get("pm2.id", -1);
int pmid3 = content.get("pm3.id", -1);
int pmid4 = content.get("pm4.id", -1);
std::string pmPrefix1 = content.get<std::string>("pm1.prefix");
std::string pmPrefix2 = content.get<std::string>("pm2.prefix");
std::string pmPrefix3 = content.get<std::string>("pm3.prefix");
std::string pmPrefix4 = content.get<std::string>("pm4.prefix");
pms.push_back(PM(pmid1, pmPrefix1));
pms.push_back(PM(pmid2, pmPrefix2));
pms.push_back(PM(pmid3, pmPrefix3));
pms.push_back(PM(pmid4, pmPrefix4));
} catch (const std::runtime_error& error) {
std::string message = "PM data error parsing. Error = " + std::string(error.what());
ERROR(message);
}
return pms;
}
std::vector<scope_config::Scin> JPetScopeConfigParser::getScins(boost::property_tree::ptree const& content) const
{
using namespace scope_config;
std::vector<Scin> scins;
try {
int scinid1 = content.get("scin1.id", 0);
int scinid2 = content.get("scin2.id", 0);
scins.push_back(Scin(scinid1));
scins.push_back(Scin(scinid2));
} catch (const std::runtime_error& error) {
std::string message = "Scin data error parsing. Error = " + std::string(error.what());
ERROR(message);
}
return scins;
}
boost::property_tree::ptree JPetScopeConfigParser::getJsonContent(const std::string& configFileName) const
{
boost::property_tree::ptree propTree;
try {
read_json(configFileName, propTree);
} catch (const std::runtime_error& error) {
std::string message = "Error opening config file. Error = " + std::string(error.what());
ERROR(message);
}
return propTree;
}
<|endoftext|> |
<commit_before>/*************************************************************************
* UrBackup - Client/Server backup system
* Copyright (C) 2011-2016 Martin Raiber
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/
#include "AESGCMEncryption.h"
#include "../stringtools.h"
#include "../Interface/Server.h"
#include <assert.h>
#define VLOG(x)
const size_t iv_size = 12;
const size_t end_marker_zeros = 4;
using namespace CryptoPPCompat;
AESGCMEncryption::AESGCMEncryption( const std::string& key, bool hash_password)
: encryption(), encryption_filter(encryption), iv_done(false), end_marker_state(0),
overhead_size(0), message_size(0)
{
if(hash_password)
{
m_sbbKey.resize(CryptoPP::SHA256::DIGESTSIZE);
CryptoPP::SHA256().CalculateDigest(m_sbbKey.BytePtr(), reinterpret_cast<const byte*>(key.data()), key.size() );
}
else
{
m_sbbKey.resize(key.size());
memcpy(m_sbbKey.BytePtr(), key.c_str(), key.size());
}
m_IV.resize(iv_size);
CryptoPP::AutoSeededRandomPool prng;
prng.GenerateBlock(m_IV.BytePtr(), m_IV.size());
encryption.SetKeyWithIV(m_sbbKey.BytePtr(), m_sbbKey.size(),
m_IV.BytePtr(), m_IV.size());
m_orig_IV = m_IV;
iv_done=false;
assert(encryption.CanUseStructuredIVs());
assert(encryption.IsResynchronizable());
}
void AESGCMEncryption::put( const char *data, size_t data_size )
{
Server->Log("AESGCMEncryption::put " + std::string(data, data_size));
encryption_filter.Put(reinterpret_cast<const byte*>(data), data_size);
message_size+=data_size;
if (message_size > 2LL * 1024 * 1024 * 1024 - 1)
{
flush();
}
}
void AESGCMEncryption::flush()
{
encryption_filter.MessageEnd();
end_markers.push_back(encryption_filter.MaxRetrievable());
CryptoPP::IncrementCounterByOne(m_IV.BytePtr(), static_cast<unsigned int>(m_IV.size()));
encryption.Resynchronize(m_IV.BytePtr(), static_cast<int>(m_IV.size()));
overhead_size+=16; //tag size
}
std::string AESGCMEncryption::get()
{
std::string ret;
size_t iv_add = iv_done ? 0 : m_IV.size();
size_t max_retrievable;
bool add_end_marker=false;
if(!end_markers.empty())
{
max_retrievable = end_markers[0];
end_markers.erase(end_markers.begin());
add_end_marker=true;
}
else
{
max_retrievable = encryption_filter.MaxRetrievable();
}
ret.resize(max_retrievable+iv_add + ( add_end_marker ? (end_marker_zeros + 1) : 0 ) );
if(!iv_done)
{
memcpy(&ret[0], m_orig_IV.BytePtr(), m_orig_IV.size());
iv_done=true;
overhead_size+=m_orig_IV.size();
}
if(max_retrievable>0)
{
size_t nb = encryption_filter.Get(reinterpret_cast<byte*>(&ret[iv_add]), max_retrievable);
assert(nb==max_retrievable);
/*if(nb!=max_retrievable)
{
ret.resize(nb+iv_add+ ( add_end_marker ? (end_marker_zeros + 1) : 0 ));
}*/
escapeEndMarker(ret, iv_add+nb, iv_add);
decEndMarkers(nb);
}
if(add_end_marker)
{
//The rest is already zero
ret[ret.size()-1]=1;
end_marker_state=0;
overhead_size+=end_marker_zeros+1;
message_size+=end_marker_zeros+1;
encryption_filter.GetNextMessage();
VLOG(Server->Log("New message. Size: "+convert(message_size), LL_DEBUG));
message_size=0;
}
return ret;
}
void AESGCMEncryption::decEndMarkers( size_t n )
{
for(size_t i=0;i<end_markers.size();++i)
end_markers[i]-=n;
}
void AESGCMEncryption::escapeEndMarker(std::string& ret, size_t size, size_t offset)
{
for(size_t i=offset;i<size;)
{
char ch=ret[i];
if(end_marker_state==0 && i+end_marker_zeros<=size
&& ret[i+end_marker_zeros-1]!=0)
{
i+=end_marker_zeros;
continue;
}
if(ch==0)
{
++end_marker_state;
if(end_marker_state==end_marker_zeros)
{
char ich=2;
ret.insert(ret.begin()+i+1, ich);
++i;
end_marker_state=0;
Server->Log("Escaped something at "+convert(i), LL_DEBUG);
++overhead_size;
}
}
else
{
end_marker_state=0;
}
++i;
}
}
int64 AESGCMEncryption::getOverheadBytes()
{
return overhead_size;
}
<commit_msg>Remove debugging<commit_after>/*************************************************************************
* UrBackup - Client/Server backup system
* Copyright (C) 2011-2016 Martin Raiber
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/
#include "AESGCMEncryption.h"
#include "../stringtools.h"
#include "../Interface/Server.h"
#include <assert.h>
#define VLOG(x)
const size_t iv_size = 12;
const size_t end_marker_zeros = 4;
using namespace CryptoPPCompat;
AESGCMEncryption::AESGCMEncryption( const std::string& key, bool hash_password)
: encryption(), encryption_filter(encryption), iv_done(false), end_marker_state(0),
overhead_size(0), message_size(0)
{
if(hash_password)
{
m_sbbKey.resize(CryptoPP::SHA256::DIGESTSIZE);
CryptoPP::SHA256().CalculateDigest(m_sbbKey.BytePtr(), reinterpret_cast<const byte*>(key.data()), key.size() );
}
else
{
m_sbbKey.resize(key.size());
memcpy(m_sbbKey.BytePtr(), key.c_str(), key.size());
}
m_IV.resize(iv_size);
CryptoPP::AutoSeededRandomPool prng;
prng.GenerateBlock(m_IV.BytePtr(), m_IV.size());
encryption.SetKeyWithIV(m_sbbKey.BytePtr(), m_sbbKey.size(),
m_IV.BytePtr(), m_IV.size());
m_orig_IV = m_IV;
iv_done=false;
assert(encryption.CanUseStructuredIVs());
assert(encryption.IsResynchronizable());
}
void AESGCMEncryption::put( const char *data, size_t data_size )
{
encryption_filter.Put(reinterpret_cast<const byte*>(data), data_size);
message_size+=data_size;
if (message_size > 2LL * 1024 * 1024 * 1024 - 1)
{
flush();
}
}
void AESGCMEncryption::flush()
{
encryption_filter.MessageEnd();
end_markers.push_back(encryption_filter.MaxRetrievable());
CryptoPP::IncrementCounterByOne(m_IV.BytePtr(), static_cast<unsigned int>(m_IV.size()));
encryption.Resynchronize(m_IV.BytePtr(), static_cast<int>(m_IV.size()));
overhead_size+=16; //tag size
}
std::string AESGCMEncryption::get()
{
std::string ret;
size_t iv_add = iv_done ? 0 : m_IV.size();
size_t max_retrievable;
bool add_end_marker=false;
if(!end_markers.empty())
{
max_retrievable = end_markers[0];
end_markers.erase(end_markers.begin());
add_end_marker=true;
}
else
{
max_retrievable = encryption_filter.MaxRetrievable();
}
ret.resize(max_retrievable+iv_add + ( add_end_marker ? (end_marker_zeros + 1) : 0 ) );
if(!iv_done)
{
memcpy(&ret[0], m_orig_IV.BytePtr(), m_orig_IV.size());
iv_done=true;
overhead_size+=m_orig_IV.size();
}
if(max_retrievable>0)
{
size_t nb = encryption_filter.Get(reinterpret_cast<byte*>(&ret[iv_add]), max_retrievable);
assert(nb==max_retrievable);
/*if(nb!=max_retrievable)
{
ret.resize(nb+iv_add+ ( add_end_marker ? (end_marker_zeros + 1) : 0 ));
}*/
escapeEndMarker(ret, iv_add+nb, iv_add);
decEndMarkers(nb);
}
if(add_end_marker)
{
//The rest is already zero
ret[ret.size()-1]=1;
end_marker_state=0;
overhead_size+=end_marker_zeros+1;
message_size+=end_marker_zeros+1;
encryption_filter.GetNextMessage();
VLOG(Server->Log("New message. Size: "+convert(message_size), LL_DEBUG));
message_size=0;
}
return ret;
}
void AESGCMEncryption::decEndMarkers( size_t n )
{
for(size_t i=0;i<end_markers.size();++i)
end_markers[i]-=n;
}
void AESGCMEncryption::escapeEndMarker(std::string& ret, size_t size, size_t offset)
{
for(size_t i=offset;i<size;)
{
char ch=ret[i];
if(end_marker_state==0 && i+end_marker_zeros<=size
&& ret[i+end_marker_zeros-1]!=0)
{
i+=end_marker_zeros;
continue;
}
if(ch==0)
{
++end_marker_state;
if(end_marker_state==end_marker_zeros)
{
char ich=2;
ret.insert(ret.begin()+i+1, ich);
++i;
end_marker_state=0;
Server->Log("Escaped something at "+convert(i), LL_DEBUG);
++overhead_size;
}
}
else
{
end_marker_state=0;
}
++i;
}
}
int64 AESGCMEncryption::getOverheadBytes()
{
return overhead_size;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.